From d3e58d60851febaa0c1389c1b288c6eb19a1632e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 23:55:21 +0000 Subject: [PATCH 001/125] docs/service-split.md: plan for moving the readings file and its syncers into an MCP service The data side (storage, the station's and the air sensor's fetching, the archive, pollen and forecast) runs on its own host as an MCP server; the bot keeps Telegram, the model, the shortcuts, the alerts and the drawing. Tools are for the model (nine, one per kind of question, over both sensors); resources are for the bot (the live readings, pushed; rows for the alerts; day figures for the gauges; chart data by link). The tools' hidden Turn inputs become arguments the bot fills from the words. Six steps, each shippable on its own. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 259 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 docs/service-split.md diff --git a/docs/service-split.md b/docs/service-split.md new file mode 100644 index 00000000..d27c5d00 --- /dev/null +++ b/docs/service-split.md @@ -0,0 +1,259 @@ +# Service split plan + +The plan for moving the readings file and everything that fills it out of the bot, into a service on its own host that any MCP client +can ask. The bot keeps Telegram, the model, the prompt, the shortcuts, the alerts and the drawing; the service keeps the devices, the +archive and the answers. This is a design and a sequence of steps, each shipped on its own, in the manner of +[storage-plan.md](storage-plan.md). + +Decided before this plan: the bot draws the charts (the service sends their data); new live readings are pushed to the bot over MCP; +the two run on separate hosts; the model is offered the service's MCP tools as they are. + +## 1. Why + +- The archive, the live poll and the backfills run only while the bot runs: a bot restart, a crash or a Telegram outage leaves holes, + and a slow chart holds up the 5-second poll. As a service, the data keeps coming whatever the bot is doing. +- The data can be asked of by Claude Desktop, Claude Code or any MCP client, with the same answers the bot gives: today only the bot + can ask, and other assistants get brendo/ecowitt-mcp's raw cloud JSON. +- The service can live next to Home Assistant and the AirGradient on the LAN; the bot can run anywhere Telegram reaches. +- It forces the tools' hidden inputs into the open (section 2.3), which the tests and the evals want anyway. + +## 2. What is there now + +From an inventory of the code (the paths below are where to look): + +### 2.1 Who asks for data + +| Asker | How | Lives in | +|---|---|---| +| The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | +| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools, through `Tools.call_all` | `lib/intent.py`, `lib/bot.py` (`_chart_in_code`, `_lookup_in_code`, `_written_in_code`) | +| Report | `weather_now`, `air_quality`, `pollen_asthma{cached}`, `weather_forecast{cached}`; parses their JSON | `lib/report.py` | +| Dashboard and status gauges | `Ecowitt.dashboard()` directly: the raw live reading, plus the year's day rows | `lib/ecowitt/dashboard.py`, `lib/gauges.py` | +| Period buttons, charts drawn ahead | the shortcut again, with new dates; every 5 minutes for the buttons' sentences and recent alerts | `bot.on_period_button`, `bot.draw_buttons_ahead` | +| Weather alerts | `station.recent(3)` (5-minute rows, may fetch), `live_rain()` (may fetch, writes bands), a 7-day 30-minute read at start | `lib/alerts/weather.py` | +| Particulates alert | `air.latest()` every 30 minutes | `lib/alerts/particulates.py` | +| Forecast, pollen alerts | `forecast.days`, `pollen.current()` in memory, after each refresh (`Warmer.after`) | `lib/alerts/forecast.py`, `pollen_and_asthma.py` | +| Irrigation | `station.recent(24)` and the forecast, once a day | `lib/alerts/irrigation.py` | +| Alert charts, their 🔄 | `source.tools[...].handler` called directly, then `turn.charts[0]` | `lib/alerts/pictures.py` | + +### 2.2 What fills the file + +The station's warm (60 s: 5-minute and 30-minute readings, 4-hour and daily records), the Home Assistant live poll (5 s; minutes, live +bands), the nightly archive, the Home Assistant range import (15 min), the AirGradient's warm (1–4 min), import and backfill, and the +pollen and forecast refreshes (30 and 15 min). Questions fetch too: `weather_history` and the air tools ask Ecowitt or the AirGradient +cloud for what the file lacks, inline. All of it shares one `Storage`, one Home Assistant client, the in-memory `Recent` locks and the +live reading the poll keeps. + +### 2.3 What makes it hard to split + +1. **The `Turn` is a second, hidden set of arguments.** "Temperature chart 1d" and "Humidity chart 1d" send the same `weather_history` + arguments; the reading charted comes from `turn.chart_field`. Tools read `chart_asked`, `chart_field`, `chart_fields`, `two_axes`, + `average_asked`, `per_day`, `readings`, `text`, `air_named` and `ahead`, and write `charts`, `times`, `forecast_shown` and + `air_extra_used`. +2. **Charts come back on the side.** Every chart tool appends a `specs.Chart` to `turn.charts`; the rain caption reads the chart's bars. +3. **In-process hooks.** `Warmer.after` and `on_live` callbacks drive the weather, forecast and pollen alerts. +4. **The station decides the time zone** (`date_zone_id`) after the file opens, and the bot's whole config is rebuilt around it. +5. **Reads that write.** `weather_now` and `live_rain()` fetch the live reading and record its bands; with the cloud only, the minute + alert check is what drives that fetch. +6. **Per-question schemas.** `Tool.asked` swaps in the air sensor's own temperature and humidity; `readings` builds its metric list from + the file. +7. **Context-variable chart sources** (`CHART_SOURCE`), and alert charts that skip `Tools.call` and so have none. + +## 3. Design + +### 3.1 The two programs + +| Service (`ecobot_service.py`, host A, near Home Assistant) | Bot (`ecobot.py`, host B) | +|---|---| +| `lib/storage`, `lib/ecowitt`, `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, `lib/alerts`, `lib/irrigation` | +| builds chart data (`specs.Chart`) next to the reads that choose its resolution | draws it (Pillow, fonts, dark mode) | +| `lib/mcp_server.py`: the tools and resources below | `lib/mcp_client.py`: one connection, reconnects, listens | + +Shared, imported by both: `lib/specs.py` (with JSON in and out, 3.6), `lib/series.py`, `lib/timeutil.py`, `lib/captions.py` (hint +texts), and the thresholds the prompt and the alerts both name (`GUST_ALERT_KMH`, `UVI_ALERT`, `TEMP_CHANGE_C`). One repository and one +image, two commands. A test reads every bot module's imports and fails if one reaches into the service's packages (`lib.storage`, +`lib.ecowitt.fetch` …): that boundary is what keeps the split real. + +`lib/ecowitt/dashboard.py`'s `sheet()` (the gauges' layout and colours) is drawing, not data: it moves to the bot beside `gauges.py`. + +### 3.2 The interface, in one rule + +**Tools are for the model; resources are for the bot.** A tool answers a question in words and figures the model can read (what the +twelve tools do today). A resource is raw data an application reads: the live reading the gauges and the alerts need, the rows an alert +looks back over, a chart's points. Other MCP clients see the same split: an assistant asks the tools; an app can subscribe to the +resources. + +Every tool and resource follows the same conventions: +- **Metrics** are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_gust`, `rainfall.rain` + (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`. A bare reading means the sensors that have it: `temperature` is outdoor and indoor, + `pm2_5` is the air sensor's. The list comes from what the file holds (as `readings` does now). +- **Times** are the station's local time, `YYYY-MM-DD HH:MM` (or `YYYY-MM-DD` for whole days); a time with an offset is moved into + local time. The station's zone is in `ecobot://station`. +- **Periods** are `start` and `end`; `end` defaults to now, and nothing reaches past it. +- **Results** are JSON with ready-made wording where the model needs it (`low_when`, ratings, emoji), notes it must pass on (`note_*`, + `missing`), and `error` with how to correct the call. Every tool is read-only to the caller (`readOnlyHint`); some fetch what the file + lacks before they answer (`openWorldHint`). + +### 3.3 Tools (model-facing) + +Nine tools in place of twelve: one per kind of question, each over both sensors where both have the reading. + +| Tool | Answers | Replaces | Arguments | +|---|---|---|---| +| `current` | "how is it now", one reading now, the air now | `weather_now`, `air_quality` (no dates) | `sensors` (default outdoor, indoor) | +| `summary` | a period's highs, lows and averages with when; daily or monthly breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` (dates) | `metrics`, `start`, `end`, `average`, `breakdown` (auto, day, month), `chart`, `layout` (auto, stack, two_axes), `rain_by` (auto, month, year), `source` | +| `readings` | values at an interval, each with its time | `readings` | `metric`, `start`, `end`, `interval` | +| `days` | find, rank and count days; a figure per month or year; holidays and weekends | `weather_days`, `air_days` (one field list: `temp_max`, `rain`, `pm2_5_max` …) | as today's day tools | +| `relate` | does one reading go with another (rain with pressure, humidity, wind; air with rain) | `weather_link`, `air_link` | `metric`, `with` (`rain`), `start`, `end`, `chart` | +| `scan` | which readings go with which, every pair | `air_scan` | `metric` (or all), `start`, `end`, `chart` | +| `chart` | any readings from both sensors on one chart, a panel each or on shared axes | `plot_chart` | `panels[{metric, style}]`, `start`, `end`, `two_axes`, `same_axis`, `invert_second_axis`, `source` | +| `forecast` | today and the days ahead | `weather_forecast` | `days` | +| `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | + +What each hidden `Turn` input becomes: + +| Today (`Turn`) | Over MCP | +|---|---| +| `chart_field`, `chart_fields`, `readings` (which readings the words name) | `summary.metrics`, in order; `layout` for how they share the chart | +| `two_axes` | `layout: "two_axes"` (`chart.two_axes`) | +| `average_asked` | `average` | +| `per_day` | `breakdown: "day"` | +| `chart_asked` | `chart` | +| `text` (rain bars by month; `only` holidays; grouping) | `rain_by`; `days.only` and `days.group_by`, which the bot drops or fills from the words before it forwards the call (3.8) | +| `air_named` (the air reading charted when none is named) | `metrics`, filled by the bot from the conversation | +| `ahead` (a chart drawn ahead, nobody waiting) | the request's `_meta.priority: "background"` | +| `charts` (written) | a `chart` link in the result (3.6) | +| `times["data"]` (written) | the result's `_meta.timing` | +| `forecast_shown` (written) | `forecast`'s structured `days`, which the bot remembers | +| `air_extra_used` (written) | known from the arguments (`metrics` names `air.air_temperature`) | +| `Tool.asked` (per-question schema) | the service lists everything; the bot leaves the air sensor's own temperature and humidity out of what it offers the model unless the words name them (3.8) | +| `CHART_SOURCE` | `source` on the chart tools, written into the chart; the service sets it for every call, so alert charts get theirs too | + +The old names stay as aliases on the service for one release (each mapped to its new tool and arguments), so the bot and the evals can +move over in their own step (section 5). + +### 3.4 Resources (bot-facing) + +| URI | Holds | Subscribe | Read by | +|---|---|---|---| +| `ecobot://station` | name, time zone, latitude and longitude, created, the sensors and their metrics, what each source is (HA, cloud, local), retention, `air_link` (the AirGradient dashboard), alert kinds the data supports, the service's start-up lines | on change (rare) | the bot at connect: time zone, capabilities, `/usage`, menus | +| `ecobot://now/weather` | the live reading, raw: `{time, group: {field: {value, unit}}}`, and the glance emoji | each new reading (5 s with HA, 60 s cloud only) | gauges, report, the rain alert | +| `ecobot://now/air` | the latest air reading, its time, `sustained` (the minimum over `ANTISPIKE_REQUIRE_CONSECUTIVE`), ratings and AQI | each new reading | the particulates alert, report | +| `ecobot://rows/weather/{resolution}{?start,end,groups}` | rows `{ts, "group.field": value, …_low, …_high}` (1min, 5min, 30min), fetching what the file lacks | `…/5min` when a 5-minute row settles | the weather alerts (3 hours, a rain spell back, 7 days at 30 minutes), irrigation (24 hours) | +| `ecobot://days/{weather,air}{?start,end,fields}` | day figures `{field: {date: value}}` | no | gauges (the year so far) | +| `ecobot://forecast` | the forecast days, raw, with `fetched_at` and `place` | on each new forecast | the forecast alert, irrigation, report | +| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | on each new page | the pollen alert, report | +| `ecobot://chart/{id}` | a chart's data (3.6), kept 15 minutes | no | the bot, after a tool returned a link to it | +| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | the bot's log line at connect; troubleshooting | + +### 3.5 Pushing new readings + +The MCP SDK (2.3, the 2026-07-28 protocol) delivers resource changes on a `subscriptions/listen` stream: each event says "this URI +changed, read it again", with no replay. So: +- The service publishes `ecobot://now/weather` after each new live reading, `ecobot://now/air` after each new air reading, + `ecobot://rows/weather/5min` when a 5-minute row settles, and `ecobot://forecast`, `ecobot://pollen` and `ecobot://station` when they + change. Repeats of an unchanged reading are not sent. +- The bot listens on one stream and, for each event, reads the resource and runs what used to hang off the hook: `check_rain` on a new + live reading, `WeatherMonitor.check` on a new 5-minute row, the forecast and pollen alerts on a new snapshot. +- The alerts also keep their own timers, reading the resource each time: the weather alerts' calm periods and quiet hours, the 7:30am + pollen start and the 30-minute particulates check depend on the clock, not only on new data. A push makes them prompt; the timer + makes them sure. +- When the stream drops (service restart, network), the bot reconnects with backoff, listens again and reads every resource it depends + on: the alerts compare against the state they keep, so a missed event costs latency, never an alert. +- The service polls the live reading itself in every mode (today, with the cloud only, the bot's minute alert check drove that fetch). + +### 3.6 Charts + +Tools that draw (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`, and the period buttons through them) build the +`specs.Chart` as now, next to the reads that chose its resolution, its buckets and its rose. The spec is plain data (strings, epochs, +floats, lists; `period` as two dates), so: +- `specs.to_json(chart)` and `specs.from_json(data)` with a `version`; `from_json` runs the same validation as building one does. + Tuples come back as lists, which the renderer already accepts. Non-finite numbers are dropped when the spec is built. +- The tool keeps the chart in `ecobot://chart/{id}` and returns a link to it (`resource_link` content, plus `chart: {uri, hint}` in its + JSON). The model sees a line, not 100 KB of points; the bot reads the link, rebuilds the spec and draws it. Another MCP client can read + the JSON and plot it however it likes. +- The rain caption reads the chart's bars from the rebuilt spec, as it does now. `newest` (what the alerts' cache keys on) and + `caption()` work on the rebuilt spec unchanged. +- The bot never asks for a stored spec again: a period button is a new `summary` call with new dates, as today; only pictures are + cached (`periods.ImageCache`). + +### 3.7 Separate hosts + +- **Transport:** MCP Streamable HTTP, served by the SDK's Starlette app under uvicorn, behind TLS (a reverse proxy such as Caddy, or + uvicorn's own certificate). One endpoint, `https:///mcp`. +- **Auth:** a bearer token checked by the SDK's `TokenVerifier` against `MCP_TOKEN`; the bot sends it from its own `MCP_TOKEN`. + Other clients get their own token (`MCP_TOKENS=name:token,…`), so one can be revoked alone. Bind to the LAN or a tailnet; nothing + needs the internet to reach it. +- **Time:** both hosts keep NTP time. The bot takes the station's time zone from `ecobot://station` before it schedules anything, as it + takes it from the station today; the dates it builds ("the last 5 hours") are local strings in that zone. +- **When the service is down:** the bot still starts and answers ("the weather station isn't reachable right now"), keeps retrying, and + starts its alerts once it has the station's zone. Calls time out within the question's budget (`TURN_SECONDS`). +- **When the bot is down:** nothing is lost; the service keeps archiving. + +### 3.8 The bot's side of a tool call + +The bot is the MCP client, so it can shape what it offers and what it forwards: +- **What it offers:** the service's `tools/list`, as it is, except the air sensor's own temperature and humidity left out of the metric + lists unless the words name them (the prompt cache holds: the list only changes with the words, as now). On `tools/list_changed` + (a sensor sent a new field) it reads the list again. +- **What it forwards:** each call the model makes, with the corrections the words call for, the ones the tools make from `Turn` today: + `chart: true` when the words ask for a chart; `days.only` dropped unless the words say holidays or weekends; `days.group_by` from + "per month"; the air reading the conversation was about when the model named none. These live in one function, `lib/arguments.py`, + with the tests of what each phrase does. +- **Shortcuts** build the new tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way. +- **Poke** goes: a tool call is itself the service's cue to refresh what it touches. + +### 3.9 Configuration + +| Service | Bot | +|---|---| +| `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*` (including `AIRGRADIENT_DASHBOARD`), `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the station names one), `DATA_DIR`, `MCP_TOKEN(S)`, `MCP_BIND` | `TELEGRAM_*`, `OPENROUTER_*`, `ADMIN_*`, `DARKMODE`, `CHART_ALL_*`, the alert settings, `IRRIGATION_*` / Tuya, `MCP_URL`, `MCP_TOKEN`, `DATA_DIR` (the bot's state file and picture cache only) | + +The bot's `bot_state.json` (chats, subscriptions, alert state, chart questions) stays with the bot; the readings file and the +snapshots go with the service. + +## 4. What does not change + +The readings file, its tables and its day rows; how each tool chooses its resolution and fetches what it lacks; the alert rules and +their state; the charts' look; the shortcuts' choices; Telegram. The split moves where code runs and makes its inputs explicit. + +## 5. Steps + +Each step ships on its own, with the tests and evals green, and the bot working the whole way. + +1. **Explicit arguments.** The tools take the `Turn`'s inputs as arguments (3.3), and the bot fills them (`lib/arguments.py`). Tools + return their charts (as specs, in the result) instead of appending to `turn.charts`; `forecast` returns its days. Still one process. + The evals check the new arguments; `Turn` loses every field the tools read. +2. **Chart JSON.** `specs.to_json` and `from_json`, and a round-trip test over every chart the samples and `scripts/dump_specs.py` draw: + the rebuilt spec draws the same picture (the golden images). +3. **The data interface, in process.** A `Data` protocol with the tools and the resources of section 3, and an in-process + implementation over today's sources. The bot's direct reads move to it: the gauges (with `sheet()` moved to the bot), the report, the + alerts (resources and timers in place of `Warmer.after` and `on_live`), irrigation, alert charts. Nothing in the bot holds a source + object after this step. +4. **The MCP server and client.** `lib/mcp_server.py` serves the `Data` implementation; `lib/mcp_client.py` implements `Data` over MCP, + with reconnects and the listen stream. The tests run the bot against the server through the SDK's in-memory transport; the contract + test (`test_contract`) checks the tool schemas and result shapes on the wire. The evals read a checked-in `tools/list` + (`tests/evals/tools.json`), which a test keeps equal to the server's. +5. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import + boundary test. Config split. One compose file per host, TLS and tokens. The service's scripts (`edit_readings`, `cache_status`, + `refill_airgradient`, `check_rain`, `bench_storage`) run on the service's host; `show_request` and `report_inputs` become MCP clients; + `dump_specs` writes JSON on the service and draws on the bot. +6. **The new names.** The prompt, the shortcuts and the evals use the nine tools; the old names go from the service one release later. + +## 6. Testing + +- The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, + report, alerts, drawing, the client). The bot's tests run against a fake `Data`, or the real server in memory over an archived file. +- A wire test for each tool and resource: the arguments it accepts, the shape it returns, a chart link that reads back as a spec. +- A reconnect test: the stream drops, the bot listens again and reads what it depends on; an alert due during the gap is sent once. +- The live evals (`--live`) run against the service's real tool list. + +## 7. Risks + +- **Latency.** Each call is a network round trip: tens of milliseconds on a LAN, against a question budget of seconds. Charts drawn + ahead are a few calls every 5 minutes. +- **The model and the new names.** Renamed tools and arguments can change what the model picks; step 6 is gated on the live evals, and + the aliases make it reversible. +- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision; the client is pinned to the SDK version the server + runs, and both upgrade together. +- **Two things to run.** More to deploy and watch; `ecobot://health` and the bot's "unreachable" answers make a failure visible. From 191d8a35821ffa1d28abdf8a7915a49f69afb853 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 00:16:21 +0000 Subject: [PATCH 002/125] docs/service-split.md: revised after review (step order, tool shapes, MCP client and transport) A review against the code and the MCP SDK (2.3) found the first draft's steps couldn't each ship: the report, captions and prompt parse today's result shapes, so the nine tools now arrive in one step, in process, gated on the live evals, before any network; no aliases. Also: - anything that answers a question calls a tool (the report included); resources are what the bot watches; raw resources keep the device's field names (rainfall.daily), and dates come back as dates - summary separates what to summarise from what to draw (chart_metrics, one layout enum shared with chart, daily_means, every_day), returns several charts, and one result shape for both sensors; days, relate and periods are specified per tool (moments vs whole days up to yesterday) - the particulates alert keeps its 30-minute clock; the 5-minute push includes provisional rows; the weather alerts keep their 60-second clock - MCP: a supervisor owns the client and rebuilds it (a failed request ends the SDK's client), the protocol revision is pinned, allowed hosts for the proxy's name, our own static TokenVerifier, the subscription bus, the low-level server for hand-written schemas; the irrigation watchdog starts whatever the service's state; the bot keeps a TZ fallback and the station's last zone - shared helpers listed and moved in step 1; every script placed Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 380 +++++++++++++++++++++++++----------------- 1 file changed, 228 insertions(+), 152 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index d27c5d00..c8e97542 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -15,34 +15,33 @@ the two run on separate hosts; the model is offered the service's MCP tools as t - The data can be asked of by Claude Desktop, Claude Code or any MCP client, with the same answers the bot gives: today only the bot can ask, and other assistants get brendo/ecowitt-mcp's raw cloud JSON. - The service can live next to Home Assistant and the AirGradient on the LAN; the bot can run anywhere Telegram reaches. -- It forces the tools' hidden inputs into the open (section 2.3), which the tests and the evals want anyway. +- It forces the tools' hidden inputs into the open (2.3), which the tests and the evals want anyway. ## 2. What is there now -From an inventory of the code (the paths below are where to look): - ### 2.1 Who asks for data | Asker | How | Lives in | |---|---|---| | The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | -| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools, through `Tools.call_all` | `lib/intent.py`, `lib/bot.py` (`_chart_in_code`, `_lookup_in_code`, `_written_in_code`) | -| Report | `weather_now`, `air_quality`, `pollen_asthma{cached}`, `weather_forecast{cached}`; parses their JSON | `lib/report.py` | +| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools through `Tools.call_all`, their JSON parsed by `lib/report.py` | `lib/intent.py`, `lib/bot.py` (`_chart_in_code`, `_lookup_in_code`, `_written_in_code`) | +| Report | `weather_now`, `air_quality`, `pollen_asthma{cached}`, `weather_forecast{cached}` (`cached`: never wait on the network) | `lib/report.py` | | Dashboard and status gauges | `Ecowitt.dashboard()` directly: the raw live reading, plus the year's day rows | `lib/ecowitt/dashboard.py`, `lib/gauges.py` | | Period buttons, charts drawn ahead | the shortcut again, with new dates; every 5 minutes for the buttons' sentences and recent alerts | `bot.on_period_button`, `bot.draw_buttons_ahead` | -| Weather alerts | `station.recent(3)` (5-minute rows, may fetch), `live_rain()` (may fetch, writes bands), a 7-day 30-minute read at start | `lib/alerts/weather.py` | -| Particulates alert | `air.latest()` every 30 minutes | `lib/alerts/particulates.py` | +| Weather alerts | `station.recent(3)` (5-minute rows, may fetch), `live_rain()` (may fetch, writes bands), a 7-day 30-minute read at start; after every 60-second refresh and every new live reading | `lib/alerts/weather.py` | +| Particulates alert | `air.latest()` every 30 minutes (its two-readings rule is set for that pace) | `lib/alerts/particulates.py` | | Forecast, pollen alerts | `forecast.days`, `pollen.current()` in memory, after each refresh (`Warmer.after`) | `lib/alerts/forecast.py`, `pollen_and_asthma.py` | -| Irrigation | `station.recent(24)` and the forecast, once a day | `lib/alerts/irrigation.py` | +| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute | `lib/alerts/irrigation.py`, `lib/irrigation` | | Alert charts, their 🔄 | `source.tools[...].handler` called directly, then `turn.charts[0]` | `lib/alerts/pictures.py` | +| The prompt, menus, `/usage` | each source's `describe()` line; which sources exist (`by_name`) | `lib/prompt.py`, `lib/templates.py`, `lib/alerts/menu.py` | ### 2.2 What fills the file The station's warm (60 s: 5-minute and 30-minute readings, 4-hour and daily records), the Home Assistant live poll (5 s; minutes, live bands), the nightly archive, the Home Assistant range import (15 min), the AirGradient's warm (1–4 min), import and backfill, and the pollen and forecast refreshes (30 and 15 min). Questions fetch too: `weather_history` and the air tools ask Ecowitt or the AirGradient -cloud for what the file lacks, inline. All of it shares one `Storage`, one Home Assistant client, the in-memory `Recent` locks and the -live reading the poll keeps. +cloud for what the file lacks, inline. All of it shares one `Storage`, one Home Assistant client, the in-memory `Recent` locks, the +live reading the poll keeps, and the station's group list (which the archive trims). ### 2.3 What makes it hard to split @@ -50,7 +49,8 @@ live reading the poll keeps. arguments; the reading charted comes from `turn.chart_field`. Tools read `chart_asked`, `chart_field`, `chart_fields`, `two_axes`, `average_asked`, `per_day`, `readings`, `text`, `air_named` and `ahead`, and write `charts`, `times`, `forecast_shown` and `air_extra_used`. -2. **Charts come back on the side.** Every chart tool appends a `specs.Chart` to `turn.charts`; the rain caption reads the chart's bars. +2. **Charts come back on the side.** Every chart tool appends `specs.Chart`s to `turn.charts` (a history can add a wind rose beside its + chart); the rain caption reads the chart's bars. 3. **In-process hooks.** `Warmer.after` and `on_live` callbacks drive the weather, forecast and pollen alerts. 4. **The station decides the time zone** (`date_zone_id`) after the file opens, and the bot's whole config is rebuilt around it. 5. **Reads that write.** `weather_now` and `live_rain()` fetch the live reading and record its bands; with the cloud only, the minute @@ -58,6 +58,8 @@ live reading the poll keeps. 6. **Per-question schemas.** `Tool.asked` swaps in the air sensor's own temperature and humidity; `readings` builds its metric list from the file. 7. **Context-variable chart sources** (`CHART_SOURCE`), and alert charts that skip `Tools.call` and so have none. +8. **Imports across the line.** The bot imports helpers from data packages (`grouping_in`, the rain helpers, `describe_day`, + `LEVEL_EMOJI`, the air labels, `unit_text`, `glance`, `POINT_BUDGET`, `STATUS`); two data sources import `intent` for `wants()`. ## 3. Design @@ -65,195 +67,269 @@ live reading the poll keeps. | Service (`ecobot_service.py`, host A, near Home Assistant) | Bot (`ecobot.py`, host B) | |---|---| -| `lib/storage`, `lib/ecowitt`, `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, `lib/alerts`, `lib/irrigation` | +| `lib/storage`, `lib/ecowitt` (less `dashboard.sheet`), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`'s `Warmer`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/sources.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/arguments.py` (3.8), `lib/report.py`, `lib/report_menu.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/topicmemory.py`, `lib/entities.py`, `lib/admins.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py` with `sheet()`, `GAUGES` and `STATUS`, `lib/alerts`, `lib/irrigation` | | builds chart data (`specs.Chart`) next to the reads that choose its resolution | draws it (Pillow, fonts, dark mode) | -| `lib/mcp_server.py`: the tools and resources below | `lib/mcp_client.py`: one connection, reconnects, listens | - -Shared, imported by both: `lib/specs.py` (with JSON in and out, 3.6), `lib/series.py`, `lib/timeutil.py`, `lib/captions.py` (hint -texts), and the thresholds the prompt and the alerts both name (`GUST_ALERT_KMH`, `UVI_ALERT`, `TEMP_CHANGE_C`). One repository and one -image, two commands. A test reads every bot module's imports and fails if one reaches into the service's packages (`lib.storage`, -`lib.ecowitt.fetch` …): that boundary is what keeps the split real. - -`lib/ecowitt/dashboard.py`'s `sheet()` (the gauges' layout and colours) is drawing, not data: it moves to the bot beside `gauges.py`. - -### 3.2 The interface, in one rule - -**Tools are for the model; resources are for the bot.** A tool answers a question in words and figures the model can read (what the -twelve tools do today). A resource is raw data an application reads: the live reading the gauges and the alerts need, the rows an alert -looks back over, a chart's points. Other MCP clients see the same split: an assistant asks the tools; an app can subscribe to the -resources. - -Every tool and resource follows the same conventions: -- **Metrics** are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_gust`, `rainfall.rain` - (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`. A bare reading means the sensors that have it: `temperature` is outdoor and indoor, - `pm2_5` is the air sensor's. The list comes from what the file holds (as `readings` does now). -- **Times** are the station's local time, `YYYY-MM-DD HH:MM` (or `YYYY-MM-DD` for whole days); a time with an offset is moved into - local time. The station's zone is in `ecobot://station`. -- **Periods** are `start` and `end`; `end` defaults to now, and nothing reaches past it. -- **Results** are JSON with ready-made wording where the model needs it (`low_when`, ratings, emoji), notes it must pass on (`note_*`, - `missing`), and `error` with how to correct the call. Every tool is read-only to the caller (`readOnlyHint`); some fetch what the file - lacks before they answer (`openWorldHint`). - -### 3.3 Tools (model-facing) - -Nine tools in place of twelve: one per kind of question, each over both sensors where both have the reading. - -| Tool | Answers | Replaces | Arguments | +| `lib/mcp_server.py`: the tools and resources below | `lib/mcp_client.py`: the connection (3.7) | +| `lib/config.py`'s service fields (3.9) | `lib/config.py`'s bot fields | + +**Shared** (`lib/common/`, imported by both, importing neither side): `specs.py` (with JSON in and out, 3.6), `series.py`, `timeutil.py`, +`captions.py` (hint texts), `tools.py`'s `json_result`, `logs.py`, `netenv.py`, `warm.py`'s `every` and `safely`, and the pure helpers +the bot uses today from data packages: the thresholds (`GUST_ALERT_KMH`, `UVI_ALERT`, `TEMP_CHANGE_C`), `glance` (`solar_band`), +`unit_text`, `POINT_BUDGET`, the air metrics' labels and units, `grouping_in`, `HOLIDAY_WORDS`, the rain helpers (`wet_flags`, +`rain_amount`, `duration`), the forecast's `describe_day` and `day_label`, and the pollen `LEVELS` and `LEVEL_EMOJI`. + +One repository and one image, two commands. A test reads every module's imports and fails if a bot module reaches a service package or +the reverse: that boundary is what keeps the split real. The sources' `wants()` (which imports `intent`) goes with the poke (3.8). + +### 3.2 The interface + +**Anything that answers a question calls a tool, whether the model asks or a shortcut does; resources are the state the bot watches.** +A tool answers in words and figures (ready-made wording, notes to pass on); the bot's shortcuts, report, captions and period buttons +parse the same results, so each tool's result shape is a contract with the bot as well as the model, pinned by `test_contract`. A +resource is raw data an application keeps an eye on: the live readings, the rows the alerts look back over, the day figures behind the +gauges, the forecast and pollen pages. Other MCP clients see the same split: an assistant asks the tools; an app reads or subscribes to +the resources. + +Conventions for the tools: +- **Metrics** are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_speed` (always drawn + shaded up to `wind.wind_gust`), `rainfall.rain` (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`. `current` and `summary` also take a + bare reading, meaning every sensor that has it (`temperature` is outdoor and indoor; `pm2_5` the air sensor's); `readings`, `chart` + and `relate` take full names only. `days` keeps its day-figure names (`temp_max` is outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), + which read better for conditions and are listed in its schema. The lists come from what the file holds. +- **Two kinds of period.** Moments (`current`, `summary`, `readings`): `start` and `end` as `YYYY-MM-DD HH:MM` in the station's local + time, `end` defaulting to now. Days (`days`, `relate`, `scan`, `chart`): `start` and `end` as `YYYY-MM-DD`, `end` defaulting to and + capped at yesterday, because today is still settling. A time with an offset is moved into local time. Each tool's default length is in + 3.3. The station's zone is in `ecobot://station`. +- **Results** are JSON: figures with their wording (`low_when`, ratings, emoji), notes to pass on (`note_*`, `missing`, `warning`), and + `error` with how to correct the call. Every tool is read-only to the caller (`readOnlyHint`); those that fetch what the file lacks + before answering say so (`openWorldHint`). +- **Request `_meta`**, for applications, never offered to the model: `priority: "background"` (a chart drawn ahead: its fetches wait + their turn; today's `turn.ahead`) and `fetch: false` (answer from what is held, never wait on the network; today's `cached`). + Result `_meta.timing` carries the seconds spent (today's `turn.times["data"]`). + +### 3.3 Tools + +Nine tools in place of twelve, one per kind of question, each over both sensors where both have the reading. + +| Tool | Answers | Replaces | Arguments (default period) | |---|---|---|---| -| `current` | "how is it now", one reading now, the air now | `weather_now`, `air_quality` (no dates) | `sensors` (default outdoor, indoor) | -| `summary` | a period's highs, lows and averages with when; daily or monthly breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` (dates) | `metrics`, `start`, `end`, `average`, `breakdown` (auto, day, month), `chart`, `layout` (auto, stack, two_axes), `rain_by` (auto, month, year), `source` | +| `current` | how it is now; one reading now; the air now | `weather_now`, `air_quality` without dates | `metrics` (default outdoor and indoor) | +| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; charts | `weather_history`, `air_quality` with dates | `metrics`, `start`, `end` (today so far), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by`, `source` | | `readings` | values at an interval, each with its time | `readings` | `metric`, `start`, `end`, `interval` | -| `days` | find, rank and count days; a figure per month or year; holidays and weekends | `weather_days`, `air_days` (one field list: `temp_max`, `rain`, `pm2_5_max` …) | as today's day tools | -| `relate` | does one reading go with another (rain with pressure, humidity, wind; air with rain) | `weather_link`, `air_link` | `metric`, `with` (`rain`), `start`, `end`, `chart` | -| `scan` | which readings go with which, every pair | `air_scan` | `metric` (or all), `start`, `end`, `chart` | -| `chart` | any readings from both sensors on one chart, a panel each or on shared axes | `plot_chart` | `panels[{metric, style}]`, `start`, `end`, `two_axes`, `same_axis`, `invert_second_axis`, `source` | +| `days` | find, rank and count days; a figure per month or year; holidays and weekends | `weather_days`, `air_days` | today's day-tool arguments over one field list (the last 30 days to yesterday) | +| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric` (`pressure.relative`, `outdoor.humidity`, `wind.wind_speed`, `air.pm2_5`, `air.pm10`), `start`, `end` (90 days; 60 for air), `chart` | +| `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `start`, `end` (90 days, at most 400), `chart` | +| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `start`, `end` (30 days), `layout`, `invert_second_axis`, `source` | | `forecast` | today and the days ahead | `weather_forecast` | `days` | | `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | -What each hidden `Turn` input becomes: +**`summary`'s figures and charts** are two inputs, as they are today (`groups` and `chart_field(s)`): +- `metrics` is what to summarise; `chart_metrics` is what to draw, defaulting to the first of `metrics` (temperature when it is there). +- `layout` (shared with `chart`): `auto` draws one panel of `chart_metrics[0]` with a line for each sensor that has it, plus a second + chart of wind with the compass rose when `wind.wind_direction` is summarised and nothing is stacked; `panels` stacks every + `chart_metrics` reading, a panel each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of one + unit over each other. `invert_second_axis` modifies `two_axes`. +- `chart` defaults to on for periods of 3 days or more, as now; `daily_means` draws one point a day (the words asked for an average); + `average` adds means to the figures; `every_day` lists every day of a period up to 31 days (whether the breakdown is by day or by month + still follows the period's length); `rain_by` (`auto`, `month`, `year`) sets the rain bars. +- A chart mixing station and air readings is `chart`'s, not `summary`'s: `summary` answers it with an error that says so. + +**`summary`'s result** is one shape for both sensors: +`{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, +"air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, +then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and +`monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever +`rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", +[emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. + +**`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question +shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each +sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; `note_hourly`, +`note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am +to 10am, not the air sensor's midnight to midnight) and says how many. + +**Charts in a result:** `charts: [{uri, title}]` with one `chart_hint`, and a `resource_link` per chart (3.6). The bot draws them in +order (up to three a question); a drawn-ahead or alert chart still expects exactly one. + +**What each hidden `Turn` input becomes:** | Today (`Turn`) | Over MCP | |---|---| -| `chart_field`, `chart_fields`, `readings` (which readings the words name) | `summary.metrics`, in order; `layout` for how they share the chart | -| `two_axes` | `layout: "two_axes"` (`chart.two_axes`) | -| `average_asked` | `average` | -| `per_day` | `breakdown: "day"` | +| `chart_field`, `chart_fields` | `summary.chart_metrics`, `layout: "panels"` | +| `readings` (which readings the words name) | `summary.metrics` | +| `two_axes` | `layout: "two_axes"` | +| `average_asked` | `daily_means` (and `average`) | +| `per_day` | `every_day` | | `chart_asked` | `chart` | -| `text` (rain bars by month; `only` holidays; grouping) | `rain_by`; `days.only` and `days.group_by`, which the bot drops or fills from the words before it forwards the call (3.8) | +| `text` (rain by month; `only` holidays; grouping) | `rain_by`; `days.only` and `days.group_by`, which the bot drops or fills from the words (3.8) | | `air_named` (the air reading charted when none is named) | `metrics`, filled by the bot from the conversation | -| `ahead` (a chart drawn ahead, nobody waiting) | the request's `_meta.priority: "background"` | -| `charts` (written) | a `chart` link in the result (3.6) | -| `times["data"]` (written) | the result's `_meta.timing` | -| `forecast_shown` (written) | `forecast`'s structured `days`, which the bot remembers | -| `air_extra_used` (written) | known from the arguments (`metrics` names `air.air_temperature`) | -| `Tool.asked` (per-question schema) | the service lists everything; the bot leaves the air sensor's own temperature and humidity out of what it offers the model unless the words name them (3.8) | -| `CHART_SOURCE` | `source` on the chart tools, written into the chart; the service sets it for every call, so alert charts get theirs too | +| `ahead` | request `_meta.priority: "background"` | +| `charts`, `times`, written | `charts` links in the result; result `_meta.timing` | +| `forecast_shown`, written | `forecast`'s result has the days shown (`days: [{date, …}]`), which the bot records | +| `air_extra_used`, written | known from the arguments (`air.air_temperature` among the metrics) | +| `Tool.asked` | the service lists every metric; the bot leaves the air sensor's own temperature and humidity out unless the words name them (3.8) | +| `CHART_SOURCE` | `source` on the chart tools, written into the chart; the service sets it on every call, so alert charts get theirs too | + +The bot keeps its own reading of the words on its `Turn` (`chart_field(s)`, `average_asked`) for its captions and for holding back the +streamed draft under a chart; only the tools stop reading it. -The old names stay as aliases on the service for one release (each mapped to its new tool and arguments), so the bot and the evals can -move over in their own step (section 5). +### 3.4 Resources -### 3.4 Resources (bot-facing) +Raw data keeps the device's own field names (`rainfall.daily`, the running total with its midnight reset; `rainfall.rain_rate`), which +the alerts' rain helpers and the Rain gauge work on; the `sensor.reading` names are the tools'. Dates arrive as ISO strings and the +client turns them back into `date`s (the day figures' keys, the forecast's and pollen's days), as `specs.from_json` does for charts. -| URI | Holds | Subscribe | Read by | +| URI | Holds | Pushed | Read by | |---|---|---|---| -| `ecobot://station` | name, time zone, latitude and longitude, created, the sensors and their metrics, what each source is (HA, cloud, local), retention, `air_link` (the AirGradient dashboard), alert kinds the data supports, the service's start-up lines | on change (rare) | the bot at connect: time zone, capabilities, `/usage`, menus | -| `ecobot://now/weather` | the live reading, raw: `{time, group: {field: {value, unit}}}`, and the glance emoji | each new reading (5 s with HA, 60 s cloud only) | gauges, report, the rain alert | -| `ecobot://now/air` | the latest air reading, its time, `sustained` (the minimum over `ANTISPIKE_REQUIRE_CONSECUTIVE`), ratings and AQI | each new reading | the particulates alert, report | -| `ecobot://rows/weather/{resolution}{?start,end,groups}` | rows `{ts, "group.field": value, …_low, …_high}` (1min, 5min, 30min), fetching what the file lacks | `…/5min` when a 5-minute row settles | the weather alerts (3 hours, a rain spell back, 7 days at 30 minutes), irrigation (24 hours) | -| `ecobot://days/{weather,air}{?start,end,fields}` | day figures `{field: {date: value}}` | no | gauges (the year so far) | -| `ecobot://forecast` | the forecast days, raw, with `fetched_at` and `place` | on each new forecast | the forecast alert, irrigation, report | -| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | on each new page | the pollen alert, report | -| `ecobot://chart/{id}` | a chart's data (3.6), kept 15 minutes | no | the bot, after a tool returned a link to it | -| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | the bot's log line at connect; troubleshooting | +| `ecobot://station` | name, time zone, latitude and longitude, created; the configured sources and each one's prompt line (`describe()`); each source's mode (HA, cloud, local); the sensors and their metrics; retention; `air_link`; the service's start-up lines. Served once the station has named its zone. | on change | the bot at connect: zone, `by_name`, prompt, menus, `/usage` | +| `ecobot://now/weather` | the live reading: `{time, group: {field: {value, unit, time}}}` (each field keeps its own time), and the glance emoji | each new reading (5 s with HA, 60 s cloud only) | the rain alert, the gauges | +| `ecobot://now/air` | the latest air reading, its time, `sustained` (the minimum over `ANTISPIKE_REQUIRE_CONSECUTIVE` readings), ratings and AQI | each new reading | the particulates alert (on its timer) | +| `ecobot://rows/weather/{resolution}{?start,end,groups}` | rows `{ts, "group.field": value, …_low, …_high}` at 1min, 5min or 30min, fetching what the file lacks; a bare read is the last 3 hours | `…/5min` whenever a 5-minute row is written or replaced, provisional ones included | the weather alerts (3 hours; back to a rain spell's start; 7 days at 30 minutes at start), irrigation (24 hours) | +| `ecobot://days/{sensor}{?start,end,fields}` | `sensor` is `weather` or `air`: day figures `{field: {date: value}}`; a bare read is the year so far | no | the gauges | +| `ecobot://forecast` | the forecast days, raw, with `fetched_at` and `place` | each new forecast | the forecast alert, irrigation | +| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | the pollen alert | +| `ecobot://chart/{id}` | a chart's data (3.6), kept 15 minutes | no | the bot, after a tool linked it | +| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | the bot's log at connect; troubleshooting | + +The bot always reads `rows` and `days` with an explicit `start` and `end`; subscriptions are on the bare URIs only. ### 3.5 Pushing new readings -The MCP SDK (2.3, the 2026-07-28 protocol) delivers resource changes on a `subscriptions/listen` stream: each event says "this URI -changed, read it again", with no replay. So: -- The service publishes `ecobot://now/weather` after each new live reading, `ecobot://now/air` after each new air reading, - `ecobot://rows/weather/5min` when a 5-minute row settles, and `ecobot://forecast`, `ecobot://pollen` and `ecobot://station` when they - change. Repeats of an unchanged reading are not sent. -- The bot listens on one stream and, for each event, reads the resource and runs what used to hang off the hook: `check_rain` on a new - live reading, `WeatherMonitor.check` on a new 5-minute row, the forecast and pollen alerts on a new snapshot. -- The alerts also keep their own timers, reading the resource each time: the weather alerts' calm periods and quiet hours, the 7:30am - pollen start and the 30-minute particulates check depend on the clock, not only on new data. A push makes them prompt; the timer - makes them sure. -- When the stream drops (service restart, network), the bot reconnects with backoff, listens again and reads every resource it depends - on: the alerts compare against the state they keep, so a missed event costs latency, never an alert. -- The service polls the live reading itself in every mode (today, with the cloud only, the bot's minute alert check drove that fetch). +The MCP SDK (2.3, protocol revision 2026-07-28) delivers changes on a `subscriptions/listen` stream: each event says "this URI changed, +read it again", with no replay. List changes travel on the same stream, when asked for. +- **The service** passes an `InMemorySubscriptionBus` to the server and its loops publish to it: `ResourceUpdated(ecobot://now/weather)` + after each new live reading, `…/now/air` after each new air reading, `…/rows/weather/5min` after each 5-minute row written, + `…/forecast`, `…/pollen` and `…/station` when they change, and `ToolsListChanged` when a sensor sends a field it never sent (the + metric lists grow). Repeats of an unchanged reading are not sent. It polls the live reading itself in every mode (today, with the + cloud only, the bot's minute alert check drove that fetch). +- **The bot** listens once, for those URIs and for tool list changes, and runs what used to hang off the hooks: `check_rain` on a new + live reading, `WeatherMonitor.check` on a new 5-minute row, the forecast and pollen alerts on a new page, a new tool list on a list + change. +- **The alerts keep their clocks**, reading the resource each time: the weather alerts every 60 seconds (as after each refresh today: + calm periods, quiet hours), the pollen alert's 7:30am start, and the particulates alert every 30 minutes and only then (its two-readings + rule counts readings across checks; a check per reading would confirm a mask alert within minutes). A push makes an alert prompt; the + clock makes it sure. +- **After a gap** (3.7) the bot listens again and reads every resource it depends on: the alerts compare against the state they keep, so + a missed event costs latency, never an alert. + +Only clients on the 2026-07-28 revision can listen; older ones can still call the tools and read the resources, and poll. ### 3.6 Charts -Tools that draw (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`, and the period buttons through them) build the -`specs.Chart` as now, next to the reads that chose its resolution, its buckets and its rose. The spec is plain data (strings, epochs, -floats, lists; `period` as two dates), so: -- `specs.to_json(chart)` and `specs.from_json(data)` with a `version`; `from_json` runs the same validation as building one does. - Tuples come back as lists, which the renderer already accepts. Non-finite numbers are dropped when the spec is built. -- The tool keeps the chart in `ecobot://chart/{id}` and returns a link to it (`resource_link` content, plus `chart: {uri, hint}` in its - JSON). The model sees a line, not 100 KB of points; the bot reads the link, rebuilds the spec and draws it. Another MCP client can read - the JSON and plot it however it likes. -- The rain caption reads the chart's bars from the rebuilt spec, as it does now. `newest` (what the alerts' cache keys on) and - `caption()` work on the rebuilt spec unchanged. -- The bot never asks for a stored spec again: a period button is a new `summary` call with new dates, as today; only pictures are - cached (`periods.ImageCache`). +The tools that draw (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`, and the period buttons through them) build `specs.Chart` +as now, next to the reads that chose its resolution, its buckets and its rose. A spec is plain data (strings, epochs, floats, lists; +`period` as two dates), so: +- `specs.to_json(chart)` and `specs.from_json(data)`, with a `version`; `from_json` runs the same checks as building one. Tuples come back + as lists, which the renderer already takes. Non-finite numbers are dropped when the spec is built. +- The tool keeps each chart at `ecobot://chart/{id}` and links it (3.3): the model reads a title, not 100 KB of points. The bot reads + each link as the tool's result arrives (so the draft is held back under a chart, as now), rebuilds the spec and draws it. Another + client can plot the JSON as it likes. +- The rain caption reads the rebuilt chart's bars; `newest` (what the alerts' picture cache keys on) and `caption()` work on it unchanged. +- A period button is a new `summary` call with new dates, as today; only pictures are cached (`periods.ImageCache`). ### 3.7 Separate hosts -- **Transport:** MCP Streamable HTTP, served by the SDK's Starlette app under uvicorn, behind TLS (a reverse proxy such as Caddy, or - uvicorn's own certificate). One endpoint, `https:///mcp`. -- **Auth:** a bearer token checked by the SDK's `TokenVerifier` against `MCP_TOKEN`; the bot sends it from its own `MCP_TOKEN`. - Other clients get their own token (`MCP_TOKENS=name:token,…`), so one can be revoked alone. Bind to the LAN or a tailnet; nothing - needs the internet to reach it. -- **Time:** both hosts keep NTP time. The bot takes the station's time zone from `ecobot://station` before it schedules anything, as it - takes it from the station today; the dates it builds ("the last 5 hours") are local strings in that zone. -- **When the service is down:** the bot still starts and answers ("the weather station isn't reachable right now"), keeps retrying, and - starts its alerts once it has the station's zone. Calls time out within the question's budget (`TURN_SECONDS`). +- **Server:** the SDK's low-level `Server`, so each tool's input schema is the hand-written JSON the tools have today (with their + descriptions); the list is built when asked, so it follows the file's metrics. Served as Streamable HTTP (`streamable_http_app`) under + uvicorn, behind TLS (a reverse proxy such as Caddy, or uvicorn's own certificate), at `https:///mcp`. The app is built with + `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by default it only answers `Host: 127.0.0.1` or `localhost`, and refuses + the name a proxy or a LAN client uses. +- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` + (`name:token,…`, one per client, so one can be revoked alone), with `AuthSettings(resource_server_url=None)` so no OAuth metadata is + published. The bot sends its token in the HTTP client's headers (`create_mcp_http_client(headers={"Authorization": …})`); a bare URL + sends none. Bind to the LAN or a tailnet; nothing needs the internet to reach it. +- **The bot's connection:** `Client(…, mode="2026-07-28")`, pinning the protocol revision as well as the SDK version (the default mode + probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). One supervisor task enters the + client and runs the listen loop; questions, alerts and drawing ahead call it from their own tasks. In the SDK a connection failure on + any request ends the whole client, so: a call that fails with "connection closed" or times out is answered as unreachable; the + supervisor discards the client when it exits with a transport error, when the listen is lost, or when the listen ends, then builds a + new one after a backoff, listens again and reads what it depends on. Nothing is sent on a dead client. The HTTP read timeout is about + 45 seconds (three of the server's 15-second pings), so a silently dead link is noticed. +- **Time:** both hosts keep NTP time. The bot takes the station's zone from `ecobot://station` and remembers it in `bot_state.json`; + until it has one (a first start with the service down), it uses its own `TZ`. When the zone arrives or changes, the bot replaces its + zone, configures the charts again and tells the irrigation check. The dates it builds ("the last 5 hours") are local strings in that + zone. +- **When the service is down:** the bot starts and answers ("the weather station isn't reachable right now"), within the question's + budget (`TURN_SECONDS`). The irrigation watchdog and the valve buttons start at once whatever the service's state (a restart mid-run + must still close the valve); the irrigation check runs on the forecast it last had and skips the measured rain. - **When the bot is down:** nothing is lost; the service keeps archiving. ### 3.8 The bot's side of a tool call -The bot is the MCP client, so it can shape what it offers and what it forwards: -- **What it offers:** the service's `tools/list`, as it is, except the air sensor's own temperature and humidity left out of the metric - lists unless the words name them (the prompt cache holds: the list only changes with the words, as now). On `tools/list_changed` - (a sensor sent a new field) it reads the list again. -- **What it forwards:** each call the model makes, with the corrections the words call for, the ones the tools make from `Turn` today: - `chart: true` when the words ask for a chart; `days.only` dropped unless the words say holidays or weekends; `days.group_by` from - "per month"; the air reading the conversation was about when the model named none. These live in one function, `lib/arguments.py`, - with the tests of what each phrase does. -- **Shortcuts** build the new tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way. -- **Poke** goes: a tool call is itself the service's cue to refresh what it touches. +The bot is the MCP client, so it shapes what it offers and what it forwards, in `lib/arguments.py`, with the tests of what each phrase +does: +- **What it offers:** the service's tool list, except the air sensor's own temperature and humidity left out of the metric lists unless + the words name them (the list only changes with the words, so the prompt cache holds, as now); a new list when the service says so. +- **What it forwards:** each call the model makes, with the corrections the tools make from `Turn` today: `chart: true` when the words + ask for a chart, `daily_means` when they ask for an average, `chart_metrics` from the readings they name, `days.only` dropped unless + they say holidays or weekends, `days.group_by` from "per month", `rain_by` from "by month", the air reading the conversation was about + when the model named none. +- **Shortcuts** build the tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way; the + report sends `_meta.fetch: false` as `cached` does now. +- **The early cue:** today the bot pokes the sources the words concern as soon as a question arrives, so they refresh while the model + thinks (a forecast question refreshes only that way). The bot sends the same cue at receipt as a request to the service's `warm` tool + (`sources`), marked for applications (`_meta` `audience: "app"`), which the bot never offers the model. The sources lose `wants()`. ### 3.9 Configuration | Service | Bot | |---|---| -| `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*` (including `AIRGRADIENT_DASHBOARD`), `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the station names one), `DATA_DIR`, `MCP_TOKEN(S)`, `MCP_BIND` | `TELEGRAM_*`, `OPENROUTER_*`, `ADMIN_*`, `DARKMODE`, `CHART_ALL_*`, the alert settings, `IRRIGATION_*` / Tuya, `MCP_URL`, `MCP_TOKEN`, `DATA_DIR` (the bot's state file and picture cache only) | +| `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*` (including `AIRGRADIENT_DASHBOARD`), `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the station names one), `DATA_DIR`, `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS` | `TELEGRAM_*`, `OPENROUTER_*`, `ADMIN_*`, `DARKMODE`, `CHART_ALL_*`, the alert settings, `IRRIGATION_*` / Tuya, `MCP_URL`, `MCP_TOKEN`, `TZ` (until the station's zone is known), `DATA_DIR` (the bot's state and picture cache only) | -The bot's `bot_state.json` (chats, subscriptions, alert state, chart questions) stays with the bot; the readings file and the -snapshots go with the service. +`bot_state.json` (chats, subscriptions, alert state, chart questions, the station's last zone) stays with the bot; the readings file +and the snapshots go with the service. ## 4. What does not change The readings file, its tables and its day rows; how each tool chooses its resolution and fetches what it lacks; the alert rules and -their state; the charts' look; the shortcuts' choices; Telegram. The split moves where code runs and makes its inputs explicit. +their state; the charts' look; the shortcuts' choices; Telegram. ## 5. Steps -Each step ships on its own, with the tests and evals green, and the bot working the whole way. - -1. **Explicit arguments.** The tools take the `Turn`'s inputs as arguments (3.3), and the bot fills them (`lib/arguments.py`). Tools - return their charts (as specs, in the result) instead of appending to `turn.charts`; `forecast` returns its days. Still one process. - The evals check the new arguments; `Turn` loses every field the tools read. -2. **Chart JSON.** `specs.to_json` and `from_json`, and a round-trip test over every chart the samples and `scripts/dump_specs.py` draw: - the rebuilt spec draws the same picture (the golden images). -3. **The data interface, in process.** A `Data` protocol with the tools and the resources of section 3, and an in-process - implementation over today's sources. The bot's direct reads move to it: the gauges (with `sheet()` moved to the bot), the report, the - alerts (resources and timers in place of `Warmer.after` and `on_live`), irrigation, alert charts. Nothing in the bot holds a source - object after this step. -4. **The MCP server and client.** `lib/mcp_server.py` serves the `Data` implementation; `lib/mcp_client.py` implements `Data` over MCP, - with reconnects and the listen stream. The tests run the bot against the server through the SDK's in-memory transport; the contract - test (`test_contract`) checks the tool schemas and result shapes on the wire. The evals read a checked-in `tools/list` - (`tests/evals/tools.json`), which a test keeps equal to the server's. -5. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import - boundary test. Config split. One compose file per host, TLS and tokens. The service's scripts (`edit_readings`, `cache_status`, - `refill_airgradient`, `check_rain`, `bench_storage`) run on the service's host; `show_request` and `report_inputs` become MCP clients; +Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new +names together. + +1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments, filled by `lib/arguments.py`; they + return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it shows. The pure + helpers the bot imports from data packages move to `lib/common` (3.1). Still one process; the evals check the new arguments. +2. **Chart JSON.** `specs.to_json` and `from_json`, and a round trip over every chart the samples and `scripts/dump_specs.py` draw: the + rebuilt spec draws the same picture (the golden images). +3. **The nine tools, in process.** The tools of 3.3 with their result shapes; the prompt, the shortcuts, `lib/report.py` (`report`, + `weather_now`, `lookup`, `chart_caption`), the alert charts and the evals move to them together; the twelve go. Shipped only when the + live evals (`--live`, all cases) do as well as before. +4. **The data interface, in process.** A `Data` protocol with the tools and resources of section 3, and an in-process implementation + over today's sources. The bot's direct reads move to it: the gauges (`sheet()` moves to the bot), the alerts (resources, clocks and an + in-process stand-in for the listen stream in place of `Warmer.after` and `on_live`), irrigation, the prompt's lines and `by_name` + (from the station resource). Nothing in the bot holds a source object after this step. +5. **The MCP server and client.** `lib/mcp_server.py` serves `Data` (the bus, the low-level server, the transport settings, the token + check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, chart links). The evals read a checked-in tool + list (`tests/evals/tools.json`), which a test keeps equal to the server's. +6. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import + boundary test, both ways. Config split. One compose file per host, TLS and tokens. Scripts go where they work: on the service's host + `edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`; on the bot's + `eval_prompts` (reading `tests/evals/tools.json`) and `update_charts`; `show_request` and `report_inputs` become MCP clients; `dump_specs` writes JSON on the service and draws on the bot. -6. **The new names.** The prompt, the shortcuts and the evals use the nine tools; the old names go from the service one release later. ## 6. Testing - The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, - report, alerts, drawing, the client). The bot's tests run against a fake `Data`, or the real server in memory over an archived file. -- A wire test for each tool and resource: the arguments it accepts, the shape it returns, a chart link that reads back as a spec. -- A reconnect test: the stream drops, the bot listens again and reads what it depends on; an alert due during the gap is sent once. -- The live evals (`--live`) run against the service's real tool list. + arguments, report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an + archived file. +- A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, a + chart link that reads back as a spec. +- A reconnect test against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't + fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the bot listens again and reads what it + depends on; a question asked while the service is down is answered as unreachable, and the next one after it is back is answered; an + alert due during the gap is sent once. +- A deploy check: a tool call through the proxy's name succeeds (the allowed hosts and the token). +- The live evals run against the service's real tool list. ## 7. Risks - **Latency.** Each call is a network round trip: tens of milliseconds on a LAN, against a question budget of seconds. Charts drawn - ahead are a few calls every 5 minutes. -- **The model and the new names.** Renamed tools and arguments can change what the model picks; step 6 is gated on the live evals, and - the aliases make it reversible. -- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision; the client is pinned to the SDK version the server - runs, and both upgrade together. + ahead are a few calls every 5 minutes. The early cue keeps the head start the poke gives today. +- **The model and the new tools.** New names, arguments and shapes can change what the model picks: step 3 ships only on the live + evals, in one process, before any network is involved. +- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision: the bot pins it, and both programs upgrade the SDK + together. - **Two things to run.** More to deploy and watch; `ecobot://health` and the bot's "unreachable" answers make a failure visible. From 4e067bf0445450a685c1bd33145081bbd288433c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:42:37 +0000 Subject: [PATCH 003/125] docs/service-split.md: the model's calls go through as they are; charts ride in the result's _meta - No rewriting of the model's arguments from the question's words. Today's regex corrections (three of which overrule the model) were patches for a cheap model's mistakes, partly caused by hidden inputs; with every choice an explicit argument the model makes it. Step 1 keeps them, moved into the bot, so it changes no answer; step 3 drops them on the live evals, and any that's still needed comes back as a fill, never an override. lib/arguments.py goes; captions follow the call that drew the chart. - Charts come back in the tool result's _meta (ecobot/charts), which clients keep for the application, not via a stored ecobot://chart/{id} link: one round trip, nothing stored. Sent only when the client asks (request _meta ecobot/charts: true); the model gets only the chart_hint line, and a client that doesn't draw gets neither. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 90 +++++++++++++++++++++++++------------------ 1 file changed, 53 insertions(+), 37 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index c8e97542..1fd8656d 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -67,7 +67,7 @@ live reading the poll keeps, and the station's group list (which the archive tri | Service (`ecobot_service.py`, host A, near Home Assistant) | Bot (`ecobot.py`, host B) | |---|---| -| `lib/storage`, `lib/ecowitt` (less `dashboard.sheet`), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`'s `Warmer`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/sources.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/arguments.py` (3.8), `lib/report.py`, `lib/report_menu.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/topicmemory.py`, `lib/entities.py`, `lib/admins.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py` with `sheet()`, `GAUGES` and `STATUS`, `lib/alerts`, `lib/irrigation` | +| `lib/storage`, `lib/ecowitt` (less `dashboard.sheet`), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`'s `Warmer`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/sources.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, `lib/report_menu.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/topicmemory.py`, `lib/entities.py`, `lib/admins.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py` with `sheet()`, `GAUGES` and `STATUS`, `lib/alerts`, `lib/irrigation` | | builds chart data (`specs.Chart`) next to the reads that choose its resolution | draws it (Pillow, fonts, dark mode) | | `lib/mcp_server.py`: the tools and resources below | `lib/mcp_client.py`: the connection (3.7) | | `lib/config.py`'s service fields (3.9) | `lib/config.py`'s bot fields | @@ -75,7 +75,7 @@ live reading the poll keeps, and the station's group list (which the archive tri **Shared** (`lib/common/`, imported by both, importing neither side): `specs.py` (with JSON in and out, 3.6), `series.py`, `timeutil.py`, `captions.py` (hint texts), `tools.py`'s `json_result`, `logs.py`, `netenv.py`, `warm.py`'s `every` and `safely`, and the pure helpers the bot uses today from data packages: the thresholds (`GUST_ALERT_KMH`, `UVI_ALERT`, `TEMP_CHANGE_C`), `glance` (`solar_band`), -`unit_text`, `POINT_BUDGET`, the air metrics' labels and units, `grouping_in`, `HOLIDAY_WORDS`, the rain helpers (`wet_flags`, +`unit_text`, `POINT_BUDGET`, the air metrics' labels and units, `grouping_in`, the rain helpers (`wet_flags`, `rain_amount`, `duration`), the forecast's `describe_day` and `day_label`, and the pollen `LEVELS` and `LEVEL_EMOJI`. One repository and one image, two commands. A test reads every module's imports and fails if a bot module reaches a service package or @@ -103,9 +103,12 @@ Conventions for the tools: - **Results** are JSON: figures with their wording (`low_when`, ratings, emoji), notes to pass on (`note_*`, `missing`, `warning`), and `error` with how to correct the call. Every tool is read-only to the caller (`readOnlyHint`); those that fetch what the file lacks before answering say so (`openWorldHint`). -- **Request `_meta`**, for applications, never offered to the model: `priority: "background"` (a chart drawn ahead: its fetches wait - their turn; today's `turn.ahead`) and `fetch: false` (answer from what is held, never wait on the network; today's `cached`). - Result `_meta.timing` carries the seconds spent (today's `turn.times["data"]`). +- **Request `_meta`**, set by the application, never by the model: `ecobot/charts: true` (this client draws: send chart data, 3.6), + `priority: "background"` (a chart drawn ahead: its fetches wait their turn; today's `turn.ahead`) and `fetch: false` (answer from + what is held, never wait on the network; today's `cached`). **Result `_meta`**, for the application, which clients don't hand to the + model: `ecobot/charts` (the chart data) and `timing` (the seconds spent; today's `turn.times["data"]`). +- **Arguments are the model's.** Every choice a tool makes is an argument the model sets (or a shortcut sets, 3.8); the bot forwards the + model's calls as they are. The tools read nothing else about the question. ### 3.3 Tools @@ -137,7 +140,7 @@ Nine tools in place of twelve, one per kind of question, each over both sensors **`summary`'s result** is one shape for both sensors: `{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, -then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and +then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. @@ -148,30 +151,36 @@ sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from `note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am to 10am, not the air sensor's midnight to midnight) and says how many. -**Charts in a result:** `charts: [{uri, title}]` with one `chart_hint`, and a `resource_link` per chart (3.6). The bot draws them in -order (up to three a question); a drawn-ahead or alert chart still expects exactly one. +**Charts in a result** (3.6): for a client that asked for them, the chart data in the result's `_meta` (`ecobot/charts`, a list: a +history can add a wind rose beside its chart) and one line for the model, `chart_hint`: that a chart goes with its reply, so the reply +is its caption (today's `CHART_HINT`). The bot draws them in order (up to three a question); a drawn-ahead or alert chart still expects +exactly one. -**What each hidden `Turn` input becomes:** +**What each hidden `Turn` input becomes.** Today the bot reads the question with regexes and the tools use that reading beside the +model's arguments: some fill an argument the model left out, three overrule the model (the reading charted, the readings stacked, a +holiday filter). Each was added for a mistake the production model made (the eval cases `humidity-chart`, `temperature-and-rain`, +`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input or an easily missed +argument. Over MCP each becomes an argument with a plain name, and the model sets it: | Today (`Turn`) | Over MCP | |---|---| -| `chart_field`, `chart_fields` | `summary.chart_metrics`, `layout: "panels"` | +| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_metrics`, `layout: "panels"` | | `readings` (which readings the words name) | `summary.metrics` | | `two_axes` | `layout: "two_axes"` | -| `average_asked` | `daily_means` (and `average`) | +| `average_asked` (daily means on the chart; the model can't ask for that today) | `daily_means` | | `per_day` | `every_day` | | `chart_asked` | `chart` | -| `text` (rain by month; `only` holidays; grouping) | `rain_by`; `days.only` and `days.group_by`, which the bot drops or fills from the words (3.8) | -| `air_named` (the air reading charted when none is named) | `metrics`, filled by the bot from the conversation | +| `text`: rain by month, grouping (fill), holidays (overrule) | `rain_by`, `days.group_by`, `days.only` | +| `air_named` (the air reading charted when none is named) | `metrics` (the conversation is in the model's context) | | `ahead` | request `_meta.priority: "background"` | -| `charts`, `times`, written | `charts` links in the result; result `_meta.timing` | +| `charts`, `times`, written | result `_meta`: `ecobot/charts`, `timing` | | `forecast_shown`, written | `forecast`'s result has the days shown (`days: [{date, …}]`), which the bot records | | `air_extra_used`, written | known from the arguments (`air.air_temperature` among the metrics) | | `Tool.asked` | the service lists every metric; the bot leaves the air sensor's own temperature and humidity out unless the words name them (3.8) | | `CHART_SOURCE` | `source` on the chart tools, written into the chart; the service sets it on every call, so alert charts get theirs too | -The bot keeps its own reading of the words on its `Turn` (`chart_field(s)`, `average_asked`) for its captions and for holding back the -streamed draft under a chart; only the tools stop reading it. +The bot's chart captions follow the arguments of the call that drew the chart (its `chart_metrics`, `daily_means`), so a caption +always matches its chart; the streamed draft is held back once a result brings chart data. ### 3.4 Resources @@ -188,7 +197,6 @@ client turns them back into `date`s (the day figures' keys, the forecast's and p | `ecobot://days/{sensor}{?start,end,fields}` | `sensor` is `weather` or `air`: day figures `{field: {date: value}}`; a bare read is the year so far | no | the gauges | | `ecobot://forecast` | the forecast days, raw, with `fetched_at` and `place` | each new forecast | the forecast alert, irrigation | | `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | the pollen alert | -| `ecobot://chart/{id}` | a chart's data (3.6), kept 15 minutes | no | the bot, after a tool linked it | | `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | the bot's log at connect; troubleshooting | The bot always reads `rows` and `days` with an explicit `start` and `end`; subscriptions are on the bare URIs only. @@ -221,9 +229,13 @@ as now, next to the reads that chose its resolution, its buckets and its rose. A `period` as two dates), so: - `specs.to_json(chart)` and `specs.from_json(data)`, with a `version`; `from_json` runs the same checks as building one. Tuples come back as lists, which the renderer already takes. Non-finite numbers are dropped when the spec is built. -- The tool keeps each chart at `ecobot://chart/{id}` and links it (3.3): the model reads a title, not 100 KB of points. The bot reads - each link as the tool's result arrives (so the draft is held back under a chart, as now), rebuilds the spec and draws it. Another - client can plot the JSON as it likes. +- The charts travel in the tool's own result, in its `_meta` (`ecobot/charts`), which MCP clients keep for the application and don't + hand to the model: one round trip, nothing stored on the service. The model gets only `chart_hint`, the line that tells it a chart + goes with its reply so the reply is the chart's caption: keep it short, don't describe the chart (today's `CHART_HINT`). Without that + line a model writes a long answer, or describes or apologises for a chart it doesn't know is there. +- Charts are sent only to a client that asks (request `_meta` `ecobot/charts: true`, which the bot always sends). For any other client + the tool builds no chart and adds no `chart_hint`, so its model is never told of a chart that won't appear. +- The bot rebuilds each spec as the result arrives (so the streamed draft is held back under a chart, as now) and draws it. - The rain caption reads the rebuilt chart's bars; `newest` (what the alerts' picture cache keys on) and `caption()` work on it unchanged. - A period button is a new `summary` call with new dates, as today; only pictures are cached (`periods.ImageCache`). @@ -256,14 +268,14 @@ as now, next to the reads that chose its resolution, its buckets and its rose. A ### 3.8 The bot's side of a tool call -The bot is the MCP client, so it shapes what it offers and what it forwards, in `lib/arguments.py`, with the tests of what each phrase -does: - **What it offers:** the service's tool list, except the air sensor's own temperature and humidity left out of the metric lists unless the words name them (the list only changes with the words, so the prompt cache holds, as now); a new list when the service says so. -- **What it forwards:** each call the model makes, with the corrections the tools make from `Turn` today: `chart: true` when the words - ask for a chart, `daily_means` when they ask for an average, `chart_metrics` from the readings they name, `days.only` dropped unless - they say holidays or weekends, `days.group_by` from "per month", `rain_by` from "by month", the air reading the conversation was about - when the model named none. + This narrows what the model can pick from; it never changes what the model picked. +- **What it forwards:** each call the model makes, as it is. The corrections the tools make from the words today are not carried over: + with every choice an explicit argument, the model gets a fair chance to make it, and the regexes overruled it even when it was right, + misfired on wording nobody foresaw ("miles per hour"), and would leave other MCP clients with different answers from the same service. + The live evals decide (step 3): the cases each correction was added for are run against the nine tools, and a correction comes back + only for one that still fails, in the bot, filling an argument the model left out, never overruling one it set, each with its case. - **Shortcuts** build the tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way; the report sends `_meta.fetch: false` as `cached` does now. - **The early cue:** today the bot pokes the sources the words concern as soon as a question arrives, so they refresh while the model @@ -289,20 +301,23 @@ their state; the charts' look; the shortcuts' choices; Telegram. Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new names together. -1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments, filled by `lib/arguments.py`; they - return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it shows. The pure - helpers the bot imports from data packages move to `lib/common` (3.1). Still one process; the evals check the new arguments. +1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the + question; they return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it + shows. So that this step changes no answer, today's corrections from the words move out of the tools into the bot, which applies them + to the model's calls on the way in, as before; step 3 removes them. The pure helpers the bot imports from data packages move to + `lib/common` (3.1). Still one process; the evals check the new arguments. 2. **Chart JSON.** `specs.to_json` and `from_json`, and a round trip over every chart the samples and `scripts/dump_specs.py` draw: the rebuilt spec draws the same picture (the golden images). 3. **The nine tools, in process.** The tools of 3.3 with their result shapes; the prompt, the shortcuts, `lib/report.py` (`report`, - `weather_now`, `lookup`, `chart_caption`), the alert charts and the evals move to them together; the twelve go. Shipped only when the - live evals (`--live`, all cases) do as well as before. + `weather_now`, `lookup`, `chart_caption`), the alert charts and the evals move to them together; the twelve go. The bot's corrections + from the words go too (3.8), and come back only for a case that then fails. Shipped only when the live evals (`--live`, all cases) + do as well as before. 4. **The data interface, in process.** A `Data` protocol with the tools and resources of section 3, and an in-process implementation over today's sources. The bot's direct reads move to it: the gauges (`sheet()` moves to the bot), the alerts (resources, clocks and an in-process stand-in for the listen stream in place of `Warmer.after` and `on_live`), irrigation, the prompt's lines and `by_name` (from the station resource). Nothing in the bot holds a source object after this step. 5. **The MCP server and client.** `lib/mcp_server.py` serves `Data` (the bus, the low-level server, the transport settings, the token - check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, chart links). The evals read a checked-in tool + check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, charts from the result's `_meta`). The evals read a checked-in tool list (`tests/evals/tools.json`), which a test keeps equal to the server's. 6. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import boundary test, both ways. Config split. One compose file per host, TLS and tokens. Scripts go where they work: on the service's host @@ -313,10 +328,10 @@ names together. ## 6. Testing - The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, - arguments, report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an + report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an archived file. -- A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, a - chart link that reads back as a spec. +- A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, chart + data in the result's `_meta` that reads back as a spec for a client that asks, and no chart and no `chart_hint` for one that doesn't. - A reconnect test against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the bot listens again and reads what it depends on; a question asked while the service is down is answered as unreachable, and the next one after it is back is answered; an @@ -328,8 +343,9 @@ names together. - **Latency.** Each call is a network round trip: tens of milliseconds on a LAN, against a question budget of seconds. Charts drawn ahead are a few calls every 5 minutes. The early cue keeps the head start the poke gives today. -- **The model and the new tools.** New names, arguments and shapes can change what the model picks: step 3 ships only on the live - evals, in one process, before any network is involved. +- **The model and the new tools.** New names, arguments and shapes can change what the model picks, and without the corrections from + the words it must make every choice itself: step 3 ships only on the live evals, in one process, before any network is involved; a + correction that turns out to be needed comes back as a fill, never an override. - **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision: the bot pins it, and both programs upgrade the SDK together. - **Two things to run.** More to deploy and watch; `ecobot://health` and the bot's "unreachable" answers make a failure visible. From 91131ef47f96b501500e6e0b2c53c136651fda49 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:46:41 +0000 Subject: [PATCH 004/125] docs/service-split.md: a chart that answers the question ends the turn without a second model call The service already replies to the bot, not the model, so the bot can stop there: a bot-only argument, chart_answers_it, on the chart tools ("the question is just to see this chart"), removed before the call is forwarded. When the model sets it and the result brings a chart, the bot draws it, writes the caption in code (report.chart_caption / lookup, as for the shortcuts' charts) and ends the turn, skipping the model's second call, the one that reads the whole result. The model decides, since it reads the question better than a regex; anything else goes back to it as usual. Step 0: it ships first, in today's bot, with an eval pair (just the chart / something else to answer). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index 1fd8656d..b0617daa 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -268,6 +268,9 @@ as now, next to the reads that chose its resolution, its buckets and its rose. A ### 3.8 The bot's side of a tool call +The model never reaches the service: it answers the bot with a tool call, the bot makes the call, and the service replies to the bot, +which hands the result back to the model for its reply. Every call passes through the bot both ways, so: + - **What it offers:** the service's tool list, except the air sensor's own temperature and humidity left out of the metric lists unless the words name them (the list only changes with the words, so the prompt cache holds, as now); a new list when the service says so. This narrows what the model can pick from; it never changes what the model picked. @@ -278,6 +281,16 @@ as now, next to the reads that chose its resolution, its buckets and its rose. A only for one that still fails, in the bot, filling an argument the model left out, never overruling one it set, each with its case. - **Shortcuts** build the tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way; the report sends `_meta.fetch: false` as `cached` does now. +- **When the chart is the answer, the model doesn't write the caption.** The bot adds one argument of its own to `summary` and to `days` + (the tools whose captions code already writes: `report.chart_caption`, and `report.lookup` for a count per month or year): + `chart_answers_it`, described as "true only when the question is just to see this chart and its figures: nothing else to answer". It + removes the argument before forwarding, so the service and other clients never see it. When every call of the model's step set it and + each result brings a chart, the bot draws them, writes the caption in code (the period, then each reading's high and low with when, + and any note about missing data) and sends them: the turn ends there, with no second call to the model, the one that reads the whole + result. A step without it, a result with no chart, an error, or a caption the code can't write goes back to the model as usual. The + model decides, because it reads the question better than a regex: "plot pressure this week" is just the chart; "plot pressure this + week: is a storm coming?" needs its words. A plain chart request the shortcuts recognise never reaches the model at all, as now. This + needs nothing from the split: it can ship first, in today's bot, on `weather_history`, `air_quality` and the day tools. - **The early cue:** today the bot pokes the sources the words concern as soon as a question arrives, so they refresh while the model thinks (a forecast question refreshes only that way). The bot sends the same cue at receipt as a request to the service's `warm` tool (`sources`), marked for applications (`_meta` `audience: "app"`), which the bot never offers the model. The sources lose `wants()`. @@ -301,6 +314,11 @@ their state; the charts' look; the shortcuts' choices; Telegram. Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new names together. +0. **The chart that answers itself** (3.8), in today's bot, independent of the rest: `chart_answers_it` on the chart tools, the bot's + early end of the turn with the caption written in code, and a pair of eval cases (a question that is just the chart, where the model + sets it; a question with something to answer beside the chart, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines + show the calls it saves. + 1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the question; they return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it shows. So that this step changes no answer, today's corrections from the words move out of the tools into the bot, which applies them @@ -310,8 +328,8 @@ names together. rebuilt spec draws the same picture (the golden images). 3. **The nine tools, in process.** The tools of 3.3 with their result shapes; the prompt, the shortcuts, `lib/report.py` (`report`, `weather_now`, `lookup`, `chart_caption`), the alert charts and the evals move to them together; the twelve go. The bot's corrections - from the words go too (3.8), and come back only for a case that then fails. Shipped only when the live evals (`--live`, all cases) - do as well as before. + from the words go too (3.8), and come back only for a case that then fails. `chart_answers_it` moves to `summary` and `days`. + Shipped only when the live evals (`--live`, all cases) do as well as before. 4. **The data interface, in process.** A `Data` protocol with the tools and resources of section 3, and an in-process implementation over today's sources. The bot's direct reads move to it: the gauges (`sheet()` moves to the bot), the alerts (resources, clocks and an in-process stand-in for the listen stream in place of `Warmer.after` and `on_live`), irrigation, the prompt's lines and `by_name` @@ -337,7 +355,8 @@ names together. depends on; a question asked while the service is down is answered as unreachable, and the next one after it is back is answered; an alert due during the gap is sent once. - A deploy check: a tool call through the proxy's name succeeds (the allowed hosts and the token). -- The live evals run against the service's real tool list. +- The live evals run against the service's real tool list, with `chart_answers_it` added as the bot offers it; the pair of cases for it + (set for a question that is only the chart, not set for one with more to answer) runs in every live run. ## 7. Risks @@ -346,6 +365,9 @@ names together. - **The model and the new tools.** New names, arguments and shapes can change what the model picks, and without the corrections from the words it must make every choice itself: step 3 ships only on the live evals, in one process, before any network is involved; a correction that turns out to be needed comes back as a fill, never an override. +- **A chart sent without the answer.** If the model sets `chart_answers_it` on a question that needed words, the person gets the chart + and its figures but not the answer. The description limits it to a question that is only the chart; the eval pair checks both sides, + and a follow-up ("but is a storm coming?") goes to the model as usual. - **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision: the bot pins it, and both programs upgrade the SDK together. - **Two things to run.** More to deploy and watch; `ecobot://health` and the bot's "unreachable" answers make a failure visible. From 94fbdd88e2de060f04caa03989924fdf403c15c2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:46:55 +0000 Subject: [PATCH 005/125] docs/service-split.md: rewrap two long lines Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index b0617daa..fb0ac462 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -140,8 +140,8 @@ Nine tools in place of twelve, one per kind of question, each over both sensors **`summary`'s result** is one shape for both sensors: `{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, -then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. The breakdown and -`monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever +then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. +The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. @@ -335,8 +335,8 @@ names together. in-process stand-in for the listen stream in place of `Warmer.after` and `on_live`), irrigation, the prompt's lines and `by_name` (from the station resource). Nothing in the bot holds a source object after this step. 5. **The MCP server and client.** `lib/mcp_server.py` serves `Data` (the bus, the low-level server, the transport settings, the token - check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, charts from the result's `_meta`). The evals read a checked-in tool - list (`tests/evals/tools.json`), which a test keeps equal to the server's. + check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, charts from the result's `_meta`). The evals + read a checked-in tool list (`tests/evals/tools.json`), which a test keeps equal to the server's. 6. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import boundary test, both ways. Config split. One compose file per host, TLS and tokens. Scripts go where they work: on the service's host `edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`; on the bot's From 2fc564455d260bb3eea3498d1146fd8d0ccfcbdc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:47:11 +0000 Subject: [PATCH 006/125] docs/service-split.md: rewrap one more long line Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index fb0ac462..1e351162 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -141,8 +141,8 @@ Nine tools in place of twelve, one per kind of question, each over both sensors `{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. -The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever -`rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", +The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; +`rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. **`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question From 5aede2bcce3dfc02b45b566a5f94ee7eb337504f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:47:24 +0000 Subject: [PATCH 007/125] docs/service-split.md: rewrap current's result shape Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index 1e351162..e17589b0 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -142,8 +142,8 @@ Nine tools in place of twelve, one per kind of question, each over both sensors "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; -`rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is `{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", -[emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. +`rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is +`{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. **`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each From 20a521bade26d330db8450d6f547f0dea6d913e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:48:26 +0000 Subject: [PATCH 008/125] docs/service-split.md: say what average_asked changes that the model's average can't Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/service-split.md b/docs/service-split.md index e17589b0..6ffecc54 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -167,7 +167,7 @@ argument. Over MCP each becomes an argument with a plain name, and the model set | `chart_field`, `chart_fields` (overrule the model) | `summary.chart_metrics`, `layout: "panels"` | | `readings` (which readings the words name) | `summary.metrics` | | `two_axes` | `layout: "two_axes"` | -| `average_asked` (daily means on the chart; the model can't ask for that today) | `daily_means` | +| `average_asked`, from the words "average", "avg", "mean": the chart drawn as daily means, the average-first hint and caption (the model's own `average` only adds averages to the figures; it can't ask for that chart today) | `daily_means` | | `per_day` | `every_day` | | `chart_asked` | `chart` | | `text`: rain by month, grouping (fill), holidays (overrule) | `rain_by`, `days.group_by`, `days.only` | From 8f4f1fc475f1d75c71e720b1a237691769a41d7c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 01:53:55 +0000 Subject: [PATCH 009/125] docs/service-split.md: averages in every tool that has them; days.hours for part of each day - An Averages table: summary (average, with per-day or per-month means; air always; daily_means for the chart), readings (each row is its interval's average), days (the _avg fields and stat avg, per month or year), chart (each panel's average). - days.hours (new; no tool can answer these today): each day's figures over a stretch of local time, "15:00-16:00" or "22:00-06:00", so "the average 3pm temperature in October" and "the typical overnight low" are one days call. Built on Reader.part_days, the day rows' own SQL over one window a day. Ships before the split (step 0), with tests and eval cases. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index 6ffecc54..1f93cdfd 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -119,7 +119,7 @@ Nine tools in place of twelve, one per kind of question, each over both sensors | `current` | how it is now; one reading now; the air now | `weather_now`, `air_quality` without dates | `metrics` (default outdoor and indoor) | | `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; charts | `weather_history`, `air_quality` with dates | `metrics`, `start`, `end` (today so far), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by`, `source` | | `readings` | values at an interval, each with its time | `readings` | `metric`, `start`, `end`, `interval` | -| `days` | find, rank and count days; a figure per month or year; holidays and weekends | `weather_days`, `air_days` | today's day-tool arguments over one field list (the last 30 days to yesterday) | +| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, and `hours` (the last 30 days to yesterday) | | `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric` (`pressure.relative`, `outdoor.humidity`, `wind.wind_speed`, `air.pm2_5`, `air.pm10`), `start`, `end` (90 days; 60 for air), `chart` | | `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `start`, `end` (90 days, at most 400), `chart` | | `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `start`, `end` (30 days), `layout`, `invert_second_axis`, `source` | @@ -151,6 +151,25 @@ sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from `note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am to 10am, not the air sensor's midnight to midnight) and says how many. +**Part of each day (`days.hours`, new):** `hours: "15:00-16:00"` works out each day's figures over that stretch of local time instead +of the whole day, and everything else in `days` then works on those figures: "the average 3pm temperature in October" is +`{hours: "15:00-16:00", stat: "avg", of: "temp_avg"}`, "the typical overnight low this month" `{hours: "22:00-06:00", stat: "avg", of: +"temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`. A moment is a short stretch ("15:00-15:05"). The +figures come from the same SQL as the day rows, over one window a day (`Reader.part_days`, which `lib/ecowitt/period.py` already uses +for a period's partial first and last days), so a part of a day is worked out exactly as a whole one is: the finest readings held, the +air sensor's glitches taken out. A stretch that crosses midnight belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is +Tuesday's night), and the result says so. Days held only as Ecowitt's daily or 4-hour records have nothing finer to cut a stretch from: +they are left out and counted in a note. No such question can be answered today, by any tool. + +**Averages**, wherever the question asks for one: + +| Tool | Averages | +|---|---| +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown; an air reading always has its average and `average_rating`. Rain has a total, not an average. `daily_means` draws the chart as each day's average. | +| `readings` | each row's value is its interval's average, with the interval's lowest and highest: hourly averages at `1hour`, daily at `1day` | +| `days` | each day's average as a field (`temp_avg`, `humidity_avg`, `co2_avg` …), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year", "average daily rain in June"); with `hours`, over that part of each day | +| `chart` | each panel's average over the period, beside its lowest and highest | + **Charts in a result** (3.6): for a client that asked for them, the chart data in the result's `_meta` (`ecobot/charts`, a list: a history can add a wind rose beside its chart) and one line for the model, `chart_hint`: that a chart goes with its reply, so the reply is its caption (today's `CHART_HINT`). The bot draws them in order (up to three a question); a drawn-ahead or alert chart still expects @@ -314,10 +333,13 @@ their state; the charts' look; the shortcuts' choices; Telegram. Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new names together. -0. **The chart that answers itself** (3.8), in today's bot, independent of the rest: `chart_answers_it` on the chart tools, the bot's - early end of the turn with the caption written in code, and a pair of eval cases (a question that is just the chart, where the model - sets it; a question with something to answer beside the chart, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines - show the calls it saves. +0. **Before the split**, in today's bot, each on its own: + - **The chart that answers itself** (3.8): `chart_answers_it` on the chart tools, the bot's early end of the turn with the caption + written in code, and a pair of eval cases (a question that is just the chart, where the model sets it; a question with something + to answer beside the chart, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines show the calls it saves. + - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against windows worked out by hand + (a midnight-crossing night, a day held only as daily records, an air glitch inside the window) and eval cases ("average 3pm + temperature in October", "typical overnight low this month"). 1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the question; they return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it @@ -348,6 +370,7 @@ names together. - The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an archived file. +- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as the day rows. - A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, chart data in the result's `_meta` that reads back as a spec for a client that asks, and no chart and no `chart_hint` for one that doesn't. - A reconnect test against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't From 5945d3cbcfda6c34ccf5421947dbfdb19634eee8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 02:04:40 +0000 Subject: [PATCH 010/125] docs/service-split.md: days.hours and the averages table, corrected against the code Checked by two agents with scratch runs against the storage code: - days.hours: rain over a stretch is the mm that fell in it (the running total's rise, as readings works it out), not the counter's highest, which is the rain since midnight; the resolution is chosen by coverage (5-minute, then 30-minute; the air sensor's 5-minute, then hourly), not period.py's fallback; stretches on the half hour, with a five-minute moment for "at 3pm"; [start, end), 24:00, nights belong to the day they end on, clock changes; today counts once its stretch is over ("last night"); at most 400 days, with measured costs - averages: readings' rain, gusts and wind direction aren't averages; chart's min and max are half-hour averages; only the six air-quality readings have ratings; summary's period average is to be weighted by time (today a part day counts as a whole one, an hourly air reading as a 5-minute one) and rain rate gets one: both fixed in step 0 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/service-split.md | 60 ++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 18 deletions(-) diff --git a/docs/service-split.md b/docs/service-split.md index 1f93cdfd..89d6a34a 100644 --- a/docs/service-split.md +++ b/docs/service-split.md @@ -139,7 +139,8 @@ Nine tools in place of twelve, one per kind of question, each over both sensors **`summary`'s result** is one shape for both sensors: `{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, -"air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band}, "wind.wind_direction": {most_common, +"air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band, average_aqi_us, average_band}, +"wind.wind_direction": {most_common, then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is @@ -151,24 +152,42 @@ sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from `note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am to 10am, not the air sensor's midnight to midnight) and says how many. -**Part of each day (`days.hours`, new):** `hours: "15:00-16:00"` works out each day's figures over that stretch of local time instead -of the whole day, and everything else in `days` then works on those figures: "the average 3pm temperature in October" is -`{hours: "15:00-16:00", stat: "avg", of: "temp_avg"}`, "the typical overnight low this month" `{hours: "22:00-06:00", stat: "avg", of: -"temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`. A moment is a short stretch ("15:00-15:05"). The -figures come from the same SQL as the day rows, over one window a day (`Reader.part_days`, which `lib/ecowitt/period.py` already uses -for a period's partial first and last days), so a part of a day is worked out exactly as a whole one is: the finest readings held, the -air sensor's glitches taken out. A stretch that crosses midnight belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is -Tuesday's night), and the result says so. Days held only as Ecowitt's daily or 4-hour records have nothing finer to cut a stretch from: -they are left out and counted in a note. No such question can be answered today, by any tool. +**Part of each day (`days.hours`, new; no tool can answer these today).** `hours` works out each day's figures over a stretch of local +time instead of the whole day, and the rest of `days` then works on those figures: "the typical overnight low this month" is +`{hours: "22:00-06:00", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`, "the average +3pm temperature in October" `{hours: "15:00-15:05", stat: "avg", of: "temp_avg"}`. +- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each + half hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be + counted as all of it. Any other time is refused, but for one exception: a moment, five minutes from the hour or half hour + ("15:00-15:05"). On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it + (on the air sensor's hourly days, the hour), and the result says so. +- **Which stretch.** `[start, end)` in local wall time, read as `start` to `end - 1` (the SQL's `BETWEEN` includes the end). "24:00" is + the next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening + before and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night): one stretch per sensor and day. A + stretch the clock change removes (02:00-03:00 on the first Sunday of October) is left out and counted. +- **Which readings.** Each sensor's stretch is read at the first of the day rows' own resolutions that holds all of it, by the + coverage (`Reader.held`): the station's 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the + minutes. A stretch held at neither (a day held only as Ecowitt's daily or 4-hour records, a night whose evening is before the + 30-minute archive) is left out and counted in a note; one that is held but has no readings (the station was off) counts as missing. + This is not `lib/ecowitt/period.py`'s choice for a period's part days, which falls back to whatever readings there are. +- **The figures** come from the day rows' own SQL over one window a day (`Reader.part_days`), so a stretch's mean, lowest, highest and + their times are worked out as a whole day's are, the air sensor's glitches taken out. Except rain: the day's `rain` is the highest + of the running daily total, which over a stretch would be the rain since midnight up to its end. Over a stretch, `rain` is the mm + that fell in it, the total's rise from the last reading before the stretch to its last reading in it, a fall counted as the midnight + reset (`lib/rain.rain_slots`, as `readings` works it out), computed beside `part_days`. +- **The period.** As `days`' (to yesterday), except that today counts once today's stretch is over and held: asked this morning, + "nights below 5°C this week" includes last night. At most 400 days, as `scan`'s: the stretches cost far more than day rows (over + four years of 5-minute readings a night takes about 1 s for a climate sensor, 3.4 s for the air sensor with its glitch rule, against + 0.01 s for the day rows; the default 30 days under 0.1 s), and a stretch that is the whole day reads the day rows. **Averages**, wherever the question asks for one: | Tool | Averages | |---|---| -| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown; an air reading always has its average and `average_rating`. Rain has a total, not an average. `daily_means` draws the chart as each day's average. | -| `readings` | each row's value is its interval's average, with the interval's lowest and highest: hourly averages at `1hour`, daily at `1day` | -| `days` | each day's average as a field (`temp_avg`, `humidity_avg`, `co2_avg` …), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year", "average daily rain in June"); with `hours`, over that part of each day | -| `chart` | each panel's average over the period, beside its lowest and highest | +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. `daily_means` draws the chart as each day's average. | +| `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | +| `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | +| `chart` | each line's average over the period (`mean`), beside the lowest and highest of its half-hour averages (`min`, `max`: not the true extremes, which `summary` gives with their times). A rain panel has its total (`total_mm`) instead, a rating panel the share of time in each rating. With `two_axes` or `same_axis`, each series keeps its own figures. | **Charts in a result** (3.6): for a client that asked for them, the chart data in the result's `_meta` (`ecobot/charts`, a list: a history can add a wind rose beside its chart) and one line for the model, `chart_hint`: that a chart goes with its reply, so the reply @@ -337,9 +356,12 @@ names together. - **The chart that answers itself** (3.8): `chart_answers_it` on the chart tools, the bot's early end of the turn with the caption written in code, and a pair of eval cases (a question that is just the chart, where the model sets it; a question with something to answer beside the chart, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines show the calls it saves. - - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against windows worked out by hand - (a midnight-crossing night, a day held only as daily records, an air glitch inside the window) and eval cases ("average 3pm - temperature in October", "typical overnight low this month"). + - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against stretches worked out by hand + (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a + night with rain in the evening only, an air glitch inside the stretch) and eval cases ("average 3pm temperature in October", + "typical overnight low this month", "nights below 5°C this week"). + - **Averages weighted by time** (3.3): `weather_history`'s and `air_quality`'s averages over the period's time, not its days or its + rows, and rain rate's average; tests with a part day at each end and an air period across its hourly history. 1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the question; they return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it @@ -370,7 +392,9 @@ names together. - The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an archived file. -- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as the day rows. +- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row (mean, lowest and highest, + and their times) for every day held whole at 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; + a day whose row comes from a daily record, or from whatever readings there were, is left out and counted. - A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, chart data in the result's `_meta` that reads back as a spec for a client that asks, and no chart and no `chart_hint` for one that doesn't. - A reconnect test against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't From c8eb42a655301027f2c0fd15492abc313562c8b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 02:15:40 +0000 Subject: [PATCH 011/125] docs/mcp-service.md: the plan is now a standalone MCP service, the bot its first client until retired Renamed from service-split.md and rewritten around the end state: the readings file, the syncers and an MCP server any client can use; no bot of ours. So: - the guidance the prompt gives the model moves into the server (instructions, tool descriptions, results that say what they are); periods in words, resolved by the service; answers ready to quote (times, days with their weather emoji); every choice an argument; errors that teach - charts are data in the result (bucketed for a model to read, a published JSON Schema); alerts are the service's rules, published as an MCP alert log clients listen to and catch up from - MCP prompts for the commands and buttons; stdio as well as HTTP - irrigation becomes its own server and repository, a client of the weather service - the bot keeps answering as the first client, gets no new features (chart_answers_it is dropped), and is deleted once a replacement does its job; evals ask several models with only the server's guidance Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 380 ++++++++++++++++++++++++++++++++++++++ docs/service-split.md | 420 ------------------------------------------ 2 files changed, 380 insertions(+), 420 deletions(-) create mode 100644 docs/mcp-service.md delete mode 100644 docs/service-split.md diff --git a/docs/mcp-service.md b/docs/mcp-service.md new file mode 100644 index 00000000..a18d1fd3 --- /dev/null +++ b/docs/mcp-service.md @@ -0,0 +1,380 @@ +# MCP service plan + +The plan for turning this repository into a weather and air-quality service that any MCP client can use: the readings file, the +syncers that fill it, and an MCP server over them. Claude Desktop, Claude Code, ChatGPT, Open WebUI or anyone's bot asks it questions +and gets answers it can pass on. Today's Telegram bot becomes the service's first client while the tools move over, and is retired +once another client does its job. Irrigation becomes a second MCP server in its own repository. This is a design and a sequence of +steps, each shipped on its own, in the manner of [storage-plan.md](storage-plan.md). + +Decided: +- **The end state is the service alone.** No bot of ours; nothing in the interface may assume one. +- **Charts are data.** Tools return a chart's data; the client draws it (or its model does). +- **Alerts are decided by the service and published over MCP only**, as a resource clients listen to. +- **This repository becomes the service**, keeping its history; the bot keeps working as a client until it is retired, then its code + goes. Irrigation moves to its own repository and server. +- **Separate hosts** are possible: the service runs near Home Assistant and the sensors; clients connect over the network. + +## 1. Why + +- The archive, the live poll and the backfills run only while the bot runs: a restart, a crash or a Telegram outage leaves holes. As a + service, the data keeps coming whatever any client is doing. +- Any assistant can ask about the station and the air sensor and get the same careful answers the bot gives today: records with when + they happened, days ranked and counted, readings at an interval, rain against pressure. Other Ecowitt MCP servers (brendo/ecowitt-mcp) + pass Ecowitt's raw cloud JSON through: 90 days at 5 minutes, running rain totals the model must difference, no air sensor. +- The bot has grown a second brain in front of the model: regex shortcuts, period hints, rewritten arguments, a 200-line prompt of + instructions about the tools. A service any model can use has to carry that knowledge itself, in its tools and its results. + +## 2. What is there now + +### 2.1 Who asks for data + +| Asker | How | Lives in | +|---|---|---| +| The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | +| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools through `Tools.call_all`, their JSON parsed by `lib/report.py` | `lib/intent.py`, `lib/bot.py` | +| Report, dashboard, period buttons, charts drawn ahead | the shortcuts, `Ecowitt.dashboard()`, the same tools with new dates | `lib/report.py`, `lib/ecowitt/dashboard.py`, `lib/bot.py` | +| Alerts | `station.recent()`, `live_rain()`, `air.latest()`, `forecast.days`, `pollen.current()`, after each refresh or new live reading | `lib/alerts` | +| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute | `lib/alerts/irrigation.py`, `lib/irrigation` | + +### 2.2 What fills the file + +The station's warm (60 s: 5-minute and 30-minute readings, 4-hour and daily records), the Home Assistant live poll (5 s; minutes, live +bands), the nightly archive, the Home Assistant range import (15 min), the AirGradient's warm (1–4 min), import and backfill, and the +pollen and forecast refreshes (30 and 15 min). Questions fetch too: `weather_history` and the air tools ask Ecowitt or the AirGradient +cloud for what the file lacks, inline. + +### 2.3 What the model is told outside the tools + +This is what a client other than the bot would not know, so it has to move into the service: +1. **The prompt** (`lib/prompt.py`): the devices and the names people use for them ("ecowitt", "ag"); what "this week", "last month", + "3m", "on record" mean; one call per period, not many; when to use which tool; how to read each result (`_when`, `_date`, notes); + Indoor and Outdoor; metric units; a weather emoji before each day, inferred from that day's figures; the caption rules under a chart. +2. **Period hints** (`intent.period_hints`, the prompt's "RIGHT NOW"): the bot works out every date range the words name and hands + them to the model, because models get calendar maths wrong. +3. **Hidden inputs** (`Turn`): the reading charted, a chart asked for, an average asked for, the air reading the conversation was about, + a holiday filter: the bot's regexes decide these beside the model's arguments, sometimes overruling them. +4. **Bot-side writing** (`lib/report.py`): the report's lines, the chart captions, the plain lookups' answers are written by the bot from + the tools' JSON. + +## 3. Design + +### 3.1 The service + +| Stays (the service) | Leaves | +|---|---| +| `lib/storage`, `lib/ecowitt`, `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.3), `lib/alert_log.py` (3.6) | **to each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | + +### 3.2 An interface any model can use + +The test of every tool, argument, result and note: would a model that has never seen this repository, given only the server's +instructions and tool list, answer the question right in one round of calls? Section 6's evals ask exactly that, of more than one model. + +- **The guidance lives in the server.** What the prompt teaches today moves to where every client gets it: the server's `instructions` + (returned when a client connects) say what the devices are and the names people use, what the sensors measure and in which units, + how to say Indoor and Outdoor, how to quote a record's time and date, how periods are written, that one call covers a period. Each + tool's description says which questions it answers, with an example call for each, and how to read what comes back. Each result says + what its figures are (`value_is`, `how_to_read`) and what to pass on (`note_*`, `missing`, `warning`). The persona (a friendly + Telegram bot, plain text, bullets) is the client's. +- **Periods in words, worked out by the service.** Every tool that takes a period takes `period`: a phrase from a small grammar the + description lists (`today`, `yesterday`, `last 5 hours`, `last 7 days`, `this week`, `last week`, `this month`, `last month`, + `October 2025`, `2025`, `3m`, `1y`, `on record`), or `start` and `end`. The service resolves it in the station's time zone, with the + rules the prompt states today (weeks start on Monday; "last week" is the previous calendar week; "the last week" or "past week" is 7 + days to now; "on record" is all of it), and every result begins with the period it used, written out ("Mon 3 – Sun 9 Nov 2026") and + as dates. No client does calendar maths; the bot's period hints and its "RIGHT NOW" block go. The current time is in every result + (`as_of`). +- **One naming scheme.** Readings are `sensor.reading` (`outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_speed`, + `rainfall.rain`, `solar_and_uvi.uvi`, `air.pm2_5`); `current` and `summary` also take a bare reading, meaning every sensor that has it + (`temperature` is outdoor and indoor). The names, their plain-language labels, units and the words people use for them are in + `ecobot://station` and in each tool's enum, built from what the file holds. `days` keeps its day-figure names (`temp_max` is + outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), listed in its schema. +- **Answers ready to pass on.** Every figure comes with its wording: a value with its unit (`"12.3 °C"`), a record with when + (`"around 3:30pm"`) and its day (`"Fri 9 Jan 2026"`), a day with its weather emoji (worked out by the service from that day's figures, + as the prompt asks the model to today), ratings and AQI for the air. A model can quote; it never formats a time or infers an emoji. +- **Every choice is an argument.** Nothing about the question reaches a tool except its arguments; there are no hidden inputs and no + client rewrites them. Arguments have plain names and defaults that suit the commonest question. +- **Errors that teach.** A wrong name lists the right ones; too many rows names the interval that fits; a period the data doesn't reach + says what it does reach. A model corrects its call once, from the error alone. +- **Small results.** A result is what a model needs to answer, not everything held: a summary's breakdown is by day or by month by the + period's length, a chart's data is bucketed to a budget (3.7), `readings` caps at 300 rows. Full detail is a further call. +- **Read-only, and honest about fetching.** Every tool is `readOnlyHint`; those that fetch what the file lacks say so + (`openWorldHint`), and request `_meta` `fetch: false` answers from what is held. + +### 3.3 Tools + +Nine tools in place of twelve, one per kind of question, each over both sensors where both have the reading. + +| Tool | Answers | Replaces | Arguments (default period) | +|---|---|---|---| +| `current` | how it is now; one reading now; the air now; with `context`, today's, this month's and this year's highs and lows beside each reading (the bot's gauges) | `weather_now`, `air_quality` without dates, the dashboard | `metrics` (default outdoor and indoor), `context` | +| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` with dates | `metrics`, `period` (today), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by` | +| `readings` | values at an interval, each with its time | `readings` | `metric`, `period`, `interval` | +| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (the last 30 days), `hours` | +| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric`, `period` (90 days; 60 for air), `chart` | +| `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `period` (90 days, at most 400), `chart` | +| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `period` (30 days), `layout`, `invert_second_axis` | +| `forecast` | today and the days ahead | `weather_forecast` | `days` | +| `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | + +Periods of whole days (`days`, `relate`, `scan`, `chart`) end yesterday, because today is still settling; the others run to now. + +**`summary`'s figures and charts** are two inputs, as they are today (`groups` and `chart_field(s)`): +- `metrics` is what to summarise; `chart_metrics` is what to draw, defaulting to the first of `metrics` (temperature when it is there). +- `layout` (shared with `chart`): `auto` draws one panel of `chart_metrics[0]` with a line for each sensor that has it, plus a second + chart of wind with the compass rose when `wind.wind_direction` is summarised and nothing is stacked; `panels` stacks every + `chart_metrics` reading, a panel each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of one + unit over each other. `invert_second_axis` modifies `two_axes`. +- `chart` defaults to on for periods of 3 days or more; `daily_means` draws one point a day; `average` adds means to the figures; + `every_day` lists every day of a period up to 31 days (by day or by month still follows the period's length); `rain_by` (`auto`, + `month`, `year`) sets the rain bars. +- A chart mixing station and air readings is `chart`'s, not `summary`'s: `summary` answers it with an error that says so. + +**`summary`'s result** is one shape for both sensors: `{period, as_of, series: {"outdoor.temperature": {unit, low, low_text, low_when, +low_date, [low_note], high…, [average], [daily|monthly]}, "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, +high_aqi_us, high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}}, +[rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and `monthly_note` are the +station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever `rainfall.rain` is +summarised. `current`'s result is `{as_of, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji], [today: +{low…, high…}], [month…], [year…]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. + +**`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question +shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each +sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; `note_hourly`, +`note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am +to 10am, not the air sensor's midnight to midnight) and says how many. + +**Part of each day (`days.hours`, new; no tool can answer these today).** `hours` works out each day's figures over a stretch of local +time instead of the whole day, and the rest of `days` then works on those figures: "the typical overnight low this month" is +`{hours: "22:00-06:00", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`, "the average +3pm temperature in October" `{hours: "15:00-15:05", stat: "avg", of: "temp_avg"}`. +- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each + half hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be + counted as all of it. Any other time is refused, but for one exception: a moment, five minutes from the hour or half hour + ("15:00-15:05"). On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it + (on the air sensor's hourly days, the hour), and the result says so. +- **Which stretch.** `[start, end)` in local wall time, read as `start` to `end - 1` (the SQL's `BETWEEN` includes the end). "24:00" is + the next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening + before and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night): one stretch per sensor and day. A + stretch the clock change removes (02:00-03:00 on the first Sunday of October) is left out and counted. +- **Which readings.** Each sensor's stretch is read at the first of the day rows' own resolutions that holds all of it, by the + coverage (`Reader.held`): the station's 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the + minutes. A stretch held at neither (a day held only as Ecowitt's daily or 4-hour records, a night whose evening is before the + 30-minute archive) is left out and counted in a note; one that is held but has no readings (the station was off) counts as missing. + This is not `lib/ecowitt/period.py`'s choice for a period's part days, which falls back to whatever readings there are. +- **The figures** come from the day rows' own SQL over one window a day (`Reader.part_days`), so a stretch's mean, lowest, highest and + their times are worked out as a whole day's are, the air sensor's glitches taken out. Except rain: the day's `rain` is the highest + of the running daily total, which over a stretch would be the rain since midnight up to its end. Over a stretch, `rain` is the mm + that fell in it, the total's rise from the last reading before the stretch to its last reading in it, a fall counted as the midnight + reset (`lib/rain.rain_slots`, as `readings` works it out), computed beside `part_days`. +- **The period.** As `days`' (to yesterday), except that today counts once today's stretch is over and held: asked this morning, + "nights below 5°C this week" includes last night. At most 400 days, as `scan`'s: the stretches cost far more than day rows (over + four years of 5-minute readings a night takes about 1 s for a climate sensor, 3.4 s for the air sensor with its glitch rule, against + 0.01 s for the day rows; the default 30 days under 0.1 s), and a stretch that is the whole day reads the day rows. + +**Averages**, wherever the question asks for one: + +| Tool | Averages | +|---|---| +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. `daily_means` draws the chart as each day's average. | +| `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | +| `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | +| `chart` | each line's average over the period (`mean`), beside the lowest and highest of its half-hour averages (`min`, `max`: not the true extremes, which `summary` gives with their times). A rain panel has its total (`total_mm`) instead, a rating panel the share of time in each rating. With `two_axes` or `same_axis`, each series keeps its own figures. | + +**What becomes of the bot's hidden inputs.** Today the bot reads the question with regexes and the tools use that reading beside the +model's arguments: some fill an argument the model left out, three overrule the model (the reading charted, the readings stacked, a +holiday filter). Each was added for a mistake the production model made (the eval cases `humidity-chart`, `temperature-and-rain`, +`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input or an easily missed +argument. In the service each is an argument with a plain name, and the model sets it: + +| Today (`Turn`) | In the service | +|---|---| +| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_metrics`, `layout: "panels"` | +| `readings` (which readings the words name) | `summary.metrics` | +| `two_axes` | `layout: "two_axes"` | +| `average_asked`, from the words "average", "avg", "mean": the chart drawn as daily means, the average-first wording (the model's own `average` only adds averages to the figures; it can't ask for that chart today) | `daily_means` | +| `per_day` | `every_day` | +| `chart_asked` | `chart` | +| `text`: rain by month, grouping (fill), holidays (overrule) | `rain_by`, `days.group_by`, `days.only` | +| `air_named` (the air reading charted when none is named) | `metrics` (the conversation is in the model's context) | +| `ahead` (a chart drawn ahead, nobody waiting) | request `_meta.priority: "background"` | +| `Tool.asked` (the air sensor's own temperature and humidity offered only when named) | always listed, described as the AirGradient's own readings, not the weather station's | +| `forecast_shown` (the forecast days a chat was shown) | gone: the forecast alert is the service's (3.6) | +| `CHART_SOURCE` | the chart data names its sources (3.7) | + +### 3.4 Resources + +For applications that keep an eye on the station rather than ask about it. + +| URI | Holds | Pushed | +|---|---|---| +| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds and what each means; the AirGradient dashboard link | on change | +| `ecobot://now/weather` | the live reading: `{as_of, group: {field: {value, unit, text, time}}}` | each new reading (5 s with HA, 60 s cloud only) | +| `ecobot://now/air` | the latest air reading, its time, ratings and AQI | each new reading | +| `ecobot://alerts{?since}` | the alerts sent, newest last, kept 30 days; `since` an alert id: those after it (3.6) | each new alert | +| `ecobot://forecast` | the forecast days, with `fetched_at` and `place` | each new forecast | +| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | +| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | + +Dates are ISO strings. The MCP SDK (2.3, protocol revision 2026-07-28) delivers changes on a `subscriptions/listen` stream: each event +says "this URI changed, read it again", with no replay. The service passes an `InMemorySubscriptionBus` to the server, and its loops +publish `ResourceUpdated` for each URI above when it changes, and `ToolsListChanged` when a sensor sends a field it never sent (the +metric lists grow). Repeats of an unchanged reading are not sent. Only clients on the 2026-07-28 revision can listen; older ones can +read the resources and poll. + +### 3.5 Prompts + +The service also offers MCP prompts, the templates clients show as commands or buttons ("/rain", "Weather now"), each a question in +words with its period as an argument: `now`, `report` (now, the air, today's forecast and pollen), `chart` (a reading and a period), +`rain`, `air`. They hold no logic of their own: the client's model answers them with the tools, as any question. They replace the bot's +keyboard and `/commands` for clients that show prompts. + +### 3.6 Alerts + +The rules move to the service: rain starting and stopping (with the quiet-hours note), gusts, UV, indoor and outdoor temperature +crossings, particulates (mask on, safe again), pollen and thunderstorm asthma, a forecast revised. Their thresholds, quiet hours and +cooldowns are the service's config, and their state its own store (`alert_state.json`, out of the bot's `bot_state.json`). Each runs +on the triggers it has today: a new live reading or 5-minute row, a new forecast or pollen page, and its own clock (the weather alerts +every 60 seconds, particulates every 30 minutes and only then, since its two-readings rule counts readings across checks). +- **An alert is an event:** `{id, kind, time, title, text, data, [chart]}`, the text ready to send ("🌧️ It's started raining: 0.4 mm + so far"), `data` the figures behind it, `chart` its chart data when it has one (gusts, UV, temperature, particulates). Each is + appended to `ecobot://alerts`, which pushes an update. +- **Delivery is the client's.** A client listens, reads `ecobot://alerts?since=`, and sends each alert to whoever + it serves. After a gap it reads from its last id, so nothing is lost while the alert is still in the 30-day log. Our bot does this + for its subscribed chats until it is retired. +- **The forecast alert is station-wide:** it compares a new forecast with the last one it alerted on, not with what each chat was + shown, which only the bot knew. +- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open; with the bot retired, alerts reach no + one unless a client that listens is set up (a few lines of Python with the SDK, or Home Assistant). Section 7. + +### 3.7 Charts + +Charts are data: the client draws them, or its model does from the numbers. +- **The tools that draw** (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`) build the chart as now (`specs.Chart`), next to + the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, panels: [{unit, + [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], [compass]}]}]`. + Times are ISO local times; a `source` names the devices ("Ecowitt weather station and AirGradient sensor"). +- **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (a week at hourly, a year at + daily-ish), the bands with it; a model can turn it into a plot with its own tools, and an application can draw it directly. Full + detail is `readings`. A JSON Schema for it is in the repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. +- **The note to the model:** a result with a chart says so in one line (`chart_note`: the chart's data is in `charts`; draw it if you + can, and keep the text to the figures; don't describe the chart), so a model neither ignores it nor repeats every point. +- **Our bot**, while it lives, draws `charts` with its renderer (`lib/charts.py`, reading the JSON) and sends the picture; the rain + caption reads its bars. The renderer leaves with the bot. + +### 3.8 Connecting + +- **Server:** the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built + when asked, so it follows the file's metrics. Served as Streamable HTTP (`streamable_http_app`) under uvicorn, behind TLS (a reverse + proxy such as Caddy, or uvicorn's own certificate), at `https:///mcp`, built with + `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)` (by default it answers only `Host: 127.0.0.1` or `localhost`, and + refuses the name a proxy or a LAN client uses). Also over stdio (`python -m ecobot_service --stdio`), for a desktop client on the + same machine as the file. +- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` + (`name:token,…`, one per client, so one can be revoked alone), with `AuthSettings(resource_server_url=None)` so no OAuth metadata is + published. Bind to the LAN or a tailnet; nothing needs the internet to reach it. +- **A client that listens** (our bot, an alert forwarder): `Client(…, mode="2026-07-28")`, pinning the protocol revision (the default + probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). In the SDK a connection failure on + any request ends the whole client, so one supervisor task owns it: it discards the client when it exits with a transport error or + the listen is lost or ends, builds a new one after a backoff, listens again and reads what it depends on. A read timeout of about 45 + seconds (three of the server's 15-second pings) notices a silently dead link. + +### 3.9 Irrigation, its own server + +`lib/irrigation` and the irrigation check move to their own repository and MCP server, next to the valve. +- **Tools:** `irrigation_status` (battery, weather delay, running or not), `water` (minutes), `stop`, `delay` (`24h`, `cancel`), the + last three `destructiveHint`, so a client asks before it calls them. +- **The watchdog** (a run must end; a restart mid-run still closes the valve) and the daily check (pause when it rained or will) run + in that server whatever any client does. +- **Rain and forecast** come from the weather service, as its client: `summary{metrics: ["rainfall.rain"], period: "last 24 hours"}` + and `forecast`. When the weather service is unreachable, the check runs on the forecast it last had and skips the measured rain. +- **Its alerts** (battery low, paused for rain) are its own `irrigation://alerts`, in the same shape. + +### 3.10 Configuration + +`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the +station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. +The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, its own `MCP_TOKENS`. + +## 4. The bot until it is retired + +The bot is the service's first client, and the measure of each step: it keeps answering in Telegram while its insides move to the +service. It gets no new features. While it lives it: +- connects to the service over MCP and offers the model the service's tools and instructions as they are, adding only its persona + (a friendly Telegram bot, plain text, bullets, the caption length a photo allows); +- keeps a few shortcuts for its buttons and commonest typed requests (a named reading's chart and a period, weather now, the report, + the gauges), each a fixed call to a service tool whose result is already worded, so it writes nothing itself; +- draws `charts` and the gauges (`current` with `context`) with its renderer; +- listens to `ecobot://alerts` and sends each alert to the chats subscribed to its kind, with its chart; +- keeps per-chat state: subscriptions, admins, the chart questions behind its period buttons. + +It is retired when a replacement does what you use it for: another client for questions (any MCP-capable assistant), and, for alerts, +a client that listens. Its code is then deleted from this repository: `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, +`lib/report.py`, the menus, the renderer and its tests and golden images. + +## 5. What does not change + +The readings file, its tables and its day rows; how each tool chooses its resolution and fetches what it lacks; the alert rules +themselves; the charts' content. + +## 6. Steps + +Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new +names together. + +0. **Fixes that belong to the service anyway**, in today's code: + - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against stretches worked out by hand + (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a + night with rain in the evening only, an air glitch inside the stretch) and eval cases ("average 3pm temperature in October", + "typical overnight low this month", "nights below 5°C this week"). + - **Averages weighted by time** (3.3): `weather_history`'s and `air_quality`'s averages over the period's time, not its days or its + rows, and rain rate's average; tests with a part day at each end and an air period across its hourly history. +1. **Explicit arguments, worded results.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the + question; they return their charts in the result (3.7) instead of appending to `turn.charts`. Results gain the wording the bot writes + today (`lib/report.py`'s lines and captions, the day emoji), and the bot quotes them instead of writing its own. So that this step + changes no answer, today's corrections from the words move out of the tools into the bot, which applies them to the model's calls on + the way in, as before; step 3 removes them. +2. **The guidance moves to the service.** Periods in words (`lib/periods_text.py`, tested against the bot's period hints for every + phrase they handle); the server instructions and the tool descriptions take over the prompt's knowledge (2.3); the bot's prompt keeps + only its persona. The evals run each question with only the instructions and the tool list, as any client would. +3. **The nine tools.** The tools of 3.3 with their result shapes; the bot's shortcuts and its alert charts move to them; the twelve go, + and with them the bot's corrections from the words, which come back only for a case that then fails. Shipped only when the live + evals (all cases) do as well as before, with the production model and one other. +4. **Alerts in the service.** The rules, their state and config move service-side and append to the alert log; the bot delivers from + the log. `current` gains `context` and the gauges come from it. +5. **MCP.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus, the low-level server, the transport settings, the + token check, stdio); the bot becomes an MCP client over the network (the supervisor, `charts` from results, the alert log). The + evals read the server's own tool list. The irrigation server is built in its own repository and the bot's irrigation buttons call + it; `lib/irrigation` goes from here. +6. **Two programs.** The service starts on its own (`python -m ecobot_service`), with its compose file; the bot connects to it. The + service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, + `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. +7. **The bot retired** (section 4), its code and tests deleted; the repository is the service. + +## 7. Testing + +- **Any model can use it.** The evals are the service's: each question is asked of a model given only the server's instructions and + tool list (no prompt of ours), and checked for the tools and arguments it picks and, where it matters, the answer. They run against + the production model and at least one other, so the interface isn't tuned to one model's habits. +- **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`), periods in + words against their dates (every phrase, a clock change, the first of a month and a year), charts against their schema. +- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row for every day held whole at + 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; a day from a daily record, or from whatever + readings there were, is left out and counted. +- **Alerts:** the rules' tests move with them; the log keeps order and survives a restart; a client that reconnects reads what it + missed, once. +- **A client that listens:** against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a + connection can't fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the client listens again + and reads the alerts after its last id. +- **A deploy check:** a tool call through the proxy's name succeeds (the allowed hosts and the token). + +## 8. Risks + +- **Alerts reach only listening clients.** With alerts over MCP only (3.6), once the bot is retired nobody gets them unless a client + that listens is running. Plan that client before step 7, or accept no alerts. +- **Charts only where a client can draw.** A client that neither renders the chart data nor lets its model draw gets the figures + without a picture. +- **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on: the guidance + in the server and the evals across models are the defence, and every answer still rests on figures the model quotes, not works out. +- **Every question through a model.** Without the bot's shortcuts each question costs at least one model call; that is the client's + choice and cost. +- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision; listening clients pin it, and the SDK is upgraded + on both sides together. diff --git a/docs/service-split.md b/docs/service-split.md deleted file mode 100644 index 89d6a34a..00000000 --- a/docs/service-split.md +++ /dev/null @@ -1,420 +0,0 @@ -# Service split plan - -The plan for moving the readings file and everything that fills it out of the bot, into a service on its own host that any MCP client -can ask. The bot keeps Telegram, the model, the prompt, the shortcuts, the alerts and the drawing; the service keeps the devices, the -archive and the answers. This is a design and a sequence of steps, each shipped on its own, in the manner of -[storage-plan.md](storage-plan.md). - -Decided before this plan: the bot draws the charts (the service sends their data); new live readings are pushed to the bot over MCP; -the two run on separate hosts; the model is offered the service's MCP tools as they are. - -## 1. Why - -- The archive, the live poll and the backfills run only while the bot runs: a bot restart, a crash or a Telegram outage leaves holes, - and a slow chart holds up the 5-second poll. As a service, the data keeps coming whatever the bot is doing. -- The data can be asked of by Claude Desktop, Claude Code or any MCP client, with the same answers the bot gives: today only the bot - can ask, and other assistants get brendo/ecowitt-mcp's raw cloud JSON. -- The service can live next to Home Assistant and the AirGradient on the LAN; the bot can run anywhere Telegram reaches. -- It forces the tools' hidden inputs into the open (2.3), which the tests and the evals want anyway. - -## 2. What is there now - -### 2.1 Who asks for data - -| Asker | How | Lives in | -|---|---|---| -| The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | -| Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools through `Tools.call_all`, their JSON parsed by `lib/report.py` | `lib/intent.py`, `lib/bot.py` (`_chart_in_code`, `_lookup_in_code`, `_written_in_code`) | -| Report | `weather_now`, `air_quality`, `pollen_asthma{cached}`, `weather_forecast{cached}` (`cached`: never wait on the network) | `lib/report.py` | -| Dashboard and status gauges | `Ecowitt.dashboard()` directly: the raw live reading, plus the year's day rows | `lib/ecowitt/dashboard.py`, `lib/gauges.py` | -| Period buttons, charts drawn ahead | the shortcut again, with new dates; every 5 minutes for the buttons' sentences and recent alerts | `bot.on_period_button`, `bot.draw_buttons_ahead` | -| Weather alerts | `station.recent(3)` (5-minute rows, may fetch), `live_rain()` (may fetch, writes bands), a 7-day 30-minute read at start; after every 60-second refresh and every new live reading | `lib/alerts/weather.py` | -| Particulates alert | `air.latest()` every 30 minutes (its two-readings rule is set for that pace) | `lib/alerts/particulates.py` | -| Forecast, pollen alerts | `forecast.days`, `pollen.current()` in memory, after each refresh (`Warmer.after`) | `lib/alerts/forecast.py`, `pollen_and_asthma.py` | -| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute | `lib/alerts/irrigation.py`, `lib/irrigation` | -| Alert charts, their 🔄 | `source.tools[...].handler` called directly, then `turn.charts[0]` | `lib/alerts/pictures.py` | -| The prompt, menus, `/usage` | each source's `describe()` line; which sources exist (`by_name`) | `lib/prompt.py`, `lib/templates.py`, `lib/alerts/menu.py` | - -### 2.2 What fills the file - -The station's warm (60 s: 5-minute and 30-minute readings, 4-hour and daily records), the Home Assistant live poll (5 s; minutes, live -bands), the nightly archive, the Home Assistant range import (15 min), the AirGradient's warm (1–4 min), import and backfill, and the -pollen and forecast refreshes (30 and 15 min). Questions fetch too: `weather_history` and the air tools ask Ecowitt or the AirGradient -cloud for what the file lacks, inline. All of it shares one `Storage`, one Home Assistant client, the in-memory `Recent` locks, the -live reading the poll keeps, and the station's group list (which the archive trims). - -### 2.3 What makes it hard to split - -1. **The `Turn` is a second, hidden set of arguments.** "Temperature chart 1d" and "Humidity chart 1d" send the same `weather_history` - arguments; the reading charted comes from `turn.chart_field`. Tools read `chart_asked`, `chart_field`, `chart_fields`, `two_axes`, - `average_asked`, `per_day`, `readings`, `text`, `air_named` and `ahead`, and write `charts`, `times`, `forecast_shown` and - `air_extra_used`. -2. **Charts come back on the side.** Every chart tool appends `specs.Chart`s to `turn.charts` (a history can add a wind rose beside its - chart); the rain caption reads the chart's bars. -3. **In-process hooks.** `Warmer.after` and `on_live` callbacks drive the weather, forecast and pollen alerts. -4. **The station decides the time zone** (`date_zone_id`) after the file opens, and the bot's whole config is rebuilt around it. -5. **Reads that write.** `weather_now` and `live_rain()` fetch the live reading and record its bands; with the cloud only, the minute - alert check is what drives that fetch. -6. **Per-question schemas.** `Tool.asked` swaps in the air sensor's own temperature and humidity; `readings` builds its metric list from - the file. -7. **Context-variable chart sources** (`CHART_SOURCE`), and alert charts that skip `Tools.call` and so have none. -8. **Imports across the line.** The bot imports helpers from data packages (`grouping_in`, the rain helpers, `describe_day`, - `LEVEL_EMOJI`, the air labels, `unit_text`, `glance`, `POINT_BUDGET`, `STATUS`); two data sources import `intent` for `wants()`. - -## 3. Design - -### 3.1 The two programs - -| Service (`ecobot_service.py`, host A, near Home Assistant) | Bot (`ecobot.py`, host B) | -|---|---| -| `lib/storage`, `lib/ecowitt` (less `dashboard.sheet`), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`'s `Warmer`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/sources.py` | `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, `lib/report_menu.py`, `lib/templates.py`, `lib/buttons.py`, `lib/periods.py`, `lib/topicmemory.py`, `lib/entities.py`, `lib/admins.py`, `lib/charts.py`, `lib/draw.py`, `lib/gauges.py` with `sheet()`, `GAUGES` and `STATUS`, `lib/alerts`, `lib/irrigation` | -| builds chart data (`specs.Chart`) next to the reads that choose its resolution | draws it (Pillow, fonts, dark mode) | -| `lib/mcp_server.py`: the tools and resources below | `lib/mcp_client.py`: the connection (3.7) | -| `lib/config.py`'s service fields (3.9) | `lib/config.py`'s bot fields | - -**Shared** (`lib/common/`, imported by both, importing neither side): `specs.py` (with JSON in and out, 3.6), `series.py`, `timeutil.py`, -`captions.py` (hint texts), `tools.py`'s `json_result`, `logs.py`, `netenv.py`, `warm.py`'s `every` and `safely`, and the pure helpers -the bot uses today from data packages: the thresholds (`GUST_ALERT_KMH`, `UVI_ALERT`, `TEMP_CHANGE_C`), `glance` (`solar_band`), -`unit_text`, `POINT_BUDGET`, the air metrics' labels and units, `grouping_in`, the rain helpers (`wet_flags`, -`rain_amount`, `duration`), the forecast's `describe_day` and `day_label`, and the pollen `LEVELS` and `LEVEL_EMOJI`. - -One repository and one image, two commands. A test reads every module's imports and fails if a bot module reaches a service package or -the reverse: that boundary is what keeps the split real. The sources' `wants()` (which imports `intent`) goes with the poke (3.8). - -### 3.2 The interface - -**Anything that answers a question calls a tool, whether the model asks or a shortcut does; resources are the state the bot watches.** -A tool answers in words and figures (ready-made wording, notes to pass on); the bot's shortcuts, report, captions and period buttons -parse the same results, so each tool's result shape is a contract with the bot as well as the model, pinned by `test_contract`. A -resource is raw data an application keeps an eye on: the live readings, the rows the alerts look back over, the day figures behind the -gauges, the forecast and pollen pages. Other MCP clients see the same split: an assistant asks the tools; an app reads or subscribes to -the resources. - -Conventions for the tools: -- **Metrics** are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_speed` (always drawn - shaded up to `wind.wind_gust`), `rainfall.rain` (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`. `current` and `summary` also take a - bare reading, meaning every sensor that has it (`temperature` is outdoor and indoor; `pm2_5` the air sensor's); `readings`, `chart` - and `relate` take full names only. `days` keeps its day-figure names (`temp_max` is outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), - which read better for conditions and are listed in its schema. The lists come from what the file holds. -- **Two kinds of period.** Moments (`current`, `summary`, `readings`): `start` and `end` as `YYYY-MM-DD HH:MM` in the station's local - time, `end` defaulting to now. Days (`days`, `relate`, `scan`, `chart`): `start` and `end` as `YYYY-MM-DD`, `end` defaulting to and - capped at yesterday, because today is still settling. A time with an offset is moved into local time. Each tool's default length is in - 3.3. The station's zone is in `ecobot://station`. -- **Results** are JSON: figures with their wording (`low_when`, ratings, emoji), notes to pass on (`note_*`, `missing`, `warning`), and - `error` with how to correct the call. Every tool is read-only to the caller (`readOnlyHint`); those that fetch what the file lacks - before answering say so (`openWorldHint`). -- **Request `_meta`**, set by the application, never by the model: `ecobot/charts: true` (this client draws: send chart data, 3.6), - `priority: "background"` (a chart drawn ahead: its fetches wait their turn; today's `turn.ahead`) and `fetch: false` (answer from - what is held, never wait on the network; today's `cached`). **Result `_meta`**, for the application, which clients don't hand to the - model: `ecobot/charts` (the chart data) and `timing` (the seconds spent; today's `turn.times["data"]`). -- **Arguments are the model's.** Every choice a tool makes is an argument the model sets (or a shortcut sets, 3.8); the bot forwards the - model's calls as they are. The tools read nothing else about the question. - -### 3.3 Tools - -Nine tools in place of twelve, one per kind of question, each over both sensors where both have the reading. - -| Tool | Answers | Replaces | Arguments (default period) | -|---|---|---|---| -| `current` | how it is now; one reading now; the air now | `weather_now`, `air_quality` without dates | `metrics` (default outdoor and indoor) | -| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; charts | `weather_history`, `air_quality` with dates | `metrics`, `start`, `end` (today so far), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by`, `source` | -| `readings` | values at an interval, each with its time | `readings` | `metric`, `start`, `end`, `interval` | -| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, and `hours` (the last 30 days to yesterday) | -| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric` (`pressure.relative`, `outdoor.humidity`, `wind.wind_speed`, `air.pm2_5`, `air.pm10`), `start`, `end` (90 days; 60 for air), `chart` | -| `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `start`, `end` (90 days, at most 400), `chart` | -| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `start`, `end` (30 days), `layout`, `invert_second_axis`, `source` | -| `forecast` | today and the days ahead | `weather_forecast` | `days` | -| `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | - -**`summary`'s figures and charts** are two inputs, as they are today (`groups` and `chart_field(s)`): -- `metrics` is what to summarise; `chart_metrics` is what to draw, defaulting to the first of `metrics` (temperature when it is there). -- `layout` (shared with `chart`): `auto` draws one panel of `chart_metrics[0]` with a line for each sensor that has it, plus a second - chart of wind with the compass rose when `wind.wind_direction` is summarised and nothing is stacked; `panels` stacks every - `chart_metrics` reading, a panel each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of one - unit over each other. `invert_second_axis` modifies `two_axes`. -- `chart` defaults to on for periods of 3 days or more, as now; `daily_means` draws one point a day (the words asked for an average); - `average` adds means to the figures; `every_day` lists every day of a period up to 31 days (whether the breakdown is by day or by month - still follows the period's length); `rain_by` (`auto`, `month`, `year`) sets the rain bars. -- A chart mixing station and air readings is `chart`'s, not `summary`'s: `summary` answers it with an error that says so. - -**`summary`'s result** is one shape for both sensors: -`{period, series: {"outdoor.temperature": {unit, low, low_time, low_when, low_date, [low_note], high…, [average], [daily|monthly]}, -"air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, high_aqi_us, high_band, average_aqi_us, average_band}, -"wind.wind_direction": {most_common, -then, steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [chart_hint], [missing], [warning]}`. -The breakdown and `monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; -`rain_total_mm` whenever `rainfall.rain` is summarised. `current`'s result is -`{time, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. - -**`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question -shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each -sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; `note_hourly`, -`note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am -to 10am, not the air sensor's midnight to midnight) and says how many. - -**Part of each day (`days.hours`, new; no tool can answer these today).** `hours` works out each day's figures over a stretch of local -time instead of the whole day, and the rest of `days` then works on those figures: "the typical overnight low this month" is -`{hours: "22:00-06:00", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`, "the average -3pm temperature in October" `{hours: "15:00-15:05", stat: "avg", of: "temp_avg"}`. -- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each - half hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be - counted as all of it. Any other time is refused, but for one exception: a moment, five minutes from the hour or half hour - ("15:00-15:05"). On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it - (on the air sensor's hourly days, the hour), and the result says so. -- **Which stretch.** `[start, end)` in local wall time, read as `start` to `end - 1` (the SQL's `BETWEEN` includes the end). "24:00" is - the next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening - before and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night): one stretch per sensor and day. A - stretch the clock change removes (02:00-03:00 on the first Sunday of October) is left out and counted. -- **Which readings.** Each sensor's stretch is read at the first of the day rows' own resolutions that holds all of it, by the - coverage (`Reader.held`): the station's 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the - minutes. A stretch held at neither (a day held only as Ecowitt's daily or 4-hour records, a night whose evening is before the - 30-minute archive) is left out and counted in a note; one that is held but has no readings (the station was off) counts as missing. - This is not `lib/ecowitt/period.py`'s choice for a period's part days, which falls back to whatever readings there are. -- **The figures** come from the day rows' own SQL over one window a day (`Reader.part_days`), so a stretch's mean, lowest, highest and - their times are worked out as a whole day's are, the air sensor's glitches taken out. Except rain: the day's `rain` is the highest - of the running daily total, which over a stretch would be the rain since midnight up to its end. Over a stretch, `rain` is the mm - that fell in it, the total's rise from the last reading before the stretch to its last reading in it, a fall counted as the midnight - reset (`lib/rain.rain_slots`, as `readings` works it out), computed beside `part_days`. -- **The period.** As `days`' (to yesterday), except that today counts once today's stretch is over and held: asked this morning, - "nights below 5°C this week" includes last night. At most 400 days, as `scan`'s: the stretches cost far more than day rows (over - four years of 5-minute readings a night takes about 1 s for a climate sensor, 3.4 s for the air sensor with its glitch rule, against - 0.01 s for the day rows; the default 30 days under 0.1 s), and a stretch that is the whole day reads the day rows. - -**Averages**, wherever the question asks for one: - -| Tool | Averages | -|---|---| -| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. `daily_means` draws the chart as each day's average. | -| `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | -| `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | -| `chart` | each line's average over the period (`mean`), beside the lowest and highest of its half-hour averages (`min`, `max`: not the true extremes, which `summary` gives with their times). A rain panel has its total (`total_mm`) instead, a rating panel the share of time in each rating. With `two_axes` or `same_axis`, each series keeps its own figures. | - -**Charts in a result** (3.6): for a client that asked for them, the chart data in the result's `_meta` (`ecobot/charts`, a list: a -history can add a wind rose beside its chart) and one line for the model, `chart_hint`: that a chart goes with its reply, so the reply -is its caption (today's `CHART_HINT`). The bot draws them in order (up to three a question); a drawn-ahead or alert chart still expects -exactly one. - -**What each hidden `Turn` input becomes.** Today the bot reads the question with regexes and the tools use that reading beside the -model's arguments: some fill an argument the model left out, three overrule the model (the reading charted, the readings stacked, a -holiday filter). Each was added for a mistake the production model made (the eval cases `humidity-chart`, `temperature-and-rain`, -`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input or an easily missed -argument. Over MCP each becomes an argument with a plain name, and the model sets it: - -| Today (`Turn`) | Over MCP | -|---|---| -| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_metrics`, `layout: "panels"` | -| `readings` (which readings the words name) | `summary.metrics` | -| `two_axes` | `layout: "two_axes"` | -| `average_asked`, from the words "average", "avg", "mean": the chart drawn as daily means, the average-first hint and caption (the model's own `average` only adds averages to the figures; it can't ask for that chart today) | `daily_means` | -| `per_day` | `every_day` | -| `chart_asked` | `chart` | -| `text`: rain by month, grouping (fill), holidays (overrule) | `rain_by`, `days.group_by`, `days.only` | -| `air_named` (the air reading charted when none is named) | `metrics` (the conversation is in the model's context) | -| `ahead` | request `_meta.priority: "background"` | -| `charts`, `times`, written | result `_meta`: `ecobot/charts`, `timing` | -| `forecast_shown`, written | `forecast`'s result has the days shown (`days: [{date, …}]`), which the bot records | -| `air_extra_used`, written | known from the arguments (`air.air_temperature` among the metrics) | -| `Tool.asked` | the service lists every metric; the bot leaves the air sensor's own temperature and humidity out unless the words name them (3.8) | -| `CHART_SOURCE` | `source` on the chart tools, written into the chart; the service sets it on every call, so alert charts get theirs too | - -The bot's chart captions follow the arguments of the call that drew the chart (its `chart_metrics`, `daily_means`), so a caption -always matches its chart; the streamed draft is held back once a result brings chart data. - -### 3.4 Resources - -Raw data keeps the device's own field names (`rainfall.daily`, the running total with its midnight reset; `rainfall.rain_rate`), which -the alerts' rain helpers and the Rain gauge work on; the `sensor.reading` names are the tools'. Dates arrive as ISO strings and the -client turns them back into `date`s (the day figures' keys, the forecast's and pollen's days), as `specs.from_json` does for charts. - -| URI | Holds | Pushed | Read by | -|---|---|---|---| -| `ecobot://station` | name, time zone, latitude and longitude, created; the configured sources and each one's prompt line (`describe()`); each source's mode (HA, cloud, local); the sensors and their metrics; retention; `air_link`; the service's start-up lines. Served once the station has named its zone. | on change | the bot at connect: zone, `by_name`, prompt, menus, `/usage` | -| `ecobot://now/weather` | the live reading: `{time, group: {field: {value, unit, time}}}` (each field keeps its own time), and the glance emoji | each new reading (5 s with HA, 60 s cloud only) | the rain alert, the gauges | -| `ecobot://now/air` | the latest air reading, its time, `sustained` (the minimum over `ANTISPIKE_REQUIRE_CONSECUTIVE` readings), ratings and AQI | each new reading | the particulates alert (on its timer) | -| `ecobot://rows/weather/{resolution}{?start,end,groups}` | rows `{ts, "group.field": value, …_low, …_high}` at 1min, 5min or 30min, fetching what the file lacks; a bare read is the last 3 hours | `…/5min` whenever a 5-minute row is written or replaced, provisional ones included | the weather alerts (3 hours; back to a rain spell's start; 7 days at 30 minutes at start), irrigation (24 hours) | -| `ecobot://days/{sensor}{?start,end,fields}` | `sensor` is `weather` or `air`: day figures `{field: {date: value}}`; a bare read is the year so far | no | the gauges | -| `ecobot://forecast` | the forecast days, raw, with `fetched_at` and `place` | each new forecast | the forecast alert, irrigation | -| `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | the pollen alert | -| `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | the bot's log at connect; troubleshooting | - -The bot always reads `rows` and `days` with an explicit `start` and `end`; subscriptions are on the bare URIs only. - -### 3.5 Pushing new readings - -The MCP SDK (2.3, protocol revision 2026-07-28) delivers changes on a `subscriptions/listen` stream: each event says "this URI changed, -read it again", with no replay. List changes travel on the same stream, when asked for. -- **The service** passes an `InMemorySubscriptionBus` to the server and its loops publish to it: `ResourceUpdated(ecobot://now/weather)` - after each new live reading, `…/now/air` after each new air reading, `…/rows/weather/5min` after each 5-minute row written, - `…/forecast`, `…/pollen` and `…/station` when they change, and `ToolsListChanged` when a sensor sends a field it never sent (the - metric lists grow). Repeats of an unchanged reading are not sent. It polls the live reading itself in every mode (today, with the - cloud only, the bot's minute alert check drove that fetch). -- **The bot** listens once, for those URIs and for tool list changes, and runs what used to hang off the hooks: `check_rain` on a new - live reading, `WeatherMonitor.check` on a new 5-minute row, the forecast and pollen alerts on a new page, a new tool list on a list - change. -- **The alerts keep their clocks**, reading the resource each time: the weather alerts every 60 seconds (as after each refresh today: - calm periods, quiet hours), the pollen alert's 7:30am start, and the particulates alert every 30 minutes and only then (its two-readings - rule counts readings across checks; a check per reading would confirm a mask alert within minutes). A push makes an alert prompt; the - clock makes it sure. -- **After a gap** (3.7) the bot listens again and reads every resource it depends on: the alerts compare against the state they keep, so - a missed event costs latency, never an alert. - -Only clients on the 2026-07-28 revision can listen; older ones can still call the tools and read the resources, and poll. - -### 3.6 Charts - -The tools that draw (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`, and the period buttons through them) build `specs.Chart` -as now, next to the reads that chose its resolution, its buckets and its rose. A spec is plain data (strings, epochs, floats, lists; -`period` as two dates), so: -- `specs.to_json(chart)` and `specs.from_json(data)`, with a `version`; `from_json` runs the same checks as building one. Tuples come back - as lists, which the renderer already takes. Non-finite numbers are dropped when the spec is built. -- The charts travel in the tool's own result, in its `_meta` (`ecobot/charts`), which MCP clients keep for the application and don't - hand to the model: one round trip, nothing stored on the service. The model gets only `chart_hint`, the line that tells it a chart - goes with its reply so the reply is the chart's caption: keep it short, don't describe the chart (today's `CHART_HINT`). Without that - line a model writes a long answer, or describes or apologises for a chart it doesn't know is there. -- Charts are sent only to a client that asks (request `_meta` `ecobot/charts: true`, which the bot always sends). For any other client - the tool builds no chart and adds no `chart_hint`, so its model is never told of a chart that won't appear. -- The bot rebuilds each spec as the result arrives (so the streamed draft is held back under a chart, as now) and draws it. -- The rain caption reads the rebuilt chart's bars; `newest` (what the alerts' picture cache keys on) and `caption()` work on it unchanged. -- A period button is a new `summary` call with new dates, as today; only pictures are cached (`periods.ImageCache`). - -### 3.7 Separate hosts - -- **Server:** the SDK's low-level `Server`, so each tool's input schema is the hand-written JSON the tools have today (with their - descriptions); the list is built when asked, so it follows the file's metrics. Served as Streamable HTTP (`streamable_http_app`) under - uvicorn, behind TLS (a reverse proxy such as Caddy, or uvicorn's own certificate), at `https:///mcp`. The app is built with - `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by default it only answers `Host: 127.0.0.1` or `localhost`, and refuses - the name a proxy or a LAN client uses. -- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` - (`name:token,…`, one per client, so one can be revoked alone), with `AuthSettings(resource_server_url=None)` so no OAuth metadata is - published. The bot sends its token in the HTTP client's headers (`create_mcp_http_client(headers={"Authorization": …})`); a bare URL - sends none. Bind to the LAN or a tailnet; nothing needs the internet to reach it. -- **The bot's connection:** `Client(…, mode="2026-07-28")`, pinning the protocol revision as well as the SDK version (the default mode - probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). One supervisor task enters the - client and runs the listen loop; questions, alerts and drawing ahead call it from their own tasks. In the SDK a connection failure on - any request ends the whole client, so: a call that fails with "connection closed" or times out is answered as unreachable; the - supervisor discards the client when it exits with a transport error, when the listen is lost, or when the listen ends, then builds a - new one after a backoff, listens again and reads what it depends on. Nothing is sent on a dead client. The HTTP read timeout is about - 45 seconds (three of the server's 15-second pings), so a silently dead link is noticed. -- **Time:** both hosts keep NTP time. The bot takes the station's zone from `ecobot://station` and remembers it in `bot_state.json`; - until it has one (a first start with the service down), it uses its own `TZ`. When the zone arrives or changes, the bot replaces its - zone, configures the charts again and tells the irrigation check. The dates it builds ("the last 5 hours") are local strings in that - zone. -- **When the service is down:** the bot starts and answers ("the weather station isn't reachable right now"), within the question's - budget (`TURN_SECONDS`). The irrigation watchdog and the valve buttons start at once whatever the service's state (a restart mid-run - must still close the valve); the irrigation check runs on the forecast it last had and skips the measured rain. -- **When the bot is down:** nothing is lost; the service keeps archiving. - -### 3.8 The bot's side of a tool call - -The model never reaches the service: it answers the bot with a tool call, the bot makes the call, and the service replies to the bot, -which hands the result back to the model for its reply. Every call passes through the bot both ways, so: - -- **What it offers:** the service's tool list, except the air sensor's own temperature and humidity left out of the metric lists unless - the words name them (the list only changes with the words, so the prompt cache holds, as now); a new list when the service says so. - This narrows what the model can pick from; it never changes what the model picked. -- **What it forwards:** each call the model makes, as it is. The corrections the tools make from the words today are not carried over: - with every choice an explicit argument, the model gets a fair chance to make it, and the regexes overruled it even when it was right, - misfired on wording nobody foresaw ("miles per hour"), and would leave other MCP clients with different answers from the same service. - The live evals decide (step 3): the cases each correction was added for are run against the nine tools, and a correction comes back - only for one that still fails, in the bot, filling an argument the model left out, never overruling one it set, each with its case. -- **Shortcuts** build the tools' arguments directly (`intent.fast_call` and the rest), so a shortcut and the model ask the same way; the - report sends `_meta.fetch: false` as `cached` does now. -- **When the chart is the answer, the model doesn't write the caption.** The bot adds one argument of its own to `summary` and to `days` - (the tools whose captions code already writes: `report.chart_caption`, and `report.lookup` for a count per month or year): - `chart_answers_it`, described as "true only when the question is just to see this chart and its figures: nothing else to answer". It - removes the argument before forwarding, so the service and other clients never see it. When every call of the model's step set it and - each result brings a chart, the bot draws them, writes the caption in code (the period, then each reading's high and low with when, - and any note about missing data) and sends them: the turn ends there, with no second call to the model, the one that reads the whole - result. A step without it, a result with no chart, an error, or a caption the code can't write goes back to the model as usual. The - model decides, because it reads the question better than a regex: "plot pressure this week" is just the chart; "plot pressure this - week: is a storm coming?" needs its words. A plain chart request the shortcuts recognise never reaches the model at all, as now. This - needs nothing from the split: it can ship first, in today's bot, on `weather_history`, `air_quality` and the day tools. -- **The early cue:** today the bot pokes the sources the words concern as soon as a question arrives, so they refresh while the model - thinks (a forecast question refreshes only that way). The bot sends the same cue at receipt as a request to the service's `warm` tool - (`sources`), marked for applications (`_meta` `audience: "app"`), which the bot never offers the model. The sources lose `wants()`. - -### 3.9 Configuration - -| Service | Bot | -|---|---| -| `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*` (including `AIRGRADIENT_DASHBOARD`), `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the station names one), `DATA_DIR`, `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS` | `TELEGRAM_*`, `OPENROUTER_*`, `ADMIN_*`, `DARKMODE`, `CHART_ALL_*`, the alert settings, `IRRIGATION_*` / Tuya, `MCP_URL`, `MCP_TOKEN`, `TZ` (until the station's zone is known), `DATA_DIR` (the bot's state and picture cache only) | - -`bot_state.json` (chats, subscriptions, alert state, chart questions, the station's last zone) stays with the bot; the readings file -and the snapshots go with the service. - -## 4. What does not change - -The readings file, its tables and its day rows; how each tool chooses its resolution and fetches what it lacks; the alert rules and -their state; the charts' look; the shortcuts' choices; Telegram. - -## 5. Steps - -Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new -names together. - -0. **Before the split**, in today's bot, each on its own: - - **The chart that answers itself** (3.8): `chart_answers_it` on the chart tools, the bot's early end of the turn with the caption - written in code, and a pair of eval cases (a question that is just the chart, where the model sets it; a question with something - to answer beside the chart, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines show the calls it saves. - - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against stretches worked out by hand - (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a - night with rain in the evening only, an air glitch inside the stretch) and eval cases ("average 3pm temperature in October", - "typical overnight low this month", "nights below 5°C this week"). - - **Averages weighted by time** (3.3): `weather_history`'s and `air_quality`'s averages over the period's time, not its days or its - rows, and rain rate's average; tests with a part day at each end and an air period across its hourly history. - -1. **Explicit arguments, shared helpers.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the - question; they return their charts in the result instead of appending to `turn.charts`, and `weather_forecast` returns the days it - shows. So that this step changes no answer, today's corrections from the words move out of the tools into the bot, which applies them - to the model's calls on the way in, as before; step 3 removes them. The pure helpers the bot imports from data packages move to - `lib/common` (3.1). Still one process; the evals check the new arguments. -2. **Chart JSON.** `specs.to_json` and `from_json`, and a round trip over every chart the samples and `scripts/dump_specs.py` draw: the - rebuilt spec draws the same picture (the golden images). -3. **The nine tools, in process.** The tools of 3.3 with their result shapes; the prompt, the shortcuts, `lib/report.py` (`report`, - `weather_now`, `lookup`, `chart_caption`), the alert charts and the evals move to them together; the twelve go. The bot's corrections - from the words go too (3.8), and come back only for a case that then fails. `chart_answers_it` moves to `summary` and `days`. - Shipped only when the live evals (`--live`, all cases) do as well as before. -4. **The data interface, in process.** A `Data` protocol with the tools and resources of section 3, and an in-process implementation - over today's sources. The bot's direct reads move to it: the gauges (`sheet()` moves to the bot), the alerts (resources, clocks and an - in-process stand-in for the listen stream in place of `Warmer.after` and `on_live`), irrigation, the prompt's lines and `by_name` - (from the station resource). Nothing in the bot holds a source object after this step. -5. **The MCP server and client.** `lib/mcp_server.py` serves `Data` (the bus, the low-level server, the transport settings, the token - check); `lib/mcp_client.py` implements `Data` over MCP (the supervisor, date parsing, charts from the result's `_meta`). The evals - read a checked-in tool list (`tests/evals/tools.json`), which a test keeps equal to the server's. -6. **Two programs.** `ecobot_service.py` starts the sources, the loops and the server; `ecobot.py` connects to `MCP_URL`. The import - boundary test, both ways. Config split. One compose file per host, TLS and tokens. Scripts go where they work: on the service's host - `edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`; on the bot's - `eval_prompts` (reading `tests/evals/tools.json`) and `update_charts`; `show_request` and `report_inputs` become MCP clients; - `dump_specs` writes JSON on the service and draws on the bot. - -## 6. Testing - -- The suite splits along the boundary: the service's tests (storage, sources, tools, resources, the server) and the bot's (intent, - report, alerts, drawing, the client), the bot's running against a fake `Data`, or against the real server in memory over an - archived file. -- `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row (mean, lowest and highest, - and their times) for every day held whole at 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; - a day whose row comes from a daily record, or from whatever readings there were, is left out and counted. -- A wire test per tool and resource: the arguments it takes, the shape it returns (`test_contract`), dates that come back as `date`s, chart - data in the result's `_meta` that reads back as a spec for a client that asks, and no chart and no `chart_hint` for one that doesn't. -- A reconnect test against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't - fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the bot listens again and reads what it - depends on; a question asked while the service is down is answered as unreachable, and the next one after it is back is answered; an - alert due during the gap is sent once. -- A deploy check: a tool call through the proxy's name succeeds (the allowed hosts and the token). -- The live evals run against the service's real tool list, with `chart_answers_it` added as the bot offers it; the pair of cases for it - (set for a question that is only the chart, not set for one with more to answer) runs in every live run. - -## 7. Risks - -- **Latency.** Each call is a network round trip: tens of milliseconds on a LAN, against a question budget of seconds. Charts drawn - ahead are a few calls every 5 minutes. The early cue keeps the head start the poke gives today. -- **The model and the new tools.** New names, arguments and shapes can change what the model picks, and without the corrections from - the words it must make every choice itself: step 3 ships only on the live evals, in one process, before any network is involved; a - correction that turns out to be needed comes back as a fill, never an override. -- **A chart sent without the answer.** If the model sets `chart_answers_it` on a question that needed words, the person gets the chart - and its figures but not the answer. The description limits it to a question that is only the chart; the eval pair checks both sides, - and a follow-up ("but is a storm coming?") goes to the model as usual. -- **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision: the bot pins it, and both programs upgrade the SDK - together. -- **Two things to run.** More to deploy and watch; `ecobot://health` and the bot's "unreachable" answers make a failure visible. From db092d7e38092609c2270818865a68fd775b30d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 02:29:52 +0000 Subject: [PATCH 012/125] docs/mcp-service.md: chart_answers_it is the service's, with a ready reply any client can end on It was dropped with the bot, because it lived in the bot. It belongs to the service: summary, days and chart take chart_answers_it (the model's judgement that the chart is the whole answer); the result then carries a finished reply for the person, as a text block annotated audience ["user"], and _meta ecobot/complete. Only a client can skip its model's second call, so the service makes it one generic rule (send the user text and chart, end the turn); our bot follows it while it lives, any bot can, and a client that doesn't still gets a reply its model can repeat. Step 0, with an eval pair. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a18d1fd3..ae9f460a 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -106,12 +106,12 @@ Nine tools in place of twelve, one per kind of question, each over both sensors | Tool | Answers | Replaces | Arguments (default period) | |---|---|---|---| | `current` | how it is now; one reading now; the air now; with `context`, today's, this month's and this year's highs and lows beside each reading (the bot's gauges) | `weather_now`, `air_quality` without dates, the dashboard | `metrics` (default outdoor and indoor), `context` | -| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` with dates | `metrics`, `period` (today), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by` | +| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` with dates | `metrics`, `period` (today), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by`, `chart_answers_it` | | `readings` | values at an interval, each with its time | `readings` | `metric`, `period`, `interval` | -| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (the last 30 days), `hours` | +| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (the last 30 days), `hours`, `chart_answers_it` | | `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric`, `period` (90 days; 60 for air), `chart` | | `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `period` (90 days, at most 400), `chart` | -| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `period` (30 days), `layout`, `invert_second_axis` | +| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `period` (30 days), `layout`, `invert_second_axis`, `chart_answers_it` | | `forecast` | today and the days ahead | `weather_forecast` | `days` | | `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | @@ -257,6 +257,16 @@ Charts are data: the client draws them, or its model does from the numbers. detail is `readings`. A JSON Schema for it is in the repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. - **The note to the model:** a result with a chart says so in one line (`chart_note`: the chart's data is in `charts`; draw it if you can, and keep the text to the figures; don't describe the chart), so a model neither ignores it nor repeats every point. +- **When the chart is the answer, the reply comes ready.** `summary`, `days` and `chart` take `chart_answers_it`, described as "true + only when the question is just to see this chart and its figures: nothing else to answer" ("plot pressure this week", not "plot + pressure this week: is a storm coming?"). The model judges that; no regex does. When it is set and a chart is made, the result + carries a finished reply for the person (the period, each reading's high and low with when, any note about missing data) as a text + block annotated `audience: ["user"]` (MCP's mark for content meant for the person, not the model), and result `_meta` + `{"ecobot/complete": true}`. Only a client can save the model's second call, since it runs the model loop and MCP gives a server no + way to keep a result from a client's model; the service makes it one generic rule: *if a result is complete, send its user text and + its chart, and end the turn*. Our bot follows the rule while it lives, and any bot can; a client that doesn't (a desktop assistant) + gives the result to its model as usual, which then has the reply ready to repeat. A result with no chart, an error or a note that + needs the model's words is never complete. - **Our bot**, while it lives, draws `charts` with its renderer (`lib/charts.py`, reading the JSON) and sends the picture; the rain caption reads its bars. The renderer leaves with the bot. @@ -300,6 +310,7 @@ The bot is the service's first client, and the measure of each step: it keeps an service. It gets no new features. While it lives it: - connects to the service over MCP and offers the model the service's tools and instructions as they are, adding only its persona (a friendly Telegram bot, plain text, bullets, the caption length a photo allows); +- ends the turn on a complete result (3.7), sending the ready reply and the chart without a second model call; - keeps a few shortcuts for its buttons and commonest typed requests (a named reading's chart and a period, weather now, the report, the gauges), each a fixed call to a service tool whose result is already worded, so it writes nothing itself; - draws `charts` and the gauges (`current` with `context`) with its renderer; @@ -321,6 +332,10 @@ Each step ships on its own, with the tests and evals green and the bot working t names together. 0. **Fixes that belong to the service anyway**, in today's code: + - **The chart that answers itself** (3.7): `chart_answers_it` on `weather_history`, `air_quality` and the day tools, the finished + reply and the complete mark in the result, and the bot's early end of the turn on it; a pair of eval cases (a question that is + just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the live evals; the + log's `LLM 2` lines show the calls it saves. - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against stretches worked out by hand (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a night with rain in the evening only, an air glitch inside the stretch) and eval cases ("average 3pm temperature in October", @@ -375,6 +390,9 @@ names together. - **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on: the guidance in the server and the evals across models are the defence, and every answer still rests on figures the model quotes, not works out. - **Every question through a model.** Without the bot's shortcuts each question costs at least one model call; that is the client's - choice and cost. + choice and cost. A chart that answers the question costs only one where the client ends the turn on a complete result (3.7). +- **A chart sent without the answer.** If a model sets `chart_answers_it` on a question that needed words, the person gets the chart + and its figures but not the answer: the description limits it to a question that is only the chart, the eval pair checks both + sides, and a follow-up goes to the model as usual. - **A protocol still settling.** `subscriptions/listen` is the 2026-07-28 revision; listening clients pin it, and the SDK is upgraded on both sides together. From d360eae3eebbb808ed3a7a67375a80434c77e7f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 02:37:33 +0000 Subject: [PATCH 013/125] docs/mcp-service.md: revised after review as a model would read it, for coverage, and for periods - The descriptions and results are the contract: instructions may never reach a model (a pinned client skips discover; many clients don't pass them on). The bot calls discover itself. - Periods: a full table of the forms people use (rolling and calendar, dates without a year, weekdays, parts of a day, holidays, since), whole-phrase matching, the person's own words passed unchanged, "this week" = the last 7 days, period or start/end, whole-day tools cut to yesterday, errors that list the forms with their dates. The model never needs today's date. - Ten tools: chart folds into summary (one owner for every chart over time; chart_readings defaults to all, as panels; average draws daily means), plus outlook (will it rain, the prompt's rules in code) and about (limits, alerts, history). Routing rules in the descriptions; days defaults to on record; bare names are the station's; aliases and sensor names; current defaults to everything, with the gauges' context; forecast takes a period; day_look for each day. - Alerts: expires, link, refresh, a defined forecast baseline; irrigation alerts on its own server. - Steps: one swap of the model's tools; nothing rewritten before it is replaced; MCP and the service's own program together; a stdio bridge, not a second process on the file; fixed auth settings and listen wiring; chart_points for the bot's renderer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 508 ++++++++++++++++++++++++++------------------ 1 file changed, 306 insertions(+), 202 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index ae9f460a..841fc129 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -9,7 +9,7 @@ steps, each shipped on its own, in the manner of [storage-plan.md](storage-plan. Decided: - **The end state is the service alone.** No bot of ours; nothing in the interface may assume one. - **Charts are data.** Tools return a chart's data; the client draws it (or its model does). -- **Alerts are decided by the service and published over MCP only**, as a resource clients listen to. +- **Alerts are decided by the service and published over MCP only**, as a log clients listen to. - **This repository becomes the service**, keeping its history; the bot keeps working as a client until it is retired, then its code goes. Irrigation moves to its own repository and server. - **Separate hosts** are possible: the service runs near Home Assistant and the sensors; clients connect over the network. @@ -19,10 +19,11 @@ Decided: - The archive, the live poll and the backfills run only while the bot runs: a restart, a crash or a Telegram outage leaves holes. As a service, the data keeps coming whatever any client is doing. - Any assistant can ask about the station and the air sensor and get the same careful answers the bot gives today: records with when - they happened, days ranked and counted, readings at an interval, rain against pressure. Other Ecowitt MCP servers (brendo/ecowitt-mcp) - pass Ecowitt's raw cloud JSON through: 90 days at 5 minutes, running rain totals the model must difference, no air sensor. + they happened, days ranked and counted, readings at an interval, rain against pressure, whether it will rain. Other Ecowitt MCP + servers (brendo/ecowitt-mcp) pass Ecowitt's raw cloud JSON through: 90 days at 5 minutes, running rain totals the model must + difference, no air sensor. - The bot has grown a second brain in front of the model: regex shortcuts, period hints, rewritten arguments, a 200-line prompt of - instructions about the tools. A service any model can use has to carry that knowledge itself, in its tools and its results. + rules about the tools. A service any model can use has to carry that knowledge itself, in its tools and its results. ## 2. What is there now @@ -33,8 +34,8 @@ Decided: | The model | 12 tools: `weather_now`, `weather_history`, `weather_days`, `weather_link`, `air_quality`, `air_days`, `plot_chart`, `air_link`, `air_scan`, `readings`, `weather_forecast`, `pollen_asthma` | `lib/ecowitt`, `lib/airgradient`, `lib/compose.py`, `lib/history.py`, `lib/forecast`, `lib/pollen` | | Shortcuts in code | `intent.fast_call`, `report_calls`, `model_prefetch`: the same tools through `Tools.call_all`, their JSON parsed by `lib/report.py` | `lib/intent.py`, `lib/bot.py` | | Report, dashboard, period buttons, charts drawn ahead | the shortcuts, `Ecowitt.dashboard()`, the same tools with new dates | `lib/report.py`, `lib/ecowitt/dashboard.py`, `lib/bot.py` | -| Alerts | `station.recent()`, `live_rain()`, `air.latest()`, `forecast.days`, `pollen.current()`, after each refresh or new live reading | `lib/alerts` | -| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute | `lib/alerts/irrigation.py`, `lib/irrigation` | +| Alerts, their charts and 🔄 | `station.recent()`, `live_rain()`, `air.latest()`, `forecast.days`, `pollen.current()`; the charts through the shortcuts' sentences ("Wind chart 1d") | `lib/alerts` | +| Irrigation | `station.recent(24)` and the forecast, once a day; the valve watchdog every minute; buttons to water, stop and pause | `lib/alerts/irrigation.py`, `lib/irrigation`, `lib/bot.py` | ### 2.2 What fills the file @@ -45,16 +46,28 @@ cloud for what the file lacks, inline. ### 2.3 What the model is told outside the tools -This is what a client other than the bot would not know, so it has to move into the service: -1. **The prompt** (`lib/prompt.py`): the devices and the names people use for them ("ecowitt", "ag"); what "this week", "last month", - "3m", "on record" mean; one call per period, not many; when to use which tool; how to read each result (`_when`, `_date`, notes); - Indoor and Outdoor; metric units; a weather emoji before each day, inferred from that day's figures; the caption rules under a chart. -2. **Period hints** (`intent.period_hints`, the prompt's "RIGHT NOW"): the bot works out every date range the words name and hands - them to the model, because models get calendar maths wrong. +All of this is what a client other than the bot would not know, so it has to move into the service: +1. **The prompt** (`lib/prompt.py`): + - the devices and the names people use for them ("ecowitt", "ag"), what they measure and in which units, Indoor and Outdoor; + - what "this week", "last month", "3m", "on record" mean; + - one call per period, not many; when to use which tool; how to read each result (`_when`, `_date`, notes); that a record with when + it happened is `weather_history`, a ranking of days `weather_days`; a period with no date named, for days, is the whole record; + - fetch again for every question and every follow-up, never reuse earlier figures; the resolution is chosen for you; + - a weather emoji before each day, inferred from that day's figures; the caption rules under a chart; + - "will it rain?": the station read (pressure tendency over 3 hours from whether the high or the low came first; down more than + 3 hPa likely, 1–3 possible, under 1 or rising unlikely; under 1005 hPa unsettled, over 1020 settled; humidity 90% or more, or the + temperature within 2°C of the dew point; recent rain; wind picking up), then the forecast; + - what the bot can't do: no lightning, soil channels, indoor air quality or other places; custom alerts can't be added; the alerts + there are and their thresholds; how far back the history goes. +2. **The date** (the prompt's "RIGHT NOW", `intent.period_hints`): today's date and time, and every date range the words name, worked + out by the bot because models get calendar maths wrong. 3. **Hidden inputs** (`Turn`): the reading charted, a chart asked for, an average asked for, the air reading the conversation was about, - a holiday filter: the bot's regexes decide these beside the model's arguments, sometimes overruling them. -4. **Bot-side writing** (`lib/report.py`): the report's lines, the chart captions, the plain lookups' answers are written by the bot from + a holiday filter, "weather all week" (every reading, in a set order): the bot's regexes decide these beside the model's arguments, + sometimes overruling them. +4. **Bot-side writing** (`lib/report.py`): the report's lines, the chart captions, the plain lookups' answers, written by the bot from the tools' JSON. +5. **Prefetching** (`intent.model_prefetch`): for "will it rain" the bot fetches the reading now, the last 3 hours and the forecast before + the model starts. ## 3. Design @@ -62,99 +75,166 @@ This is what a client other than the bot would not know, so it has to move into | Stays (the service) | Leaves | |---|---| -| `lib/storage`, `lib/ecowitt`, `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.3), `lib/alert_log.py` (3.6) | **to each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | +| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` and `sheet()` from `lib/ecowitt/dashboard.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | ### 3.2 An interface any model can use -The test of every tool, argument, result and note: would a model that has never seen this repository, given only the server's -instructions and tool list, answer the question right in one round of calls? Section 6's evals ask exactly that, of more than one model. - -- **The guidance lives in the server.** What the prompt teaches today moves to where every client gets it: the server's `instructions` - (returned when a client connects) say what the devices are and the names people use, what the sensors measure and in which units, - how to say Indoor and Outdoor, how to quote a record's time and date, how periods are written, that one call covers a period. Each - tool's description says which questions it answers, with an example call for each, and how to read what comes back. Each result says - what its figures are (`value_is`, `how_to_read`) and what to pass on (`note_*`, `missing`, `warning`). The persona (a friendly - Telegram bot, plain text, bullets) is the client's. -- **Periods in words, worked out by the service.** Every tool that takes a period takes `period`: a phrase from a small grammar the - description lists (`today`, `yesterday`, `last 5 hours`, `last 7 days`, `this week`, `last week`, `this month`, `last month`, - `October 2025`, `2025`, `3m`, `1y`, `on record`), or `start` and `end`. The service resolves it in the station's time zone, with the - rules the prompt states today (weeks start on Monday; "last week" is the previous calendar week; "the last week" or "past week" is 7 - days to now; "on record" is all of it), and every result begins with the period it used, written out ("Mon 3 – Sun 9 Nov 2026") and - as dates. No client does calendar maths; the bot's period hints and its "RIGHT NOW" block go. The current time is in every result - (`as_of`). -- **One naming scheme.** Readings are `sensor.reading` (`outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_speed`, - `rainfall.rain`, `solar_and_uvi.uvi`, `air.pm2_5`); `current` and `summary` also take a bare reading, meaning every sensor that has it - (`temperature` is outdoor and indoor). The names, their plain-language labels, units and the words people use for them are in - `ecobot://station` and in each tool's enum, built from what the file holds. `days` keeps its day-figure names (`temp_max` is - outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), listed in its schema. +The test of every tool, argument, result and note: would a model that has never seen this repository, given only the tool list, +answer the question right in one round of calls? Section 7's evals ask exactly that, of more than one model. + +- **The tool descriptions and the results are the contract.** Every rule a choice of tool or the reading of a result depends on is in + that tool's description (which questions it answers, an example call for each, how to read what comes back) or in the result itself + (`value_is`, `how_to_read`, `note_*`, `missing`, `warning`). The server's `instructions` repeat a short summary (the devices and their + nicknames, Indoor and Outdoor, units), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking + (`server/discover`), and many don't pass them to their model. The persona (a friendly Telegram bot, plain text, bullets) is the + client's. +- **Periods in words, worked out by the service.** Every tool that takes a period takes `period`, the person's own words for it, passed + unchanged ("this week", "in the last year", "past two years", "yesterday afternoon"), or `start` (and `end`). The service reads them + by the table below, in the station's time zone, and every result begins with how it read them (`period: {asked: "this week", text: + "the last 7 days: Wed 4 – Tue 10 Nov 2026", start, end}`) and the time of the figures (`as_of`). The model never needs today's date: + every relative form is in the table, and the descriptions carry the table. The bot's period hints and its "RIGHT NOW" block go. +- **One naming scheme.** Readings are `sensor.reading`: `outdoor.temperature`, `indoor.humidity`, `pressure.relative`, + `wind.wind_speed`, `rainfall.rain` (mm that fell), `solar_and_uvi.uvi`, `air.pm2_5`, `air.temperature` (the AirGradient's own). + Tools that take readings also take the words people use, resolved by the service and listed in each description: a bare reading is + the weather station's (`temperature` and `humidity` are outdoor and indoor; the AirGradient's own are only ever `air.temperature` + and `air.humidity`), `pressure` is relative pressure, `uv`, `solar`, `rain` the main gauge, `wind` its speed shaded up to the gusts + (and the compass rose on a chart); a sensor's name (`outdoor`, `indoor`, `wind`, `air`) is its usual set; `all` is every reading. + The device nicknames ("ecowitt", "weather station", "ag", "airgradient", "air gradient") are in the descriptions too. `days` keeps + its day-figure names (`temp_max` is outdoor, `indoor_temp_max`, `rain`, `pm2_5_max`), listed in its schema. - **Answers ready to pass on.** Every figure comes with its wording: a value with its unit (`"12.3 °C"`), a record with when - (`"around 3:30pm"`) and its day (`"Fri 9 Jan 2026"`), a day with its weather emoji (worked out by the service from that day's figures, - as the prompt asks the model to today), ratings and AQI for the air. A model can quote; it never formats a time or infers an emoji. -- **Every choice is an argument.** Nothing about the question reaches a tool except its arguments; there are no hidden inputs and no - client rewrites them. Arguments have plain names and defaults that suit the commonest question. -- **Errors that teach.** A wrong name lists the right ones; too many rows names the interval that fits; a period the data doesn't reach - says what it does reach. A model corrects its call once, from the error alone. + (`"around 3:30pm"`) and its day (`"Fri 9 Jan 2026"`), ratings and AQI for the air, and each day's look (`day_look: {word: "wet", + emoji: "🌧️"}`), worked out by the service from that day's rain, highest gust, highest and lowest temperature and solar radiation, by + a rule with its thresholds in the code (step 2). A model quotes; it never formats a time or works out a day's weather. +- **Every choice is an argument**, with a plain name and a default that suits the commonest question. Nothing about the question reaches + a tool except its arguments: no hidden inputs, and no client rewrites them. +- **Fresh every time.** Every result says its figures are as of `as_of` and that a follow-up or a challenge ("that's wrong, it was + cooler") needs the tool called again. The resolution is the service's choice, never an argument: a record is refined to the 5-minute + reading where it is held, and `low_note` or `high_note` says when it isn't. +- **Errors that teach.** A wrong name lists the right ones; a period that isn't in the table lists the forms with what each means now + (which also tells the model today's date); too many rows names the interval that fits; a period the data doesn't reach says what it + does reach; a future period points to `forecast`. A model corrects its call once, from the error alone. - **Small results.** A result is what a model needs to answer, not everything held: a summary's breakdown is by day or by month by the period's length, a chart's data is bucketed to a budget (3.7), `readings` caps at 300 rows. Full detail is a further call. - **Read-only, and honest about fetching.** Every tool is `readOnlyHint`; those that fetch what the file lacks say so - (`openWorldHint`), and request `_meta` `fetch: false` answers from what is held. + (`openWorldHint`); request `_meta` `fetch: false` answers from what is held. + +**Periods.** `period` must match a form below as a whole phrase (case aside; N a digit or a word up to twelve). There is no partial match +and no falling back to a default: anything else is an error that lists the forms. Examples are as asked on Tue 10 Nov 2026 at 14:05. + +| `period` | Means | +|---|---| +| `today` | 00:00 today to now | +| `yesterday` | yesterday 00:00–24:00 | +| `last N minutes`, `N min` | the last N minutes (`m` alone never means minutes) | +| `last N hours`, `Nh`, `last 24 hours`, `1d`, `last day` | the last N hours | +| `last N days`, `Nd` (N ≥ 2) | today and the N−1 whole days before it (`last 7 days`: Wed 4 Nov 00:00 to now) | +| `this week`, `past week`, `the last week`, `week`, `1w` | the last 7 days, as above | +| `last N weeks`, `Nw`, `fortnight` | the last 7N days | +| `past month`, `the last month`, `month`, `1m`, `last 30 days` | the last 30 days | +| `last N months`, `Nm`, `N mo` | the last round(N×365/12) days (`3m`: 12 Aug to now) | +| `past year`, `the last year`, `year`, `1y`, `last 12 months` | the last 365 days | +| `last N years`, `Ny` | the last 365N days | +| `week to date`, `since Monday` | Monday 00:00 to now (Mon 9 Nov) | +| `last week` | the previous Monday to Sunday (Mon 2 – Sun 8 Nov) | +| `this month`, `last month` | 1 Nov to now; all of October | +| `this year`, `last year` | 1 Jan 2026 to now; all of 2025 | +| `2025` | that year (to now if it is this one) | +| `October 2025`, `October` | that month; with no year, the latest that has begun (`December` is December 2025) | +| `A to B`, `between A and B`, `June to August 2026` | from the start of A to the end of B | +| `2026-09-05`, `5 Sep`, `5 September 2025`, `Sat 5 Sep` | that day; with no year, the latest not after today; a weekday that doesn't match the date is an error naming the right one | +| `Monday` … `Sunday`, `last Saturday` | the latest such day before today | +| `Christmas Day`, `Melbourne Cup` (any public holiday), with or without a year | that day, from the service's holiday calendar; the latest not after today | +| `this morning`, `yesterday afternoon`, `Tuesday evening` | 06:00–12:00, 12:00–18:00, 18:00–24:00 of that day | +| `last night`, `Tuesday night`, `overnight` | 22:00 the evening before to 06:00 that day | +| `since 6am`, `since Monday` | from the latest such time (or that day's 00:00) to now | +| `on record`, `all time`, `ever` | from the first reading held, for the sensors asked about, to now | + +- **`period` or `start`**, never both (both is an error). `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD + HH:MM`; one with an offset or `Z` is moved into local time. An `end` that is a date includes that whole day; one with a time stops at + it. No `end` means to now; `end` without `start` is an error. +- **Whole-day tools** (`days`, `relate`, `scan`) take whole days ending yesterday, because today is still settling: a rolling phrase is + that many whole days to yesterday (`last 7 days`: Tue 3 – Mon 9 Nov), a calendar one runs to yesterday, and the result's `period` + says it was cut ("to Mon 9 Nov: today isn't over"). A phrase that leaves nothing (`today`, `last 5 hours`, `this month` on the 1st) + is an error that points to `summary` or `readings`. They take dates only; a time is refused with the same pointer. +- **A future period** is an error that points to `forecast`. ### 3.3 Tools -Nine tools in place of twelve, one per kind of question, each over both sensors where both have the reading. +Ten tools in place of twelve: one per kind of question, each over both sensors where both have the reading. -| Tool | Answers | Replaces | Arguments (default period) | +| Tool | Answers | Replaces | Arguments (default) | |---|---|---|---| -| `current` | how it is now; one reading now; the air now; with `context`, today's, this month's and this year's highs and lows beside each reading (the bot's gauges) | `weather_now`, `air_quality` without dates, the dashboard | `metrics` (default outdoor and indoor), `context` | -| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart | `weather_history`, `air_quality` with dates | `metrics`, `period` (today), `average`, `every_day`, `chart`, `chart_metrics`, `layout`, `daily_means`, `rain_by`, `chart_answers_it` | -| `readings` | values at an interval, each with its time | `readings` | `metric`, `period`, `interval` | -| `days` | find, rank and count days; a figure per month or year; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (the last 30 days), `hours`, `chart_answers_it` | -| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `metric`, `period` (90 days; 60 for air), `chart` | -| `scan` | each air reading against every weather reading: which go together | `air_scan` | `metric` (or all), `period` (90 days, at most 400), `chart` | -| `chart` | any readings from both sensors on one chart: a panel each, or two on one panel | `plot_chart` | `panels[{metric, style}]`, `period` (30 days), `layout`, `invert_second_axis`, `chart_answers_it` | -| `forecast` | today and the days ahead | `weather_forecast` | `days` | +| `current` | how it is now: every reading, or the ones named; with `context`, today's, this month's and this year's highs and lows beside each reading, and rain's totals | `weather_now`, `air_quality` without dates, the gauges | `readings` (all), `context` | +| `summary` | a period's highs and lows with when; averages; day or month breakdown; wind direction; rain total; air ratings and AQI; a chart of any readings from either sensor or both | `weather_history`, `air_quality` with dates, `plot_chart` | `readings`, `period` (today; a chart with no period, the last 24 hours), `average`, `every_day`, `chart`, `chart_readings`, `layout`, `invert_second_axis`, `chart_answers_it` | +| `readings` | values at an interval, each with its time | `readings` | `reading`, `period` (the last 24 hours), `interval` | +| `days` | days found, ranked or counted by their figures; a figure per month or year, as bars; holidays and weekends; the same over part of each day (the 3pm temperature, the overnight low) | `weather_days`, `air_days` | today's day-tool arguments over one field list, `period` (on record; with `hours`, the last 30 days), `hours`, `chart_answers_it` | +| `relate` | rain against one reading: for pressure, humidity or wind, does rain follow a change in it; for PM2.5 or PM10, is the air cleaner after rain | `weather_link`, `air_link` | `reading`, `period` (90 days; 60 for air), `chart` | +| `scan` | each air reading against every weather reading: which go together | `air_scan` | `reading` (or all), `period` (90 days, at most 400), `chart` | +| `outlook` | will it rain in the next few hours: the station's read and the forecast's | the prompt's outlook rules, `model_prefetch` | none | +| `forecast` | today and the days ahead | `weather_forecast` | `period` (the next 7 days: `today`, `tomorrow`, `next 3 days`, `this weekend`) | | `pollen` | grass pollen and thunderstorm asthma | `pollen_asthma` | none | - -Periods of whole days (`days`, `relate`, `scan`, `chart`) end yesterday, because today is still settling; the others run to now. - -**`summary`'s figures and charts** are two inputs, as they are today (`groups` and `chart_field(s)`): -- `metrics` is what to summarise; `chart_metrics` is what to draw, defaulting to the first of `metrics` (temperature when it is there). -- `layout` (shared with `chart`): `auto` draws one panel of `chart_metrics[0]` with a line for each sensor that has it, plus a second - chart of wind with the compass rose when `wind.wind_direction` is summarised and nothing is stacked; `panels` stacks every - `chart_metrics` reading, a panel each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of one - unit over each other. `invert_second_axis` modifies `two_axes`. -- `chart` defaults to on for periods of 3 days or more; `daily_means` draws one point a day; `average` adds means to the figures; - `every_day` lists every day of a period up to 31 days (by day or by month still follows the period's length); `rain_by` (`auto`, - `month`, `year`) sets the rain bars. -- A chart mixing station and air readings is `chart`'s, not `summary`'s: `summary` answers it with an error that says so. +| `about` | what the service measures and doesn't, how far back each kind of history goes, the alerts there are with their thresholds, that alerts can't be added or changed by asking | the prompt's capabilities and limits | none | + +**Which tool, in their descriptions.** Each description says what it is not for and where that goes: +- the highest or lowest reading of a period with when it happened (the hottest, coldest, fastest gust, "on record") is `summary`; + a day's total, or days ranked, counted or filtered on a day's figures (the wettest day, the windiest day, the hottest day it also + rained, days over 35°C, rain per month) is `days`; +- any chart over time is `summary`'s (one reading, several, both sensors, ratings); a figure per month or year is `days.group_by`; + "X against rain" is `relate`; +- values at set times or per interval are `readings`; +- "report", "status", "sitrep": `current`, `forecast` (today) and `pollen`, called together; "will it rain" is `outlook`. + +**`summary`'s figures and charts:** +- `readings` is what to summarise (default: the weather station's usual set, outdoor and indoor temperature and humidity); + `chart_readings` is what to draw, defaulting to all of `readings`. +- `layout`: `auto` draws one reading as a line for each sensor that has it, plus the compass rose when wind direction is among them; + more than one reading as panels, one each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of + one unit over each other; `invert_second_axis` modifies `two_axes`. A reading can be drawn as its traffic-light rating + (`air.pm2_5:rating`). `all` draws every reading in the station's usual order (temperature, humidity, solar, pressure, rain, dew point, + then feels-like and VPD where configured, then wind), as "weather all week" does today. +- `chart` defaults to on for periods of 3 days or more. `average: true` adds each reading's average to the figures and draws the chart + as each day's average. +- `every_day` lists every day of a period up to 31 days (by day or by month still follows the period's length). **`summary`'s result** is one shape for both sensors: `{period, as_of, series: {"outdoor.temperature": {unit, low, low_text, low_when, -low_date, [low_note], high…, [average], [daily|monthly]}, "air.pm2_5": {unit, low…, high…, average, high_rating, average_rating, -high_aqi_us, high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}}, -[rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and `monthly_note` are the -station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever `rainfall.rain` is -summarised. `current`'s result is `{as_of, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji], [today: -{low…, high…}], [month…], [year…]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`. +low_date, low_day_look, [low_note], high…, [average], [daily|monthly: each row with its day_look]}, "air.pm2_5": {unit, low…, high…, +average, high_rating, average_rating, high_aqi_us, high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, +steadiness, [daily]}}, [rain_total_mm], [monthly_note], [notes: {sensor: {…}}], [charts], [missing], [warning]}`. The breakdown and +`monthly_note` are the station's; ratings, AQI and the 400-day cap (30 days fetched inline) the air sensor's; `rain_total_mm` whenever +rain is summarised. + +**`current`'s result:** `{as_of, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji], [today: {low, low_text, +low_when, high…}], [month…], [year…]}}, "rainfall": {"rain": {…, [today: {total}], [month: {total, wettest_day}], [year…]}}, "wind": +{"wind_speed": {…, [today: {high_gust…}]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`: with `context`, everything the +bot's gauges show (rain as totals and its wettest day, wind's highest gust). + +**`outlook`'s result** is the prompt's outlook rules, worked out by the service (`lib/outlook.py`) from the reading now and the last 3 +hours: `{as_of, verdict: "likely"|"possible"|"unlikely", reason: "pressure down 2.4 hPa in 3 hours, humidity 91%", pressure: {change_hpa, +tendency, level, text}, moisture: {humidity, dew_point_spread}, recent_rain, wind_trend, forecast: [today's and tomorrow's lines, when +the forecast is on]}`. With the forecast off, the station's read is the whole answer. **`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each -sensor's source; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; `note_hourly`, -`note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily records (10am -to 10am, not the air sensor's midnight to midnight) and says how many. +sensor's source and its `day_look`; the result keeps both sensors' notes (`note_daily`, `exact_from`, `note_trace`, `note_averaged`; +`note_hourly`, `note_missing`). A condition mixing the two sensors leaves out the days whose station figures come from Ecowitt's daily +records (10am to 10am, not the air sensor's midnight to midnight) and says how many. With no period, every day on record: "per year", +"how many times", "the windiest day ever". **Part of each day (`days.hours`, new; no tool can answer these today).** `hours` works out each day's figures over a stretch of local time instead of the whole day, and the rest of `days` then works on those figures: "the typical overnight low this month" is -`{hours: "22:00-06:00", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "22:00-06:00", where: temp_min < 5}`, "the average -3pm temperature in October" `{hours: "15:00-15:05", stat: "avg", of: "temp_avg"}`. -- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each - half hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be - counted as all of it. Any other time is refused, but for one exception: a moment, five minutes from the hour or half hour - ("15:00-15:05"). On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it - (on the air sensor's hourly days, the hour), and the result says so. +`{hours: "night", stat: "avg", of: "temp_min"}`, "nights below 5°C" `{hours: "night", where: temp_min < 5}`, "the average 3pm +temperature in October" `{hours: "15:00", stat: "avg", of: "temp_avg"}`. +- **Named stretches:** `night` (22:00–06:00), `morning` (06:00–12:00), `afternoon` (12:00–18:00), `evening` (18:00–24:00), `daytime` + (06:00–18:00), as the periods table has them. The result states the stretch it used. +- **Times on the half hour.** A stretch starts and ends on the half hour ("15:00-16:00", "22:30-06:00"): the figures take each half + hour's mean, and a 30-minute reading's own lowest and highest run to the end of its half hour, so part of a half hour would be + counted as all of it. Any other time is refused, but for a moment: a single time on the hour or half hour ("15:00", or "15:00-15:05"). + On a day held at 5 minutes a moment is that reading; on a day held only at 30 minutes it is the half hour from it (on the air + sensor's hourly days, the hour), and the result says so. - **Which stretch.** `[start, end)` in local wall time, read as `start` to `end - 1` (the SQL's `BETWEEN` includes the end). "24:00" is the next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening before and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night): one stretch per sensor and day. A - stretch the clock change removes (02:00-03:00 on the first Sunday of October) is left out and counted. + stretch the clock change removes (02:00–03:00 on the first Sunday of October) is left out and counted. - **Which readings.** Each sensor's stretch is read at the first of the day rows' own resolutions that holds all of it, by the coverage (`Reader.held`): the station's 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the minutes. A stretch held at neither (a day held only as Ecowitt's daily or 4-hour records, a night whose evening is before the @@ -174,58 +254,61 @@ time instead of the whole day, and the rest of `days` then works on those figure | Tool | Averages | |---|---| -| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. `daily_means` draws the chart as each day's average. | +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown, and draws the chart as each day's average. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. A chart's panels report each line's average beside the lowest and highest of its half-hour averages, a rain panel its total. | | `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | | `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | -| `chart` | each line's average over the period (`mean`), beside the lowest and highest of its half-hour averages (`min`, `max`: not the true extremes, which `summary` gives with their times). A rain panel has its total (`total_mm`) instead, a rating panel the share of time in each rating. With `two_axes` or `same_axis`, each series keeps its own figures. | **What becomes of the bot's hidden inputs.** Today the bot reads the question with regexes and the tools use that reading beside the model's arguments: some fill an argument the model left out, three overrule the model (the reading charted, the readings stacked, a holiday filter). Each was added for a mistake the production model made (the eval cases `humidity-chart`, `temperature-and-rain`, -`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input or an easily missed -argument. In the service each is an argument with a plain name, and the model sets it: +`days-over-limit-by-year`, `rain-by-month-two-years`), several of them because the choice was a hidden input, an easily missed argument +or a default that suited the wrong question. In the service each is an argument with a plain name and a default that suits the +question, and the model sets it: | Today (`Turn`) | In the service | |---|---| -| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_metrics`, `layout: "panels"` | -| `readings` (which readings the words name) | `summary.metrics` | +| `chart_field`, `chart_fields` (overrule the model) | `summary.chart_readings`, defaulting to every reading summarised, drawn as panels | +| `readings` (which readings the words name) | `summary.readings` | | `two_axes` | `layout: "two_axes"` | -| `average_asked`, from the words "average", "avg", "mean": the chart drawn as daily means, the average-first wording (the model's own `average` only adds averages to the figures; it can't ask for that chart today) | `daily_means` | +| `average_asked` (the chart drawn as daily means; the model can't ask for that today) | `average` (figures and chart together) | | `per_day` | `every_day` | | `chart_asked` | `chart` | -| `text`: rain by month, grouping (fill), holidays (overrule) | `rain_by`, `days.group_by`, `days.only` | -| `air_named` (the air reading charted when none is named) | `metrics` (the conversation is in the model's context) | +| `text`: rain by month, grouping (fill), holidays (overrule) | `days.group_by`, `days.only`; the rain bars' grouping follows the period's length | +| `air_named` (the air reading charted when none is named) | `readings` (the conversation is in the model's context) | +| "weather all week" (`ALL_ORDER`, `CHART_ALL_*`) | `chart_readings: "all"`, in the service's order and settings | | `ahead` (a chart drawn ahead, nobody waiting) | request `_meta.priority: "background"` | -| `Tool.asked` (the air sensor's own temperature and humidity offered only when named) | always listed, described as the AirGradient's own readings, not the weather station's | +| `Tool.asked` (the air sensor's own temperature and humidity offered only when named) | always listed, only as `air.temperature` and `air.humidity`, described as the AirGradient's own | | `forecast_shown` (the forecast days a chat was shown) | gone: the forecast alert is the service's (3.6) | | `CHART_SOURCE` | the chart data names its sources (3.7) | ### 3.4 Resources -For applications that keep an eye on the station rather than ask about it. +For applications that keep an eye on the station rather than ask about it; a model doesn't read them (what it needs is in the tools). | URI | Holds | Pushed | |---|---|---| -| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds and what each means; the AirGradient dashboard link | on change | +| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds, what each means and its threshold; the AirGradient dashboard link | on change | | `ecobot://now/weather` | the live reading: `{as_of, group: {field: {value, unit, text, time}}}` | each new reading (5 s with HA, 60 s cloud only) | | `ecobot://now/air` | the latest air reading, its time, ratings and AQI | each new reading | -| `ecobot://alerts{?since}` | the alerts sent, newest last, kept 30 days; `since` an alert id: those after it (3.6) | each new alert | -| `ecobot://forecast` | the forecast days, with `fetched_at` and `place` | each new forecast | +| `ecobot://alerts` (in the resource list) and `ecobot://alerts{?since,expired}` (a template) | the alerts, newest last, kept 30 days; `since` an alert id: those after it; unexpired ones only unless `expired=true` (3.6) | each new alert, on the bare URI | +| `ecobot://forecast` | the forecast days, structured (min and max, rain chance, chance of at least 1 mm, summary), with `fetched_at` and `place` | each new forecast | | `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | | `ecobot://health` | each loop's last success and failure, archive progress, the file's size | no | +| `ecobot://schema/chart` | the chart data's JSON Schema (3.7) | no | -Dates are ISO strings. The MCP SDK (2.3, protocol revision 2026-07-28) delivers changes on a `subscriptions/listen` stream: each event -says "this URI changed, read it again", with no replay. The service passes an `InMemorySubscriptionBus` to the server, and its loops -publish `ResourceUpdated` for each URI above when it changes, and `ToolsListChanged` when a sensor sends a field it never sent (the -metric lists grow). Repeats of an unchanged reading are not sent. Only clients on the 2026-07-28 revision can listen; older ones can -read the resources and poll. +Dates are ISO strings. On the 2026-07-28 protocol (MCP SDK 2.3), changes are delivered on a `subscriptions/listen` stream: each event +says "this URI changed, read it again", with no replay. The low-level server serves it with `Server(…, +on_subscriptions_listen=ListenHandler(bus))` and a `bus = InMemorySubscriptionBus()`; the service's loops `await +bus.publish(ResourceUpdated(uri))` for each URI above when it changes (repeats of an unchanged reading not sent), and +`ToolsListChanged()` when a sensor sends a field it never sent. Subscriptions match exact URIs, so clients subscribe to the bare URIs +the resource list gives. Only clients on the 2026-07-28 revision can listen; older ones read the resources and poll. ### 3.5 Prompts -The service also offers MCP prompts, the templates clients show as commands or buttons ("/rain", "Weather now"), each a question in -words with its period as an argument: `now`, `report` (now, the air, today's forecast and pollen), `chart` (a reading and a period), -`rain`, `air`. They hold no logic of their own: the client's model answers them with the tools, as any question. They replace the bot's -keyboard and `/commands` for clients that show prompts. +The service also offers MCP prompts, the templates clients show as commands or buttons, each a question in words with its period as an +argument: `now`, `report`, `will_it_rain`, `weather` (every reading, a panel each), `chart` (a reading and a period), `rain`, `air`. +They hold no logic: the client's model answers them with the tools, as any question. They replace the bot's keyboard and `/commands` +for clients that show prompts. ### 3.6 Alerts @@ -234,87 +317,106 @@ crossings, particulates (mask on, safe again), pollen and thunderstorm asthma, a cooldowns are the service's config, and their state its own store (`alert_state.json`, out of the bot's `bot_state.json`). Each runs on the triggers it has today: a new live reading or 5-minute row, a new forecast or pollen page, and its own clock (the weather alerts every 60 seconds, particulates every 30 minutes and only then, since its two-readings rule counts readings across checks). -- **An alert is an event:** `{id, kind, time, title, text, data, [chart]}`, the text ready to send ("🌧️ It's started raining: 0.4 mm - so far"), `data` the figures behind it, `chart` its chart data when it has one (gusts, UV, temperature, particulates). Each is - appended to `ecobot://alerts`, which pushes an update. +- **An alert is an event:** `{id, kind, time, expires, title, text, data, [link: {label, url}], [chart], [refresh: {tool, arguments}]}`. + `text` is ready to send ("🌧️ It's started raining: 0.4 mm so far"); `data` the figures behind it; `link` the page that goes with it + (the AirGradient dashboard for particulates, the pollen site for pollen); `chart` its chart data when it has one (gusts, UV, + temperature, particulates); `refresh` the call that draws that chart again with the latest readings (gusts: + `summary{readings: ["wind"], period: "last 24 hours", chart: true}`), so a client's 🔄 needs no knowledge of the kinds. +- **Alerts go stale:** `expires` is set by the rule (rain and gusts about an hour, UV its rearm time, particulates the next check, + pollen the end of its day, a forecast the day it is about), and `ecobot://alerts?since=` returns only unexpired alerts unless asked. + A client back after a gap sends what is still true, never the morning's rain as news. - **Delivery is the client's.** A client listens, reads `ecobot://alerts?since=`, and sends each alert to whoever - it serves. After a gap it reads from its last id, so nothing is lost while the alert is still in the 30-day log. Our bot does this - for its subscribed chats until it is retired. -- **The forecast alert is station-wide:** it compares a new forecast with the last one it alerted on, not with what each chat was - shown, which only the bot knew. -- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open; with the bot retired, alerts reach no - one unless a client that listens is set up (a few lines of Python with the SDK, or Home Assistant). Section 7. + it serves. Our bot does this for its subscribed chats until it is retired. +- **The forecast alert is station-wide:** for today and tomorrow, it compares each new forecast with the first one fetched after 6am + that day (its baseline), alerts when the maximum moves by more than 2°C or the chance of rain crosses 50%, and makes the forecast it + alerted on the new baseline. Its text says what changed ("The forecast for tomorrow has changed: was 24°C and dry, now 19°C with + rain likely"), not "since I sent it", which only the bot could say. +- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open; once the bot is retired, alerts reach + no one unless a client that listens is running (a short script with the SDK, or Home Assistant). Section 8. ### 3.7 Charts Charts are data: the client draws them, or its model does from the numbers. -- **The tools that draw** (`summary`, `days` with `group_by`, `relate`, `scan`, `chart`) build the chart as now (`specs.Chart`), next to - the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, panels: [{unit, - [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], [compass]}]}]`. - Times are ISO local times; a `source` names the devices ("Ecowitt weather station and AirGradient sensor"). -- **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (a week at hourly, a year at - daily-ish), the bands with it; a model can turn it into a plot with its own tools, and an application can draw it directly. Full - detail is `readings`. A JSON Schema for it is in the repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. +- **`summary` and `days` (with `group_by`) draw** (and `relate` and `scan` when asked); they build the chart as now (`specs.Chart`), next + to the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, panels: + [{unit, [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], [compass]}]}]`. + Times are ISO local times; `source` names the devices ("Ecowitt weather station and AirGradient sensor"). The JSON Schema is in the + repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. +- **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (the bands with it), so a model can turn + it into a plot with its own tools and an application can draw it directly. An application that draws for itself asks for more with + request `_meta` `chart_points` (at most 500, today's budget); the bot asks for 500, so its pictures and golden images don't change. + Full detail is `readings`. - **The note to the model:** a result with a chart says so in one line (`chart_note`: the chart's data is in `charts`; draw it if you can, and keep the text to the figures; don't describe the chart), so a model neither ignores it nor repeats every point. -- **When the chart is the answer, the reply comes ready.** `summary`, `days` and `chart` take `chart_answers_it`, described as "true - only when the question is just to see this chart and its figures: nothing else to answer" ("plot pressure this week", not "plot - pressure this week: is a storm coming?"). The model judges that; no regex does. When it is set and a chart is made, the result - carries a finished reply for the person (the period, each reading's high and low with when, any note about missing data) as a text - block annotated `audience: ["user"]` (MCP's mark for content meant for the person, not the model), and result `_meta` - `{"ecobot/complete": true}`. Only a client can save the model's second call, since it runs the model loop and MCP gives a server no - way to keep a result from a client's model; the service makes it one generic rule: *if a result is complete, send its user text and - its chart, and end the turn*. Our bot follows the rule while it lives, and any bot can; a client that doesn't (a desktop assistant) - gives the result to its model as usual, which then has the reply ready to repeat. A result with no chart, an error or a note that - needs the model's words is never complete. +- **When the chart is the answer, the reply comes ready.** `summary` and `days` take `chart_answers_it`, described as "true only when + the question is just to see this chart and its figures: nothing else to answer" ("plot pressure this week", not "plot pressure this + week: is a storm coming?"). The model judges that; no regex does. When it is set and a chart is made, the result carries a finished + reply for the person (the period, each reading's high and low with when, any note about missing data) as a text block annotated + `audience: ["user"]` (MCP's mark for content meant for the person, not the model), and result `_meta` `{"ecobot/complete": true}`. + Only a client can save the model's second call, since it runs the model loop and MCP gives a server no way to keep a result from a + client's model; the service makes it one generic rule: *if a result is complete, send its user text and its chart, and end the + turn*. Our bot follows the rule while it lives, and any bot can; a client that doesn't (a desktop assistant) gives the result to its + model as usual, which then has the reply ready to repeat. A result with no chart, an error or a note that needs the model's words is + never complete. - **Our bot**, while it lives, draws `charts` with its renderer (`lib/charts.py`, reading the JSON) and sends the picture; the rain caption reads its bars. The renderer leaves with the bot. ### 3.8 Connecting -- **Server:** the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built - when asked, so it follows the file's metrics. Served as Streamable HTTP (`streamable_http_app`) under uvicorn, behind TLS (a reverse - proxy such as Caddy, or uvicorn's own certificate), at `https:///mcp`, built with - `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)` (by default it answers only `Host: 127.0.0.1` or `localhost`, and - refuses the name a proxy or a LAN client uses). Also over stdio (`python -m ecobot_service --stdio`), for a desktop client on the - same machine as the file. +- **One program:** `python -m ecobot_service` runs the syncers, the alert rules and the server, at `https:///mcp` + (Streamable HTTP, `streamable_http_app`, under uvicorn behind TLS: a reverse proxy such as Caddy, or uvicorn's own certificate). The + server is the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built when + asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by + default it answers only `Host: 127.0.0.1` or `localhost`, and refuses the name a proxy or a LAN client uses. +- **Stdio, for a desktop client:** `python -m ecobot_service.bridge` is a thin bridge, an SDK client to the running service re-exposed + on stdio (tools, resources, prompts and the listen stream forwarded), with no syncers, no rules and no file of its own. A second + process on the readings file would duplicate the fetching and the alerts, and its in-memory bus would hear nothing. - **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` - (`name:token,…`, one per client, so one can be revoked alone), with `AuthSettings(resource_server_url=None)` so no OAuth metadata is - published. Bind to the LAN or a tailnet; nothing needs the internet to reach it. + (`name:token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://", + resource_server_url=None)` (`issuer_url` is required but unused without an OAuth provider; no OAuth metadata is published). Bind to + the LAN or a tailnet; nothing needs the internet to reach it. - **A client that listens** (our bot, an alert forwarder): `Client(…, mode="2026-07-28")`, pinning the protocol revision (the default - probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). In the SDK a connection failure on - any request ends the whole client, so one supervisor task owns it: it discards the client when it exits with a transport error or - the listen is lost or ends, builds a new one after a backoff, listens again and reads what it depends on. A read timeout of about 45 - seconds (three of the server's 15-second pings) notices a silently dead link. + probes, and a proxy's 502 during a restart can land it on the older revision, which cannot listen). A pinned client skips + `server/discover`, so it calls it once itself (`session.send_discover`, then `session.adopt`) to get the instructions and + capabilities. In the SDK a connection failure on any request ends the whole client, so one supervisor task owns it: it discards the + client when it exits with a transport error or the listen is lost or ends, builds a new one after a backoff, discovers and listens + again, and reads the alerts after its last id. A read timeout of about 45 seconds (three of the server's 15-second pings) notices a + silently dead link. ### 3.9 Irrigation, its own server -`lib/irrigation` and the irrigation check move to their own repository and MCP server, next to the valve. -- **Tools:** `irrigation_status` (battery, weather delay, running or not), `water` (minutes), `stop`, `delay` (`24h`, `cancel`), the - last three `destructiveHint`, so a client asks before it calls them. -- **The watchdog** (a run must end; a restart mid-run still closes the valve) and the daily check (pause when it rained or will) run - in that server whatever any client does. -- **Rain and forecast** come from the weather service, as its client: `summary{metrics: ["rainfall.rain"], period: "last 24 hours"}` - and `forecast`. When the weather service is unreachable, the check runs on the forecast it last had and skips the measured rain. -- **Its alerts** (battery low, paused for rain) are its own `irrigation://alerts`, in the same shape. +`lib/irrigation` and the irrigation check move to their own repository and MCP server, next to the valve, once the weather service runs +on its own (step 5). +- **Tools:** `irrigation_status` (battery, weather delay, running or not), `water` (minutes; refused while a weather delay is on, with an + error that says so), `stop`, `delay` (`24h`, `48h`, `72h`, `cancel`); the last three `destructiveHint`, so a client asks before it + calls them. +- **The watchdog** (a run must end; a restart mid-run still closes the valve) and the daily check (pause when it rained or will) run in + that server whatever any client does. +- **Rain and forecast** come from the weather service, as its client: the measured rain from `summary{readings: ["rain"], period: "last + 24 hours"}`, the forecast from `ecobot://forecast` (its days' chance of at least 1 mm and `fetched_at`). When the weather service is + unreachable, the check runs on the forecast it last read and skips the measured rain. +- **Its alerts** (battery low, paused for rain) are its own `irrigation://alerts`, in the same shape; a client listens to both servers. ### 3.10 Configuration `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the -station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. -The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, its own `MCP_TOKENS`. +station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `CHART_ALL_FEELS_LIKE`, `CHART_ALL_VPD`, +`MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, +its own `MCP_TOKENS`. ## 4. The bot until it is retired The bot is the service's first client, and the measure of each step: it keeps answering in Telegram while its insides move to the -service. It gets no new features. While it lives it: -- connects to the service over MCP and offers the model the service's tools and instructions as they are, adding only its persona - (a friendly Telegram bot, plain text, bullets, the caption length a photo allows); +service. Beyond what the steps need, it gets no new features. While it lives it: +- offers the model the service's tools as they are, with the server's instructions, adding only its persona (a friendly Telegram bot, + plain text, bullets, the caption length a photo allows); - ends the turn on a complete result (3.7), sending the ready reply and the chart without a second model call; - keeps a few shortcuts for its buttons and commonest typed requests (a named reading's chart and a period, weather now, the report, the gauges), each a fixed call to a service tool whose result is already worded, so it writes nothing itself; - draws `charts` and the gauges (`current` with `context`) with its renderer; -- listens to `ecobot://alerts` and sends each alert to the chats subscribed to its kind, with its chart; +- listens to `ecobot://alerts` (and, from step 5, `irrigation://alerts`) and sends each alert to the chats subscribed to its kind, with + its chart, its link and a 🔄 that calls its `refresh`; +- builds `/usage`, Help and its alert menu from `ecobot://station` (and whether an irrigation server is configured); - keeps per-chat state: subscriptions, admins, the chart questions behind its period buttons. It is retired when a replacement does what you use it for: another client for questions (any MCP-capable assistant), and, for alerts, @@ -328,67 +430,69 @@ themselves; the charts' content. ## 6. Steps -Each step ships on its own, with the tests and evals green and the bot working the whole way. The tool list never offers old and new -names together. +Each step ships on its own, with the tests and evals green and the bot working the whole way. The model's tool list changes once +(step 3): old and new names are never offered together, and no tool interface is rewritten before it is replaced. -0. **Fixes that belong to the service anyway**, in today's code: - - **The chart that answers itself** (3.7): `chart_answers_it` on `weather_history`, `air_quality` and the day tools, the finished - reply and the complete mark in the result, and the bot's early end of the turn on it; a pair of eval cases (a question that is - just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the live evals; the - log's `LLM 2` lines show the calls it saves. - - **Part of each day** (3.3, `days.hours`): `hours` on `weather_days` and `air_days`, with tests against stretches worked out by hand - (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a - night with rain in the evening only, an air glitch inside the stretch) and eval cases ("average 3pm temperature in October", - "typical overnight low this month", "nights below 5°C this week"). +0. **Fixes the service needs anyway**, in today's code: + - **Part of each day** (3.3): the engine (stretches through `Reader.part_days`, rain over a stretch, the coverage choice) with tests + against stretches worked out by hand (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, + a day held only as daily records, a night with rain in the evening only, an air glitch inside the stretch). The `hours` argument + comes with `days` (step 2). - **Averages weighted by time** (3.3): `weather_history`'s and `air_quality`'s averages over the period's time, not its days or its rows, and rain rate's average; tests with a part day at each end and an air period across its hourly history. -1. **Explicit arguments, worded results.** The twelve tools take the `Turn`'s inputs as arguments and read nothing else about the - question; they return their charts in the result (3.7) instead of appending to `turn.charts`. Results gain the wording the bot writes - today (`lib/report.py`'s lines and captions, the day emoji), and the bot quotes them instead of writing its own. So that this step - changes no answer, today's corrections from the words move out of the tools into the bot, which applies them to the model's calls on - the way in, as before; step 3 removes them. -2. **The guidance moves to the service.** Periods in words (`lib/periods_text.py`, tested against the bot's period hints for every - phrase they handle); the server instructions and the tool descriptions take over the prompt's knowledge (2.3); the bot's prompt keeps - only its persona. The evals run each question with only the instructions and the tool list, as any client would. -3. **The nine tools.** The tools of 3.3 with their result shapes; the bot's shortcuts and its alert charts move to them; the twelve go, - and with them the bot's corrections from the words, which come back only for a case that then fails. Shipped only when the live - evals (all cases) do as well as before, with the production model and one other. -4. **Alerts in the service.** The rules, their state and config move service-side and append to the alert log; the bot delivers from - the log. `current` gains `context` and the gauges come from it. -5. **MCP.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus, the low-level server, the transport settings, the - token check, stdio); the bot becomes an MCP client over the network (the supervisor, `charts` from results, the alert log). The - evals read the server's own tool list. The irrigation server is built in its own repository and the bot's irrigation buttons call - it; `lib/irrigation` goes from here. -6. **Two programs.** The service starts on its own (`python -m ecobot_service`), with its compose file; the bot connects to it. The - service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, - `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. -7. **The bot retired** (section 4), its code and tests deleted; the repository is the service. + - **The chart that answers itself** (3.7): `chart_answers_it` on `weather_history`, `air_quality` and the day tools, the finished + reply (today's `report.chart_caption`) and the complete mark in the result, and the bot's early end of the turn on it; an eval pair + (a question that is just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the + live evals; the log's `LLM 2` lines show the calls it saves. It carries over to `summary` and `days` in step 2. +1. **Charts as data, periods in words.** The chart builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON + (at 500 points, so the golden images don't change). `lib/periods_text.py` reads the periods table, tested by hand against it at fixed + times (a Monday, a Tuesday, the 1st of a month, 1 January, 29 February, 00:30, both clock-change days), with whole-day tools cut to + yesterday and errors for phrases outside the table and for the future. No tool interface changes. +2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready + lines, captions), charts, descriptions and errors, and `lib/outlook.py`; offered to no model yet. Contract tests; the evals run + against them with the tool list alone. The bot's own code paths move to them: its shortcuts, report, lookups, period buttons, + gauges and alert charts. +3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the + instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period + hints, the prefetch and the corrections from the words go. +4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, + `link`, `chart` and `refresh`; the forecast alert gets its station-wide baseline. The bot delivers from the log. +5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the + transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the + stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the + alert log). Then the irrigation server is built in its own repository against it, the bot connects to both, and `lib/irrigation` + goes from here. The service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, + `conditions`, `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. +6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. ## 7. Testing -- **Any model can use it.** The evals are the service's: each question is asked of a model given only the server's instructions and - tool list (no prompt of ours), and checked for the tools and arguments it picks and, where it matters, the answer. They run against - the production model and at least one other, so the interface isn't tuned to one model's habits. -- **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`), periods in - words against their dates (every phrase, a clock change, the first of a month and a year), charts against their schema. +- **Any model can use it.** The evals are the service's: each question is asked of a model given only the tool list (no prompt of + ours), and again with the server's instructions, and checked for the tools and arguments it picks and, where it matters, the answer. + They run against the production model and at least one other, so the interface isn't tuned to one model's habits. The cases carry + over from `tests/evals/cases.json`, with their periods checked as the service reads them, and gain one for each periods form, each + routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. +- **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods + table at its fixed times (step 1); charts against their schema; `day_look` against its rule. - `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row for every day held whole at 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; a day from a daily record, or from whatever readings there were, is left out and counted. - **Alerts:** the rules' tests move with them; the log keeps order and survives a restart; a client that reconnects reads what it - missed, once. + missed, once, and nothing that has expired; the forecast alert's baseline. - **A client that listens:** against the real app under uvicorn on a localhost port the test stops and starts (not in memory: a connection can't fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the client listens again - and reads the alerts after its last id. + and reads the alerts after its last id; the bot's model request carries the instructions from discover. - **A deploy check:** a tool call through the proxy's name succeeds (the allowed hosts and the token). ## 8. Risks - **Alerts reach only listening clients.** With alerts over MCP only (3.6), once the bot is retired nobody gets them unless a client - that listens is running. Plan that client before step 7, or accept no alerts. -- **Charts only where a client can draw.** A client that neither renders the chart data nor lets its model draw gets the figures - without a picture. -- **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on: the guidance - in the server and the evals across models are the defence, and every answer still rests on figures the model quotes, not works out. + that listens is running. Plan that client before step 6, or accept no alerts. +- **Charts only where a client can draw.** A client that neither draws the chart data nor lets its model draw gets the figures without + a picture. +- **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on; some clients + never pass the instructions on. The descriptions and results as the contract, and the evals across models with and without the + instructions, are the defence, and every answer still rests on figures the model quotes, not works out. - **Every question through a model.** Without the bot's shortcuts each question costs at least one model call; that is the client's choice and cost. A chart that answers the question costs only one where the client ends the turn on a complete result (3.7). - **A chart sent without the answer.** If a model sets `chart_answers_it` on a question that needed words, the person gets the chart From 50ec83d08bae3e28a1ea07a157ef743797072876 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:11:38 +0000 Subject: [PATCH 014/125] Part of each day: the engine (lib/partday.py), no tool uses it yet Step 0 of docs/mcp-service.md (3.3, "Part of each day"): a sensor's figures over one stretch of local time on each day of a period, worked out as a day row is, so step 2's days.hours can find, rank and count nights, mornings or the 3pm reading as it does days. - parse_stretch reads night, morning, afternoon, evening, daytime, two times on the half hour ("22:30-06:00"), or a moment ("15:00", "15:00-15:05"); anything else is a ValueError that says what is allowed. - One window a day, [start, end) in local wall time, read by Reader.part_days as start to end - 1: "24:00" is the next midnight, a night starts the evening before and belongs to the day it ends on, a time the clocks skip is the moment they jump (so October's 02:00-03:00 is left out), a time that happens twice is the first. - Each day is read at the first of its day rows' resolutions the coverage holds whole (the station's 5 then 30 minutes, the air sensor's 5 minutes then hourly; never the minutes); held at neither, it is left out and why; held with no readings, it is missing. A moment on a 30-minute or hourly day is the half hour or hour that holds it, and the note says so. - The rain counters are the mm that fell in the stretch (the running daily total's rise, the midnight reset counted, by rain_slots), not part_days' highest, which would be the rain since midnight. - over() says whether a day's stretch has ended, so a caller can count today. Tests worked out by hand: a night across midnight, both Melbourne clock changes, moments on 5-minute, 30-minute and hourly days, days from daily records, partly held or with no readings, rain in the evening only, an air glitch inside the stretch, and "00:00-24:00" against the day rows for the station and the air sensor at each resolution. Over a year of 5-minute readings (tests/bench_cache.py) a night of every day takes about 0.2 s for the outdoor sensor, 0.25 s for the rain gauge, 0.8 s for the air sensor. No behaviour changes: nothing calls it until step 2. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/partday.py | 245 ++++++++++++++++++++++++++++++++++++++++++ tests/test_partday.py | 244 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 489 insertions(+) create mode 100644 lib/partday.py create mode 100644 tests/test_partday.py diff --git a/lib/partday.py b/lib/partday.py new file mode 100644 index 00000000..d0f61d2f --- /dev/null +++ b/lib/partday.py @@ -0,0 +1,245 @@ +"""Part of each day (docs/mcp-service.md 3.3): a sensor's figures over one stretch of local time on each day of a period, worked out as a +day row is from a whole day's readings (lib/storage/days.py), so the overnight low, the nights below 5°C or the 3pm temperature can be +found, ranked and counted as days are. + +- **A stretch** is named (night 22:00–06:00, morning 06:00–12:00, afternoon 12:00–18:00, evening 18:00–24:00, daytime 06:00–18:00), two + times on the half hour ("15:00-16:00", "22:30-06:00"), or a moment: one time on the hour or half hour ("15:00", or "15:00-15:05"). + Times are on the half hour because a 30-minute reading's own lowest and highest run to the end of its half hour: part of one would + count as all of it. +- **One window a day**, [start, end) in local wall time, read as start to end - 1 (the SQL's BETWEEN takes in its end). "24:00" is the + next local midnight, so a whole day is 23 or 25 hours on a clock-change day. A stretch that crosses midnight starts the evening before + and belongs to the day it ends on (Monday 22:00 to Tuesday 06:00 is Tuesday's night). A time the clocks skip is the moment they jump, + so a stretch the October change removes (02:00–03:00 on its Sunday) has no time and is left out; a time that happens twice is the + first. +- **Which readings:** each day's window at the first of the day rows' own resolutions that holds all of it (the coverage): the station's + 5-minute, then 30-minute readings; the air sensor's 5-minute, then hourly ones; never the minutes. Held at neither (a day held only as + Ecowitt's daily or 4-hour records, a night whose evening is before the 30-minute archive): left out. Held but with no readings (the + station was off): missing. Nothing falls back to whatever readings there are, as a period's part days do (ecowitt/period.py). +- **A moment** is the 5-minute reading at that time; on a day held only at 30 minutes it is the half hour from it, on the air sensor's + hourly days the hour that holds it, and the note says so. +- **The figures** are the day rows' own SQL over the windows (Reader.part_days, one query for them all): a stretch's mean (of its half + hours'), lowest, highest and when those happened are worked out as a whole day's are, the air sensor's glitches taken out. Except the + rain counters: a day's rain is the highest of its running total, which over a stretch would be the rain since midnight up to its end. + Over a stretch each counter (they all count the one gauge) is the mm that fell in it, the running daily total's rise from the last + reading before the stretch to its last one in it, a fall counted as the midnight reset (lib/rain.rain_slots, as the readings tool + works it out). + +The cost, over a year of 5-minute readings (tests/bench_cache.py): a night of every day takes about 0.2 s for the outdoor sensor, 0.25 s +for the rain gauge and 0.8 s for the air sensor with its glitch rule (30 nights under 0.07 s); a moment 0.05 s; the whole day 0.55, 0.6 +and 2.5 s. The day rows take 0.005 s, so a caller wanting whole days reads those. +""" + +import re +from bisect import bisect_left +from collections import Counter +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta, tzinfo + +from .rain import MAX_GAP, rain_slots +from .storage import Sensor +from .storage.catalogue import RAIN_COUNTERS +from .storage.coverage import merge +from .storage.read import Days, Reader +from .timeutil import local_epoch, naive_local + +DAY = 24 * 60 # minutes +MOMENT = 5 # a moment is one 5-minute reading: "15:00" is "15:00-15:05" +NAMED = {"night": (22 * 60, 6 * 60), "morning": (6 * 60, 12 * 60), "afternoon": (12 * 60, 18 * 60), "evening": (18 * 60, DAY), + "daytime": (6 * 60, 18 * 60)} +ALLOWED = ("night (22:00-06:00), morning (06:00-12:00), afternoon (12:00-18:00), evening (18:00-24:00), daytime (06:00-18:00), two times " + "on the half hour ('15:00-16:00', '22:30-06:00'; '24:00' is the midnight that ends the day), or a moment on the hour or half " + "hour ('15:00')") +TIMES = re.compile(r"(\d{1,2}):(\d\d)(?:\s*(?:-|–|—|to)\s*(\d{1,2}):(\d\d))?") +STATION = ("5min", "30min") # what a stretch is read from, finest first, as the day rows are +FROM = {"air": ("5min", "1hour")} # ... where a sensor's day rows differ +SECONDS = {"5min": 300, "30min": 1800, "1hour": 3600} +COARSE = {"30min": ("30-minute averages", "the half hour from it"), "1hour": ("hourly averages", "the hour that holds it")} + +NOT_HELD = "not held finely enough" # why a day is left out: held at neither resolution (daily or 4-hour records only) +CLOCK_CHANGE = "removed by the clock change" +NOT_OVER = "not over yet" + + +def _clock(minutes: int) -> str: + return f"{minutes // 60:02d}:{minutes % 60:02d}" + + +@dataclass(frozen=True) +class Stretch: + """A stretch of each day's local time, in minutes after midnight: an `end` of DAY is the next midnight, and one before the start + crosses midnight (the stretch starts the evening before). One five minutes long is a moment.""" + start: int + end: int + name: str | None = None + + @property + def moment(self) -> bool: + return self.end == self.start + MOMENT + + @property + def overnight(self) -> bool: + return self.end < self.start + + @property + def text(self) -> str: + """The stretch as a result states it: "night (22:00–06:00)", "15:00–16:00", "15:00".""" + times = _clock(self.start) if self.moment else f"{_clock(self.start)}–{_clock(self.end)}" + return f"{self.name} ({times})" if self.name else times + + +def _minutes(hours: str, minutes: str) -> int | None: + """"15:30" as minutes after midnight ("24:00" the next midnight); None for a time that is no time.""" + found = int(hours) * 60 + int(minutes) + return found if int(minutes) < 60 and found <= DAY else None + + +def parse_stretch(text: str) -> Stretch: + """The stretch these words name (ALLOWED says which); ValueError, saying what is allowed, for anything else.""" + words = " ".join(str(text).lower().split()) + if words in NAMED: + return Stretch(*NAMED[words], words) + if found := TIMES.fullmatch(words): + start = _minutes(found[1], found[2]) + end = _minutes(found[3], found[4]) if found[3] else None if start is None else start + MOMENT + end = DAY if end == 0 else end # ("18:00-00:00" runs to midnight) + if (start is not None and end is not None and start < DAY and start % 30 == 0 and end != start + and (end % 30 == 0 or end == start + MOMENT)): + return Stretch(start, end) + raise ValueError(f"{str(text)!r} is not a part of the day I can read: use {ALLOWED}") + + +# ---------- each day's window ---------- +def clock_time(day: date, minutes: int, tz: tzinfo) -> tuple[int, bool]: + """(the epoch at which the clock on `day` first reads this time, in minutes after its midnight (DAY: the next midnight, as day_bounds + has it), and whether it reads it at all): a time the clocks skip is the moment they jump, the first whose clock reads later.""" + local = datetime.combine(day, time()) + timedelta(minutes=minutes) + t = local_epoch(local, tz) # (the first, in the hour that happens twice) + if naive_local(t, tz) == local: + return t, True + early = local_epoch(local.replace(fold=1), tz) # (a skipped time told with the offset after the jump: a moment before it) + while t - early > 1: + middle = (early + t) // 2 + early, t = (early, middle) if naive_local(middle, tz) >= local else (middle, t) + return t, False + + +def window(stretch: Stretch, day: date, tz: tzinfo, res: str = "5min") -> tuple[int, int] | None: + """[start, end) (epochs) of the day's stretch read at this resolution, or None where the clock change removes it. A moment is the + reading that holds it: its 5 minutes, half hour or hour.""" + if stretch.moment: + t, real = clock_time(day, stretch.start, tz) + t -= t % SECONDS[res] + return (t, t + SECONDS[res]) if real else None + start = clock_time(day - timedelta(days=1) if stretch.overnight else day, stretch.start, tz)[0] + end = clock_time(day, stretch.end, tz)[0] + return (start, end) if end > start else None + + +def over(stretch: Stretch, day: date, tz: tzinfo, now: float) -> bool: + """Has the day's stretch ended by `now` (epoch)? A caller counts today once it has: asked at 7am, last night is over.""" + return clock_time(day, stretch.end, tz)[0] <= now + + +def _plan(r: Reader, kind: str, sensor: int, stretch: Stretch, day: date, tz: tzinfo, now: float) -> tuple[str, int, int] | str: + """(the resolution the day's stretch is read at, its start, its end), or why the day is left out.""" + if window(stretch, day, tz) is None: + return CLOCK_CHANGE + for res in FROM.get(kind, STATION): + start, end = window(stretch, day, tz, res) + if end > now: + return NOT_OVER + if r.held(sensor, res, start, end - 1): + return res, start, end + return NOT_HELD + + +# ---------- the figures ---------- +@dataclass +class PartDays: + """A sensor's figures over a stretch of each day of a period (stretch_figures).""" + stretch: Stretch + days: Days = field(default_factory=Days) # the days worked out, oldest first, each as a day row has it: per reading its mean, lowest + # and highest and when those happened, `n`, and in `source` the resolution read + windows: dict[date, tuple[int, int]] = field(default_factory=dict) # each day read: its window, [start, end) epochs + left_out: dict[date, str] = field(default_factory=dict) # the days not read, and why (NOT_HELD, CLOCK_CHANGE, NOT_OVER) + missing: list[date] = field(default_factory=list) # the days held but with no readings (the station was off) + + @property + def note(self) -> str | None: + """What a moment was on the days held too coarsely for its 5-minute reading, else None.""" + coarse = Counter(res for res in self.days.source if res in COARSE) + if not self.stretch.moment or not coarse: + return None + return f"{self.stretch.text} is the 5-minute reading at that time; " + "; ".join( + f"on {n} day{'' if n == 1 else 's'} held only as {COARSE[res][0]}, {COARSE[res][1]}" for res, n in sorted(coarse.items())) + "." + + +def stretch_figures(r: Reader, kind: str, sensor: Sensor | int, first: date, last: date, stretch: Stretch | str, + columns: list[str] | None, tz: tzinfo, now: float) -> PartDays: + """A sensor's figures over the stretch on each day from first to last (a night belongs to the day it ends on), these columns of its + kind (None: all): one query for the figures, and for the rain counters a look at the running total around each stretch. On the + reader's thread (Storage.read). A day whose stretch has not ended by `now` (epoch) is left out.""" + stretch = parse_stretch(stretch) if isinstance(stretch, str) else stretch + sensor = sensor if isinstance(sensor, int) else sensor.id + out, plans = PartDays(stretch), {} + for n in range((last - first).days + 1): + day = first + timedelta(days=n) + plan = _plan(r, kind, sensor, stretch, day, tz, now) + if isinstance(plan, str): + out.left_out[day] = plan + else: + plans[day], out.windows[day] = plan, plan[1:] + got = r.part_days(kind, [(sensor, day, start, end - 1, res) for day, (res, start, end) in plans.items()], columns).get(sensor) + if got is not None: + got.complete = [True] * len(got.day) # (each held whole at the resolution it was read at) + _rain(r, kind, sensor, got, plans) + out.days = got + read = set(out.days.day) + out.missing = [day for day in plans if day not in read] + return out + + +def _rain(r: Reader, kind: str, sensor: int, days: Days, plans: dict[date, tuple[str, int, int]]): + """The rain counters' figures over each stretch: the mm that fell in it, from the running daily total whichever counter it is (in + `hi`, where a day row has the day's total), and when the last of it fell (`hi_ts`; None when none did). A total has no mean or + lowest.""" + counters = [c for c in days.hi if c in RAIN_COUNTERS] + if not counters: + return + spans = merge([(start - MAX_GAP, end - 1) for _, start, end in plans.values()]) # (only what the stretches need: a night is a third) + totals = {} + for res in STATION: # (both: the reading before a stretch may be at the other) + ts, values = [], [] + for start, end in spans: + if got := r.rows(kind, [sensor], res, start, end, ["daily"]).get(sensor): + ts += got.ts + values += got.values["daily"] + totals[res] = ts, values + for i, day in enumerate(days.day): + mm, when = _fell(totals, *plans[day]) + for c in counters: + days.mean[c][i] = days.lo[c][i] = days.lo_ts[c][i] = None + days.hi[c][i], days.hi_ts[c][i] = mm, when + + +def _fell(totals: dict[str, tuple[list[int], list[float]]], res: str, start: int, end: int) -> tuple[float | None, int | None]: + """(the mm that fell in [start, end), when the last of it fell) from the running daily totals read at `res`: its rise from the last + reading before the stretch (at the other resolution where `res` has none close enough) to its last reading in it. None for a stretch + with no totals.""" + ts, values = totals[res] + i, j = bisect_left(ts, start), bisect_left(ts, end) + if i == j: + return None, None + running = dict(zip(ts[i:j], values[i:j])) + for other in (res, *(o for o in totals if o != res)): + before, held = totals[other] + k = bisect_left(before, start) - 1 + if k >= 0 and before[k] >= start - MAX_GAP: + running[before[k]] = held[k] + break + fell = {t: mm for t, mm in rain_slots(running).items() if t >= start} + return round(sum(fell.values()), 3), max((t for t, mm in fell.items() if mm > 0), default=None) + + +__all__ = ["CLOCK_CHANGE", "NAMED", "NOT_HELD", "NOT_OVER", "PartDays", "Stretch", "clock_time", "over", "parse_stretch", + "stretch_figures", "window"] diff --git a/tests/test_partday.py b/tests/test_partday.py new file mode 100644 index 00000000..05a50c20 --- /dev/null +++ b/tests/test_partday.py @@ -0,0 +1,244 @@ +"""Part of each day (lib/partday.py): a sensor's figures over a stretch of each day, checked against stretches worked out by hand on a +small file, and for the whole day against the day rows.""" + +import random +from datetime import date, datetime, time, timedelta + +import pytest + +from lib.partday import CLOCK_CHANGE, NOT_HELD, NOT_OVER, SECONDS, Stretch, over, parse_stretch, stretch_figures +from lib.storage import Storage +from lib.storage.catalogue import CLOUD, RAIN_COUNTERS +from lib.storage.days import utc_days +from lib.storage.read import DAY_PARTS +from lib.timeutil import day_bounds, local_epoch +from tests.fakes import TZ + +MAC, LOC = "M", "42" +NOW = local_epoch(datetime(2026, 11, 10, 14, 5), TZ) # Tue 10 Nov 2026 2:05pm +DAY = timedelta(days=1) + + +def at(d: date, hour: int, minute: int = 0) -> int: + """The epoch of a local time (the first, in the hour that happens twice).""" + return local_epoch(datetime.combine(d, time(hour, minute)), TZ) + + +@pytest.fixture +def storage(tmp_path): + s = Storage(tmp_path / "ecobot.sqlite", TZ) + yield s + s.close() + + +def put(storage, group: str, res: str, rows: list[dict], start: int, end: int): + """Readings written as a source writes them (an Ecowitt group's, or the air sensor's: "air"), [start, end] held at `res`.""" + def write(w): + s = w.air_sensor(LOC) if group == "air" else w.ecowitt_sensor(MAC, group) + w.put(s, res, rows, CLOUD) + w.cover(s, res, start, end) + return s + return storage.writer.run(write, ()) + + +def figures(storage, sensor, first: date, last: date, stretch: str, columns: list[str] | None = None, now: int = NOW): + return storage.reader.run(lambda r: stretch_figures(r, sensor.kind, sensor, first, last, stretch, columns, TZ, now), ()) + + +# ---------- the stretches ---------- +def test_a_stretch_is_named_two_times_on_the_half_hour_or_a_moment_and_anything_else_says_what_is_allowed(): + assert parse_stretch(" Night ") == Stretch(22 * 60, 6 * 60, "night") and parse_stretch("night").overnight + assert [(parse_stretch(n).start, parse_stretch(n).end) for n in ("morning", "afternoon", "evening", "daytime")] == [ + (360, 720), (720, 1080), (1080, 1440), (360, 1080)] + assert parse_stretch("22:30-06:00") == Stretch(1350, 360) and parse_stretch("22:30-06:00").overnight + assert parse_stretch("18:00-00:00") == parse_stretch("18:00-24:00") == Stretch(1080, 1440) # to midnight, not the evening before + assert parse_stretch("15:00") == parse_stretch("15:00-15:05") == Stretch(900, 905) and parse_stretch("15:00").moment + assert parse_stretch("night").text == "night (22:00–06:00)" and parse_stretch("15:30").text == "15:30" + for wrong in ("15:10", "15:00-15:10", "15:00-15:07", "3pm", "24:00-02:00", "06:00-06:00", "15:60", "25:00", "dawn", ""): + with pytest.raises(ValueError, match=r"night \(22:00-06:00\).*a moment on the hour or half hour"): + parse_stretch(wrong) + + +def test_today_counts_once_its_stretch_is_over(storage): + today = date(2026, 11, 10) + night, three = parse_stretch("night"), parse_stretch("15:00") + assert not over(night, today, TZ, at(today, 5, 59)) and over(night, today, TZ, at(today, 6)) + assert not over(three, today, TZ, at(today, 15, 4)) and over(three, today, TZ, at(today, 15, 5)) + seven = at(today, 7) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 9.0} for t in range(at(today - DAY, 12), seven, 300)], + at(today - DAY, 12), seven - 1) + assert figures(storage, s, today, today, "night", now=seven).days.day == [today] # last night, asked this morning + assert figures(storage, s, today, today, "morning", now=seven).left_out == {today: NOT_OVER} + + +# ---------- the figures ---------- +def test_a_night_starts_the_evening_before_and_belongs_to_the_day_it_ends_on(storage): + mon, tue = date(2026, 11, 2), date(2026, 11, 3) + coldest = at(tue, 4, 30) + temp = lambda t: round(2 + abs(t - coldest) / 3600, 2) # 2° at 4:30am, a degree warmer for each hour either side + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": temp(t)} for t in range(at(mon, 0), at(tue, 12), 300)], + at(mon, 0), at(tue, 12) - 1) + got = figures(storage, s, mon, tue, "night", ["temperature"]) + assert got.left_out == {mon: NOT_HELD} # (Monday's night began on Sunday evening, which isn't held) + assert got.windows == {tue: (at(mon, 22), at(tue, 6))} and got.missing == [] + days, night = got.days, [temp(t) for t in range(at(mon, 22), at(tue, 6), 300)] + assert (days.day, days.source, days.complete, days.n) == ([tue], ["5min"], [True], [96]) + assert (days.lo["temperature"], days.lo_ts["temperature"]) == ([2.0], [coldest]) + assert (days.hi["temperature"], days.hi_ts["temperature"]) == ([8.5], [at(mon, 22)]) # not 9:55pm's 8.58: before the night + assert days.mean["temperature"] == [pytest.approx(sum(night) / len(night))] + + +def test_the_clock_changes_make_a_night_9_or_7_hours_and_the_hour_october_skips_is_left_out(storage): + april, october = date(2026, 4, 5), date(2026, 10, 4) # Melbourne: 2am happens twice, then 2am is 3am + for d in (april, october): + start, end = at(d - DAY, 0), at(d + DAY, 0) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 10.0 + (t - start) / 3600} for t in range(start, end, 300)], + start, end - 1) + night = figures(storage, s, april, october, "night") + assert night.days.day == [april, october] and night.days.n == [9 * 12, 7 * 12] + assert set(night.left_out.values()) == {NOT_HELD} + skipped, twice = (figures(storage, s, d, d, "02:00-03:00") for d in (october, april)) + assert (skipped.left_out, skipped.days.day) == ({october: CLOCK_CHANGE}, []) + assert twice.days.n == [24] and twice.windows[april] == (at(april, 2), at(april, 3)) # 2:00 AEDT to 3:00 AEST: both of its 2ams + part = figures(storage, s, october, october, "01:30-02:30") # what is left of it: 1:30 to the jump + assert part.days.n == [6] and part.windows[october] == (at(october, 1, 30), at(october, 3)) + assert figures(storage, s, october, october, "02:30").left_out == {october: CLOCK_CHANGE} + first = figures(storage, s, april, april, "02:30") # the first 2:30 of the two + assert first.windows[april] == (at(april, 2, 30), at(april, 2, 30) + 300) and first.days.n == [1] + + +def test_a_moment_is_the_5_minute_reading_at_that_time_or_on_a_coarser_day_the_half_hour_or_hour_that_holds_it(storage): + coarse, fine = date(2026, 11, 2), date(2026, 11, 3) + a, b = day_bounds(fine, TZ, True) + s = put(storage, "outdoor", "5min", [{"ts": t, "temperature": 10 + (t - a) / 30000} for t in range(a, b, 300)], a, b) + a, b = day_bounds(coarse, TZ, True) + put(storage, "outdoor", "30min", [{"ts": t, "temperature": 20 + i, "temperature_lo": 19.5 + i, "temperature_hi": 21 + i} + for i, t in enumerate(range(a, b, 1800))], a, b) + got = figures(storage, s, coarse, fine, "15:00") + days = got.days + assert days.day == [coarse, fine] and days.source == ["30min", "5min"] and days.n == [1, 1] + assert got.windows == {coarse: (at(coarse, 15), at(coarse, 15, 30)), fine: (at(fine, 15), at(fine, 15, 5))} + assert days.mean["temperature"] == [50.0, pytest.approx(10 + 15 * 3600 / 30000)] # (not 3:05's) + assert days.lo["temperature"] == [49.5, pytest.approx(10 + 15 * 3600 / 30000)] + assert days.hi["temperature"] == [51.0, pytest.approx(10 + 15 * 3600 / 30000)] # the half hour's own lowest and highest + assert days.hi_ts["temperature"] == [at(coarse, 15), at(fine, 15)] + assert got.note == "15:00 is the 5-minute reading at that time; on 1 day held only as 30-minute averages, the half hour from it." + a, b = day_bounds(coarse, TZ, True) + air = put(storage, "air", "1hour", [{"ts": t, "pm2_5": float(i)} for i, t in enumerate(range(a, b, 3600))], a, b) + hourly = figures(storage, air, coarse, coarse, "15:30") + assert hourly.windows == {coarse: (at(coarse, 15), at(coarse, 16))} and hourly.days.mean["pm2_5"] == [15.0] + assert "on 1 day held only as hourly averages, the hour that holds it" in hourly.note + assert figures(storage, s, fine, fine, "15:00").note is None + + +def test_a_day_held_only_as_daily_records_or_in_part_is_left_out_and_one_held_with_no_readings_is_missing(storage): + old, off, part = date(2025, 3, 10), date(2025, 3, 11), date(2025, 3, 12) + first, last = utc_days(old, TZ) + with storage.writer.transaction() as w: + s = w.ecowitt_sensor(MAC, "outdoor") + w.put(s, "1day", [{"ts": first, "temperature": 15.0, "temperature_lo": 8.0, "temperature_hi": 22.0}]) + w.put(s, "4hour", [{"ts": first + 4 * 3600 * i, "temperature": 15.0} for i in range(6)]) + w.cover(s, "1day", first, last + 86400 - 1) + w.cover(s, "4hour", first, last + 86400 - 1) + w.cover(s, "5min", *day_bounds(off, TZ, True)) # the station was off + w.put(s, "5min", [{"ts": t, "temperature": 11.0} for t in range(at(part, 0), at(part, 12), 300)]) + w.cover(s, "5min", at(part, 0), at(part, 12) - 1) # the morning held, the afternoon not + assert storage.reader.run(lambda r: r.days("climate", [s.id], old, old)[s.id].source, ()) == ["1day"] # (a day row, all the same) + got = figures(storage, s, old, part, "00:00-24:00") + assert got.left_out == {old: NOT_HELD, part: NOT_HELD} and got.missing == [off] and got.days.day == [] + assert figures(storage, s, part, part, "morning").days.n == [72] + + +def test_rain_over_a_stretch_is_what_fell_in_it_not_the_running_total_since_midnight(storage): + mon, tue, wed = date(2026, 11, 2), date(2026, 11, 3), date(2026, 11, 4) + fell = {at(mon, 18) + 300 * i: 0.2 for i in range(30)} # 6 mm on Monday evening, then dry all night + fell |= {at(tue, 15) + 300 * i: 0.2 for i in range(5)} # 1 mm on Tuesday afternoon + fell |= {at(tue, 23) + 300 * i: 0.1 for i in range(5)} # 0.5 mm late on Tuesday evening ... + fell |= {at(wed, 2) + 300 * i: 0.1 for i in range(3)} # ... and 0.3 after midnight + start, end = at(mon, 0), at(wed, 12) + rows, total = [], 0.0 + for t in range(start, end, 300): + total = (0.0 if t in (at(tue, 0), at(wed, 0)) else total) + fell.get(t, 0.0) # the daily total, from 0 at midnight + rows.append({"ts": t, "daily": round(total, 1), "rain_rate": 2.4 if t in fell else 0.0}) + s = put(storage, "rainfall", "5min", rows, start, end - 1) + nights = figures(storage, s, tue, wed, "night", ["daily", "rain_rate"]).days + assert nights.hi["daily"] == [0.0, pytest.approx(0.8)] # not Monday's 6 mm, held all night as the day's total + assert nights.hi_ts["daily"] == [None, at(wed, 2, 10)] and nights.mean["daily"] == nights.lo["daily"] == [None, None] + assert nights.hi["rain_rate"] == [0.0, 2.4] # (the rest as a day row has them) + window = (s.id, tue, at(mon, 22), at(tue, 6) - 1, "5min") + assert storage.reader.run(lambda r: r.part_days("rain", [window], ["daily"])[s.id].hi["daily"], ()) == [6.0] # (what it isn't) + assert figures(storage, s, mon, tue, "evening", ["daily"]).days.hi["daily"] == [pytest.approx(6.0), pytest.approx(0.5)] + assert figures(storage, s, mon, tue, "afternoon", ["daily"]).days.hi["daily"] == [0.0, pytest.approx(1.0)] + + +def test_the_reading_before_a_stretch_may_be_at_the_other_resolution(storage): + """A 5-minute day after one held only at 30 minutes: the rain in its first 5 minutes is the rise from the half hour before.""" + mon, tue = date(2026, 11, 2), date(2026, 11, 3) + a, b = day_bounds(mon, TZ, True) + put(storage, "rainfall", "30min", [{"ts": t, "daily": 3.0} for t in range(a, b, 1800)], a, b) + a, b = day_bounds(tue, TZ, True) + s = put(storage, "rainfall", "5min", [{"ts": t, "daily": 0.4} for t in range(a, b, 300)], a, b) # 0.4 mm in its first 5 minutes + assert figures(storage, s, tue, tue, "00:00-24:00", ["daily"]).days.hi["daily"] == [0.4] + + +def test_an_air_glitch_inside_the_stretch_is_taken_out_and_a_rise_that_lasts_is_not(storage): + d = date(2026, 11, 3) + start, end = at(d - DAY, 12), at(d, 12) + pm = {t: 5.0 for t in range(start, end, 300)} + pm[at(d - DAY, 22)] = pm[at(d, 2)] = 60.0 # one reading far above those either side: a glitch (at the night's edge too) + pm[at(d, 4)] = pm[at(d, 4, 5)] = 30.0 # two in a row: the air + s = put(storage, "air", "5min", [{"ts": t, "pm2_5": v} for t, v in pm.items()], start, end - 1) + days = figures(storage, s, d, d, "night", ["pm2_5"]).days + assert (days.hi["pm2_5"], days.hi_ts["pm2_5"]) == ([30.0], [at(d, 4)]) + assert days.n == [96 - 2] # (the two glitches' readings held nothing else) + assert figures(storage, s, d, d, "02:00-03:00", ["pm2_5"]).days.hi["pm2_5"] == [5.0] + + +# ---------- the whole day ---------- +def _same(got: list, row: list) -> bool: + return all(g == pytest.approx(r) if isinstance(r, float) else g == r for g, r in zip(got, row, strict=True)) + + +def _running(times: range, rng: random.Random): + """(ts, the day's running rain total) at each reading: from 0 at local midnight, a shower now and then after the day's first hour.""" + total = 0.0 + for t in times: + local = datetime.fromtimestamp(t, TZ) + if local.time() == time(0): + total = 0.0 + elif local.hour >= 1: + total += rng.choice([0.0] * 6 + [0.2, 0.6]) + yield t, round(total, 1) + + +@pytest.mark.parametrize("group, res", [("outdoor", "5min"), ("outdoor", "30min"), ("air", "5min"), ("air", "1hour")]) +def test_the_whole_day_has_its_day_rows_figures_wherever_it_is_held_whole(storage, group, res): + """"00:00-24:00" over days held whole, a clock-change day among those at 5 minutes: each reading's figures, n and the resolution are + its day row's (the rain counters' total too: the day's starts at midnight).""" + rng = random.Random(f"{group} {res}") + first, last = (date(2026, 4, 4), date(2026, 4, 6)) if res == "5min" else (date(2026, 2, 27), date(2026, 3, 1)) + start, end = at(first, 0), at(last + DAY, 0) + times = range(start, end, SECONDS[res]) + if group == "air": # a glitch now and then + rows = [{"ts": t, "pm2_5": 60.0 if rng.random() < 0.05 else rng.uniform(3, 9), "co2": rng.uniform(400, 900)} for t in times] + else: + rows = [{"ts": t, "temperature": round(rng.uniform(5, 25), 1), "humidity": float(round(rng.uniform(40, 99)))} for t in times] + if res == "30min": + rows = [row | {"temperature_lo": row["temperature"] - rng.uniform(0, 2), "temperature_hi": row["temperature"] + rng.uniform(0, 2)} + for row in rows] + sensors = [put(storage, group, res, rows, start, end - 1)] + if group == "outdoor": + if res == "5min": # the half hours' own lows and highs, which a day of 5-minute readings takes in + put(storage, "outdoor", "30min", [{"ts": t, "temperature": 15.0, "temperature_lo": rng.uniform(1, 5), + "temperature_hi": rng.uniform(26, 30)} for t in range(start, end, 1800)], start, end - 1) + sensors.append(put(storage, "rainfall", res, [{"ts": t, "daily": v} for t, v in _running(times, rng)], start, end - 1)) + for s in sensors: + got = figures(storage, s, first, last, "00:00-24:00").days + row = storage.reader.run(lambda r: r.days(s.kind, [s.id], first, last)[s.id], ()) + assert got.day == row.day == [first, first + DAY, last] and got.source == row.source == [res] * 3 + assert (got.n, got.complete, set(got.mean)) == (row.n, row.complete, set(row.mean)) + for c in row.mean: + for part in ("hi", "hi_ts") if c in RAIN_COUNTERS else DAY_PARTS: + assert _same(getattr(got, part)[c], getattr(row, part)[c]), (c, part) + if res == "5min": + assert got.n[1] == 25 * 12 # (the day the clocks went back) From c5e3d9ed2ed3f9fce39474480bb42b30ba54186e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:16:03 +0000 Subject: [PATCH 015/125] periods_text: periods in words, read by the table of docs/mcp-service.md 3.2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 1 of the MCP service plan. lib/periods_text.py reads a tool's period the way the service will: `period` in the person's own words ("this week", "3m", "yesterday afternoon", "Melbourne Cup"), or `start` and `end`, in the station's time zone, so a model never works out a date. Nothing calls it yet: no tool interface or behaviour changes. - read_period() gives a Period: the words asked, start and end on the station's clock (end not included), how it was read ("the last 7 days: Wed 4 – Tue 10 Nov 2026"), first_day and last_day, and the 'YYYY-MM-DD HH:MM:SS' strings today's tools take. - The rules are today's (intent.py's period phrases and numbered periods, the prompt's TIME PERIODS) as the table writes them: "last N days" and "this week" are today and the days before it, bare "last week" is the previous Monday to Sunday, "Nm" is months, never minutes, a date or month with no year is the latest one, a weekday the latest before today. - Whole phrases only: anything else is a PeriodError listing every form with what it means now, so the error also tells a model today's date. A future period points to forecast; a weekday that doesn't match its date names the right one. - whole_days=True (days, relate, scan) gives whole days to yesterday, with a note that today was cut; what leaves no whole day, or is part of a day, points to summary or readings. - Hours are real hours across a clock change, and a time the clocks skip is read as the moment they jump. tests/test_periods_text.py works every row of the table out by hand at a Tuesday (the doc's examples), a Monday, the 1st of a month, 1 January, 29 February 2028, 00:30 and both Melbourne clock-change days, with the whole-day cuts, start and end, and the errors. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/periods_text.py | 570 +++++++++++++++++++++++++++++++++++++ tests/test_periods_text.py | 426 +++++++++++++++++++++++++++ 2 files changed, 996 insertions(+) create mode 100644 lib/periods_text.py create mode 100644 tests/test_periods_text.py diff --git a/lib/periods_text.py b/lib/periods_text.py new file mode 100644 index 00000000..717fd485 --- /dev/null +++ b/lib/periods_text.py @@ -0,0 +1,570 @@ +"""Periods in words: the person's own words for a stretch of time ("this week", "3m", "yesterday afternoon"), read by one table in +the station's time zone, so a model never works out a date (docs/mcp-service.md 3.2). Every tool that takes a period reads it here, +and its result begins with how it was read. + + - `period` must be one of the table's forms as a whole phrase, case aside; N is a number in digits or a word up to twelve. There is + no partial match and no falling back to a default: anything else is a PeriodError listing the forms with what each means now. + - Or `start` (and `end`), on the station's clock: 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM'; one with an offset or Z is moved into local + time. An end that is a date includes that day; no end is now. + - Whole-day tools (days, relate, scan) take whole days up to yesterday, because today is still settling. + - A period in the future is an error that points to the forecast. + +Times are worked out as instants (UTC) and handed back on the station's clock, so an hour is a real hour across a clock change and +a day runs midnight to midnight, 23 or 25 hours on the days the clocks change. +""" + +import re +from calendar import monthrange +from dataclasses import dataclass, replace +from datetime import UTC, date, datetime, time, timedelta, tzinfo +from functools import lru_cache + +from .ecowitt.calendar import PublicHolidays +from .timeutil import clock_text, day_text + +DAY = timedelta(days=1) +MAX_DAYS = 3650 # ten years: longer than anything held +PARTS = {"morning": (6, 12), "afternoon": (12, 18), "evening": (18, 24)} # the parts of a day, in hours +NIGHT = (22, 6) # a night runs from 22:00 the evening before to 06:00 +FOR_PART_OF_A_DAY = "use summary or readings" +FOR_WHAT_IS_AHEAD = "use forecast" + +NUMBER_WORDS = {w: i for i, w in enumerate("one two three four five six seven eight nine ten eleven twelve".split(), 1)} +WEEKDAY_NAMES = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday") +MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") +_WEEKDAYS = {name.lower(): i for i, name in enumerate(WEEKDAY_NAMES)} | { + "mon": 0, "tue": 1, "tues": 1, "wed": 2, "weds": 2, "thu": 3, "thur": 3, "thurs": 3, "fri": 4, "sat": 5, "sun": 6} +_MONTHS = {name.lower(): i for i, name in enumerate(MONTH_NAMES, 1)} | {name[:3].lower(): i for i, name in enumerate(MONTH_NAMES, 1)} | {"sept": 9} +_UNITS = {"minutes": ("min", "mins", "minute", "minutes"), "hours": ("h", "hr", "hrs", "hour", "hours"), "days": ("d", "day", "days"), + "weeks": ("w", "wk", "wks", "week", "weeks"), "months": ("m", "mo", "mos", "month", "months"), # "m" is months, never minutes + "years": ("y", "yr", "yrs", "year", "years")} +_UNIT = {word: unit for unit, words in _UNITS.items() for word in words} + + +def _either(words) -> str: + return "|".join(sorted(words, key=len, reverse=True)) + + +_WD, _MON, _YEAR = _either(_WEEKDAYS), _either(_MONTHS), r"(?:19|20)\d\d" +ON_RECORD = re.compile(r"on record|(?:of )?all[- ]time|ever(?: recorded)?|(?:the )?(?:full|whole|entire|complete|all(?: the)?) (?:history|record|data)") +ROLLING = ( # (words, how they read, days, or hours when it is a number of hours) + (re.compile(r"this week|(?:the )?past week|the last week|week"), "the last 7 days", 7, 0), + (re.compile(r"(?:(?:the )?(?:last|past) )?fortnight"), "the last 14 days", 14, 0), + (re.compile(r"(?:the )?past month|the last month|month"), "the last 30 days", 30, 0), + (re.compile(r"(?:the )?past year|the last year|year"), "the last 365 days", 365, 0), + (re.compile(r"(?:the )?(?:last|past) day"), "the last 24 hours", 0, 24), + (re.compile(r"(?:the )?(?:last|past) hour"), "the last hour", 0, 1), +) +NUMBERED = re.compile(rf"(?:(?:the )?(?:last|past) )?(?P\d+|{_either(NUMBER_WORDS)}) ?(?P{_either(_UNIT)})") +YEAR = re.compile(rf"(?P{_YEAR})") +MONTH = re.compile(rf"(?P{_MON})\.?(?:,? (?P{_YEAR}))?") +DAYS = ( # "2026-09-05", "Sat 5 Sep", "5th of September 2025", "September 5, 2025" + re.compile(rf"(?P{_YEAR})-(?P\d\d)-(?P\d\d)"), + re.compile(rf"(?:(?P{_WD}),? )?(?:the )?(?P\d{{1,2}})(?:st|nd|rd|th)?(?: of)? (?P{_MON})\.?(?:,? (?P{_YEAR}))?"), + re.compile(rf"(?:(?P{_WD}),? )?(?P{_MON})\.? (?:the )?(?P\d{{1,2}})(?:st|nd|rd|th)?(?:,? (?P{_YEAR}))?"), +) +BARE_DAY = re.compile(rf"(?:(?P{_WD}),? )?(?:the )?(?P\d{{1,2}})(?:st|nd|rd|th)?") # the "5" of "5 to 10 Sep" +WEEKDAY = re.compile(rf"(?:last )?(?P{_WD})") +PART = re.compile(rf"(?Pthis|yesterday|(?:last )?(?P{_WD})) (?Pmorning|afternoon|evening)") +NIGHT_OF = re.compile(rf"(?:last )?(?P{_WD}) night") +SINCE = re.compile(r"since (?P.+)") +CLOCK = re.compile(r"(?P\d{1,2})(?:[:.](?P\d\d))? ?(?Pam|pm|a\.m\.|p\.m\.)|(?P\d{1,2}):(?P\d\d)|noon|midday|midnight") +RANGE_SEP = re.compile(r" (?:to|until|till|through|thru) | ?– ?| - ") +LEAD = re.compile(r"(?:in|over|during|for|within|across|throughout|on) (?P.+)") # "in the last year", "over the past week" +FUTURE = re.compile(r"(?:the )?(?:day after )?tomorrow(?: .+)?|(?:the |this )?(?:next|coming|upcoming|following) .+|later(?: today| on)?") +HOLIDAY_ALIASES = {"cup day": "melbourne cup day", "grand final friday": "friday before the afl grand final", "easter": "easter sunday", + "new year": "new years day"} + +# The forms a PeriodError lists, each with an example read at the time asked; `timed` ones are left out for whole-day tools +FORMS = ( # (form, example, timed) + ("today", "today", True), + ("yesterday", "yesterday", False), + ("last N minutes, N min", "last 30 minutes", True), + ("last N hours, Nh, last 24 hours, 1d, last day", "last 24 hours", True), + ("last N days, Nd (N from 2)", "last 7 days", False), + ("this week, past week, the last week, week, 1w", "this week", False), + ("last N weeks, Nw, fortnight", "last 2 weeks", False), + ("past month, the last month, month, 1m, last 30 days", "past month", False), + ("last N months, Nm, N mo (m is months, never minutes)", "3m", False), + ("past year, the last year, year, 1y, last 12 months", "past year", False), + ("last N years, Ny", "2y", False), + ("week to date, since Monday", "week to date", False), + ("last week (the previous Monday to Sunday)", "last week", False), + ("this month", "this month", False), + ("last month", "last month", False), + ("this year", "this year", False), + ("last year", "last year", False), + ("a year, such as 2025", "{last_year}", False), + ("a month, such as October 2025, or October (the latest that has begun)", "October", False), + ("A to B, between A and B, such as June to August 2026", "June to August", False), + ("a day, such as 2026-09-05, 5 Sep, 5 September 2025, Sat 5 Sep (with no year, the latest not after today)", "5 Sep", False), + ("Monday … Sunday, last Saturday (the latest before today)", "Saturday", False), + ("a public holiday by name, with or without a year, such as Christmas Day or Melbourne Cup", "Christmas Day", False), + ("this morning, yesterday afternoon, Tuesday evening (06:00-12:00, 12:00-18:00, 18:00-24:00)", "yesterday afternoon", True), + ("last night, Tuesday night, overnight (22:00 the evening before to 06:00)", "last night", True), + ("since 6am, since Monday", "since 6am", True), + ("on record, all time, ever (from the first reading held)", "on record", False), +) + + +@dataclass(frozen=True) +class Period: + """A period as read: the words asked (or "start/end"), its start and end on the station's clock (the end not included), how it + was read, ready to pass on, and, when a whole-day tool cut it to yesterday, a note saying so.""" + asked: str + start: datetime + end: datetime + text: str + cut: str | None = None + + @property + def first_day(self) -> date: + return self.start.date() + + @property + def last_day(self) -> date: + """The day of its last moment: the day before an end at midnight.""" + return (self.end - timedelta(microseconds=1)).date() + + def as_naive_strings(self) -> tuple[str, str]: + """Start and end as today's tools take them: 'YYYY-MM-DD HH:MM:SS' on the station's clock, the end its last second.""" + return f"{self.start:%Y-%m-%d %H:%M:%S}", f"{self.end - timedelta(seconds=1):%Y-%m-%d %H:%M:%S}" + + +class PeriodError(ValueError): + """A period that can't be read, saying what to send instead. When the words aren't a form at all, `forms` holds each form with + what it means now, so the error also tells a model today's date.""" + + def __init__(self, message: str, forms: tuple[tuple[str, str], ...] = ()): + super().__init__(message + "".join(f"\n- {form} → {means}" for form, means in forms)) + self.message, self.forms = message, forms + + +class _NotAForm(Exception): + """Words that match no form (read_period lists the forms).""" + + +@dataclass(frozen=True) +class _Read: + """Words read, before the cut to now and to whole days: kind is "calendar" (named days, cut at yesterday by a whole-day tool), + "days" (the last `days` days), "hours" (a length of real time, `days` its whole days) or "time" (part of a day).""" + label: str | None + start: datetime + end: datetime + kind: str + days: int = 0 + + +@dataclass(frozen=True) +class _Clock: + """The time asked, as an instant and on the station's clock.""" + at: datetime + local: datetime + tz: tzinfo + + @classmethod + def of(cls, now: datetime, tz: tzinfo) -> "_Clock": + local = now.astimezone(tz) if now.tzinfo else now.replace(tzinfo=tz) + return cls(local.astimezone(UTC), local, tz) + + @property + def today(self) -> date: + return self.local.date() + + def wall(self, day: date, at: time = time(), fold: int = 0) -> datetime: + """The instant the station's clock shows `at` on `day`. In the hour the clocks go back, `fold` picks the first (0) or the + second (1); a time the clocks skip is read as the moment they jump.""" + local = datetime.combine(day, at, tzinfo=self.tz).replace(fold=fold) + instant = local.astimezone(UTC) + if instant.astimezone(self.tz).replace(tzinfo=None) == local.replace(tzinfo=None): + return instant + instant = min(local.replace(fold=0).astimezone(UTC), local.replace(fold=1).astimezone(UTC)) + while instant.astimezone(self.tz).replace(tzinfo=None) < local.replace(tzinfo=None): + instant += timedelta(minutes=1) + return instant + + def midnight(self, day: date) -> datetime: + return self.wall(day) + + def error(self, message: str, forms: tuple[tuple[str, str], ...] = ()) -> PeriodError: + return PeriodError(f"{message} It is now {day_text(self.local)} {clock_text(self.local)}.", forms) + + +def read_period(period: str | None, start: str | None, end: str | None, *, now: datetime, tz: tzinfo, default: str, + whole_days: bool = False, first_held: date | datetime | None = None) -> Period: + """The period a tool was asked for: `period` in words, or `start` (and `end`), or else `default` (words). `now` is the time asked + (aware; naive is taken as the station's clock), `first_held` the first reading held for the readings asked about ("on record"). + whole_days: the tool works on whole days, up to yesterday. PeriodError says what to send instead.""" + clock = _Clock.of(now, tz) + try: + return _read(period, start, end, clock, default, whole_days, first_held)[0] + except _NotAForm as e: + dates = "as dates ('YYYY-MM-DD'): this tool takes whole days, up to yesterday" if whole_days else \ + "('YYYY-MM-DD' or 'YYYY-MM-DD HH:MM', the station's local time)" + raise clock.error(f"{e.args[0]!r} isn't a period this tool can read. Send `period` as one of these forms, as a whole phrase " + f"(N is a number, in digits or a word up to twelve), or send `start` and `end` {dates}.", + _forms(clock, whole_days, first_held)) from None + + +def _read(period, start, end, clock: _Clock, default: str, whole_days: bool, first_held) -> tuple[Period, str | None]: + """The Period and the label it was read as (None for plain dates).""" + period, start, end = (str(x).strip() if x is not None and str(x).strip() else None for x in (period, start, end)) + if period and (start or end): + raise clock.error(f"Send `period` or `start` (with `end`), not both: `period` {period!r}, `start` {start!r}, `end` {end!r}.") + if end and not start: + raise clock.error(f"`end` {end!r} needs a `start`: send `start` too, or a `period` instead.") + if start: + asked, what, read = "start/end", f"`start` {start!r}", _dates(start, end, clock, whole_days) + else: + asked = period or default + what, read = repr(asked), _words(asked, clock, first_held) + if read.start > clock.at: + raise clock.error(f"{what} is in the future ({_text(read, clock)}). This tool reads what has been measured: for what's ahead, " + f"{FOR_WHAT_IS_AHEAD}.") + read = replace(read, end=min(read.end, clock.at)) + cut = None + if whole_days: + read, cut = _whole_days(read, what, clock) + return Period(asked, read.start.astimezone(clock.tz), read.end.astimezone(clock.tz), _text(read, clock), cut), read.label + + +def _whole_days(read: _Read, what: str, clock: _Clock) -> tuple[_Read, str | None]: + """The period in whole days up to yesterday, and the note when today was cut from it.""" + today, yesterday = clock.midnight(clock.today), clock.today - DAY + cut = f"to {day_text(yesterday, year=False)}: today isn't over" + if read.kind == "time": + raise clock.error(f"{what} is part of a day: this tool takes whole days, up to yesterday ({day_text(yesterday)}). For part of a " + f"day, {FOR_PART_OF_A_DAY}.") + nothing = clock.error(f"{what} leaves no whole day: this tool takes whole days up to yesterday ({day_text(yesterday)}), as today " + f"isn't over. For today or part of a day, {FOR_PART_OF_A_DAY}.") + if read.kind in ("days", "hours"): + if not read.days: + raise nothing + label = read.label if read.kind == "days" else "the last day" if read.days == 1 else f"the last {read.days} days" + return _Read(label, clock.midnight(clock.today - read.days * DAY), today, "days", read.days), cut + if read.end <= today: + return read, None + if read.start >= today: + raise nothing + return replace(read, end=today), cut + + +# ---------- start and end ---------- +def _dates(start: str, end: str | None, clock: _Clock, whole_days: bool) -> _Read: + first, _ = _moment("start", start, clock, whole_days) + if end is None: + return _Read(None, first, clock.at, "calendar") + last, is_date = _moment("end", end, clock, whole_days) + if is_date: # a date includes that whole day + last = clock.midnight(last.astimezone(clock.tz).date() + DAY) + if first >= last: + raise clock.error(f"`start` {start!r} must be before `end` {end!r}.") + return _Read(None, first, last, "calendar") + + +def _moment(name: str, text: str, clock: _Clock, whole_days: bool) -> tuple[datetime, bool]: + """A start or end as an instant, and whether it was a date alone.""" + try: + dt = datetime.fromisoformat(text) + except ValueError: + raise clock.error(f"`{name}` {text!r} isn't a date or time: send 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM', the station's local " + f"time.") from None + is_date = bool(re.fullmatch(r"\d{4}-\d\d-\d\d", text)) + if whole_days and not is_date: + raise clock.error(f"`{name}` {text!r} has a time: this tool takes whole days ('YYYY-MM-DD'), up to yesterday " + f"({day_text(clock.today - DAY)}). For part of a day, {FOR_PART_OF_A_DAY}.") + return (dt.astimezone(UTC) if dt.tzinfo else clock.wall(dt.date(), dt.time())), is_date + + +# ---------- words ---------- +def _words(asked: str, clock: _Clock, first_held) -> _Read: + p = " ".join(asked.replace("’", "'").replace("—", "–").lower().split()) + lead = LEAD.fullmatch(p) + read = _phrase(p, clock, first_held) or (lead and _phrase(lead["rest"], clock, first_held)) + if read: + return read + if FUTURE.fullmatch(p) or (lead and FUTURE.fullmatch(lead["rest"])): + raise clock.error(f"{asked!r} is in the future. This tool reads what has been measured: for what's ahead, {FOR_WHAT_IS_AHEAD}.") + raise _NotAForm(asked) + + +def _phrase(p: str, clock: _Clock, first_held) -> _Read | None: + """The words as one of the forms, or None.""" + if ON_RECORD.fullmatch(p): + return _on_record(clock, first_held) + for words, label, days, hours in ROLLING: + if words.fullmatch(p): + return _last_days(label, days, clock) if days else _last_time(label, timedelta(hours=hours), clock) + if m := NUMBERED.fullmatch(p): + return _numbered(p, m, clock) + if p in ("last night", "overnight"): + return _night("last night", clock.today, clock) + if m := NIGHT_OF.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + return _night(f"{WEEKDAY_NAMES[wd]} night", _latest_weekday(wd, clock.today, strict=True), clock) + if m := PART.fullmatch(p): + return _part(m, clock) + if m := SINCE.fullmatch(p): + return _since(m["what"], clock) + if read := _range(p, clock): + return read + return _calendar(p, clock, clock.today, strict=True) + + +def _on_record(clock: _Clock, first_held) -> _Read: + if first_held is None: + raise clock.error("Nothing is held yet for these readings, so 'on record' has no start.") + if isinstance(first_held, datetime): + first_held = (first_held.astimezone(clock.tz) if first_held.tzinfo else first_held).date() + return _Read("on record", clock.midnight(first_held), clock.at, "calendar") + + +def _last_days(label: str, days: int, clock: _Clock) -> _Read: + """Today and the days-1 whole days before it, to now.""" + return _Read(label, clock.midnight(clock.today - (days - 1) * DAY), clock.at, "days", days) + + +def _last_time(label: str, length: timedelta, clock: _Clock) -> _Read: + """The last `length` of real time, to now.""" + return _Read(label, clock.at - length, clock.at, "hours", length // DAY) + + +def _numbered(p: str, m: re.Match, clock: _Clock) -> _Read | None: + """"last 7 days", "3m", "past two years", "45 min": a rolling period to now. One day is the last 24 hours; a month is + round(N×365/12) days, a year 365.""" + if len(m["n"]) > 6 or not (n := int(m["n"]) if m["n"].isdigit() else NUMBER_WORDS[m["n"]]): + return None + unit = _UNIT[m["unit"]] + if unit in ("minutes", "hours") or (unit == "days" and n == 1): + length = timedelta(minutes=n) if unit == "minutes" else timedelta(hours=24 if unit == "days" else n) + if length > MAX_DAYS * DAY: + raise clock.error(f"{p!r} is longer than ten years, more than anything held: for all of it, send 'on record'.") + hours = length // timedelta(hours=1) + label = (f"the last {n} minutes" if n > 1 else "the last minute") if unit == "minutes" else \ + f"the last {hours} hours" if hours > 1 else "the last hour" + return _last_time(label, length, clock) + days = {"days": n, "weeks": 7 * n, "months": round(n * 365 / 12), "years": 365 * n}[unit] + if days > MAX_DAYS: + raise clock.error(f"{p!r} is longer than ten years, more than anything held: for all of it, send 'on record'.") + return _last_days(f"the last {days} days" if n == 1 or unit == "days" else f"the last {n} {unit}", days, clock) + + +def _night(label: str, day: date, clock: _Clock) -> _Read: + """The night that ends on `day`: 22:00 the evening before to 06:00.""" + return _Read(label, clock.wall(day - DAY, time(NIGHT[0])), clock.wall(day, time(NIGHT[1])), "time") + + +def _part(m: re.Match, clock: _Clock) -> _Read: + """"this morning", "yesterday afternoon", "Tuesday evening" (the latest Tuesday before today).""" + if m["wd"]: + wd = _WEEKDAYS[m["wd"]] + day, said = _latest_weekday(wd, clock.today, strict=True), WEEKDAY_NAMES[wd] + else: + day, said = (clock.today, "this") if m["day"] == "this" else (clock.today - DAY, "yesterday") + first, last = PARTS[m["part"]] + end = clock.midnight(day + DAY) if last == 24 else clock.wall(day, time(last)) + return _Read(f"{said} {m['part']}", clock.wall(day, time(first)), end, "time") + + +def _since(what: str, clock: _Clock) -> _Read | None: + """"since 6am": from the latest such time; "since Monday", "since 5 Sep": from that day's 00:00 (a weekday may be today).""" + if (m := CLOCK.fullmatch(what)) and (at := _time_of_day(m)) is not None: + days = (clock.today, clock.today - DAY) + start = max(t for t in (clock.wall(d, at, fold) for d in days for fold in (0, 1)) if t <= clock.at) + said = "midnight" if at == time() else "noon" if at == time(12) else clock_text(datetime.combine(clock.today, at), whole_hours=True) + return _Read(f"since {said}", start, clock.at, "time") + if anchor := _calendar(what, clock, clock.today, strict=False): + return _Read(f"since {anchor.label}" if anchor.label else None, anchor.start, clock.at, "calendar") + return None + + +def _time_of_day(m: re.Match) -> time | None: + if m[0] in ("noon", "midday", "midnight"): + return time(12) if m[0] != "midnight" else time() + hour, minute = int(m["h"] or m["h24"]), int(m["mi"] or m["mi24"] or 0) + if m["ap"]: + if not 1 <= hour <= 12: + return None + hour = hour % 12 + (12 if m["ap"][0] == "p" else 0) + return time(hour, minute) if hour < 24 and minute < 60 else None + + +def _range(p: str, clock: _Clock) -> _Read | None: + """"A to B", "between A and B", "from A until B": the start of A to the end of B. B is read as it would be alone; A, when it + names no year (or is a weekday), is the latest not after B, so "December to February" is the summer just gone.""" + between = p.startswith("between ") + body = p.removeprefix("between ") if between else p.removeprefix("from ") + for sep in re.finditer(" and " if between else RANGE_SEP, body): + a, b = body[:sep.start()], body[sep.end():] + last = _Read("now", clock.at, clock.at, "calendar") if b == "now" else _calendar(b, clock, clock.today, strict=True) + if last is None: + continue + b_day = last.start.astimezone(clock.tz).date() + if BARE_DAY.fullmatch(a) and any(d.fullmatch(b) for d in DAYS): # "5 to 10 Sep": the 5th of B's month + a = f"{a} {MONTH_NAMES[b_day.month - 1].lower()} {b_day.year}" + if (first := _calendar(a, clock, b_day, strict=False)) is None: + continue + if first.start >= last.end: + raise clock.error(f"{p!r} starts after it ends.") + return _Read(f"{first.label} to {last.label}" if first.label and last.label else None, first.start, last.end, "calendar") + return None + + +def _calendar(p: str, clock: _Clock, ref: date, strict: bool) -> _Read | None: + """A stretch of whole days with a name: today, yesterday, last week, this or last month or year, a year, a month, a day, a + weekday, a public holiday. A month, day or holiday with no year is the latest not after `ref`; a weekday the latest before it + (strict) or not after it.""" + if named := _named(p, clock.today): + label, first, end = named + return _Read(label, clock.midnight(first), clock.midnight(end), "calendar") + if m := YEAR.fullmatch(p): + year = int(m["y"]) + return _Read(m["y"], clock.midnight(date(year, 1, 1)), clock.midnight(date(year + 1, 1, 1)), "calendar") + if m := MONTH.fullmatch(p): + month = _MONTHS[m["mon"]] + year = int(m["y"]) if m["y"] else ref.year if month <= ref.month else ref.year - 1 + first = date(year, month, 1) + end = date(year + month // 12, month % 12 + 1, 1) + return _Read(f"{MONTH_NAMES[month - 1]} {year}", clock.midnight(first), clock.midnight(end), "calendar") + for pattern in DAYS: + if m := pattern.fullmatch(p): + return _one_day(None, _day(m, ref, clock), clock) + if m := WEEKDAY.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + return _one_day(WEEKDAY_NAMES[wd], _latest_weekday(wd, ref, strict), clock) + if holiday := _holiday(p, ref, clock): + return _one_day(*holiday, clock) + return None + + +def _named(p: str, today: date) -> tuple[str, date, date] | None: + """The calendar's named stretches as (label, first day, the day after the last).""" + monday, month = today - timedelta(days=today.weekday()), today.replace(day=1) + previous = (month - DAY).replace(day=1) + following = (month + 31 * DAY).replace(day=1) + return {"today": ("today", today, today + DAY), "so far today": ("today", today, today + DAY), + "yesterday": ("yesterday", today - DAY, today), + "week to date": ("week to date", monday, today + DAY), + "last week": ("last week", monday - 7 * DAY, monday), + "this month": ("this month", month, following), "last month": ("last month", previous, month), + "this year": ("this year", date(today.year, 1, 1), date(today.year + 1, 1, 1)), + "last year": ("last year", date(today.year - 1, 1, 1), date(today.year, 1, 1))}.get(p) + + +def _one_day(label: str | None, day: date, clock: _Clock) -> _Read: + return _Read(label, clock.midnight(day), clock.midnight(day + DAY), "calendar") + + +def _day(m: re.Match, ref: date, clock: _Clock) -> date: + """The day a date names: with no year, the latest not after `ref`. A weekday that doesn't match it is an error.""" + g = m.groupdict() # (the ISO form has no weekday or month name) + month, day = int(g["m"]) if g.get("m") else _MONTHS[g["mon"]], int(g["d"]) + if not 1 <= month <= 12 or not 1 <= day <= monthrange(2000, month)[1]: # (2000: a leap year, so 29 Feb is a date) + raise clock.error(f"{m[0]!r} isn't a date.") + if g["y"]: + try: + found = date(int(g["y"]), month, day) + except ValueError: + raise clock.error(f"{day} {MONTH_NAMES[month - 1]} {g['y']} isn't a date.") from None + else: + found = next(d for year in range(ref.year, ref.year - 9, -1) if (d := _date_or_none(year, month, day)) and d <= ref) + if g.get("wd") and (wanted := _WEEKDAYS[g["wd"]]) != found.weekday(): + raise clock.error(f"{found.day} {found:%B %Y} is a {found:%A}, not a {WEEKDAY_NAMES[wanted]}: send '{day_text(found)}', " + f"or the date alone.") + return found + + +def _date_or_none(year: int, month: int, day: int) -> date | None: + try: + return date(year, month, day) + except ValueError: # 29 Feb in a year that has none + return None + + +def _latest_weekday(wd: int, ref: date, strict: bool) -> date: + """The latest such weekday not after `ref`, or before it if strict.""" + back = (ref.weekday() - wd) % 7 + return ref - timedelta(days=back or (7 if strict else 0)) + + +# ---------- public holidays ---------- +def _holiday(p: str, ref: date, clock: _Clock) -> tuple[str, date] | None: + """A public holiday by name, from the station's holiday calendar ("Christmas Day", "Melbourne Cup 2025"): (its name, its day), + with no year the latest not after `ref`.""" + m = re.fullmatch(rf"(?:the )?(?P.+?)(?: (?P{_YEAR}))?", p) + key = _holiday_key(m["name"]) + key = HOLIDAY_ALIASES.get(key, key) + years = (int(m["y"]),) if m["y"] else (ref.year, ref.year - 1) + found = [(day, name) for year in years for day, name in _holidays(clock.tz, year).get(key, ()) if m["y"] or day <= ref] + return max(found, key=lambda found: found[0])[::-1] if found else None + + +def _holiday_key(name: str) -> str: + return " ".join(name.lower().replace("'", "").replace("’", "").split()) + + +@lru_cache(maxsize=None) +def _holidays(tz: tzinfo, year: int) -> dict[str, tuple[tuple[date, str], ...]]: + """The year's public holidays by the words that name them: the name, and the name without "Day" ("Christmas", "Melbourne Cup").""" + calendar, found = PublicHolidays(tz), {} + day = date(year, 1, 1) + while calendar.available and day.year == year: + for name in (calendar.name(day) or "").split("; "): + if name and "observed" not in name.lower(): + key = _holiday_key(name) + for words in {key, key.removesuffix(" day")}: + found[words] = found.get(words, ()) + ((day, name),) + day += DAY + return found + + +# ---------- in words ---------- +def _text(read: _Read, clock: _Clock) -> str: + """How the period was read: "the last 7 days: Wed 4 – Tue 10 Nov 2026"; plain dates without the label. Days run from midnight + to midnight, the last of them today for a period to now; a length of time or part of a day shows its times.""" + start, end = read.start.astimezone(clock.tz), read.end.astimezone(clock.tz) + as_days = read.kind in ("calendar", "days") and start.time() == time() and (end.time() == time() or read.end == clock.at) + span = _days_text(start.date(), max(start.date(), end.date() - DAY if end.time() == time() else end.date())) if as_days \ + else _times_text(start, end) + return f"{read.label}: {span}" if read.label else span + + +def _times_text(start: datetime, end: datetime) -> str: + """"Tue 10 Nov 2026 6am – 12pm", "Tue 3 Nov 2026 6pm – midnight", "Mon 9 Nov 10pm – Tue 10 Nov 2026 6am".""" + midnight = time() + if start.date() == end.date(): + return f"{day_text(start)} {_clock(start)} – {_clock(end)}" + if end.time() == midnight and end.date() == start.date() + DAY: + return f"{day_text(start)} {_clock(start)} – midnight" + return f"{day_text(start, year=start.year != end.year)} {_clock(start)} – {day_text(end)} {_clock(end)}" + + +def _days_text(first: date, last: date) -> str: + """"Tue 10 Nov 2026", "Wed 4 – Tue 10 Nov 2026", "Wed 12 Aug – Tue 10 Nov 2026", "Mon 10 Nov 2025 – Tue 10 Nov 2026".""" + if first == last: + return day_text(first) + if (first.year, first.month) == (last.year, last.month): + return f"{first:%a} {first.day} – {day_text(last)}" + return f"{day_text(first, year=first.year != last.year)} – {day_text(last)}" + + +def _clock(t: datetime) -> str: + return clock_text(t, whole_hours=True) + + +def _forms(clock: _Clock, whole_days: bool, first_held) -> tuple[tuple[str, str], ...]: + """Each form with what its example means now (a whole-day tool's leaves out the ones it refuses).""" + forms = [] + for form, example, timed in FORMS: + if whole_days and timed: + continue + example = example.format(last_year=clock.today.year - 1) + if example == "on record" and first_held is None: + forms.append((form, "from the first reading held, for the readings asked about, to now")) + continue + try: + period, label = _read(example, None, None, clock, example, whole_days, first_held) + except (PeriodError, _NotAForm): # (no holiday calendar here, or not on this day: "this month" on the 1st, for whole days) + continue + forms.append((form, period.text if label else f"{example}: {period.text}")) + return tuple(forms) diff --git a/tests/test_periods_text.py b/tests/test_periods_text.py new file mode 100644 index 00000000..a6fd25b5 --- /dev/null +++ b/tests/test_periods_text.py @@ -0,0 +1,426 @@ +"""Periods in words (lib/periods_text.py): the table of docs/mcp-service.md 3.2 read at fixed times, every answer worked out by hand. +Melbourne's clocks go back an hour at 3am on 5 Apr 2026 (2am to 3am happens twice) and forward at 2am on 4 Oct 2026 (2am to 3am +never happens).""" + +from datetime import datetime + +import pytest + +from lib.periods_text import PeriodError, read_period +from tests.fakes import TZ + + +def at(*when, fold: int = 0) -> datetime: + """A time on the station's clock.""" + return datetime(*when, tzinfo=TZ, fold=fold) + + +def read(words, now, start=None, end=None, **kw): + return read_period(words, start, end, now=now, tz=TZ, default="today", **kw) + + +def hours(period) -> float: + """The period's length in real hours (on one clock, aware datetimes subtract as wall times).""" + return (period.end.timestamp() - period.start.timestamp()) / 3600 + + +def check(now, words, start, end, text, **kw): + """Each of the words (a "|" between the ones that mean the same) reads as start to end, written as text.""" + for said in words.split("|"): + period = read(said.strip(), now, **kw) + assert (period.asked, period.start, period.end, period.text) == (said.strip(), at(*start), at(*end), text), said + + +def rows(*table): + return pytest.mark.parametrize("words, start, end, text", table, ids=[row[0].split("|")[0].strip() for row in table]) + + +HELD = at(2024, 3, 1, 15, 20) # the first reading held, for "on record" + +# ---------- Tue 10 Nov 2026 14:05: the doc's examples, every row of the table ---------- +TUESDAY = at(2026, 11, 10, 14, 5) +NOW = (2026, 11, 10, 14, 5) + + +@rows( + ("today | Today | so far today", (2026, 11, 10), NOW, "today: Tue 10 Nov 2026"), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026"), + ("last 30 minutes | 30 min | 30min | 30 mins | the past 30 minutes", (2026, 11, 10, 13, 35), NOW, + "the last 30 minutes: Tue 10 Nov 2026 1:35pm – 2:05pm"), + ("last 6 hours | 6h | 6 hrs | the past six hours", (2026, 11, 10, 8, 5), NOW, "the last 6 hours: Tue 10 Nov 2026 8:05am – 2:05pm"), + ("last 24 hours | 24h | 1d | last day | the past day | last 1 day | in the last 24 hours", (2026, 11, 9, 14, 5), NOW, + "the last 24 hours: Mon 9 Nov 2:05pm – Tue 10 Nov 2026 2:05pm"), + ("last hour | the past hour | 1h", (2026, 11, 10, 13, 5), NOW, "the last hour: Tue 10 Nov 2026 1:05pm – 2:05pm"), + ("last 7 days | 7d | 7D | seven days | the past 7 days | over the last seven days", (2026, 11, 4), NOW, + "the last 7 days: Wed 4 – Tue 10 Nov 2026"), + ("this week | past week | the past week | the last week | week | 1w | in the last week | This Week", (2026, 11, 4), NOW, + "the last 7 days: Wed 4 – Tue 10 Nov 2026"), + ("last 2 weeks | 2w | two weeks", (2026, 10, 28), NOW, "the last 2 weeks: Wed 28 Oct – Tue 10 Nov 2026"), + ("fortnight | the last fortnight", (2026, 10, 28), NOW, "the last 14 days: Wed 28 Oct – Tue 10 Nov 2026"), + ("past month | the last month | the past month | month | 1m | 1M | last 30 days | last 1 month", (2026, 10, 12), NOW, + "the last 30 days: Mon 12 Oct – Tue 10 Nov 2026"), + ("last 3 months | 3m | 3 mo | 3M | past three months", (2026, 8, 12), NOW, "the last 3 months: Wed 12 Aug – Tue 10 Nov 2026"), + ("5m | 5 months", (2026, 6, 12), NOW, "the last 5 months: Fri 12 Jun – Tue 10 Nov 2026"), # round(5×365/12) = 152 days: never minutes + ("past year | the last year | in the last year | year | 1y", (2025, 11, 11), NOW, "the last 365 days: Tue 11 Nov 2025 – Tue 10 Nov 2026"), + ("last 12 months | last twelve months", (2025, 11, 11), NOW, "the last 12 months: Tue 11 Nov 2025 – Tue 10 Nov 2026"), + ("last 2 years | 2y | past two years | the past 2 years", (2024, 11, 11), NOW, "the last 2 years: Mon 11 Nov 2024 – Tue 10 Nov 2026"), + ("week to date", (2026, 11, 9), NOW, "week to date: Mon 9 – Tue 10 Nov 2026"), + ("since Monday", (2026, 11, 9), NOW, "since Monday: Mon 9 – Tue 10 Nov 2026"), + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026"), + ("this month", (2026, 11, 1), NOW, "this month: Sun 1 – Tue 10 Nov 2026"), + ("last month", (2026, 10, 1), (2026, 11, 1), "last month: Thu 1 – Sat 31 Oct 2026"), + ("this year", (2026, 1, 1), NOW, "this year: Thu 1 Jan – Tue 10 Nov 2026"), + ("last year", (2025, 1, 1), (2026, 1, 1), "last year: Wed 1 Jan – Wed 31 Dec 2025"), + ("2025", (2025, 1, 1), (2026, 1, 1), "2025: Wed 1 Jan – Wed 31 Dec 2025"), + ("2026", (2026, 1, 1), NOW, "2026: Thu 1 Jan – Tue 10 Nov 2026"), + ("October 2025 | Oct 2025", (2025, 10, 1), (2025, 11, 1), "October 2025: Wed 1 – Fri 31 Oct 2025"), + ("October | oct", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026"), + ("November", (2026, 11, 1), NOW, "November 2026: Sun 1 – Tue 10 Nov 2026"), + ("December", (2025, 12, 1), (2026, 1, 1), "December 2025: Mon 1 – Wed 31 Dec 2025"), # the latest December that has begun + ("June to August 2026 | between June and August 2026 | from June to August 2026 | June - August 2026", (2026, 6, 1), (2026, 9, 1), + "June 2026 to August 2026: Mon 1 Jun – Mon 31 Aug 2026"), + ("December to February", (2025, 12, 1), (2026, 3, 1), "December 2025 to February 2026: Mon 1 Dec 2025 – Sat 28 Feb 2026"), + ("5 to 10 Sep | 5 Sep to 10 Sep | Sat 5 – Thu 10 Sep 2026", (2026, 9, 5), (2026, 9, 11), "Sat 5 – Thu 10 Sep 2026"), + ("Saturday to Sunday", (2026, 11, 7), (2026, 11, 9), "Saturday to Sunday: Sat 7 – Sun 8 Nov 2026"), + ("Monday to now", (2026, 11, 9), NOW, "Monday to now: Mon 9 – Tue 10 Nov 2026"), + ("2026-09-05 | 5 Sep | 5 September | Sat 5 Sep | Saturday 5 September 2026 | 5th of September | September 5 | on 5 Sep", + (2026, 9, 5), (2026, 9, 6), "Sat 5 Sep 2026"), + ("5 September 2025 | Sep 5, 2025", (2025, 9, 5), (2025, 9, 6), "Fri 5 Sep 2025"), + ("29 Feb", (2024, 2, 29), (2024, 3, 1), "Thu 29 Feb 2024"), # the latest that has been + ("Monday | last Monday | on Monday", (2026, 11, 9), (2026, 11, 10), "Monday: Mon 9 Nov 2026"), + ("Tuesday | tue", (2026, 11, 3), (2026, 11, 4), "Tuesday: Tue 3 Nov 2026"), # the latest before today: never today + ("last Saturday | Saturday | sat", (2026, 11, 7), (2026, 11, 8), "Saturday: Sat 7 Nov 2026"), + ("Christmas Day | Christmas | christmas day 2025", (2025, 12, 25), (2025, 12, 26), "Christmas Day: Thu 25 Dec 2025"), + ("Melbourne Cup | Melbourne Cup Day | the Melbourne Cup | cup day", (2026, 11, 3), (2026, 11, 4), "Melbourne Cup Day: Tue 3 Nov 2026"), + ("Melbourne Cup 2025", (2025, 11, 4), (2025, 11, 5), "Melbourne Cup Day: Tue 4 Nov 2025"), + ("Christmas to New Year's Day", (2025, 12, 25), (2026, 1, 2), "Christmas Day to New Year's Day: Thu 25 Dec 2025 – Thu 1 Jan 2026"), + ("this morning", (2026, 11, 10, 6), (2026, 11, 10, 12), "this morning: Tue 10 Nov 2026 6am – 12pm"), + ("this afternoon", (2026, 11, 10, 12), NOW, "this afternoon: Tue 10 Nov 2026 12pm – 2:05pm"), + ("yesterday afternoon", (2026, 11, 9, 12), (2026, 11, 9, 18), "yesterday afternoon: Mon 9 Nov 2026 12pm – 6pm"), + ("Tuesday evening", (2026, 11, 3, 18), (2026, 11, 4), "Tuesday evening: Tue 3 Nov 2026 6pm – midnight"), + ("Saturday morning", (2026, 11, 7, 6), (2026, 11, 7, 12), "Saturday morning: Sat 7 Nov 2026 6am – 12pm"), + ("last night | overnight", (2026, 11, 9, 22), (2026, 11, 10, 6), "last night: Mon 9 Nov 10pm – Tue 10 Nov 2026 6am"), + ("Tuesday night", (2026, 11, 2, 22), (2026, 11, 3, 6), "Tuesday night: Mon 2 Nov 10pm – Tue 3 Nov 2026 6am"), + ("since 6am | since 6 am | since 06:00", (2026, 11, 10, 6), NOW, "since 6am: Tue 10 Nov 2026 6am – 2:05pm"), + ("since 3pm | since 15:00", (2026, 11, 9, 15), NOW, "since 3pm: Mon 9 Nov 3pm – Tue 10 Nov 2026 2:05pm"), # the latest 3pm + ("since midnight", (2026, 11, 10), NOW, "since midnight: Tue 10 Nov 2026 12am – 2:05pm"), + ("since 5 Sep", (2026, 9, 5), NOW, "Sat 5 Sep – Tue 10 Nov 2026"), + ("on record | all time | all-time | ever | of all time | the whole record", (2024, 3, 1), NOW, "on record: Fri 1 Mar 2024 – Tue 10 Nov 2026"), +) +def test_every_row_of_the_table_on_a_tuesday(words, start, end, text): + check(TUESDAY, words, start, end, text, first_held=HELD) + + +def test_a_period_hands_back_its_days_and_the_strings_todays_tools_take(): + week = read("last week", TUESDAY) + assert (week.first_day, week.last_day, week.cut) == (at(2026, 11, 2).date(), at(2026, 11, 8).date(), None) + assert week.as_naive_strings() == ("2026-11-02 00:00:00", "2026-11-08 23:59:59") + assert read("today", TUESDAY).as_naive_strings() == ("2026-11-10 00:00:00", "2026-11-10 14:04:59") + assert read("last night", TUESDAY).as_naive_strings() == ("2026-11-09 22:00:00", "2026-11-10 05:59:59") + assert read_period(None, None, None, now=TUESDAY, tz=TZ, default="last 24 hours").asked == "last 24 hours" # nothing asked: the default + assert read_period("", " ", None, now=TUESDAY, tz=TZ, default="yesterday").text == "yesterday: Mon 9 Nov 2026" # blanks aren't asking + + +# ---------- Mon 9 Nov 2026 10:00 ---------- +MONDAY = at(2026, 11, 9, 10) + + +@rows( + ("week to date", (2026, 11, 9), (2026, 11, 9, 10), "week to date: Mon 9 Nov 2026"), + ("since Monday", (2026, 11, 9), (2026, 11, 9, 10), "since Monday: Mon 9 Nov 2026"), # this Monday: today + ("Monday | last Monday", (2026, 11, 2), (2026, 11, 3), "Monday: Mon 2 Nov 2026"), # the latest before today + ("Sunday", (2026, 11, 8), (2026, 11, 9), "Sunday: Sun 8 Nov 2026"), + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026"), + ("this week", (2026, 11, 3), (2026, 11, 9, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026"), + ("Monday night", (2026, 11, 1, 22), (2026, 11, 2, 6), "Monday night: Sun 1 Nov 10pm – Mon 2 Nov 2026 6am"), + ("Sunday evening", (2026, 11, 8, 18), (2026, 11, 9), "Sunday evening: Sun 8 Nov 2026 6pm – midnight"), + ("Saturday to Sunday", (2026, 11, 7), (2026, 11, 9), "Saturday to Sunday: Sat 7 – Sun 8 Nov 2026"), +) +def test_on_a_monday(words, start, end, text): + check(MONDAY, words, start, end, text) + + +# ---------- Sun 1 Nov 2026 14:05: the 1st of a month ---------- +FIRST = at(2026, 11, 1, 14, 5) +FIRST_NOW = (2026, 11, 1, 14, 5) + + +@rows( + ("this month", (2026, 11, 1), FIRST_NOW, "this month: Sun 1 Nov 2026"), + ("last month", (2026, 10, 1), (2026, 11, 1), "last month: Thu 1 – Sat 31 Oct 2026"), + ("November", (2026, 11, 1), FIRST_NOW, "November 2026: Sun 1 Nov 2026"), + ("October", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026"), + ("December", (2025, 12, 1), (2026, 1, 1), "December 2025: Mon 1 – Wed 31 Dec 2025"), + ("this week", (2026, 10, 26), FIRST_NOW, "the last 7 days: Mon 26 Oct – Sun 1 Nov 2026"), + ("last week", (2026, 10, 19), (2026, 10, 26), "last week: Mon 19 – Sun 25 Oct 2026"), + ("week to date", (2026, 10, 26), FIRST_NOW, "week to date: Mon 26 Oct – Sun 1 Nov 2026"), + ("past month", (2026, 10, 3), FIRST_NOW, "the last 30 days: Sat 3 Oct – Sun 1 Nov 2026"), + ("1 Nov", (2026, 11, 1), FIRST_NOW, "Sun 1 Nov 2026"), + ("Sunday", (2026, 10, 25), (2026, 10, 26), "Sunday: Sun 25 Oct 2026"), + ("since Sunday", (2026, 11, 1), FIRST_NOW, "since Sunday: Sun 1 Nov 2026"), # since a weekday: today, if it is that day + ("yesterday", (2026, 10, 31), (2026, 11, 1), "yesterday: Sat 31 Oct 2026"), + ("October to November", (2026, 10, 1), FIRST_NOW, "October 2026 to November 2026: Thu 1 Oct – Sun 1 Nov 2026"), +) +def test_on_the_first_of_a_month(words, start, end, text): + check(FIRST, words, start, end, text) + + +# ---------- Fri 1 Jan 2027 09:00 ---------- +NEW_YEAR = at(2027, 1, 1, 9) +NEW_YEAR_NOW = (2027, 1, 1, 9) + + +@rows( + ("this year", (2027, 1, 1), NEW_YEAR_NOW, "this year: Fri 1 Jan 2027"), + ("last year", (2026, 1, 1), (2027, 1, 1), "last year: Thu 1 Jan – Thu 31 Dec 2026"), + ("2026", (2026, 1, 1), (2027, 1, 1), "2026: Thu 1 Jan – Thu 31 Dec 2026"), + ("this month", (2027, 1, 1), NEW_YEAR_NOW, "this month: Fri 1 Jan 2027"), + ("last month", (2026, 12, 1), (2027, 1, 1), "last month: Tue 1 – Thu 31 Dec 2026"), + ("December", (2026, 12, 1), (2027, 1, 1), "December 2026: Tue 1 – Thu 31 Dec 2026"), + ("January", (2027, 1, 1), NEW_YEAR_NOW, "January 2027: Fri 1 Jan 2027"), + ("February", (2026, 2, 1), (2026, 3, 1), "February 2026: Sun 1 – Sat 28 Feb 2026"), + ("Christmas Day", (2026, 12, 25), (2026, 12, 26), "Christmas Day: Fri 25 Dec 2026"), + ("New Year's Day | new years day", (2027, 1, 1), NEW_YEAR_NOW, "New Year's Day: Fri 1 Jan 2027"), + ("last week", (2026, 12, 21), (2026, 12, 28), "last week: Mon 21 – Sun 27 Dec 2026"), + ("this week", (2026, 12, 26), NEW_YEAR_NOW, "the last 7 days: Sat 26 Dec 2026 – Fri 1 Jan 2027"), + ("31 Dec", (2026, 12, 31), (2027, 1, 1), "Thu 31 Dec 2026"), + ("5 Jan", (2026, 1, 5), (2026, 1, 6), "Mon 5 Jan 2026"), + ("past year", (2026, 1, 2), NEW_YEAR_NOW, "the last 365 days: Fri 2 Jan 2026 – Fri 1 Jan 2027"), + ("December to January", (2026, 12, 1), NEW_YEAR_NOW, "December 2026 to January 2027: Tue 1 Dec 2026 – Fri 1 Jan 2027"), + ("yesterday", (2026, 12, 31), (2027, 1, 1), "yesterday: Thu 31 Dec 2026"), +) +def test_on_new_years_day(words, start, end, text): + check(NEW_YEAR, words, start, end, text) + + +# ---------- Tue 29 Feb 2028 14:05 ---------- +LEAP = at(2028, 2, 29, 14, 5) +LEAP_NOW = (2028, 2, 29, 14, 5) + + +@rows( + ("29 Feb | 29 February 2028", (2028, 2, 29), LEAP_NOW, "Tue 29 Feb 2028"), + ("28 Feb", (2028, 2, 28), (2028, 2, 29), "Mon 28 Feb 2028"), + ("this month", (2028, 2, 1), LEAP_NOW, "this month: Tue 1 – Tue 29 Feb 2028"), + ("February", (2028, 2, 1), LEAP_NOW, "February 2028: Tue 1 – Tue 29 Feb 2028"), + ("last month", (2028, 1, 1), (2028, 2, 1), "last month: Sat 1 – Mon 31 Jan 2028"), + ("last year", (2027, 1, 1), (2028, 1, 1), "last year: Fri 1 Jan – Fri 31 Dec 2027"), + ("past year | 1y", (2027, 3, 2), LEAP_NOW, "the last 365 days: Tue 2 Mar 2027 – Tue 29 Feb 2028"), + ("3m", (2027, 12, 1), LEAP_NOW, "the last 3 months: Wed 1 Dec 2027 – Tue 29 Feb 2028"), + ("February 2027", (2027, 2, 1), (2027, 3, 1), "February 2027: Mon 1 – Sun 28 Feb 2027"), +) +def test_on_29_february(words, start, end, text): + check(LEAP, words, start, end, text) + + +def test_29_february_in_a_year_without_one_is_no_date(): + with pytest.raises(PeriodError, match="29 February 2027 isn't a date"): + read("29 Feb 2027", LEAP) + with pytest.raises(PeriodError, match="isn't a date"): + read("31 Sep", LEAP) + + +# ---------- Tue 10 Nov 2026 00:30 ---------- +LATE = at(2026, 11, 10, 0, 30) +LATE_NOW = (2026, 11, 10, 0, 30) + + +@rows( + ("today", (2026, 11, 10), LATE_NOW, "today: Tue 10 Nov 2026"), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026"), + ("last 2 hours", (2026, 11, 9, 22, 30), LATE_NOW, "the last 2 hours: Mon 9 Nov 10:30pm – Tue 10 Nov 2026 12:30am"), + ("since 6am", (2026, 11, 9, 6), LATE_NOW, "since 6am: Mon 9 Nov 6am – Tue 10 Nov 2026 12:30am"), + ("last night | overnight", (2026, 11, 9, 22), LATE_NOW, "last night: Mon 9 Nov 10pm – Tue 10 Nov 2026 12:30am"), # still going + ("yesterday evening", (2026, 11, 9, 18), (2026, 11, 10), "yesterday evening: Mon 9 Nov 2026 6pm – midnight"), + ("last 7 days", (2026, 11, 4), LATE_NOW, "the last 7 days: Wed 4 – Tue 10 Nov 2026"), +) +def test_at_half_past_midnight(words, start, end, text): + check(LATE, words, start, end, text) + + +def test_at_half_past_midnight_this_morning_is_still_ahead(): + with pytest.raises(PeriodError, match="in the future .*use forecast"): + read("this morning", LATE) + + +# ---------- the days the clocks change ---------- +def test_the_day_the_clocks_go_back_has_25_hours_and_its_hours_are_real(): + noon = at(2026, 4, 5, 12) + assert hours(read("today", noon)) == 13 # midnight was summer time + assert read("last 24 hours", noon).start == at(2026, 4, 4, 13) and hours(read("last 24 hours", noon)) == 24 + night = read("last night", noon) + assert (night.start, night.end, hours(night)) == (at(2026, 4, 4, 22), at(2026, 4, 5, 6), 9) + assert hours(read("yesterday", at(2026, 4, 6, 12))) == 25 + since = read("since 2am", noon) # the second 2am: the latest + assert (since.start.fold, since.start.timestamp(), hours(since)) == (1, at(2026, 4, 5, 2, fold=1).timestamp(), 10) + early = read("last 3 hours", at(2026, 4, 5, 4)) # 4am back to the first 2am + assert (early.start.fold, hours(early), early.text) == (0, 3, "the last 3 hours: Sun 5 Apr 2026 2am – 4am") + assert read("Easter Sunday", noon).text == "Easter Sunday: Sun 5 Apr 2026" + two = read("last 2 days", at(2026, 4, 6, 12), whole_days=True) + assert (two.start, two.end, hours(two), two.text) == (at(2026, 4, 4), at(2026, 4, 6), 49, "the last 2 days: Sat 4 – Sun 5 Apr 2026") + + +def test_the_day_the_clocks_go_forward_has_23_hours_and_its_hours_are_real(): + noon = at(2026, 10, 4, 12) + assert hours(read("today", noon)) == 11 + assert read("last 24 hours", noon).start == at(2026, 10, 3, 11) and hours(read("last 24 hours", noon)) == 24 + night = read("last night", noon) + assert (night.start, night.end, hours(night)) == (at(2026, 10, 3, 22), at(2026, 10, 4, 6), 7) + assert hours(read("yesterday", at(2026, 10, 5, 12))) == 23 + early = read("last 3 hours", at(2026, 10, 4, 4)) # three real hours: 2am to 3am never happened + assert (early.start, early.text) == (at(2026, 10, 4), "the last 3 hours: Sun 4 Oct 2026 12am – 4am") + skipped = read("since 2:30am", noon) # a time that never happened: when the clocks jump + assert (skipped.start, hours(skipped)) == (at(2026, 10, 4, 3), 9) + assert read(None, noon, start="2026-10-04 02:30").start == at(2026, 10, 4, 3) + + +# ---------- whole-day tools ---------- +CUT = "to Mon 9 Nov: today isn't over" +WHOLE_DAYS = [ # (words, start, end, text, cut) at TUESDAY + ("last 7 days", (2026, 11, 3), (2026, 11, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026", CUT), # that many whole days to yesterday + ("this week", (2026, 11, 3), (2026, 11, 10), "the last 7 days: Tue 3 – Mon 9 Nov 2026", CUT), + ("3m", (2026, 8, 11), (2026, 11, 10), "the last 3 months: Tue 11 Aug – Mon 9 Nov 2026", CUT), + ("past year", (2025, 11, 10), (2026, 11, 10), "the last 365 days: Mon 10 Nov 2025 – Mon 9 Nov 2026", CUT), + ("1d", (2026, 11, 9), (2026, 11, 10), "the last day: Mon 9 Nov 2026", CUT), + ("last 48 hours", (2026, 11, 8), (2026, 11, 10), "the last 2 days: Sun 8 – Mon 9 Nov 2026", CUT), + ("this month", (2026, 11, 1), (2026, 11, 10), "this month: Sun 1 – Mon 9 Nov 2026", CUT), # a calendar one runs to yesterday + ("this year", (2026, 1, 1), (2026, 11, 10), "this year: Thu 1 Jan – Mon 9 Nov 2026", CUT), + ("since Monday", (2026, 11, 9), (2026, 11, 10), "since Monday: Mon 9 Nov 2026", CUT), + ("on record", (2024, 3, 1), (2026, 11, 10), "on record: Fri 1 Mar 2024 – Mon 9 Nov 2026", CUT), + ("yesterday", (2026, 11, 9), (2026, 11, 10), "yesterday: Mon 9 Nov 2026", None), # nothing of today: not cut + ("last week", (2026, 11, 2), (2026, 11, 9), "last week: Mon 2 – Sun 8 Nov 2026", None), + ("October", (2026, 10, 1), (2026, 11, 1), "October 2026: Thu 1 – Sat 31 Oct 2026", None), + ("Christmas Day", (2025, 12, 25), (2025, 12, 26), "Christmas Day: Thu 25 Dec 2025", None), +] + + +@pytest.mark.parametrize("words, start, end, text, cut", WHOLE_DAYS, ids=[row[0] for row in WHOLE_DAYS]) +def test_whole_day_tools_take_whole_days_to_yesterday(words, start, end, text, cut): + period = read(words, TUESDAY, whole_days=True, first_held=HELD) + assert (period.start, period.end, period.text, period.cut) == (at(*start), at(*end), text, cut) + + +def test_whole_day_tools_cut_on_other_days_too(): + monday = read("this week", MONDAY, whole_days=True) + assert (monday.text, monday.cut) == ("the last 7 days: Mon 2 – Sun 8 Nov 2026", "to Sun 8 Nov: today isn't over") + leap = read("this month", LEAP, whole_days=True) + assert (leap.text, leap.cut) == ("this month: Tue 1 – Mon 28 Feb 2028", "to Mon 28 Feb: today isn't over") + assert read("1y", LEAP, whole_days=True).text == "the last 365 days: Mon 1 Mar 2027 – Mon 28 Feb 2028" + assert read("past year", NEW_YEAR, whole_days=True).text == "the last 365 days: Thu 1 Jan – Thu 31 Dec 2026" + assert read("this year", FIRST, whole_days=True).text == "this year: Thu 1 Jan – Sat 31 Oct 2026" + + +@pytest.mark.parametrize("words, now", [ + ("today", TUESDAY), ("last 5 hours", TUESDAY), ("30 min", TUESDAY), ("this month", FIRST), ("November", FIRST), + ("week to date", MONDAY), ("since Monday", MONDAY), ("this year", NEW_YEAR), ("New Year's Day", NEW_YEAR), ("29 Feb", LEAP), +]) +def test_a_whole_day_tool_refuses_what_leaves_no_whole_day(words, now): + with pytest.raises(PeriodError, match=r"leaves no whole day.*use summary or readings") as caught: + read(words, now, whole_days=True) + assert caught.value.forms == () + + +@pytest.mark.parametrize("words", ["this morning", "yesterday afternoon", "last night", "Tuesday night", "since 6am"]) +def test_a_whole_day_tool_refuses_part_of_a_day(words): + with pytest.raises(PeriodError, match=r"is part of a day.*use summary or readings"): + read(words, TUESDAY, whole_days=True) + + +def test_a_whole_day_tool_takes_dates_only_and_cuts_them_to_yesterday(): + period = read(None, TUESDAY, start="2026-11-01", whole_days=True) + assert (period.start, period.end, period.text, period.cut) == (at(2026, 11, 1), at(2026, 11, 10), "Sun 1 – Mon 9 Nov 2026", CUT) + period = read(None, TUESDAY, start="2026-10-01", end="2026-10-31", whole_days=True) + assert (period.start, period.end, period.cut) == (at(2026, 10, 1), at(2026, 11, 1), None) + with pytest.raises(PeriodError, match=r"has a time.*use summary or readings"): + read(None, TUESDAY, start="2026-11-01 06:00", whole_days=True) + with pytest.raises(PeriodError, match="leaves no whole day"): + read(None, TUESDAY, start="2026-11-10", whole_days=True) + + +# ---------- start and end ---------- +def test_start_and_end_are_the_stations_clock_and_a_date_end_includes_the_day(): + period = read(None, TUESDAY, start="2026-11-01", end="2026-11-03") + assert (period.asked, period.start, period.end, period.text) == ("start/end", at(2026, 11, 1), at(2026, 11, 4), "Sun 1 – Tue 3 Nov 2026") + assert (period.first_day, period.last_day, period.as_naive_strings()) == ( + at(2026, 11, 1).date(), at(2026, 11, 3).date(), ("2026-11-01 00:00:00", "2026-11-03 23:59:59")) + period = read(None, TUESDAY, start="2026-11-01 06:00", end="2026-11-01 09:30") # an end with a time stops at it + assert (period.start, period.end, period.text) == (at(2026, 11, 1, 6), at(2026, 11, 1, 9, 30), "Sun 1 Nov 2026 6am – 9:30am") + assert read(None, TUESDAY, start="2026-11-01").end == TUESDAY # no end: to now + assert read(None, TUESDAY, start="2026-11-01", end="2026-12-25").end == TUESDAY # nor past it + + +def test_a_start_or_end_with_an_offset_is_moved_to_the_stations_clock(): + assert read(None, TUESDAY, start="2026-11-09T20:00:00Z").start == at(2026, 11, 10, 7) # UTC: 7am in daylight saving + period = read(None, TUESDAY, start="2026-11-01T00:00:00+00:00", end="2026-11-01T06:00:00+00:00") + assert (period.start, period.end) == (at(2026, 11, 1, 11), at(2026, 11, 1, 17)) + assert read(None, at(2026, 6, 10, 12), start="2026-06-01T00:00:00Z").start == at(2026, 6, 1, 10) # standard time + + +@pytest.mark.parametrize("period, start, end, says", [ + ("today", "2026-11-01", None, "not both"), + ("today", None, "2026-11-03", "not both"), + (None, None, "2026-11-03", "needs a `start`"), + (None, "1 Nov", None, "isn't a date or time"), + (None, "2026-11-05", "2026-11-03", "must be before"), + (None, "2026-11-11", None, "in the future.*use forecast"), +]) +def test_start_and_end_errors_say_what_to_send(period, start, end, says): + with pytest.raises(PeriodError, match=says) as caught: + read(period, TUESDAY, start=start, end=end) + assert "It is now Tue 10 Nov 2026 2:05pm." in str(caught.value) + + +# ---------- errors that teach ---------- +@pytest.mark.parametrize("words", ["yesterday afternoon and", "June, July", "last summer", "the last 7 days please", "rain this week", + "0 days", "last thirteen days", "m", "5", "tonight"]) +def test_words_outside_the_table_list_the_forms_with_what_each_means_now(words): + with pytest.raises(PeriodError) as caught: + read(words, TUESDAY, first_held=HELD) + error = caught.value + assert f"{words!r} isn't a period this tool can read" in error.message and "It is now Tue 10 Nov 2026 2:05pm." in error.message + forms = dict(error.forms) + assert forms["today"] == "today: Tue 10 Nov 2026" + assert forms["last N days, Nd (N from 2)"] == "the last 7 days: Wed 4 – Tue 10 Nov 2026" + assert forms["last N months, Nm, N mo (m is months, never minutes)"] == "the last 3 months: Wed 12 Aug – Tue 10 Nov 2026" + assert forms["last week (the previous Monday to Sunday)"] == "last week: Mon 2 – Sun 8 Nov 2026" + assert forms["a year, such as 2025"] == "2025: Wed 1 Jan – Wed 31 Dec 2025" + assert forms["a day, such as 2026-09-05, 5 Sep, 5 September 2025, Sat 5 Sep (with no year, the latest not after today)"] == \ + "5 Sep: Sat 5 Sep 2026" + assert forms["on record, all time, ever (from the first reading held)"] == "on record: Fri 1 Mar 2024 – Tue 10 Nov 2026" + assert "- last N days, Nd (N from 2) → the last 7 days: Wed 4 – Tue 10 Nov 2026" in str(error) + assert len(forms) == 27 + + +def test_a_whole_day_tools_forms_are_its_own(): + with pytest.raises(PeriodError) as caught: + read("last summer", TUESDAY, whole_days=True) + forms = dict(caught.value.forms) + assert "as dates ('YYYY-MM-DD')" in caught.value.message + assert forms["last N days, Nd (N from 2)"] == "the last 7 days: Tue 3 – Mon 9 Nov 2026" + assert not {"today", "last N minutes, N min", "since 6am, since Monday"} & set(forms) + assert forms["on record, all time, ever (from the first reading held)"] == "from the first reading held, for the readings asked about, to now" + + +@pytest.mark.parametrize("words", ["tomorrow", "tomorrow morning", "next week", "the next 3 days", "December 2026", "2027", + "Christmas Day 2026", "5 Dec 2026", "this evening"]) +def test_a_future_period_points_to_the_forecast(words): + with pytest.raises(PeriodError, match=r"is in the future.*for what's ahead, use forecast") as caught: + read(words, TUESDAY) + assert caught.value.forms == () and "It is now Tue 10 Nov 2026 2:05pm." in str(caught.value) + + +def test_a_weekday_that_does_not_match_the_date_is_named(): + with pytest.raises(PeriodError, match=r"5 September 2026 is a Saturday, not a Friday: send 'Sat 5 Sep 2026'"): + read("Fri 5 Sep", TUESDAY) + + +def test_longer_than_anything_held_points_to_on_record(): + with pytest.raises(PeriodError, match="longer than ten years.*'on record'"): + read("last 20 years", TUESDAY) + assert read("last 10 years", TUESDAY).start == at(2016, 11, 13) # 3650 days: today and the 3649 before + + +def test_on_record_needs_the_first_reading_held(): + with pytest.raises(PeriodError, match="Nothing is held yet"): + read("on record", TUESDAY) + assert read("on record", TUESDAY, first_held=at(2025, 6, 1).date()).start == at(2025, 6, 1) From d8b066e5c4766a1ea453da5b60f9a6c337ae0d76 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:26:12 +0000 Subject: [PATCH 016/125] Averages weighted by time: part days for their hours, hourly air days for theirs weather_history's average was the mean of the period's day means, and the part of a day at either end of a period is its own day (ecowitt/period.py), so an hour of a day weighed as much as a whole one (a 13-hour span gave 16.2 where the figure over its time is about 13.1). air_quality's was the mean of every stored reading, so a day held only as the cloud's hourly averages counted its 24 readings against a 5-minute day's 288. Both now take a period's average over its time, by the rule the day rows (storage/days.py) use for a day: - lines.time_mean: each day's mean counts for the seconds of it the period holds (a part day for its hours, a clock-change day for its 23 or 25). Chosen over the mean of the period's half-hour means because a day row's mean already is the mean of its half-hour means and stands for the whole day; weighting the days by time carries that rule up a level and is the same figure wherever every half hour is held. It also keeps the period's average the time-weighted mean of the per-day averages the answer lists, needs no count of half hours (the day rows keep none), and works for Ecowitt's daily records, which have a mean but no half hours. - weather_history: the period's average and each row of the breakdown (a day, or a month over its time) by time_mean. - lines.readings_mean, for air_quality: each day's mean of its half-hour means (so a whole day's average is its day row's, air_days' _avg), the days by time_mean. Rather than each reading weighted by the time it covers: the rows carry no resolution, and within a day that would differ from the day row where a half hour is short of readings. - Rain rate gets an average in weather_history; the rain counters (daily, event, 1_hour, weekly, monthly, yearly) still don't: a reading told as its last (column mode "last") has no mean, where before every rainfall reading was left out. - The prompt no longer calls the average "the mean of the daily means". Tests: tests/test_averages.py, worked out by hand: a 36-hour period with a part day at each end (13.0, not 10.0), a month row with a part day (10.8, not 18.0), rain rate's average present and the counters' absent, an air period across an hourly-only day and a 5-minute one, whole and in parts (14.0 and 12.0, not 19.1 and 18.3), and an air day held sparsely in the afternoon whose average is its day row's. Updated test_airgradient.py::test_a_single_reading_spike_is_in_none_of_the_figures_either, which asserted the plain mean of the readings: it now starts on a half hour and asserts the mean by half hours. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/airgradient/source.py | 15 +++++--- lib/ecowitt/query.py | 33 ++++++++-------- lib/lines.py | 33 +++++++++++++++- lib/prompt.py | 2 +- tests/test_airgradient.py | 9 +++-- tests/test_averages.py | 80 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 143 insertions(+), 29 deletions(-) create mode 100644 tests/test_averages.py diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 6c355a1a..43901973 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -37,7 +37,7 @@ from ..ecowitt.homeassistant import HomeAssistant from ..ecowitt.live import BUCKET from ..ecowitt.query import KEEP_HOURS, MINUTE_HOURS -from ..lines import RANGE_KEEP_DAYS, Plotted, Sample, build_line +from ..lines import RANGE_KEEP_DAYS, Plotted, Sample, build_line, readings_mean from ..panels import panel_for from ..specs import AIR_SOURCE, Chart, Line from ..storage import Storage @@ -691,9 +691,10 @@ async def history(self, start: str | None, end: str | None, chart: bool = False, "readings": len(rows)} units = {**{name: unit for name, (_, unit) in METRICS.items()}, **{name: EXTRA_UNITS[name] for name in metrics or [] if name in EXTRA}} # the sensor's own temperature and humidity, only when asked for + span = local_epoch(t0, self.tz), local_epoch(t1, self.tz) for name, unit in units.items(): if pts := [(r["ts"], r[name]) for r in rows if name in r]: - out[name] = self._entry(name, pts, unit) + out[name] = self._entry(name, pts, unit, span) if trimmed: out["note_period"] = f"Only the last {MAX_DAYS} days can be covered per question; this covers {out['period']}." if hourly: @@ -714,12 +715,14 @@ async def history(self, start: str | None, end: str | None, chart: bool = False, out["chart"] = CHART_HINT return out - def _entry(self, name: str, pts: list[tuple[int, float]], unit: str) -> dict: - """A metric's lowest, highest and average over these readings ((ts, value)), with when the extremes happened; a rated metric - (METRICS) with the ratings of its high and average, and PM2.5 with their AQI and band too.""" + def _entry(self, name: str, pts: list[tuple[int, float]], unit: str, span: tuple[int, int]) -> dict: + """A metric's lowest, highest and average over these readings ((ts, value)) of the period `span` (epochs), with when the extremes + happened; a rated metric (METRICS) with the ratings of its high and average, and PM2.5 with their AQI and band too. The average is + by time, as the day rows take a day's (lines.readings_mean): an hourly reading of the older history counts for its hour, not as one + reading among a 5-minute hour's twelve.""" lo, hi = min(pts, key=lambda p: p[1]), max(pts, key=lambda p: p[1]) entry = {"unit": unit, "low": lo[1], "low_time": when(lo[0], self.tz), "high": hi[1], "high_time": when(hi[0], self.tz), - "average": round(statistics.fmean(v for _, v in pts), 1)} + "average": round(readings_mean(pts, *span, self.tz), 1)} if name in METRICS: entry["high_rating"], entry["average_rating"] = rating(name, hi[1]), rating(name, entry["average"]) if name == "pm2_5": diff --git a/lib/ecowitt/query.py b/lib/ecowitt/query.py index 3caf4db7..ba830c08 100644 --- a/lib/ecowitt/query.py +++ b/lib/ecowitt/query.py @@ -4,15 +4,15 @@ where the storage has it, else 30-minute: one request per week); longer, the 30-minute readings where the storage holds them all, else Ecowitt's daily records (10am to 10am in Melbourne: UTC days) and the newest days at 30 minutes. The records, the breakdown by day or by month and the averages come from the period's days instead (period.py): each whole day's row, worked out from the finest readings held -for it, so a record's time is as close as those readings give it, and the part of a day at either end from its own readings. +for it, so a record's time is as close as those readings give it, and the part of a day at either end from its own readings. An average +weighs each of those days by the time of it the period holds. """ import logging from datetime import date, datetime, time, timedelta -from statistics import fmean from ..captions import AVERAGE_CHART_HINT, CHART_HINT, STACK_CHART_HINT, DIRECTION_CHART_HINT, wants_chart -from ..lines import DAY, Plotted, Sample, build_line, how_drawn, shaded_up_to +from ..lines import DAY, Plotted, Sample, build_line, how_drawn, shaded_up_to, time_mean from ..daytable import grouping_in from ..rain import rain_bars, rain_slots from ..timeutil import at_hour, day_bounds, day_text, local_date, now_local, parse_local, SLOT @@ -301,7 +301,7 @@ def _result(self, key: str, ext: dict) -> dict: if self.held: # each month's low/high with when and date for w, e in d.items(): _, row[f"{w}_when"], row[f"{w}_date"] = describe_time(e.ts, e.cycle, tz) - if (self.args.get("average") or self.turn.average_asked) and not key.startswith("rainfall"): # a rain total has no mean + if (self.args.get("average") or self.turn.average_asked) and p.column.mode != "last": # a rain counter (a total) has no mean; rain rate has self._add_averages(entry, {d.day: d.mean for d in p.days if d.mean is not None}) return entry @@ -337,21 +337,22 @@ def _label(self, day: date) -> str: ("Oct 2026") when the period is broken down by month.""" return day_text(day, year=False) if self.by_day else f"{day:%b %Y}" - def _add_averages(self, entry: dict, means: dict): - """The mean over the period, and per row of the breakdown (each day, or each month): the answer to "what was the average".""" - if not means: + def _add_averages(self, entry: dict, means: dict[date, float]): + """The mean over the period, and per row of the breakdown (each day, or each month): the answer to "what was the average". By + time, as a day row takes its own mean (lines.time_mean): each day's mean counts for the seconds of it the period holds, so the part + of a day at either end counts for its hours, not as a whole day, and a month for its time.""" + span = self.f.epoch(self.start), self.f.epoch(self.end), self.tz + if (mean := time_mean(means, *span)) is None: return fmt = lambda v: f"{v:.1f}" - entry["average"] = fmt(fmean(means.values())) - table = entry.get("daily" if self.by_day else "monthly") + entry["average"] = fmt(mean) + table = entry.get("daily" if self.by_day else "monthly") or {} + rows: dict[str, dict[date, float]] = {} for d, v in means.items(): - if table is not None and (label := self._label(d)) in table: - table[label].setdefault("_sum", []).append(v) - for table in (entry.get("daily"), entry.get("monthly")): - for row in (table or {}).values(): - values = row.pop("_sum", None) - if values: - row["avg"] = fmt(fmean(values)) + if (label := self._label(d)) in table: + rows.setdefault(label, {})[d] = v + for label, days in rows.items(): + table[label]["avg"] = fmt(time_mean(days, *span)) def _chart_spec(self, series_out: dict, field: str | None = None) -> Chart | None: """Line chart: one line per group for the field asked about (`field`, else chart_field; temperature by default, diff --git a/lib/lines.py b/lib/lines.py index 38f6a33a..06576853 100644 --- a/lib/lines.py +++ b/lib/lines.py @@ -12,13 +12,13 @@ import math from bisect import bisect_left, bisect_right from dataclasses import dataclass -from datetime import date, tzinfo +from datetime import date, timedelta, tzinfo from itertools import accumulate from statistics import fmean from typing import NamedTuple from .specs import Line -from .timeutil import SLOT, at_hour, local_date +from .timeutil import SLOT, at_hour, day_bounds, local_date DAY = 86400 SMOOTH_POINTS = 3 # a smoothed 5-minute line: each point is the mean of this many readings (15 minutes) @@ -114,6 +114,35 @@ def daily_summary(points, tz: tzinfo) -> dict[date, tuple[float, float, float]]: return _summarise(points, lambda ts: local_date(ts, tz)) +def time_mean(means: dict[date, float], start: int, end: int, tz: tzinfo) -> float | None: + """The mean over [start, end] (epochs, both included) of these days' means, each day counting for the seconds of it inside: a part of + a day at either end for its hours, a whole day for its 24 (23 or 25 on a clock-change day), however many readings it had. A day's own + mean is of its half-hour means (daily_summary's, its day row's), so where every half hour is held this is the mean of the period's + half-hour means. None when no day is inside.""" + weights = {d: min(b, end + 1) - max(a, start) for d in means for a, b in [day_bounds(d, tz)]} + inside = [d for d, w in weights.items() if w > 0] + return fmean([means[d] for d in inside], [weights[d] for d in inside]) if inside else None + + +def readings_mean(points: list[tuple[int, float]], start: int, end: int, tz: tzinfo) -> float | None: + """The mean of these readings ((ts, value)) over [start, end], by time as a day row takes it: each day's mean of its half-hour means, + then the days by time_mean. So a day held only as hourly averages counts for its hours, as a day of 5-minute readings does, not for + its number of readings. (A reading's day is found among the period's midnights, not worked out for each of a year's readings.)""" + first = local_date(start, tz) + days = [first + timedelta(days=n) for n in range((local_date(end, tz) - first).days + 1)] + ends = [day_bounds(d, tz)[1] for d in days] + slots: dict[tuple[int, int], list] = {} # (the day, the half hour): [sum, count] + for ts, value in points: + if start <= ts <= end: + got = slots.setdefault((bisect_right(ends, ts), ts // SLOT), [0.0, 0]) + got[0] += value + got[1] += 1 + means: dict[date, list[float]] = {} + for (day, _), (total, n) in slots.items(): + means.setdefault(days[day], []).append(total / n) + return time_mean({d: fmean(m) for d, m in means.items()}, start, end, tz) + + def summary_by(points, key) -> dict: """{key(ts): (mean, lowest low, highest high)} for buckets of any shape (the readings tool's blocks of local time); see _summarise.""" return _summarise(points, key) diff --git a/lib/prompt.py b/lib/prompt.py index 7f7628a2..9ab9eafa 100644 --- a/lib/prompt.py +++ b/lib/prompt.py @@ -65,7 +65,7 @@ - Say when each high or low happened by copying its "_when" text exactly as given ("at 7:05am", "around 3:30pm", or a window), then "on", the day's emoji and its "_date": "28.3°C around 3:30pm on ☀️ Fri 9 Jan 2026". Never change "at" to "around" or the reverse. - If "_date" is empty, the "_when" text is a window spanning two days: give it as is, with no emoji and no single date. - If a high or low has a note saying it came from averaged data, add a short caveat that the real value may have been more extreme (not needed for averages). -- Default to highs and lows. Give averages only when asked ("average", "mean"): set average=true on the history call, then use the series' "average" for the period (and "avg" per day or month), the mean of the daily means. Never work an average out from lows and highs. +- Default to highs and lows. Give averages only when asked ("average", "mean"): set average=true on the history call, then use the series' "average" for the period (and "avg" per day or month), each the average over its time (a part day counts for its hours). Never work an average out from lows and highs. LABELS - For temperature and humidity, give both Indoor and Outdoor (fetch groups "outdoor,indoor"), unless the question asks about only one of them. Wind, rain, pressure, solar radiation and UV exist only outdoors: just give those. diff --git a/tests/test_airgradient.py b/tests/test_airgradient.py index 5c104e04..5de684fe 100644 --- a/tests/test_airgradient.py +++ b/tests/test_airgradient.py @@ -453,17 +453,18 @@ async def test_a_single_reading_spike_is_in_none_of_the_figures_either(tmp_path) from lib.timeutil import local_date from tests.fakes import TZ air, _ = await make(tmp_path) - start = air.now().replace(microsecond=0) - timedelta(hours=1) - t0 = int(start.replace(tzinfo=TZ).timestamp()) + 600 + first = (int(air.now().replace(tzinfo=TZ).timestamp()) - 3600) // 1800 * 1800 # the start of a half hour, an hour or more ago + start = datetime.fromtimestamp(first, TZ).replace(tzinfo=None) + t0 = first + 600 levels = [(1, 2, 3), (1, 2, 4), (15.3, 14.2, 28.7), (3, 8, 10), (2, 4, 5), (2, 3, 4)] rows = [{"ts": t0 + 300 * i, "pm1": a, "pm2_5": b, "pm10": c} for i, (a, b, c) in enumerate(levels)] async def day_rows(day, refresh=False): return [r for r in rows if local_date(r["ts"], TZ) == day] air._day_rows = day_rows - out = await air.history(start.strftime("%Y-%m-%d %H:%M:%S"), None) + out = await air.history(f"{start:%Y-%m-%d %H:%M:%S}", f"{start + timedelta(hours=1):%Y-%m-%d %H:%M:%S}") assert out["pm10"]["high"] == 10 and out["pm2_5"]["high"] == 8 and out["pm1"]["high"] == 3 # not 28.7, 14.2 and 15.3 - assert out["pm10"]["average"] == round((3 + 4 + 10 + 5 + 4) / 5, 1) # and not in the mean + assert out["pm10"]["average"] == round(((3 + 4 + 10) / 3 + (5 + 4) / 2) / 2, 1) # and not in the mean (by half hours) day = local_date(t0, TZ) await air.store.save_day(day, [r for r in rows if local_date(r["ts"], TZ) == day]) # the day rows take the same spikes out figures = await air.store.day_figures(day, day, ["pm10_max", "pm2_5_max", "pm10_avg"]) diff --git a/tests/test_averages.py b/tests/test_averages.py new file mode 100644 index 00000000..71f0fc34 --- /dev/null +++ b/tests/test_averages.py @@ -0,0 +1,80 @@ +"""Averages weighted by time (docs/mcp-service.md 3.3): weather_history's and air_quality's average of a period count each day for the time of +it the period holds (lines.time_mean), so the part of a day at either end counts for its hours, not as a whole day, and an air day held only +as hourly averages counts for its 24 hours, not for its 24 readings against a 5-minute day's 288. Rain rate has an average; the rain +counters, which are totals, have none.""" + +import json +from datetime import date, datetime + +from lib.airgradient import AirGradient +from lib.ecowitt.query import HistoryQuery +from lib.storage.catalogue import RAIN_COUNTERS +from lib.timeutil import local_epoch +from lib.tools import Turn +from tests.fakes import TZ, air_transport, config, fetcher_on, storage_with + +NOW = datetime(2026, 10, 23, 12, 0) # Fri 23 Oct 2026, noon: the days below are over (and none of them changes the clock) + + +def at(day: int, hour: float = 0, month: int = 10) -> int: + """An epoch on a day of October 2026 (`month`), `hour` hours after its midnight.""" + return local_epoch(datetime(2026, month, day), TZ) + int(hour * 3600) + + +def every(seconds: int, *stretches: tuple[int, int, float]) -> dict[str, str]: + """{epoch: value}, a reading every `seconds` through each (start, end, value) stretch [start, end), as Ecowitt's lists have them.""" + return {str(t): f"{v}" for a, b, v in stretches for t in range(a, b, seconds)} + + +async def test_a_part_day_at_either_end_counts_for_its_hours_and_rain_rate_has_an_average(tmp_path): + temperature = every(300, (at(20), at(20, 18), 20.0), (at(20, 18), at(21), 10.0), (at(21), at(22), 16.0), (at(22), at(22, 6), 4.0), + (at(22, 6), at(23), 30.0)) # (the 20.0 and the 30.0 outside the period) + rain_rate = every(300, (at(20), at(21), 0.0), (at(21), at(22), 1.2), (at(22), at(23), 0.0)) + rainfall = {"rain_rate": {"unit": "mm/hr", "list": rain_rate}, + **{name: {"unit": "mm", "list": every(300, (at(20), at(23), 0.0))} for name in RAIN_COUNTERS}} + storage = storage_with(tmp_path, ("5min", ["outdoor", "rainfall"], {"outdoor": {"temperature": {"unit": "℃", "list": temperature}}, + "rainfall": rainfall}, at(20), at(23) - 1)) + q = HistoryQuery(fetcher_on(storage, None, ["outdoor", "rainfall"]), + {"start_date": "2026-10-20 18:00:00", "end_date": "2026-10-22 05:59:59", "average": True}, Turn()) + q.now = NOW + series = json.loads(await q.run())["series"] + temp = series["outdoor.temperature"] + assert {day: row["avg"] for day, row in temp["daily"].items()} == {"Tue 20 Oct": "10.0", "Wed 21 Oct": "16.0", "Thu 22 Oct": "4.0"} + assert temp["average"] == "13.0" # (6 h × 10.0 + 24 h × 16.0 + 6 h × 4.0) / 36 h; the mean of the three days' means would be 10.0 + assert series["rainfall.rain_rate"]["average"] == "0.8" # 1.2 mm/hr through the 24 of the period's 36 hours that are Wednesday's + assert not [name for name in RAIN_COUNTERS if "average" in series[f"rainfall.{name}"]] # a total, not a mean + storage.close() + + +def test_a_months_average_is_over_its_time_too(): + q = HistoryQuery.__new__(HistoryQuery) + q.f, q.tz = fetcher_on(None), TZ + q.start, q.end = datetime(2026, 9, 29, 18), datetime(2026, 10, 31, 23, 59, 59) + q.span = q.end - q.start # (over a month: by month) + entry = {"monthly": {"Sep 2026": {"low": "6.0", "high": "30.0"}, "Oct 2026": {"low": "12.0", "high": "12.0"}}} + means = {date(2026, 9, 29): 30.0, date(2026, 9, 30): 6.0} | {date(2026, 10, d): 12.0 for d in range(1, 32)} + q._add_averages(entry, means) + assert entry["monthly"]["Sep 2026"]["avg"] == "10.8" # (6 h × 30.0 + 24 h × 6.0) / 30 h, not (30.0 + 6.0) / 2 + assert entry["monthly"]["Oct 2026"]["avg"] == "12.0" + assert entry["average"] == "12.0" # 9,240 / 773 hours (4 October has 23): 11.95; the mean of the 33 days' means would be 12.4 + + +async def test_an_air_day_held_only_as_hourly_averages_counts_for_its_hours_and_a_day_s_average_is_its_day_row_s(tmp_path): + transport, _ = air_transport() + air = AirGradient(config(tmp_path), transport=transport) + await air.start() + air.now = lambda: NOW + await air.store.save_day(date(2026, 10, 20), [{"ts": t, "pm2_5": 8.0} for t in range(at(20), at(21), 3600)]) # the cloud's older history + await air.store.save_day(date(2026, 10, 21), [{"ts": t, "pm2_5": 20.0} for t in range(at(21), at(22), 300)]) + both = await air.history("2026-10-20 00:00:00", "2026-10-21 23:59:59") + assert both["readings"] == 24 + 288 and "hourly averages" in both["note_resolution"] + assert both["pm2_5"]["average"] == 14.0 # a day each: (8.0 + 20.0) / 2; the mean of the 312 readings would be 19.1 + parts = await air.history("2026-10-20 12:00:00", "2026-10-21 05:59:59") + assert parts["pm2_5"]["average"] == 12.0 # (12 h × 8.0 + 6 h × 20.0) / 18 h; the readings' mean would be 18.3 + + sparse = [{"ts": t, "pm2_5": 10.0} for t in range(at(22), at(22, 12), 300)] + [{"ts": t, "pm2_5": 16.0} for t in range(at(22, 12), at(23), 1800)] + await air.store.save_day(date(2026, 10, 22), sparse) # the afternoon held at one reading a half hour + day = await air.history("2026-10-22 00:00:00", "2026-10-22 23:59:59") + row = (await air.store.day_figures(date(2026, 10, 22), date(2026, 10, 22), ["pm2_5_avg"])).values["pm2_5_avg"][date(2026, 10, 22)] + assert day["pm2_5"]["average"] == round(row, 1) == 13.0 # each half hour's mean, then theirs; the readings' mean would be 10.9 + await air.close() From 70b07469d7af6e85017a15d750ea3511013668aa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:33:57 +0000 Subject: [PATCH 017/125] Charts as data: specs.to_json / from_json, schemas/chart.json, the bot draws from JSON Step 1 of docs/mcp-service.md (3.7): a chart is handed over as JSON, and the bot's renderer reads that JSON, so the tools can later return charts to any client. - lib/specs.py: to_json(chart, tz, max_points=None) writes a chart as version-1 JSON (title, subtitle, period, source, newest, and per panel its series: "line", "band", "bars" or "rating", with every field the renderer reads, the rose on its panel), times as ISO local times with their UTC offset so each gives its epoch back exactly, even in the repeated hour. from_json builds the same Chart back through the usual constructors (tuples as tuples, the source as written rather than CHART_SOURCE's, a line drawn with no records kept without them) and raises ValueError for anything malformed. max_points buckets each line into at most that many equal stretches of time (the mean, with the lowest and highest as its band), for model-facing results later; None keeps the points, which is what the bot uses, so its pictures don't change. - schemas/chart.json: the JSON Schema (draft 2020-12, $id ecobot://schema/chart). - lib/charts.py: render_data(data, tz, times, dark) = render(from_json(data)). The bot's answer charts, its charts drawn ahead and the alert charts all go to_json -> render_data. Gauges are unchanged. - Tests: every sample chart round-trips field by field and draws byte-identical PNGs (and matches its reference image); charts with the fields the samples lack; times across both clock changes; malformed JSON refused by from_json and, where it can tell, the schema (checked by a small checker in the test, since jsonschema isn't installed); bucketing keeps the true extremes within the budget. A conftest fixture puts every chart any test builds through JSON and back. The golden images are unchanged. to_json takes the time zone as its second argument: local times need one, and it is explicit everywhere else times are written (render, day_bounds). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/how-it-works.md | 6 +- lib/alerts/pictures.py | 5 +- lib/bot.py | 9 +- lib/charts.py | 11 +- lib/specs.py | 148 ++++++++++++++++++++++- schemas/chart.json | 145 ++++++++++++++++++++++ tests/conftest.py | 39 ++++++ tests/test_bot.py | 6 +- tests/test_chart_json.py | 255 +++++++++++++++++++++++++++++++++++++++ tests/test_periods.py | 2 +- 10 files changed, 609 insertions(+), 17 deletions(-) create mode 100644 schemas/chart.json create mode 100644 tests/test_chart_json.py diff --git a/docs/how-it-works.md b/docs/how-it-works.md index a1c4d47c..41dd9680 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -22,9 +22,11 @@ lib/lines.py the one rule that turns readings into a chart line (raw, lib/rain.py rain per slot, spells and bars from the daily total lib/analysis/ pairs (rain vs a reading, rain vs air quality), scan (air quality vs everything) lib/compose.py plot_chart / air_link / air_scan: any series on one time axis -lib/specs.py what a chart is (typed: Chart > Panel > Line/Bars/Shares), validated when built; stack() titles a stacked chart +lib/specs.py what a chart is (typed: Chart > Panel > Line/Bars/Shares), validated when built; stack() titles a stacked chart; + to_json / from_json: the chart as JSON (schemas/chart.json, versioned), times local with their offset lib/panels.py how a reading becomes a panel (title, unit, colour key, zones): every chart producer uses it -lib/charts.py the one renderer: panels on a shared time axis, rain behind the lines, one colour per reading +lib/charts.py the one renderer: panels on a shared time axis, rain behind the lines, one colour per reading; the bot draws + every chart from its JSON (render_data) lib/captions.py when a chart is drawn, and the hint that makes the model's reply its caption lib/ecowitt/ api, fetch (what a job reads, from the storage or Ecowitt), reads and period (what a question reads of the storage: its period's days, readings, lines), extremes, query (one history question), link (weather_link), days (rank/count diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index d388f7d8..2bc4f6f9 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -9,7 +9,8 @@ from typing import Callable, NamedTuple from .. import intent -from ..charts import render +from ..charts import render_data +from ..specs import to_json from ..timeutil import now_local from ..tools import Turn @@ -37,7 +38,7 @@ async def chart(source, text: str, tz) -> Picture | None: handler = next(t for t in source.tools if t.name == tool).handler await handler(args, turn) spec = turn.charts[0] - return Picture(await asyncio.to_thread(render, spec, tz), spec.caption(now.date()), spec.newest) + return Picture(await asyncio.to_thread(render_data, to_json(spec, tz), tz), spec.caption(now.date()), spec.newest) except Exception as e: log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) return None diff --git a/lib/bot.py b/lib/bot.py index 24172286..417969cf 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -29,7 +29,8 @@ from .irrigation import IrrigationError, Watchdog from .irrigation import menu as irrigation_menu from . import gauges -from .charts import render as render_chart +from .charts import render_data +from .specs import to_json from .ecowitt.dashboard import STATUS from .tools import Turn from .config import Config @@ -1065,7 +1066,7 @@ async def _draw_ahead(self, text: str, now) -> tuple[str, bytes, str, str, int] caption = await asyncio.wait_for(self._chart_in_code(read, turn), TURN_SECONDS) if caption is None or len(turn.charts) != 1: raise ValueError("no chart came of it") - png = await asyncio.to_thread(render_chart, turn.charts[0], self.cfg.tz) + png = await asyncio.to_thread(render_data, to_json(turn.charts[0], self.cfg.tz), self.cfg.tz) return key, png, turn.charts[0].caption(now.date()), caption, turn.charts[0].newest def preload_soon(self, bot, question: str): @@ -1202,9 +1203,9 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text | {intent.TOOL_TOPICS[t] for t in tools_used if t in intent.TOOL_TOPICS} | ({"air_extra"} if turn.air_extra_used else set())) chat.history = shorten_old(trim_history(strip_tool_turns(working))) - for spec in turn.charts[:MAX_CHARTS]: # drawn while "typing..." is still showing + for spec in turn.charts[:MAX_CHARTS]: # drawn (from its JSON, as a tool will hand it over) while "typing..." is still showing try: - answer.photos.append(await asyncio.to_thread(render_chart, spec, self.cfg.tz, turn.times)) + answer.photos.append(await asyncio.to_thread(render_data, to_json(spec, self.cfg.tz), self.cfg.tz, turn.times)) answer.titles.append(spec.caption(now.date())) except Exception as e: log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) diff --git a/lib/charts.py b/lib/charts.py index 2097f623..8464df09 100644 --- a/lib/charts.py +++ b/lib/charts.py @@ -1,7 +1,8 @@ """Charts sent alongside history answers, for both Ecowitt and AirGradient. A history tool adds a specs.Chart to turn.charts (the question's Turn, made by the bot) when a chart was asked for; the -bot renders them after the answer is written and sends them with it. Every chart is one or more panels on a shared time +bot renders them after the answer is written and sends them with it, drawing each from its JSON (specs.to_json, then +render_data here), as any client draws the charts a tool hands over. Every chart is one or more panels on a shared time axis (see specs.py): - one panel of lines is drawn large, with the records marked as pills, an end dot and (for wind) the compass beside it, at exactly 1280x720, the size Telegram displays photos at, so nothing is rescaled; @@ -22,7 +23,7 @@ from . import draw from .draw import DPI, PT, Canvas, blend, nice_ticks, rgb -from .specs import Chart, Compass, Line, Panel +from .specs import Chart, Compass, Line, Panel, from_json # Palette. Slate neutrals for the furniture; one hue per reading (weather and air quality, kept clear of the green/yellow/red # rating zones); the same reading indoors is its complementary hue (opposite on the colour wheel, as a painter pairs them). @@ -900,6 +901,12 @@ def render(chart: Chart, tz: tzinfo, times: dict | None = None, dark: bool | Non return png +def render_data(data: dict, tz: tzinfo, times: dict | None = None, dark: bool | None = None) -> bytes: + """PNG bytes for a chart given as its JSON (specs.to_json, schemas/chart.json): how the bot draws every chart, as a client + draws the charts a tool hands over. Raises ValueError for JSON that isn't a chart; otherwise as render.""" + return render(from_json(data), tz, times, dark) + + def draw_texts(chart: Chart, tz: tzinfo, dark: bool = False) -> list[draw.Text]: """Every label recorded while drawing the chart (its values, pills and bar numbers), in the order drawn: for tests.""" with _DRAWING: diff --git a/lib/specs.py b/lib/specs.py index f65a3372..2ae2bcb3 100644 --- a/lib/specs.py +++ b/lib/specs.py @@ -6,11 +6,15 @@ - shares (the traffic-light share of each bar's time in good, poor and very poor). A Line is a series of points, each optionally with the low and high it stands for (drawn as a band around the line), and optionally the true records (lowest and highest reading, with when). Anything malformed raises here, when the chart is -built, not when it is drawn.""" +built, not when it is drawn. +A chart also goes as JSON (to_json, from_json; its schema is schemas/chart.json): what a tool hands over, for whoever draws it.""" + +import math from contextvars import ContextVar -from dataclasses import dataclass, field -from datetime import date, tzinfo +from dataclasses import dataclass, field, replace +from datetime import date, datetime, tzinfo +from statistics import fmean from .series import RAIN_WITH, WEATHER from .timeutil import day_bounds, day_text @@ -242,3 +246,141 @@ class Dashboard: """The gauges of the weather station, left to right and top to bottom, three to a row.""" tiles: list[Tile] per_row: int = 3 + + +# ---------- a chart as JSON ---------- +# How a chart is handed over (schemas/chart.json): its title, subtitle, period, source and the time of its newest reading, then each +# panel with its series. A series is a "line" ("band" when each point carries the low and high shaded around it), rain-style "bars", +# or a "rating" (each bar's share of time in good, poor and very poor). Times are ISO local times with their UTC offset, so each gives +# its epoch back exactly, even in the hour that happens twice when the clocks go back. +CHART_VERSION = 1 +COLUMNS = {"line": 2, "band": 4, "bars": 2, "rating": 4} # a point of each kind: [time, value], [time, value, low, high], + # [time, value] and [time, good, poor, very poor] (percent) + + +def to_json(chart: Chart, tz: tzinfo, max_points: int | None = None) -> dict: + """The chart as JSON, with everything the renderer reads, so from_json gives the same chart back. Times are local to `tz`. + max_points: each line in at most that many buckets of time (for a model to read), each the mean with the bucket's lowest + and highest as its band, so the true extremes stay; None keeps the points as drawn (the bot's own charts, already within + lines.POINT_BUDGET).""" + if max_points is not None and max_points < 2: + raise ValueError("max_points: a line needs at least two points") + when = lambda t: datetime.fromtimestamp(t, tz).isoformat() + + def line(s: Line) -> dict: + s = _bucketed(s, max_points) if max_points else s + band = s.low is not None + return {"name": s.label, "kind": "band" if band else "line", + "points": [[when(t), *v] for t, *v in zip(s.x, s.y, *((s.low, s.high) if band else ()))], + "records": {k: [when(t), v] for k, (t, v) in s.records.items()}, + "reading": s.reading, "smoothed": s.smoothed, "indoor": s.indoor, "right": s.right, "on_line": s.on_line} + + def panel(p: Panel, compass: Compass | None) -> dict: + series = [line(s) for s in p.lines] + if b := p.bars: + series.append({"name": b.label, "kind": "bars", "unit": b.unit, "width": b.width, "per": b.per, "values": b.values, + "points": [[when(t), v] for t, v in zip(b.x, b.y)]}) + if r := p.shares: + series.append({"name": r.label, "kind": "rating", "width": r.width, "per": r.per, + "points": [[when(t), *v] for t, *v in zip(r.x, r.good, r.poor, r.very_poor)]}) + out = {"label": p.label, "unit": p.unit, "reading": p.reading, "series": series, "flip_right": p.flip_right, "peaks": p.peaks} + if p.zones is not None: + out["zones"] = list(p.zones) + if compass: + out["compass"] = {"rose": [list(row) for row in compass.rose], "speeds": compass.speeds, + "speed_steps": list(compass.speed_steps)} + return out + return {"version": CHART_VERSION, "title": chart.title, "subtitle": chart.subtitle, + "period": [d.isoformat() for d in chart.period] if chart.period else None, "source": chart.source, + "newest": when(chart.newest), "panels": [panel(p, chart.compass if i == 0 else None) for i, p in enumerate(chart.panels)]} + + +def _bucketed(line: Line, most: int) -> Line: + """The line in at most `most` buckets of equal time, each the mean of its points at their mean time, with the lowest low and + highest high among them as its band (the true extremes stay). A line of no more points is left as it is.""" + if len(line.x) <= most: + return line + start, width = line.x[0], (line.x[-1] - line.x[0]) // most + 1 # so the last point falls in bucket `most - 1` at the latest + buckets: dict = {} + for i, t in enumerate(line.x): + buckets.setdefault((t - start) // width, []).append(i) + if len(buckets) < 2: + return line + lows, highs, groups = line.low or line.y, line.high or line.y, list(buckets.values()) + return replace(line, x=[round(fmean(line.x[i] for i in g)) for g in groups], y=[fmean(line.y[i] for i in g) for g in groups], + low=[min(lows[i] for i in g) for g in groups], high=[max(highs[i] for i in g) for g in groups]) + + +def from_json(data: dict) -> Chart: + """The Chart to_json wrote, built the way any chart is: anything malformed raises ValueError here.""" + if not isinstance(data, dict) or data.get("version") != CHART_VERSION: + raise ValueError(f"not a chart of version {CHART_VERSION}") + try: + panels, compass, recordless = [], None, [] + for p in data["panels"]: + built = [_series(s) for s in p["series"]] + lines = [s for s in built if isinstance(s, Line)] + bars = [s for s in built if isinstance(s, Bars)] + shares = [s for s in built if isinstance(s, Shares)] + if len(bars) > 1 or len(shares) > 1: + raise ValueError(f"panel {p['label']!r}: one series of bars and one rating at most") + recordless += [s for s in lines if not s.records] + panels.append(Panel(p["label"], p["unit"], lines, bars[0] if bars else None, shares[0] if shares else None, + _pair(p["zones"]) if "zones" in p else None, p["reading"], p["flip_right"], p["peaks"])) + if "compass" in p: + compass = _compass(p["compass"]) + period = None if data["period"] is None else _pair(data["period"], date.fromisoformat) + chart = Chart(data["title"], data["subtitle"], panels, compass, period) + chart.source = source_text(data["source"]) # as written (not the CHART_SOURCE of whatever call this is) + except (KeyError, TypeError, IndexError, AttributeError) as e: + raise ValueError(f"not a chart: {type(e).__name__}: {e}") from None + for line in recordless: # drawn without records (a reading with no low, and no high given): a chart would give it its own + line.records = {} + return chart + + +def _series(s: dict) -> Line | Bars | Shares: + """One series of a panel's JSON as what draws it.""" + kind, points = s["kind"], s["points"] + if kind not in COLUMNS: + raise ValueError(f"series {s['name']!r}: its kind is one of {', '.join(COLUMNS)}, not {kind!r}") + if any(len(point) != COLUMNS[kind] for point in points): + raise ValueError(f"series {s['name']!r}: a point of a {kind} is {COLUMNS[kind]} values") + x = [_epoch(point[0]) for point in points] + columns = [[_number(point[i]) for point in points] for i in range(1, COLUMNS[kind])] + if kind == "bars": + return Bars(s["name"], s["unit"], x, columns[0], s["width"], s["per"], s["values"]) + if kind == "rating": + return Shares(s["name"], x, s["width"], *columns, s["per"]) + low, high = columns[1:] if kind == "band" else (None, None) + records = {k: (_epoch(t), _number(v)) for k, (t, v) in s["records"].items()} + return Line(s["name"], x, columns[0], low, high, s["smoothed"], records, s["reading"], s["indoor"], s["right"], s["on_line"]) + + +def _compass(c: dict) -> Compass: + if len(c["rose"]) != 16 or any(len(row) != 3 for row in c["rose"]): + raise ValueError("a wind rose is 16 compass points of 3 speed steps") + return Compass([[_number(v) for v in row] for row in c["rose"]], c["speeds"], _pair(c["speed_steps"])) + + +def _pair(values: list, read=None) -> tuple: + """Two values (zones, a period, speed steps) as a tuple, each read by `read` (else checked to be a number).""" + if len(values) != 2: + raise ValueError(f"two values, not {values!r}") + return tuple(map(read or _number, values)) + + +def _epoch(text: str) -> int | float: + """An ISO time with its UTC offset as epoch seconds (an int when whole, as the charts hold them).""" + t = datetime.fromisoformat(text) + if t.tzinfo is None: + raise ValueError(f"a time needs its UTC offset: {text!r}") + seconds = t.timestamp() + return int(seconds) if seconds.is_integer() else seconds + + +def _number(v) -> float: + """A value as given, checked to be a finite number (not a string, a bool or None).""" + if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v): + raise ValueError(f"not a number: {v!r}") + return v diff --git a/schemas/chart.json b/schemas/chart.json new file mode 100644 index 00000000..0875103e --- /dev/null +++ b/schemas/chart.json @@ -0,0 +1,145 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "ecobot://schema/chart", + "title": "Chart, version 1", + "description": "A chart as data (lib/specs.py: to_json, from_json): one or more panels on a shared time axis, top to bottom. Times are ISO local times with their UTC offset; dates are ISO dates.", + "type": "object", + "required": ["version", "title", "subtitle", "period", "source", "newest", "panels"], + "additionalProperties": false, + "properties": { + "version": {"const": 1, "description": "This schema's version: a change that would misread an older chart gets a new one."}, + "title": {"type": "string", "description": "What is drawn: the panels' names."}, + "subtitle": {"type": "string", "description": "The period, how the lines were drawn (\"30-minute readings\", \"daily averages\"), what a bar covers and whether a range is shaded."}, + "period": { + "type": ["array", "null"], + "description": "The first and last day the chart covers, or null when it doesn't say.", + "prefixItems": [{"$ref": "#/$defs/date"}, {"$ref": "#/$defs/date"}], + "items": false, + "minItems": 2 + }, + "source": {"type": "string", "description": "Where the data came from (\"Ecowitt weather station\"), written small in the corner; \"\" for none."}, + "newest": {"$ref": "#/$defs/time", "description": "The time of the newest reading drawn: a line's last point or the start of the last bar."}, + "panels": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/panel"}} + }, + "$defs": { + "date": {"type": "string", "format": "date", "pattern": "^\\d{4}-\\d{2}-\\d{2}$"}, + "time": { + "type": "string", + "format": "date-time", + "description": "A local time with its UTC offset, e.g. 2026-10-04T03:30:00+11:00.", + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?([+-]\\d{2}:\\d{2}|Z)$" + }, + "pair": {"type": "array", "prefixItems": [{"type": "number"}, {"type": "number"}], "items": false, "minItems": 2}, + "value_point": {"type": "array", "prefixItems": [{"$ref": "#/$defs/time"}, {"type": "number"}], "items": false, "minItems": 2}, + "four_point": { + "type": "array", + "prefixItems": [{"$ref": "#/$defs/time"}, {"type": "number"}, {"type": "number"}, {"type": "number"}], + "items": false, + "minItems": 4 + }, + "panel": { + "type": "object", + "description": "One panel: lines (each a line or a band) with rain-style bars behind them on a scale of their own, or bars alone, or a rating alone.", + "required": ["label", "unit", "reading", "series", "flip_right", "peaks"], + "additionalProperties": false, + "properties": { + "label": {"type": "string"}, + "unit": {"type": "string", "description": "The unit of the lines' axis (\"\" when each line carries its own, on two axes)."}, + "reading": {"type": "string", "description": "Which reading the panel is (\"humidity\", \"pm2_5\" ...), for its colours; \"\" for a mix."}, + "series": { + "type": "array", + "minItems": 1, + "items": {"oneOf": [{"$ref": "#/$defs/line"}, {"$ref": "#/$defs/band"}, {"$ref": "#/$defs/bars"}, {"$ref": "#/$defs/rating"}]} + }, + "flip_right": {"type": "boolean", "description": "The right-hand axis runs top to bottom (a line on it falls as its reading rises)."}, + "peaks": {"enum": ["pills", "aside", "none"], "description": "How the highs and lows are labelled: on the lines, beside them, or not at all."}, + "zones": {"$ref": "#/$defs/pair", "description": "A rated reading's limits: good up to the first, poor up to the second, very poor above."}, + "compass": {"$ref": "#/$defs/compass"} + } + }, + "line": { + "type": "object", + "description": "A line of readings: points [time, value].", + "required": ["name", "kind", "points", "records", "reading", "smoothed", "indoor", "right", "on_line"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "line"}, + "points": {"type": "array", "minItems": 2, "items": {"$ref": "#/$defs/value_point"}}, + "records": { + "type": "object", + "description": "The true lowest and highest readings, with when: the labels on the line.", + "additionalProperties": false, + "properties": {"low": {"$ref": "#/$defs/value_point"}, "high": {"$ref": "#/$defs/value_point"}} + }, + "reading": {"type": "string", "description": "Which reading the line is, for its colour; \"\" for its panel's."}, + "smoothed": {"type": "boolean", "description": "The line is a light average of the readings, not the readings."}, + "indoor": {"type": "boolean", "description": "The indoor sensor's line (drawn in its reading's complementary colour)."}, + "right": {"type": "boolean", "description": "Read against the panel's right-hand axis."}, + "on_line": {"type": "boolean", "description": "Its peak is marked on the line itself, not on the top of its band."} + } + }, + "band": { + "type": "object", + "description": "A line with the range each point stands for shaded around it: points [time, value, low, high].", + "required": ["name", "kind", "points", "records", "reading", "smoothed", "indoor", "right", "on_line"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "band"}, + "points": {"type": "array", "minItems": 2, "items": {"$ref": "#/$defs/four_point"}}, + "records": {"$ref": "#/$defs/line/properties/records"}, + "reading": {"$ref": "#/$defs/line/properties/reading"}, + "smoothed": {"$ref": "#/$defs/line/properties/smoothed"}, + "indoor": {"$ref": "#/$defs/line/properties/indoor"}, + "right": {"$ref": "#/$defs/line/properties/right"}, + "on_line": {"$ref": "#/$defs/line/properties/on_line"} + } + }, + "bars": { + "type": "object", + "description": "Bars (rain, or a count or figure per month or year): points [the bar's start, value].", + "required": ["name", "kind", "unit", "width", "per", "values", "points"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "bars"}, + "unit": {"type": "string"}, + "width": {"type": "integer", "minimum": 1, "description": "The seconds a bar covers."}, + "per": {"type": "string", "description": "What a bar covers, in words: \"hour\", \"6 hours\", \"day\", \"month\", \"year\"; \"\" when not said."}, + "values": {"type": "boolean", "description": "Each bar's number is written above it."}, + "points": {"type": "array", "items": {"$ref": "#/$defs/value_point"}} + } + }, + "rating": { + "type": "object", + "description": "The share of each bar's time in each rating: points [the bar's start, good, poor, very poor] (percent).", + "required": ["name", "kind", "width", "per", "points"], + "additionalProperties": false, + "properties": { + "name": {"type": "string"}, + "kind": {"const": "rating"}, + "width": {"type": "integer", "minimum": 1, "description": "The seconds a bar covers."}, + "per": {"type": "string"}, + "points": {"type": "array", "items": {"$ref": "#/$defs/four_point"}} + } + }, + "compass": { + "type": "object", + "description": "A wind rose of the whole period, beside a chart of one panel of lines.", + "required": ["rose", "speeds", "speed_steps"], + "additionalProperties": false, + "properties": { + "rose": { + "type": "array", + "description": "For each of the 16 compass points, N first and clockwise: the readings in each speed step (light, middle, strong).", + "minItems": 16, + "maxItems": 16, + "items": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3} + }, + "speeds": {"type": "boolean", "description": "The readings carried a wind speed, so the steps mean something."}, + "speed_steps": {"$ref": "#/$defs/pair", "description": "Where the middle and strong steps begin (km/h)."} + } + } + } +} diff --git a/tests/conftest.py b/tests/conftest.py index 3e5c64e0..0a291375 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -110,3 +110,42 @@ def fast_connect(*args, **kwargs): # tests don't need the caches to survive a p yield for db in opened: db.close() + + +@pytest.fixture(autouse=True) +def charts_come_back_from_json(monkeypatch): + """Every chart a test builds is also written as JSON and read back (specs.to_json, from_json), and must come back the same: the + bot draws each chart from its JSON. A chart that doesn't fails the test when it ends (a tool that drew it may catch the error).""" + import json + from lib import specs + from tests.fakes import TZ + built, wrong, busy = specs.Chart.__post_init__, [], [] + + def checked(chart): + built(chart) + if busy: # the chart from_json is building + return + busy.append(chart) + try: + back = specs.from_json(json.loads(json.dumps(specs.to_json(chart, TZ)))) + if back != chart: + wrong.append(f"{chart.title!r} came back from its JSON changed: {difference(chart, back)}") + except Exception as e: + wrong.append(f"{chart.title!r} couldn't go through JSON: {type(e).__name__}: {e}") + finally: + busy.pop() + monkeypatch.setattr(specs.Chart, "__post_init__", checked) + yield + assert not wrong, wrong[0] + + +def difference(a, b, path: str = "chart") -> str: + """Where two charts (or parts of them) first differ, "chart.panels[0].lines[1].x[0]: 1 != 2", rather than both whole.""" + from dataclasses import fields, is_dataclass + if is_dataclass(a) and type(a) is type(b): + name = next(f.name for f in fields(a) if getattr(a, f.name) != getattr(b, f.name)) + return difference(getattr(a, name), getattr(b, name), f"{path}.{name}") + if type(a) is type(b) and isinstance(a, (list, tuple)) and len(a) == len(b): + i = next(i for i, (x, y) in enumerate(zip(a, b)) if x != y) + return difference(a[i], b[i], f"{path}[{i}]") + return f"{path}: {a!r} != {b!r}" diff --git a/tests/test_bot.py b/tests/test_bot.py index 22f1bad9..d9c77b6f 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -321,7 +321,7 @@ async def run(self, *a, **k): async def reply_photo(photo, caption=None, **kw): sent.append(caption) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) @@ -359,7 +359,7 @@ async def run(self, *a, **k): async def reply(*a, **k): return NS(message_id=7) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: pokes.append(1), describe=lambda: "Ecowitt")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply, reply_text=reply, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) @@ -613,7 +613,7 @@ async def run(self, *a, **k): async def reply_photo(photo, caption=None, **kw): sent.append(caption) - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] for text, caption_wanted in (("ecowitt all week", True), ("temperature chart 7d", True)): sent.clear() diff --git a/tests/test_chart_json.py b/tests/test_chart_json.py new file mode 100644 index 00000000..45af760c --- /dev/null +++ b/tests/test_chart_json.py @@ -0,0 +1,255 @@ +"""Charts as data (specs.to_json and from_json, schemas/chart.json): a chart written as JSON comes back the same and is drawn the +same, the schema holds every chart the bot draws, and a line for a model to read is bucketed to its budget with its true lowest and +highest kept. (Every chart any test builds also goes through JSON and back: conftest.charts_come_back_from_json.) + +jsonschema isn't one of the requirements, so the schema is checked here by a small checker of the keywords it uses (`errors`); +a test makes sure it uses no others.""" + +import copy +import json +import math +import re +from datetime import date, datetime +from pathlib import Path + +import pytest + +from lib import charts +from lib.specs import CHART_SOURCE, Bars, Chart, Compass, Line, Panel, Shares, from_json, stack, to_json +from tests import chart_samples, imagecmp +from tests.fakes import TZ + +SCHEMA = json.loads((Path(__file__).resolve().parent.parent / "schemas" / "chart.json").read_text()) +SAMPLES = [name for name, make in chart_samples.SAMPLES.items() if isinstance(make(), Chart)] # (not the gauges) +T0 = int(datetime(2026, 9, 1, tzinfo=TZ).timestamp()) + + +def sent(chart: Chart, **kw) -> dict: + """The chart's JSON as a client gets it: written out as text and read back.""" + return json.loads(json.dumps(to_json(chart, TZ, **kw), allow_nan=False)) + + +# ---------- a small JSON Schema checker: the keywords schemas/chart.json uses, as draft 2020-12 reads them ---------- +TYPES = {"object": dict, "array": list, "string": str, "boolean": bool, "null": type(None)} +CHECKED = {"$ref", "type", "const", "enum", "properties", "required", "additionalProperties", "items", "prefixItems", "minItems", + "maxItems", "oneOf", "pattern", "minimum"} +NOTES = {"$schema", "$id", "$defs", "title", "description", "format"} # annotations: nothing to check + + +def is_type(value, name: str) -> bool: + if name in ("number", "integer"): + return isinstance(value, (int, float)) and not isinstance(value, bool) and (name == "number" or float(value).is_integer()) + return isinstance(value, TYPES[name]) + + +def resolve(ref: str) -> dict: + node = SCHEMA + for part in ref.removeprefix("#/").split("/"): + node = node[part] + return node + + +def errors(value, schema: dict | bool = SCHEMA, at: str = "$") -> list[str]: + """What is wrong with `value` against `schema`: [] when it conforms.""" + if schema is False: + return [f"{at}: not allowed"] + if schema is True: + return [] + out = errors(value, resolve(schema["$ref"]), at) if "$ref" in schema else [] + if "type" in schema and not any(is_type(value, t) for t in ([schema["type"]] if isinstance(schema["type"], str) else schema["type"])): + return out + [f"{at}: not of type {schema['type']}"] + if "const" in schema and value != schema["const"]: + out.append(f"{at}: not {schema['const']!r}") + if "enum" in schema and value not in schema["enum"]: + out.append(f"{at}: not one of {schema['enum']}") + if "pattern" in schema and isinstance(value, str) and not re.search(schema["pattern"], value): + out.append(f"{at}: {value!r} doesn't match {schema['pattern']}") + if "minimum" in schema and is_type(value, "number") and value < schema["minimum"]: + out.append(f"{at}: under {schema['minimum']}") + if "oneOf" in schema and sum(not errors(value, s, at) for s in schema["oneOf"]) != 1: + out.append(f"{at}: not exactly one of its kinds") + if isinstance(value, dict): + props = schema.get("properties", {}) + out += [f"{at}: no {key!r}" for key in schema.get("required", []) if key not in value] + for key, item in value.items(): + if key in props: + out += errors(item, props[key], f"{at}.{key}") + elif "additionalProperties" in schema: + out += errors(item, schema["additionalProperties"], f"{at}.{key}") + if isinstance(value, list): + if len(value) < schema.get("minItems", 0) or len(value) > schema.get("maxItems", math.inf): + out.append(f"{at}: {len(value)} items") + first = schema.get("prefixItems", []) + for i, item in enumerate(value): + out += errors(item, first[i] if i < len(first) else schema.get("items", True), f"{at}[{i}]") + return out + + +def keywords(schema, under_names: bool = False) -> set[str]: + """Every keyword the schema uses (the names under properties and $defs are names, not keywords).""" + if isinstance(schema, list): + return set().union(*(keywords(s) for s in schema)) + if not isinstance(schema, dict): + return set() + if under_names: + return set().union(*(keywords(s) for s in schema.values())) + return set(schema) | set().union(*(keywords(v, k in ("properties", "$defs")) for k, v in schema.items())) + + +def test_the_schema_uses_only_keywords_the_checker_reads_and_is_versioned(): + assert keywords(SCHEMA) <= CHECKED | NOTES, keywords(SCHEMA) - CHECKED - NOTES + assert SCHEMA["$schema"] == "https://json-schema.org/draft/2020-12/schema" and SCHEMA["properties"]["version"]["const"] == 1 + + +# ---------- every sample chart, through JSON and back ---------- +@pytest.mark.parametrize("name", SAMPLES) +def test_every_sample_chart_comes_back_the_same_and_is_drawn_the_same(name): + chart, dark = chart_samples.SAMPLES[name](), name.endswith("_dark") + data = sent(chart) + back = from_json(data) + assert back == chart # field by field: the tuples (period, zones, records, speed steps) come back tuples + assert to_json(back, TZ) == data + assert charts.render_data(data, TZ, dark=dark) == charts.render(chart, TZ, dark=dark) # the same PNG, byte for byte + assert not errors(data), errors(data) + + +@pytest.mark.golden +@pytest.mark.parametrize("name", SAMPLES) +def test_every_sample_chart_drawn_from_its_json_matches_its_reference_image(name): + assert imagecmp.check(name, from_json(sent(chart_samples.SAMPLES[name]()))) is None + + +def every_field() -> list[Chart]: + """Charts with what the samples leave out: a rating, bars with their numbers, a line on a flipped right-hand axis, a smoothed + indoor line marked on itself, zones, a rose with no speeds, and a line whose only record is a low its reading never shows.""" + xs = [T0 + i * 3600 for i in range(8)] + ys = [3.0, 5.5, 4.0, 9.25, 7.0, 6.0, 2.0, 4.5] + rating = Panel("PM2.5 rating", "%", shares=Shares("PM2.5", xs, 3600, [80.0] * 8, [15.0] * 8, [5.0] * 8, "hour")) + months = Panel("Days", "", bars=Bars("Days", "days", xs[:3], [1, 0, 4], 28 * 86400, "month", values=True)) + twin = Panel("UV and Solar", "", [Line("UV", xs, ys, reading="uv"), + Line("Solar", xs, [y * 100 for y in ys], [y * 90 for y in ys], [y * 110 for y in ys], + smoothed=True, reading="solar", indoor=True, right=True, on_line=True)], + flip_right=True, peaks="none") + rated = Panel("PM2.5", "µg/m³", [Line("PM2.5", xs, ys, reading="pm2_5")], zones=(12.0, 35.5), reading="pm2_5", peaks="aside") + calm = Panel("Wind", "km/h", [Line("Wind", xs, ys, records={"low": (xs[6], 2.0)})], reading="wind") + return [stack([rating, months], date(2026, 9, 1), date(2026, 9, 1)), Chart("Two scales", "s", [twin]), + Chart("Rated", "s", [rated], source="Somewhere"), Chart("Wind", "s", [calm], Compass([[1, 2, 3]] * 16, False, (5, 15)))] + + +@pytest.mark.parametrize("i", range(len(every_field()))) +def test_every_field_the_renderer_reads_comes_back(i): + chart = every_field()[i] + data = sent(chart) + assert from_json(data) == chart and charts.render_data(data, TZ) == charts.render(chart, TZ) + assert not errors(data), errors(data) + + +def test_a_line_drawn_without_records_comes_back_without_them(): + chart = every_field()[3] + assert chart.panels[0].lines[0].records == {} # wind's low isn't labelled, so its only record went + assert from_json(sent(chart)).panels[0].lines[0].records == {} # not its own high and low, as a chart would give it + + +def test_the_source_is_the_charts_own_not_the_tool_call_it_is_read_in(): + data = sent(every_field()[1]) + token = CHART_SOURCE.set("Ecowitt weather station") + try: + assert data["source"] == "" and from_json(data).source == "" + finally: + CHART_SOURCE.reset(token) + + +def test_times_are_local_with_their_offset_and_give_the_same_epochs_back_across_both_clock_changes(): + forward = int(datetime(2026, 10, 4, 1, tzinfo=TZ).timestamp()) # Melbourne: 2am is 3am + back = int(datetime(2026, 4, 5, 1, 30, tzinfo=TZ).timestamp()) # 3am is 2am again: 2 to 3am happens twice + for start, want in ((forward, ["01:00:00+10:00", "01:30:00+10:00", "03:00:00+11:00", "03:30:00+11:00"]), + (back, ["01:30:00+11:00", "02:00:00+11:00", "02:30:00+11:00", "02:00:00+10:00", "02:30:00+10:00"])): + xs = [start + i * 1800 for i in range(len(want))] + chart = Chart("T", "s", [Panel("Temperature", "°C", [Line("Outdoor", xs, [float(i) for i in range(len(xs))])])]) + data = sent(chart) + assert [p[0][11:] for p in data["panels"][0]["series"][0]["points"]] == want + assert from_json(data).panels[0].lines[0].x == xs + assert data["newest"] == data["panels"][0]["series"][0]["points"][-1][0] + + +def test_a_chart_says_its_period_source_and_the_kind_of_each_series(): + data = sent(chart_samples.humidity_rain()) + assert data["version"] == 1 and data["period"] == ["2026-09-28", "2026-10-04"] and data["source"] == "" + assert [(s["name"], s["kind"]) for s in data["panels"][0]["series"]] == [("Outdoor", "line"), ("Indoor", "line"), ("Rain", "bars")] + wind = sent(chart_samples.wind())["panels"][0] + assert wind["series"][0]["kind"] == "band" and len(wind["series"][0]["points"][0]) == 4 and len(wind["compass"]["rose"]) == 16 + assert sent(chart_samples.quarter())["period"] is None + + +# ---------- what isn't a chart ---------- +def broken(change) -> dict: + data = copy.deepcopy(sent(chart_samples.humidity_rain())) + change(data) + return data + + +def series(data: dict, i: int = 0) -> dict: + return data["panels"][0]["series"][i] + + +BROKEN = { # name: (the change, whether the schema sees it: the rest only building the chart can tell) + "another version": (lambda d: d.update(version=2), True), + "no title": (lambda d: d.pop("title"), True), + "a time without its offset": (lambda d: series(d)["points"][0].__setitem__(0, "2026-09-28T00:00:00"), True), + "a kind of series there isn't": (lambda d: series(d).update(kind="pie"), True), + "a band's point without its range": (lambda d: series(d).update(kind="band"), True), + "a value that isn't a number": (lambda d: series(d)["points"][3].__setitem__(1, "62"), True), + "a line of one point": (lambda d: series(d).update(points=series(d)["points"][:1]), True), + "a period of three days": (lambda d: d["period"].append("2026-10-05"), True), + "a period of none": (lambda d: d.update(period=[]), True), + "two series of bars in a panel": (lambda d: d["panels"][0]["series"].append(series(d, 2)), False), + "a rose beside a stack": (lambda d: d["panels"].append({**d["panels"][0], "compass": sent(chart_samples.wind())["panels"][0]["compass"]}), + False), +} + + +@pytest.mark.parametrize("name", BROKEN) +def test_what_is_not_a_chart_is_refused_when_it_is_read_and_by_the_schema_where_it_can_tell(name): + change, schema_sees = BROKEN[name] + data = broken(change) + with pytest.raises(ValueError): + from_json(data) + with pytest.raises(ValueError): + charts.render_data(data, TZ) + assert bool(errors(data)) == schema_sees, errors(data) + + +def test_the_checker_finds_what_it_should(): + assert not errors(sent(chart_samples.wind())) + assert errors({"version": 1}) and errors(broken(lambda d: d["panels"][0].update(extra=1))) + + +# ---------- a line for a model to read ---------- +def test_a_long_line_is_bucketed_to_the_budget_keeping_its_true_lowest_and_highest(): + xs = [T0 + i * 300 for i in range(2016)] # a week of 5-minute readings + ys = [12 + 6 * math.sin(i / 40) for i in range(len(xs))] + ys[300], ys[1500] = 41.5, -3.25 # one reading far above, one far below + xs, ys = xs[:600] + xs[888:], ys[:600] + ys[888:] # and a day missing + rain = Bars("Rain", "mm", [T0 + i * 3600 for i in range(168)], [0.2] * 168, 3600, "hour") + chart = Chart("T", "s", [Panel("Temperature", "°C", [Line("Outdoor", xs, ys, reading="temperature")], bars=rain)]) + whole = sent(chart) + data = sent(chart, max_points=150) + line, bars = series(data), series(data, 1) + assert line["kind"] == "band" and 100 < len(line["points"]) <= 150 + times, means, lows, highs = zip(*line["points"]) + assert min(lows) == -3.25 and max(highs) == 41.5 and all(lo <= y <= hi for _, y, lo, hi in line["points"]) + assert list(times) == sorted(set(times)) and line["records"] == series(whole)["records"] # the true records, with when + assert bars == series(whole, 1) # bars aren't lines: as they are + assert not errors(data) and len(from_json(data).panels[0].lines[0].x) == len(line["points"]) + assert to_json(chart, TZ) == to_json(chart, TZ, max_points=None) and from_json(whole) == chart + + +def test_a_band_keeps_its_own_extremes_and_a_short_line_is_left_as_it_is(): + wind = chart_samples.wind() + line = series(sent(wind, max_points=40)) + assert len(line["points"]) <= 40 and max(p[3] for p in line["points"]) == max(wind.panels[0].lines[0].high) + assert min(p[2] for p in line["points"]) == min(wind.panels[0].lines[0].low) + quarter = chart_samples.quarter() # 90 days: within a budget of 150 + assert sent(quarter, max_points=150) == sent(quarter) + with pytest.raises(ValueError): + to_json(quarter, TZ, max_points=1) diff --git a/tests/test_periods.py b/tests/test_periods.py index bfb00c89..4338a7ce 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -68,7 +68,7 @@ class Agent: async def run(self, *a, **k): raise AssertionError("no model for a plain chart") - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] return Bot(NS(tz=TZ), Agent(), sources, alert_state) From c55863623287f4e205ffe9ae52348318cc31c02b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:37:50 +0000 Subject: [PATCH 018/125] A chart that answers the question ends the turn: no second model call Step 0 of docs/mcp-service.md (3.7, "the chart that answers itself"). A question that is only a chart, and that the model takes ("plot pressure since Sunday"), used to cost two model calls: one to fetch, one to word a caption the bot can already write. Now the model says so itself. - weather_history, air_quality, weather_days and air_days take a boolean chart_answers_it (lib/captions.py CHART_ANSWERS_IT): true only when the question is just to see the chart and its figures, nothing else to answer. The handlers ignore it. - Agent.run takes finish(calls, results), asked after each step of the model's own tool calls (never the bot's first_call). Text from it is the reply: it joins the conversation and the turn ends, with a log line ("The turn ended on a chart that answers the question (...): no LLM 2"). The heads-up for a heavy question now comes after it, so a chart that ends the turn doesn't warn of a wait first. - Bot._chart_answer is that finish: when every call of the step is one of the four tools, set chart_answers_it, drew its chart (its result's "chart" note) and can be captioned in code, the reply is their captions in call order: report.chart_caption for weather_history and air_quality, the days line of report.lookup for the day tools. Anything else (an error, no chart, nothing to caption) leaves it to the model. The caption follows what the tool drew: the person's words, else the model's chart_field, chart_fields, metrics and average (_as_drawn). - An eval pair (q:chart-only): "plot pressure since Sunday" (the model sets it) and "plot pressure since Sunday, is a storm coming?" (it doesn't); a weekday keeps both off the fast path. Visible change: such a question now gets the bot's own caption (the period, then low and high with when) with its chart, in place of the model's wording, and comes back one model call sooner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/how-it-works.md | 1 + lib/airgradient/source.py | 3 +- lib/bot.py | 55 ++++++++++- lib/captions.py | 6 ++ lib/daytable.py | 3 +- lib/ecowitt/source.py | 2 + lib/llm.py | 21 +++-- tests/evalkit.py | 1 + tests/evals/cases.json | 47 ++++++++++ tests/test_chart_answers.py | 180 ++++++++++++++++++++++++++++++++++++ 10 files changed, 308 insertions(+), 11 deletions(-) create mode 100644 tests/test_chart_answers.py diff --git a/docs/how-it-works.md b/docs/how-it-works.md index a1c4d47c..4ddd9784 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -72,6 +72,7 @@ Both are off by default. They are websites, not APIs (the pollen page is parsed) "report" (and "status", "sitrep") and "weather now" are written in code, with no model call (`lib/report.py`): the bot fetches the tools' results together and lays them out, so they are quick and always the same. Sun, UV and wind are left out when zero (night, calm). The report is: Weather station, Air quality, and Pollen & asthma and Forecast when those sources are on (pollen and forecast always come from the cache). The report carries a 🔄 Refresh button that reads everything again and redraws it in the same message (`lib/report_menu.py`). With the weather station, the report is the caption of a picture of its temperature, humidity and rain gauges (`ecowitt.dashboard.STATUS`, drawn by `lib/gauges.py` while the report is fetched); Refresh redraws both. The gauges' highs and lows are the year's day rows, read in one go (today's from its readings so far). A report longer than a caption (1,024 characters) goes after the picture as a message of its own; a refreshed one that has grown too long keeps its first sections. A plain chart request ("rain chart 7d", "plot temperature and humidity", "air quality 30d", the chart buttons) is also drawn and written up in code, with no model call (the chart goes out with just its title as the caption; the write-up is kept in the chat's memory, not sent) (`intent.weather_chart`, `report.chart_caption`): the period, then low and high per reading (the average first if one was asked), the peak and rating for air quality, and for a rain chart the least and most rain and whether more is expected. Anything that asks for correlation, analysis, a forecast, thinking or a description, or compares readings or names a particular date or time, still goes to the model. +A chart question the model takes ("plot pressure since Sunday") can still end after its first call: `weather_history`, `air_quality`, `weather_days` and `air_days` take `chart_answers_it`, which the model sets only when the question is just to see the chart and its figures. When every call of its step set it and drew a chart, the bot sends the chart with the same write-up made in code (`report.chart_caption`, or the days line of `report.lookup`) as the reply, and the model is not asked again (`Bot._chart_answer`, the agent's `finish`; the log says "The turn ended on a chart that answers the question"). A call that failed, drew nothing or can't be written up leaves the answer to the model as before. Other plain lookups are answered in code too, from the one tool result (`intent.plain_lookup`, `report.lookup`): a single reading now ("how hot is it", "is it raining", "uv"), the air ("how's the air", "pm10"), pollen, the plain forecast ("forecast", "7 day forecast"), the highs, lows or average of a short period ("hottest today", "average temp yesterday", "highest humidity yesterday") and what the bot can do ("what can you do"). Any question with forecast, correlation, thinking, analysis or description words, a comparison, or anything beyond the reading itself goes to the model; so does a lookup whose result can't be used. diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 6c355a1a..b2354e29 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -31,7 +31,7 @@ import httpx from .. import intent -from ..captions import CHART_HINT, wants_chart +from ..captions import CHART_ANSWERS_IT, CHART_HINT, wants_chart from ..config import Config from ..sources import Source from ..ecowitt.homeassistant import HomeAssistant @@ -83,6 +83,7 @@ "properties": { "chart": {"type": "boolean", "description": "Set true to send a chart (graph) with the answer. Without dates, " "it covers the last 24 hours."}, + "chart_answers_it": CHART_ANSWERS_IT, "metrics": {"type": "array", "items": {"type": "string", "enum": list(LABELS)}, "description": "Which metrics to chart (several are drawn as panels in one image; " "for 'all', list all six). Default: the reading the person named, else pm2_5."}, diff --git a/lib/bot.py b/lib/bot.py index 24172286..3714e1dc 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -13,7 +13,7 @@ import time from collections import defaultdict from collections.abc import Coroutine -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import datetime, UTC from typing import NamedTuple @@ -31,6 +31,7 @@ from . import gauges from .charts import render as render_chart from .ecowitt.dashboard import STATUS +from .ecowitt.query import chart_field, stack_names from .tools import Turn from .config import Config from .entities import utf16_len, with_link @@ -45,6 +46,8 @@ TG_LIMIT = 4000 CAPTION_LIMIT = 1024 # what Telegram lets a photo's caption hold MAX_CHARTS = 3 +DAY_TOOLS = ("weather_days", "air_days") +ANSWERING_CHARTS = ("weather_history", "air_quality", *DAY_TOOLS) # the tools whose chart can be the whole answer (chart_answers_it) RETRY_SECONDS = 60 # the second try, one reasoning step lower, after a question timed out PENDING_MAX_SECONDS = 10 * 60 # a message that waited longer (the bot was down) is not answered: its moment has passed TURN_SECONDS = 90 # a question that takes longer is given up on, so the ones queued behind it in the chat are not stuck @@ -171,6 +174,24 @@ def strip_chart_talk(text: str) -> str: return "\n".join(lines).strip() or text +def _drew_chart(result: str) -> bool: + """Does this tool result say it drew a chart (the "chart" note a tool adds when it does)?""" + try: + data = json.loads(result) + except ValueError: + return False + return isinstance(data, dict) and "chart" in data and "error" not in data + + +def _as_drawn(tool: str, args: dict, turn: Turn) -> tuple[dict, Turn]: + """(args, turn) as the tool read them to draw its chart, so its caption speaks of what the chart shows: the readings the person's + words name, else the model's (air quality: its metrics, else those named, else PM2.5), and an average if either asked for one.""" + if tool == "air_quality": + return {**args, "metrics": args.get("metrics") or turn.air_named or ["pm2_5"]}, turn + return args, replace(turn, chart_field=chart_field(args, turn), chart_fields=stack_names(args, turn), + average_asked=turn.average_asked or bool(args.get("average"))) + + def chat_tag(chat_id: int) -> str: """"[Telegram 5467329077]": what every log line about a chat starts with, so a request and its reply are found together.""" return f"[Telegram {chat_id}]" @@ -1033,16 +1054,44 @@ async def _lookup_in_code(self, read, turn: Turn) -> str | None: result = await self.agent.tools.call(name, json.dumps(args), turn) return report.lookup(read.lookup, result, read.lookup_arg, read.sides, now_local(self.cfg.tz).date()) + def _chart_answer(self, turn: Turn): + """The model loop's finish: when each call the model made in a step set chart_answers_it, drew its chart and can be captioned + here, their captions in order are the reply and the model is asked nothing more; else None, and the model answers as usual.""" + def finish(calls: list[dict], results: list[str]) -> str | None: + try: + captions = [self._answer_caption(call, result, turn) for call, result in zip(calls, results)] + except Exception as e: # the model answers instead + log.error("Couldn't caption a chart that answers the question (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + return None + return None if None in captions else "\n\n".join(captions) + return finish + + def _answer_caption(self, call: dict, result: str, turn: Turn) -> str | None: + """One call's chart as the whole answer: its caption, written from the tool's result as for a chart made in code (the day tools: + as for a days lookup); None when the call didn't set chart_answers_it, drew no chart, failed or left nothing to caption.""" + try: + args = json.loads(call["arguments"] or "{}") + except ValueError: + return None + if (call["name"] not in ANSWERING_CHARTS or not isinstance(args, dict) or args.get("chart_answers_it") is not True + or not _drew_chart(result)): + return None + if call["name"] in DAY_TOOLS: + return report.lookup("days", result, [], [], now_local(self.cfg.tz).date()) + args, drawn = _as_drawn(call["name"], args, turn) + return report.chart_caption(call["name"], args, result, drawn, self.cfg.tz) + async def _ask_model(self, working: list[dict], system: str, read, turn: Turn, draft, on_heavy=None) -> str: """The model's answer. If it has not answered in TURN_SECONDS, ask again once with one reasoning step less (medium > low > - none), for RETRY_SECONDS; a question already at no reasoning just times out.""" + none), for RETRY_SECONDS; a question already at no reasoning just times out. A chart that answers the question by itself + ends the turn with its caption written here (_chart_answer).""" first = [*([read.fast[:2], *read.more] if read.fast else []), *read.extra] or None before, effort, budget, retried = list(working), read.effort, TURN_SECONDS, False while True: try: return await asyncio.wait_for( self.agent.run(working, system, effort, first_call=first, tool_choice=read.tool_choice, turn=turn, - on_heavy=on_heavy, + on_heavy=on_heavy, finish=self._chart_answer(turn), **({"on_text": lambda text: None if turn.chart_asked or turn.charts else draft.update(text)} if draft else {})), budget) except TimeoutError: diff --git a/lib/captions.py b/lib/captions.py index 7ba95269..74fc6e3e 100644 --- a/lib/captions.py +++ b/lib/captions.py @@ -34,3 +34,9 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | "most common direction and how steady it was. Don't mention or describe the chart.") COUNT_CHART_HINT = ("Your reply is sent as a message just before a bar chart of these counts, so keep it to one short line: how many of the days " "matched (matching_days of days_checked) and the period. Don't list the bars or describe the chart.") + +# The argument that says the chart is the whole answer (weather_history, air_quality and the day tools offer it; their handlers ignore +# it): the bot then sends the chart with a caption written in code and asks the model nothing more (bot.Bot._chart_answer) +CHART_ANSWERS_IT = {"type": "boolean", "description": "true only when the question is just to see this chart and its figures: nothing " + "else to answer (\"plot pressure this week\", not \"plot pressure this week: is a " + "storm coming?\"). Then the chart and a ready caption are the whole answer."} diff --git a/lib/daytable.py b/lib/daytable.py index 0244d07b..08e002fc 100644 --- a/lib/daytable.py +++ b/lib/daytable.py @@ -13,7 +13,7 @@ from datetime import date, datetime, timedelta, tzinfo from statistics import fmean -from .captions import COUNT_CHART_HINT +from .captions import CHART_ANSWERS_IT, COUNT_CHART_HINT from .series import AIR from .specs import Chart, Panel, calendar_bars from .timeutil import day_text, parse_period @@ -52,6 +52,7 @@ def parameters(fields: list[str], what: str, extra: dict | None = None) -> dict: "order": {"type": "string", "enum": ["desc", "asc"], "description": "desc = highest first (default), asc = lowest first."}, "count_only": {"type": "boolean", "description": "true for \"how many days\": returns just the counts, no list of days (much smaller). Use it whenever the days themselves aren't asked for."}, "group_by": {"type": "string", "enum": ["month", "year"], "description": "Break the result down per month or year, months with none included. It is drawn as a bar chart."}, + "chart_answers_it": CHART_ANSWERS_IT, "stat": {"type": "string", "enum": list(STATS), "description": "What each month or year (or the whole period, with no group_by) shows: count (default: matching days), or the max, min, avg or sum of the field `of` over the matching days. E.g. rain total per month: stat sum, of rain, group_by month."}, "of": {"type": "string", "description": "The field to take max, min, avg or sum of (a field from the where.field list; not needed for count)."}, "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always counted."}, diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index 68574ff0..f2995151 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -10,6 +10,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +from ..captions import CHART_ANSWERS_IT from ..config import Config from ..lines import RANGE_KEEP_DAYS from ..sources import Source @@ -68,6 +69,7 @@ def parse_groups(value, default: str = DEFAULT_GROUPS) -> list[str]: "Omit for temperature."}, "chart": {"type": "boolean", "description": "Set true to send a chart with the answer: for trends over several " "days or longer, or when a graph/chart is asked for."}, + "chart_answers_it": CHART_ANSWERS_IT, "include_derived": {"type": "array", "items": {"type": "string", "enum": ["feels_like", "app_temp", "dew_point", "vpd"]}, "description": "Only when the question asks about feels-like, apparent temperature, dew point or " "VPD: which of them to include. Otherwise omit (they are left out by default)."}, diff --git a/lib/llm.py b/lib/llm.py index e32f748a..b156d4ed 100644 --- a/lib/llm.py +++ b/lib/llm.py @@ -80,7 +80,7 @@ async def _stream(self, kwargs: dict, on_text) -> tuple[str, list[dict], object] async def run(self, messages: list[dict], system_prompt: str, effort: str, *, first_call: tuple[str, dict] | list[tuple[str, dict]] | None = None, tool_choice: str = "required", - turn: Turn | None = None, on_text=None, on_heavy=None) -> str: + turn: Turn | None = None, on_text=None, on_heavy=None, finish=None) -> str: """Runs the tool loop, appending assistant/tool turns to `messages` in place. The prompt is passed per question (not stored) so concurrent chats can't clash. @@ -91,7 +91,9 @@ async def run(self, messages: list[dict], system_prompt: str, effort: str, *, on_text(text so far) is called as each answer streams in (private chats show it as a draft). on_heavy(tokens) is called once, before the model is sent a lot of data: when the tool results of a question pass WARN_TOKENS (twice a 500-point query), so the chat can be told - first. The work carries on; nothing waits for a reply.""" + first. The work carries on; nothing waits for a reply. + finish(calls, results) is asked after each step of the model's own tool calls (never after first_call): text from it is + the reply, and the turn ends there with no further model call (the bot's chart that answers the question by itself).""" cache: dict = {} # identical tool calls within one question are only made once async def call(name: str, args: str) -> str: @@ -116,14 +118,14 @@ async def heavy_check(): llm_time = tool_time = 0.0 - async def run_calls(calls: list[dict]): - """The calls ({"id", "name", "arguments"}), made together; their results join the messages.""" + async def run_calls(calls: list[dict]) -> list[str]: + """The calls ({"id", "name", "arguments"}), made together; their results join the messages and are returned in order.""" nonlocal tool_time t0 = time.monotonic() results = await asyncio.gather(*(call(c["name"], c["arguments"]) for c in calls)) tool_time += time.monotonic() - t0 messages.extend({"role": "tool", "tool_call_id": c["id"], "content": r} for c, r in zip(calls, results)) - await heavy_check() + return results first_step = 0 try: @@ -132,6 +134,7 @@ async def run_calls(calls: list[dict]): for i, (n, a) in enumerate(first_call if isinstance(first_call, list) else [first_call], 1)] messages.append({"role": "assistant", "content": "", "tool_calls": [_tool_call(c) for c in fast]}) await run_calls(fast) + await heavy_check() first_step = 1 # data is in; the model just answers (and may still call tools) for step in range(first_step, MAX_STEPS + 1): final = step == MAX_STEPS # out of steps: force an answer from what we have @@ -153,7 +156,13 @@ async def run_calls(calls: list[dict]): messages.append(entry) if not tool_calls or final: return content.strip() or "Sorry, I couldn't get an answer together - try a narrower question." - await run_calls(tool_calls) + results = await run_calls(tool_calls) + if finish and (reply := finish(tool_calls, results)): + log.info("The turn ended on a chart that answers the question (%s): no LLM %d", + ", ".join(c["name"] for c in tool_calls), step + 2) + messages.append({"role": "assistant", "content": reply}) + return reply + await heavy_check() finally: log.info("Timing: LLM %.1fs, tools %.1fs", llm_time, tool_time) diff --git a/tests/evalkit.py b/tests/evalkit.py index 00914895..be39cde3 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -38,6 +38,7 @@ "q:command": "asking the bot to do something (alerts)", "q:chat": "thanks and small talk", "q:report": "status / report", "q:dashboard": "the station's gauges", "q:detail-level": "asking for a finer data resolution", "q:cross-source": "a question that needs both devices together", "q:scan": "which readings go with which (every pair)", "q:interval": "values at an interval (each hour, every 30 minutes)", + "q:chart-only": "a question that is only a chart (chart_answers_it), and one that asks something beside it", "m:temperature": "temperature", "m:humidity": "humidity", "m:pressure": "pressure", "m:wind-speed": "wind speed and gusts", "m:wind-direction": "wind direction", "m:rain": "rain", "m:air-quality": "air quality", "c:line": "a line chart of one reading", "c:daily-band": "a long chart: daily mean with its range", diff --git a/tests/evals/cases.json b/tests/evals/cases.json index 5510a28b..926737ac 100644 --- a/tests/evals/cases.json +++ b/tests/evals/cases.json @@ -1553,5 +1553,52 @@ "q:interval", "m:temperature" ] + }, + { + "id": "chart-only-answers-itself", + "ask": "plot pressure since Sunday", + "note": "only the chart is asked for: the model says so (chart_answers_it) and the bot sends the chart with its caption written in code, with no second model call. A weekday keeps it off the fast path, so the model decides", + "expect": { + "fast": null, + "chart_in_code": false, + "tools": [ + "weather_history" + ], + "args": { + "weather_history": { + "chart_answers_it": true + } + } + }, + "covers": [ + "q:chart-only", + "m:pressure" + ] + }, + { + "id": "chart-and-a-question", + "ask": "plot pressure since Sunday, is a storm coming?", + "note": "the chart and something else to answer: the model writes the reply, so chart_answers_it stays unset", + "expect": { + "fast": null, + "chart_in_code": false, + "tools": [ + "weather_history" + ], + "args": { + "weather_history": { + "chart_answers_it": { + "any_of": [ + null, + false + ] + } + } + } + }, + "covers": [ + "q:chart-only", + "m:pressure" + ] } ] diff --git a/tests/test_chart_answers.py b/tests/test_chart_answers.py new file mode 100644 index 00000000..a7a04c35 --- /dev/null +++ b/tests/test_chart_answers.py @@ -0,0 +1,180 @@ +"""A question that is only a chart: the model sets chart_answers_it, the chart's caption is written in code and the model is asked +nothing more (docs/mcp-service.md 3.7). A real Agent over a scripted model and stand-in tools, through the bot's own model call.""" + +import json +import logging +from datetime import datetime +from types import SimpleNamespace as NS + +from lib import intent, llm +from lib.bot import Bot +from lib.specs import Chart, Line, Panel +from lib.tools import Tool, Tools, Turn +from tests.fakes import TZ +from tests.test_agent import FakeLLM + +NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday +ONLY_A_CHART = "plot pressure since Sunday" +PERIOD = "Sun 27 Sep 2026 - Tue 29 Sep 2026" +PRESSURE = {"period": PERIOD, "series": {"pressure.relative": { + "unit": "hPa", "low": "1004.2", "low_when": "at 4am", "low_date": "Mon 28 Sep 2026", + "high": "1021.7", "high_when": "at 10pm", "high_date": "Sun 27 Sep 2026"}}, "chart": "(the chart hint)"} +CAPTION = ("Sun 27 Sep – Tue 29 Sep 2026\n" + "Pressure: low 1004.2 hPa, Mon 28 Sep at 4am · high 1021.7 hPa, Sun 27 Sep at 10pm") +ASKED = {"start_date": "2026-09-27 00:00:00", "end_date": "2026-09-29 14:05:00", "groups": "pressure", "chart": True, + "chart_field": "pressure"} +EMPTY = {"type": "object", "properties": {}} + + +def chart(title: str = "Pressure") -> Chart: + return Chart(title, "", [Panel(title, "", [Line(title, [1, 2], [1.0, 2.0])])]) + + +def stand_in(name: str = "weather_history", result: dict | str = PRESSURE, draws: bool = True): + """The tool as a stand-in: it draws its chart (when `draws`) and answers `result`. Returns (the tool, the arguments it was given).""" + seen = [] + + async def handler(args, turn=None): + seen.append(args) + if isinstance(result, Exception): + raise result + if draws: + turn.charts.append(chart()) + return result if isinstance(result, str) else json.dumps(result) + return Tool(name, "d", EMPTY, handler), seen + + +async def ask(alert_state, script, tools, text=ONLY_A_CHART, turn=None): + """`text` through the bot's model call with a scripted model: (reply, the model's requests, the turn, the conversation).""" + client = FakeLLM(script) + bot = Bot(NS(tz=TZ), llm.Agent(client, "m", Tools(tools)), [], alert_state) + read = intent.read(text, NOW) + turn = turn or Turn.of(read, text) + working = [{"role": "user", "content": text}] + reply = await bot._ask_model(working, "sys", read, turn, None) + return reply, client.requests, turn, working + + +def test_the_tools_whose_chart_can_be_the_answer_offer_the_flag_and_say_when_to_set_it(): + from lib.airgradient import days as air_days, source as air + from lib.ecowitt import days, source as station + for parameters in (station.HISTORY_PARAMS, air.PARAMETERS, air.asked()[1], days.PARAMETERS, air_days.PARAMETERS): + flag = parameters["properties"]["chart_answers_it"] + assert flag["type"] == "boolean" and "nothing else to answer" in flag["description"] and "is a storm coming?" in flag["description"] + + +async def test_a_chart_that_answers_the_question_is_the_reply_written_in_code_and_the_model_is_asked_once(alert_state, caplog): + tool, seen = stand_in() + assert intent.read(ONLY_A_CHART, NOW).fast is None # the model takes it, not a shortcut + with caplog.at_level(logging.INFO, logger="lib.llm"): + reply, requests, turn, working = await ask(alert_state, [[("weather_history", {**ASKED, "chart_answers_it": True})], + "the model's own caption"], [tool]) + assert reply == CAPTION and len(requests) == 1 and len(turn.charts) == 1 and len(seen) == 1 + assert working[-1] == {"role": "assistant", "content": CAPTION} # the conversation keeps it as the answer + assert any("ended on a chart that answers the question (weather_history): no LLM 2" in r.getMessage() for r in caplog.records) + + +async def test_without_the_flag_the_model_writes_the_answer_as_before(alert_state): + tool, _ = stand_in() + reply, requests, turn, _ = await ask(alert_state, [[("weather_history", ASKED)], "The model's answer."], [tool]) + assert reply == "The model's answer." and len(requests) == 2 and len(turn.charts) == 1 + reply, requests, _, _ = await ask(alert_state, [[("weather_history", {**ASKED, "chart_answers_it": False})], "Again."], [tool]) + assert reply == "Again." and len(requests) == 2 + + +async def test_the_flag_with_no_chart_or_a_failed_call_leaves_the_answer_to_the_model(alert_state): + flagged = [("weather_history", {**ASKED, "chart_answers_it": True})] + for result, draws in (({k: v for k, v in PRESSURE.items() if k != "chart"}, False), # no chart drawn + ({"error": "bad date"}, False), # the tool said no + (RuntimeError("Ecowitt is down"), False), # the tool failed + ({"period": PERIOD, "series": {}, "chart": "(hint)"}, True)): # a chart, but nothing to caption it with + tool, _ = stand_in(result=result, draws=draws) + reply, requests, _, _ = await ask(alert_state, [flagged, "The model's answer."], [tool]) + assert reply == "The model's answer." and len(requests) == 2, result + + +async def test_a_step_with_any_call_that_is_not_a_chart_answering_the_question_goes_back_to_the_model(alert_state): + history, _ = stand_in() + now, _ = stand_in("weather_now", result={"outdoor": {"temperature": "12 ℃"}}, draws=False) + flagged = ("weather_history", {**ASKED, "chart_answers_it": True}) + for step in ([flagged, ("weather_history", ASKED | {"groups": "outdoor"})], # one of the two calls didn't set it + [flagged, ("weather_now", {"chart_answers_it": True})]): # a tool whose answer is not a chart + reply, requests, _, _ = await ask(alert_state, [step, "The model's answer."], [history, now]) + assert reply == "The model's answer." and len(requests) == 2 + + +async def test_several_charts_that_answer_the_question_are_captioned_in_the_order_called(alert_state): + pressure, _ = stand_in() + air = {"period": PERIOD, "pm2_5": {"unit": "µg/m³", "high": 34.2, "high_time": "Mon 28 Sep 2026 3:00pm", "high_rating": "🟠 Poor", + "average": 8.1, "low": 1.0, "low_time": "x"}, "chart": "(hint)"} + quality, _ = stand_in("air_quality", result=air) + script = [[("weather_history", {**ASKED, "chart_answers_it": True}), + ("air_quality", {"start_date": ASKED["start_date"], "end_date": ASKED["end_date"], "metrics": ["pm2_5"], "chart": True, + "chart_answers_it": True})], "unused"] + reply, requests, turn, _ = await ask(alert_state, script, [pressure, quality], text="plot pressure and pm2.5 since Sunday") + assert len(requests) == 1 and len(turn.charts) == 2 + assert reply == CAPTION + "\n\nSun 27 Sep – Tue 29 Sep 2026\n• PM2.5: peak 34.2 µg/m³ (Mon 28 Sep 3:00pm) · 🟠 Poor · average 8.1" + + +async def test_a_day_tools_chart_is_captioned_with_the_days_answer(alert_state): + counted = {"period": "Sat 01 Aug 2026 - Mon 28 Sep 2026", "days_checked": 59, "matching_days": 17, "condition": "rain ≥ 1 mm", + "by_month": {"2026-08": 9, "2026-09": 8}, "chart": "(hint)"} + days, _ = stand_in("weather_days", result=counted) + script = [[("weather_days", {"start_date": "2026-08-01", "end_date": "2026-09-28", "where": [{"field": "rain", "op": ">=", "value": 1}], + "count_only": True, "group_by": "month", "chart_answers_it": True})], "unused"] + reply, requests, _, _ = await ask(alert_state, script, [days], text="chart the rainy days each month since August") + assert reply == "17 of 59 days with rain ≥ 1 mm (Sat 01 Aug – Mon 28 Sep 2026)." and len(requests) == 1 + + +async def test_the_caption_speaks_of_the_readings_the_chart_shows_when_only_the_model_named_them(alert_state): + both = {"period": PERIOD, "chart": "(hint)", "series": { + "outdoor.temperature": {"unit": "℃", "low": "8.1", "high": "24.3"}, "outdoor.humidity": {"unit": "%", "low": "41", "high": "93"}}} + tool, _ = stand_in(result=both) + asked = {**ASKED, "groups": "outdoor", "chart_field": "humidity", "chart_answers_it": True} + reply, _, _, _ = await ask(alert_state, [[("weather_history", asked)], "unused"], [tool], turn=Turn(chart_asked=True)) + assert reply.splitlines()[1].startswith("Humidity: low 41 %") and "Temperature" not in reply + air = {"period": PERIOD, "chart": "(hint)", "pm2_5": {"unit": "µg/m³", "high": 9, "high_time": "x", "average": 3}, + "co2": {"unit": "ppm", "high": 812, "high_time": "Mon 28 Sep 2026 7:00am", "average": 455}} + tool, _ = stand_in("air_quality", result=air) + flagged = {"start_date": ASKED["start_date"], "end_date": ASKED["end_date"], "chart": True, "chart_answers_it": True} + reply, _, _, _ = await ask(alert_state, [[("air_quality", flagged)], "unused"], [tool], text="graph the air since Sunday", + turn=Turn(chart_asked=True, air_named=["co2"])) # no metrics: the tool charts the reading talked about + assert reply.splitlines()[1:] == ["• CO₂: peak 812 ppm (Mon 28 Sep 7:00am) · average 455"] + + +async def test_the_bots_own_first_call_never_ends_the_turn(): + tool, seen = stand_in() + finished = [] + + def finish(calls, results): + finished.append(calls) + return "ended in code" + client = FakeLLM(["The model's answer."]) + reply = await llm.Agent(client, "m", Tools([tool])).run( + [{"role": "user", "content": "q"}], "sys", "none", first_call=("weather_history", {**ASKED, "chart_answers_it": True}), + turn=Turn(), finish=finish) + assert reply == "The model's answer." and len(client.requests) == 1 and finished == [] and len(seen) == 1 + + +async def test_the_whole_answer_goes_out_with_its_chart(alert_state, monkeypatch): + from lib import bot as botmod + from tests.test_bot import telegram + tool, _ = stand_in() + client = FakeLLM([[("weather_history", {**ASKED, "chart_answers_it": True})], "unused"]) + sent = [] + + async def reply_photo(photo, caption=None, **kw): + sent.append(caption) + return NS(message_id=7) + + async def send_chat_action(*a, **k): + pass + monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, + chat=NS(type="supergroup", title="g"), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + bot = Bot(NS(tz=TZ), llm.Agent(client, "m", Tools([tool])), sources, alert_state) + await bot.respond(update, NS(bot=telegram(send_chat_action)), ONLY_A_CHART) + assert sent == ["Pressure\n\n" + CAPTION] and len(client.requests) == 1 + assert bot.chats[(1, None)].history[-1] == {"role": "assistant", "content": CAPTION} From c79cac16f584ad05caae5957a0f70d916df692b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:38:43 +0000 Subject: [PATCH 019/125] docs/mcp-service.md: step 2 changes the calls behind the period buttons, not where the buttons live Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 841fc129..01d5f3cb 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -450,8 +450,9 @@ Each step ships on its own, with the tests and evals green and the bot working t yesterday and errors for phrases outside the table and for the future. No tool interface changes. 2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready lines, captions), charts, descriptions and errors, and `lib/outlook.py`; offered to no model yet. Contract tests; the evals run - against them with the tool list alone. The bot's own code paths move to them: its shortcuts, report, lookups, period buttons, - gauges and alert charts. + against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, + lookups, gauges and alert charts, and the calls behind its period buttons (a press calls `summary` again with a new `period`; the + buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of buttons. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. From 0dc0e0d4758b72faa11ea2a0d97b41475ae12a27 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:42:18 +0000 Subject: [PATCH 020/125] Steps 0 and 1 merged: a chart answers the question only when no note needs the model's words The five branches (periods in words, the part-day engine, averages weighted by time, charts as data, chart_answers_it) are merged. Where they met, the chart-answers test stubbed the old render_chart; it now stubs render_data, as the chart-JSON branch did for the others. The plan says a result with a note that needs the model's words is never complete. The bot now ends the turn on a chart only when the result's notes are ones its own caption passes on (note_missing, warning; a day count's note_averaged); a monthly_note, note_resolution, note_daily or trace_rain_days goes back to the model. docs/mcp-service.md marks steps 0 and 1 done. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 10 +++++----- lib/bot.py | 15 ++++++++++++++- tests/test_chart_answers.py | 13 ++++++++++++- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 01d5f3cb..4b8ab829 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -254,7 +254,7 @@ temperature in October" `{hours: "15:00", stat: "avg", of: "temp_avg"}`. | Tool | Averages | |---|---| -| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown, and draws the chart as each day's average. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (today the station's average is the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour: fixed in step 0). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (today `weather_history` leaves every rain reading out, though `days` has `rain_rate_avg`); wind direction has its most common direction instead. A chart's panels report each line's average beside the lowest and highest of its half-hour averages, a rain panel its total. | +| `summary` | `average: true` adds each reading's average over the period, and one per day or month in its breakdown, and draws the chart as each day's average. The average is weighted by time: a part day at either end of the period counts for its hours, and an air day held only as hourly averages for its hours (until step 0 the station's average was the mean of its days' means, a part day counting as a whole one, and the air sensor's the mean of its stored readings, an hourly reading counting as one twelfth of a 5-minute hour). An air reading always has its average; its six air-quality readings also their `average_rating`, and PM2.5 its `average_aqi_us` and `average_band`; the air sensor's own temperature and humidity have no rating. Rain is a total, not an average; rain rate has an average (`weather_history` has given it one since step 0); wind direction has its most common direction instead. A chart's panels report each line's average beside the lowest and highest of its half-hour averages, a rain panel its total. | | `readings` | for a reading that is averaged, each row is its interval's average with its lowest and highest: hourly averages at `1hour`; at `1day` the day's average, lowest and highest, and when those two happened; at `1min` and `5min` the stored reading itself. Rain is the mm that fell in the interval (at `1day`, the day's total); gusts the interval's highest (at `1day`, with when); wind direction the reading at the interval's end (at `1day`, the day's last). Those three have no lowest and highest. | | `days` | a field for each day's average of every reading but rain, gusts and wind direction (`temp_avg`, `humidity_avg`, `pressure_avg`, `wind_speed_avg`, `rain_rate_avg`, `indoor_temp_avg` …; the air sensor's `pm2_5_avg`, `co2_avg` … for its six air-quality readings), and `stat: "avg"` over the matching days, overall or per month or year ("average humidity per year"). Rain is a day's total (`rain`), so "average daily rain in June" is `stat: "avg", of: "rain"`. With `hours`, the same over that part of each day (rain: the mm that fell in it). | @@ -433,7 +433,7 @@ themselves; the charts' content. Each step ships on its own, with the tests and evals green and the bot working the whole way. The model's tool list changes once (step 3): old and new names are never offered together, and no tool interface is rewritten before it is replaced. -0. **Fixes the service needs anyway**, in today's code: +0. **Fixes the service needs anyway**, in today's code (done: `lib/partday.py`, the averages, `chart_answers_it`): - **Part of each day** (3.3): the engine (stretches through `Reader.part_days`, rain over a stretch, the coverage choice) with tests against stretches worked out by hand (a night across midnight, a clock-change day, a moment on a 5-minute and on a 30-minute day, a day held only as daily records, a night with rain in the evening only, an air glitch inside the stretch). The `hours` argument @@ -444,8 +444,8 @@ Each step ships on its own, with the tests and evals green and the bot working t reply (today's `report.chart_caption`) and the complete mark in the result, and the bot's early end of the turn on it; an eval pair (a question that is just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines show the calls it saves. It carries over to `summary` and `days` in step 2. -1. **Charts as data, periods in words.** The chart builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON - (at 500 points, so the golden images don't change). `lib/periods_text.py` reads the periods table, tested by hand against it at fixed +1. **Charts as data, periods in words** (done: `specs.to_json`/`from_json`, `schemas/chart.json`, `lib/periods_text.py`). The chart + builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON (at 500 points, so the golden images don't change). `lib/periods_text.py` reads the periods table, tested by hand against it at fixed times (a Monday, a Tuesday, the 1st of a month, 1 January, 29 February, 00:30, both clock-change days), with whole-day tools cut to yesterday and errors for phrases outside the table and for the future. No tool interface changes. 2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready @@ -461,7 +461,7 @@ Each step ships on its own, with the tests and evals green and the bot working t 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the - alert log). Then the irrigation server is built in its own repository against it, the bot connects to both, and `lib/irrigation` + alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). Then the irrigation server is built in its own repository against it, the bot connects to both, and `lib/irrigation` goes from here. The service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. 6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. diff --git a/lib/bot.py b/lib/bot.py index 05688c53..11fbea7a 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -175,6 +175,11 @@ def strip_chart_talk(text: str) -> str: return "\n".join(lines).strip() or text +# The notes a caption written here passes on itself (report.chart_caption, report.lookup); any other note needs the model's words +CAPTIONED_NOTES = {"weather_history": {"note_missing", "warning", "missing"}, "air_quality": {"note_missing", "warning", "missing"}, + **{tool: {"note_averaged"} for tool in DAY_TOOLS}} + + def _drew_chart(result: str) -> bool: """Does this tool result say it drew a chart (the "chart" note a tool adds when it does)?""" try: @@ -184,6 +189,14 @@ def _drew_chart(result: str) -> bool: return isinstance(data, dict) and "chart" in data and "error" not in data +def _needs_words(tool: str, result: str) -> bool: + """Does this result carry a note the person should hear that a caption written here would leave out (a month's figures without + dates, the older days held only as daily records or hourly averages, a rarer day that nearly counted ...)? Then the model answers.""" + data = json.loads(result) + notes = {k for k in data if k.startswith("note") or k.endswith("_note") or k in ("warning", "missing", "exact_from", "trace_rain_days")} + return bool(notes - CAPTIONED_NOTES.get(tool, set())) + + def _as_drawn(tool: str, args: dict, turn: Turn) -> tuple[dict, Turn]: """(args, turn) as the tool read them to draw its chart, so its caption speaks of what the chart shows: the readings the person's words name, else the model's (air quality: its metrics, else those named, else PM2.5), and an average if either asked for one.""" @@ -1075,7 +1088,7 @@ def _answer_caption(self, call: dict, result: str, turn: Turn) -> str | None: except ValueError: return None if (call["name"] not in ANSWERING_CHARTS or not isinstance(args, dict) or args.get("chart_answers_it") is not True - or not _drew_chart(result)): + or not _drew_chart(result) or _needs_words(call["name"], result)): return None if call["name"] in DAY_TOOLS: return report.lookup("days", result, [], [], now_local(self.cfg.tz).date()) diff --git a/tests/test_chart_answers.py b/tests/test_chart_answers.py index a7a04c35..e7c5290c 100644 --- a/tests/test_chart_answers.py +++ b/tests/test_chart_answers.py @@ -93,6 +93,17 @@ async def test_the_flag_with_no_chart_or_a_failed_call_leaves_the_answer_to_the_ assert reply == "The model's answer." and len(requests) == 2, result +async def test_a_note_the_caption_would_leave_out_leaves_the_answer_to_the_model(alert_state): + flagged = [("weather_history", {**ASKED, "chart_answers_it": True})] + for note in ({"monthly_note": "Monthly figures for long periods come from daily data"}, {"note_resolution": "hourly averages"}): + tool, _ = stand_in(result={**PRESSURE, **note}) + reply, requests, _, _ = await ask(alert_state, [flagged, "The model's answer."], [tool]) + assert reply == "The model's answer." and len(requests) == 2, note + tool, _ = stand_in(result={**PRESSURE, "note_missing": "older days are downloading"}) # a note the caption writes itself + reply, requests, _, _ = await ask(alert_state, [flagged, "unused"], [tool]) + assert len(requests) == 1 and "still downloading" in reply + + async def test_a_step_with_any_call_that_is_not_a_chart_answering_the_question_goes_back_to_the_model(alert_state): history, _ = stand_in() now, _ = stand_in("weather_now", result={"outdoor": {"temperature": "12 ℃"}}, draws=False) @@ -169,7 +180,7 @@ async def reply_photo(photo, caption=None, **kw): async def send_chat_action(*a, **k): pass - monkeypatch.setattr(botmod, "render_chart", lambda spec, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="supergroup", title="g"), from_user=NS(full_name="Rob"), reply_to_message=None) From c1bed7b68ff4d8676b730740419e97009839dcf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:42:38 +0000 Subject: [PATCH 021/125] docs/mcp-service.md: rewrap the steps' long lines Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 4b8ab829..ea58471a 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -445,9 +445,10 @@ Each step ships on its own, with the tests and evals green and the bot working t (a question that is just the chart, where the model sets it; one with something else to answer, where it doesn't). Shipped on the live evals; the log's `LLM 2` lines show the calls it saves. It carries over to `summary` and `days` in step 2. 1. **Charts as data, periods in words** (done: `specs.to_json`/`from_json`, `schemas/chart.json`, `lib/periods_text.py`). The chart - builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON (at 500 points, so the golden images don't change). `lib/periods_text.py` reads the periods table, tested by hand against it at fixed - times (a Monday, a Tuesday, the 1st of a month, 1 January, 29 February, 00:30, both clock-change days), with whole-day tools cut to - yesterday and errors for phrases outside the table and for the future. No tool interface changes. + builders return 3.7's JSON with its schema, and the bot's renderer reads the JSON (at 500 points, so the golden images don't change). + `lib/periods_text.py` reads the periods table, tested by hand against it at fixed times (a Monday, a Tuesday, the 1st of a month, 1 + January, 29 February, 00:30, both clock-change days), with whole-day tools cut to yesterday and errors for phrases outside the table + and for the future. No tool interface changes. 2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready lines, captions), charts, descriptions and errors, and `lib/outlook.py`; offered to no model yet. Contract tests; the evals run against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, @@ -461,9 +462,10 @@ Each step ships on its own, with the tests and evals green and the bot working t 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the - alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). Then the irrigation server is built in its own repository against it, the bot connects to both, and `lib/irrigation` - goes from here. The service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, - `conditions`, `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. + alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). Then the irrigation server is built in its own + repository against it, the bot connects to both, and `lib/irrigation` goes from here. The service's scripts (`edit_readings`, + `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`, `dump_specs`) stay; + `show_request` and `report_inputs` become MCP clients. 6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. ## 7. Testing From 9a4fb21f6907fea29236cecfb9f6f8f53537cc01 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:44:43 +0000 Subject: [PATCH 022/125] docs/mcp-service.md: every chart carries drawn_by, the call that drew it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A chart's drawn_by is the call as the service read it (names resolved, defaults filled in, the period stated), so a client replays it for the latest readings or swaps only the period for another: period buttons and an alert's 🔄 need no knowledge of which tool or readings made the chart, and never the model. It replaces the alert event's separate refresh; the bot's period buttons keep each chart's drawn_by instead of the question's text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index ea58471a..c41f19bc 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -317,11 +317,11 @@ crossings, particulates (mask on, safe again), pollen and thunderstorm asthma, a cooldowns are the service's config, and their state its own store (`alert_state.json`, out of the bot's `bot_state.json`). Each runs on the triggers it has today: a new live reading or 5-minute row, a new forecast or pollen page, and its own clock (the weather alerts every 60 seconds, particulates every 30 minutes and only then, since its two-readings rule counts readings across checks). -- **An alert is an event:** `{id, kind, time, expires, title, text, data, [link: {label, url}], [chart], [refresh: {tool, arguments}]}`. - `text` is ready to send ("🌧️ It's started raining: 0.4 mm so far"); `data` the figures behind it; `link` the page that goes with it - (the AirGradient dashboard for particulates, the pollen site for pollen); `chart` its chart data when it has one (gusts, UV, - temperature, particulates); `refresh` the call that draws that chart again with the latest readings (gusts: - `summary{readings: ["wind"], period: "last 24 hours", chart: true}`), so a client's 🔄 needs no knowledge of the kinds. +- **An alert is an event:** `{id, kind, time, expires, title, text, data, [link: {label, url}], [chart]}`. `text` is ready to send + ("🌧️ It's started raining: 0.4 mm so far"); `data` the figures behind it; `link` the page that goes with it (the AirGradient + dashboard for particulates, the pollen site for pollen); `chart` its chart data when it has one (gusts, UV, temperature, + particulates), which like every chart carries the call that drew it (`drawn_by`, 3.7), so a client's 🔄 calls it again for the + latest readings with no knowledge of the kinds. - **Alerts go stale:** `expires` is set by the rule (rain and gusts about an hour, UV its rearm time, particulates the next check, pollen the end of its day, a forecast the day it is about), and `ecobot://alerts?since=` returns only unexpired alerts unless asked. A client back after a gap sends what is still true, never the morning's rain as news. @@ -338,10 +338,14 @@ every 60 seconds, particulates every 30 minutes and only then, since its two-rea Charts are data: the client draws them, or its model does from the numbers. - **`summary` and `days` (with `group_by`) draw** (and `relate` and `scan` when asked); they build the chart as now (`specs.Chart`), next - to the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, panels: - [{unit, [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], [compass]}]}]`. - Times are ISO local times; `source` names the devices ("Ecowitt weather station and AirGradient sensor"). The JSON Schema is in the - repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. + to the reads that chose its resolution, buckets and rose, and return it in the result: `charts: [{title, period, source, drawn_by, + panels: [{unit, [label], series: [{name, kind: "line"|"band"|"bars"|"rating", points: [[time, value, (low, high)]]}], [zones], + [compass]}]}]`. Times are ISO local times; `source` names the devices ("Ecowitt weather station and AirGradient sensor"). The JSON + Schema is in the repository (`schemas/chart.json`) and at `ecobot://schema/chart`, versioned. +- **Every chart says how to draw it again:** `drawn_by: {tool, arguments}` is the call that drew it as the service read it, with the + readings' names resolved, every default filled in and the period stated, so the same call with only `period` changed draws the same + chart over another period, and the same call again draws it with the latest readings. A client's period buttons, or an alert's 🔄, + replay it; they need no knowledge of which tool or readings made the chart, and never the model. - **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (the bands with it), so a model can turn it into a plot with its own tools and an application can draw it directly. An application that draws for itself asks for more with request `_meta` `chart_points` (at most 500, today's budget); the bot asks for 500, so its pictures and golden images don't change. @@ -415,9 +419,10 @@ service. Beyond what the steps need, it gets no new features. While it lives it: the gauges), each a fixed call to a service tool whose result is already worded, so it writes nothing itself; - draws `charts` and the gauges (`current` with `context`) with its renderer; - listens to `ecobot://alerts` (and, from step 5, `irrigation://alerts`) and sends each alert to the chats subscribed to its kind, with - its chart, its link and a 🔄 that calls its `refresh`; + its chart, its link and a 🔄 that replays its chart's `drawn_by`; - builds `/usage`, Help and its alert menu from `ecobot://station` (and whether an irrigation server is configured); -- keeps per-chat state: subscriptions, admins, the chart questions behind its period buttons. +- keeps per-chat state: subscriptions, admins, and each chart's `drawn_by` behind its period buttons (a press replays it with a new + `period`). It is retired when a replacement does what you use it for: another client for questions (any MCP-capable assistant), and, for alerts, a client that listens. Its code is then deleted from this repository: `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, @@ -452,13 +457,14 @@ Each step ships on its own, with the tests and evals green and the bot working t 2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready lines, captions), charts, descriptions and errors, and `lib/outlook.py`; offered to no model yet. Contract tests; the evals run against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, - lookups, gauges and alert charts, and the calls behind its period buttons (a press calls `summary` again with a new `period`; the - buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of buttons. + lookups, gauges and alert charts, and the calls behind its period buttons (a press replays the chart's `drawn_by` with a new + `period`; the buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of + buttons. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. 4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, - `link`, `chart` and `refresh`; the forecast alert gets its station-wide baseline. The bot delivers from the log. + `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the @@ -476,7 +482,8 @@ Each step ships on its own, with the tests and evals green and the bot working t over from `tests/evals/cases.json`, with their periods checked as the service reads them, and gain one for each periods form, each routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. - **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods - table at its fixed times (step 1); charts against their schema; `day_look` against its rule. + table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, + and with only `period` changed, the same chart over that period; `day_look` against its rule. - `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row for every day held whole at 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; a day from a daily record, or from whatever readings there were, is left out and counted. From 6cd8bd23e437dee00a4d2983ae218a4fab42b964 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:46:19 +0000 Subject: [PATCH 023/125] docs/mcp-service.md: the period buttons, the preloads and the charts drawn ahead replay drawn_by The bot's picture cache and pre-upload are keyed by the call, not the question's words. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index c41f19bc..ba30c4d2 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -459,7 +459,11 @@ Each step ships on its own, with the tests and evals green and the bot working t against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, lookups, gauges and alert charts, and the calls behind its period buttons (a press replays the chart's `drawn_by` with a new `period`; the buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of - buttons. + buttons. Everything the bot draws ahead replays a call too: the other periods preloaded after a chart is sent (`drawn_by` with + `1d`, `7d`, `1m`, `3m`, `1y`), the keyboard's charts every 5 minutes (each button a fixed `summary` call), recent alerts' charts + (their `drawn_by`). The picture cache and the pre-upload are keyed by the call (tool and arguments), not the question's words, so + two chats asking the same thing share a picture. Period buttons stay on single charts over time; a replay the service refuses + shows its error on the button. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. From 6317fdbc175412c17a5d900fc1e2c1e58d0f3668 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 03:55:53 +0000 Subject: [PATCH 024/125] docs/mcp-service.md: each chart lists the periods it can be redrawn over drawn_by.periods [{period, label}], decided by the service: a chart over time gets 1D-1Y; a count per month 3M, 1Y and All; per year none; relate and scan 1M-1Y. The bot shows a button for each, and none when there are none, instead of all five under every single chart (a count per month offers a 1D that draws nothing today). Tested: every listed period replays without an error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index ba30c4d2..7e7ca4f9 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -346,6 +346,11 @@ Charts are data: the client draws them, or its model does from the numbers. readings' names resolved, every default filled in and the period stated, so the same call with only `period` changed draws the same chart over another period, and the same call again draws it with the latest readings. A client's period buttons, or an alert's 🔄, replay it; they need no knowledge of which tool or readings made the chart, and never the model. +- **And the periods it makes sense over:** `drawn_by.periods: [{period, label}]`, decided by the service for that chart, so a client + offers only buttons that draw something worth having. A chart of readings over time: `1d` "1D", `7d` "7D", `1m` "1M", `3m` "3M", + `1y` "1Y". A count or total per month (`days` with `group_by`): `3m`, `1y`, `on record` "All"; per year: `on record` alone, so no + buttons. Rain against a reading (`relate`) and `scan`: `1m`, `3m`, `1y`. A chart that can't be redrawn over another period lists + none. - **Small enough for a model to read and redraw:** each line is bucketed to at most 150 points (the bands with it), so a model can turn it into a plot with its own tools and an application can draw it directly. An application that draws for itself asks for more with request `_meta` `chart_points` (at most 500, today's budget); the bot asks for 500, so its pictures and golden images don't change. @@ -462,8 +467,9 @@ Each step ships on its own, with the tests and evals green and the bot working t buttons. Everything the bot draws ahead replays a call too: the other periods preloaded after a chart is sent (`drawn_by` with `1d`, `7d`, `1m`, `3m`, `1y`), the keyboard's charts every 5 minutes (each button a fixed `summary` call), recent alerts' charts (their `drawn_by`). The picture cache and the pre-upload are keyed by the call (tool and arguments), not the question's words, so - two chats asking the same thing share a picture. Period buttons stay on single charts over time; a replay the service refuses - shows its error on the button. + two chats asking the same thing share a picture. A single chart gets a button for each of its `drawn_by.periods`, labelled as the + service labels them, and none when it lists none (today every single chart gets all five, so a count per month offers a 1D that + draws nothing); a replay the service still refuses shows its error on the button. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. @@ -487,7 +493,7 @@ Each step ships on its own, with the tests and evals green and the bot working t routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. - **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, - and with only `period` changed, the same chart over that period; `day_look` against its rule. + and with only `period` changed to each of its `periods`, the same chart over that period, never an error; `day_look` against its rule. - `days.hours` gives, for a stretch that is the whole day ("00:00-24:00"), the same figures as its day row for every day held whole at 5 or 30 minutes (the air sensor's at 5 minutes or an hour), a clock-change day included; a day from a daily record, or from whatever readings there were, is left out and counted. From e7f8b25769369ff8d8bcb05b54d871f4dec2aa86 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:01:23 +0000 Subject: [PATCH 025/125] lib/service: what the ten tools will share (step 2's foundation) Nothing a model or a person sees changes: no tool is built or offered yet. - common.py: a ServiceTool, whose handler is sent its arguments and the request's metadata (chart_points, fetch, priority) and nothing else; in the bot it reads only the new Turn.meta, with Turn.ahead as a background request. Every answer starts with how its period was read and the time of its figures, with one line saying a follow-up needs the tool called again; refusals teach the right call, a period that is no form listing every form with what it means now. Also the period, start and end parameters, the period read through lib/periods_text.py, and charts as data within the request's budget (150 points a line unless it asks for up to 500), with the one-line note for the model. - names.py: every reading as sensor.reading, from what the file holds, and the words people use for them (a bare temperature or humidity is outdoor and indoor, never the AirGradient's; wind is its speed shaded up to the gusts with its direction; a sensor's name is its usual set; all is every station reading in the usual chart order). An unknown name is refused with the names and the words. The settings "all" follows (ALL_ORDER and the feels-like and VPD flags) move here; intent and ecobot.py read them here. - daylook.py: a day's look (stormy, wet, showery, windy, very hot, very cold, then sunny to overcast by its solar radiation against a clear sky's for that date and latitude), each threshold a named constant. history.station_fields is what History.open read inline, now shared with the catalogue. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 4 +- ecobot.py | 7 +- lib/history.py | 12 +- lib/intent.py | 10 +- lib/service/__init__.py | 10 + lib/service/common.py | 259 +++++++++++++++++++++++++ lib/service/daylook.py | 102 ++++++++++ lib/service/names.py | 318 ++++++++++++++++++++++++++++++ lib/tools.py | 2 + tests/test_intent.py | 9 +- tests/test_service_base.py | 388 +++++++++++++++++++++++++++++++++++++ 11 files changed, 1102 insertions(+), 19 deletions(-) create mode 100644 lib/service/__init__.py create mode 100644 lib/service/common.py create mode 100644 lib/service/daylook.py create mode 100644 lib/service/names.py create mode 100644 tests/test_service_base.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index ea58471a..db790e6b 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -75,7 +75,7 @@ All of this is what a client other than the bot would not know, so it has to mov | Stays (the service) | Leaves | |---|---| -| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` and `sheet()` from `lib/ecowitt/dashboard.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | +| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` and `sheet()` from `lib/ecowitt/dashboard.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | ### 3.2 An interface any model can use @@ -454,6 +454,8 @@ Each step ships on its own, with the tests and evals green and the bot working t against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, lookups, gauges and alert charts, and the calls behind its period buttons (a press calls `summary` again with a new `period`; the buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of buttons. + Begun: what the tools share, in `lib/service/` (`common.py`: a tool and its request metadata, answers, refusals, periods, chart + data; `names.py`: the reading names and the words for them; `daylook.py`: a day's look by its rule). 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. diff --git a/ecobot.py b/ecobot.py index 01f9e063..a71d5365 100644 --- a/ecobot.py +++ b/ecobot.py @@ -18,7 +18,7 @@ from telegram.error import InvalidToken, NetworkError from telegram.ext import Application, Defaults -from lib import charts, intent +from lib import charts from lib.airgradient import AirGradient from lib.airgradient import metrics as air_metrics from lib.alerts.forecast import ForecastMonitor @@ -37,6 +37,7 @@ from lib.llm import Agent from lib.logs import BUGS, LogFormat, on_journal, stream_handlers from lib.pollen import Pollen +from lib.service import names as service_names from lib.compose import Composer from lib.history import History from lib.sources import Source @@ -225,8 +226,8 @@ async def main(): for name in ("ecobot", "lib"): # the bot's own lines: the libraries keep theirs logging.getLogger(name).setLevel(cfg.log_level) air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive - intent.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like - intent.VPD_IN_ALL = cfg.chart_all_vpd + service_names.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like # "all" (and "weather all week") draws these too + service_names.VPD_IN_ALL = cfg.chart_all_vpd # Whatever starts is closed on the way out, the last started first, however the bot stops (a failure part-way included) async with contextlib.AsyncExitStack() as stack: app = (Application.builder().token(cfg.telegram_token).concurrent_updates(True) diff --git a/lib/history.py b/lib/history.py index 2d7faaed..746a1600 100644 --- a/lib/history.py +++ b/lib/history.py @@ -104,6 +104,12 @@ def station_metrics(sent: dict[str, dict[str, str]] | None = None) -> list[Metri return out +async def station_fields(eco) -> dict[str, dict[str, str]]: + """The fields the station (an Ecowitt source, started) has sent, as the file's `fields` table has them: {group: {field: unit}}, the + `sent` station_metrics reads.""" + return await eco.storage.read(lambda r: {s.external: r.fields(s.id) for s in r.sensors(device=eco.mac) if s.kind != AIR_SENSOR}) + + def air_metrics(extra: bool = False) -> list[Metric]: """The air sensor's readings, with its own temperature and humidity when `extra` (offered only when a question names them).""" names = [*AIR, *(AIR_EXTRA if extra else ())] @@ -354,8 +360,7 @@ def __init__(self, eco=None, air=None, sent: dict[str, dict[str, str]] | None = @classmethod async def open(cls, eco=None, air=None) -> "History": """The tool, with the readings the station has sent read from the file.""" - sent = await eco.storage.read(lambda r: {s.external: r.fields(s.id) for s in r.sensors(device=eco.mac) if s.kind != AIR_SENSOR}) if eco else None - return cls(eco, air, sent) + return cls(eco, air, await station_fields(eco) if eco else None) def find(self, name: str) -> Metric | None: """The metric a name means: its own name, else a reading's ("humidity", "uv", "pm2_5", "rain") on the sensor that has it. A sensor @@ -432,4 +437,5 @@ async def handle(self, args: dict, turn: Turn | None = None) -> str: return json_result(out) -__all__ = ["DESCRIPTION", "History", "INTERVALS", "MAX_ROWS", "PARAMETERS", "air_metrics", "interval_starts", "parameters", "station_metrics"] +__all__ = ["DESCRIPTION", "History", "INTERVALS", "MAX_ROWS", "PARAMETERS", "air_metrics", "interval_starts", "parameters", "station_fields", + "station_metrics"] diff --git a/lib/intent.py b/lib/intent.py index 2b130c4e..67f76d9c 100644 --- a/lib/intent.py +++ b/lib/intent.py @@ -17,6 +17,7 @@ from .logs import BUGS from .daytable import GROUPING, grouping_in from .series import AIR as AIR_TABLE, INDOOR_READINGS, PRESSURE_WORDS, READING_GROUPS, SPECIFIC, WEATHER as WEATHER_READINGS +from .service import names as service_names log = logging.getLogger(__name__) @@ -416,12 +417,6 @@ def _named(text: str) -> dict[str, int]: return found -FEELS_LIKE_IN_ALL = False # CHART_ALL_FEELS_LIKE=on puts the feels-like panel in "weather all week" (set from the config at startup) -VPD_IN_ALL = False # CHART_ALL_VPD=on puts the vapour pressure deficit panel in "weather all week" (it is temperature and humidity combined) -ALL_ORDER = ("temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "uv", "wind") # the panels of "weather all week", top to bottom -LEFT_OUT_OF_ALL = ("uv",) # "weather all week" leaves these out: the UV index has the same shape as solar radiation - - # "on two axes", "dual axis", "2 axes", "secondary axis", "overlay": two readings on one panel, each with a scale of its own TWO_AXES = re.compile(r"\b(?:(?:two|2|dual|twin|double|secondary|second)[- ](?:y[- ]?)?ax[ie]s|overla(?:y(?:ed|ing|s)?|id))\b", I) @@ -441,8 +436,7 @@ def chart_fields(text: str) -> list[str]: found = _named(text) if wants_chart_all(text): # "weather all week", "chart all 90d", "weather chart 90d": every reading, a panel each indoors = _sides(text) == ["indoor"] # the indoor sensor only has these - return [n for n in ALL_ORDER if n not in LEFT_OUT_OF_ALL and (FEELS_LIKE_IN_ALL or n != "feels_like") - and (VPD_IN_ALL or n != "vpd") and (not indoors or n in INDOOR_READINGS)] # naming one still works + return [n for n in service_names.in_all() if not indoors or n in INDOOR_READINGS] # the service's order and settings; naming one still works return sorted(found, key=found.get) if len(found) >= 2 else [] diff --git a/lib/service/__init__.py b/lib/service/__init__.py new file mode 100644 index 00000000..54d5c867 --- /dev/null +++ b/lib/service/__init__.py @@ -0,0 +1,10 @@ +"""The service's tools (docs/mcp-service.md 3.2 and 3.3): the ten that will replace the bot's twelve, each in a module of its own, on +what every one of them shares: + + - common.py: how a tool is made, what it is sent (its arguments and the request's metadata, nothing else), and the shape of what it + answers: the period it read, the time of its figures, its charts, and its refusals; + - names.py: the readings the service has, one name each (`outdoor.temperature`, `air.pm2_5`), and the words people use for them; + - daylook.py: a day's look ("wet", 🌧️) from its figures. + +Nothing here is offered to a model yet, and nothing here knows of Telegram, of the bot's buttons or of who draws a chart. +""" diff --git a/lib/service/common.py b/lib/service/common.py new file mode 100644 index 00000000..abe1ac13 --- /dev/null +++ b/lib/service/common.py @@ -0,0 +1,259 @@ +"""What every service tool shares (docs/mcp-service.md 3.2, 3.7): how a tool is made and what it is sent, how it reads a period, and +the shape of what it answers. + +A tool is a ServiceTool: its handler is `handler(args, meta)`, the arguments as sent and the request's metadata (`request_meta`), and +nothing else about the question. In the bot, `ServiceTool.tool()` makes it a lib.tools.Tool that reads only `Turn.meta` (and +`Turn.ahead`, the old name for a background request); over MCP, `meta` is the request's `_meta`. + +Every answer is compact JSON (`answer`), and starts the same way: + + {"period": {"asked": "this week", "text": "the last 7 days: Wed 4 – Tue 10 Nov 2026", + "start": "2026-11-04T00:00:00+11:00", "end": "2026-11-10T14:05:00+11:00", "cut": "to Mon 9 Nov: today isn't over"}, + "as_of": {"text": "Tue 10 Nov 2026 2:05pm", "time": "2026-11-10T14:05:00+11:00"}, + "fresh": FRESH, + ... the tool's own fields ..., + "chart_note": CHART_NOTE, "charts": [...]} + + - `period`: how the words were read (lib/periods_text.Period): `asked` the words (or "start/end"), `text` how they were read, ready + to pass on, `start` and `end` ISO local times with their offset (the end not included), and `cut` only when a whole-day tool cut + today off. Left out by a tool that takes no period. + - `as_of`: the time of the figures, `text` written as the tools write a time (timeutil.when), `time` ISO. + - `fresh`: one fixed line for the model: the figures are as of `as_of`, and a follow-up or a challenge needs the tool called again. + - `chart_note` and `charts` (`with_charts`): the charts as data (specs.to_json, bucketed to the request's `chart_points`), and the + one line that tells the model what to do with them. Left out when there is no chart. + - `reply` and `complete: true` (`complete`), only when the chart is the whole answer (3.7, `chart_answers_it`). + +A refusal is `{"error": message, ...what teaches the right call}` (`refuse`). A handler can raise Refusal anywhere instead: the tool +answers with its JSON. A period that isn't one of the forms is refused with each form and what it means now (`refuse_period`). +""" + +import inspect +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import date, datetime, tzinfo + +from .. import specs +from ..periods_text import Period, PeriodError, read_period as read_words +from ..timeutil import clock_text, day_text +from ..tools import Tool, Turn, json_result + +# ---------- the request's metadata ---------- +CHART_POINTS = 150 # the most points a line of a chart is sent in, unless the request asks for more (3.7): enough for a model to redraw +MAX_CHART_POINTS = 500 # the most a request may ask for: today's drawing budget (lines.POINT_BUDGET), what the bot asks for +NORMAL, BACKGROUND = "normal", "background" # priority: someone is waiting, or the work is ahead of need (a chart drawn ahead) +META = {"chart_points": CHART_POINTS, "fetch": True, "priority": NORMAL} # each key a handler reads, with its default + + +def request_meta(raw: dict | None = None) -> dict: + """The request's metadata as a handler reads it: every key in META, each checked, defaulted where missing or not understood; any + other key passed on as it came. + - chart_points: the most points a chart's line is sent in, a whole number from 2 to MAX_CHART_POINTS (default CHART_POINTS); + - fetch: False answers from what is held, fetching nothing that is missing (default True); + - priority: "background" for work nobody is waiting on (a chart drawn ahead), whose requests wait their turn; else "normal".""" + raw = dict(raw) if isinstance(raw, dict) else {} + points = raw.get("chart_points") + try: + points = CHART_POINTS if points is None or isinstance(points, bool) else min(max(int(points), 2), MAX_CHART_POINTS) + except (TypeError, ValueError): + points = CHART_POINTS + fetch = raw.get("fetch", True) + fetch = not (fetch is False or str(fetch).strip().lower() in ("false", "0", "no", "off")) + priority = BACKGROUND if str(raw.get("priority") or "").strip().lower() == BACKGROUND else NORMAL + return {**raw, "chart_points": points, "fetch": fetch, "priority": priority} + + +def turn_meta(turn: Turn | None) -> dict: + """The metadata of a question the bot asks: Turn.meta, a chart drawn ahead (Turn.ahead) being a background request.""" + if turn is None: + return request_meta() + raw = dict(turn.meta) + if turn.ahead and "priority" not in raw: + raw["priority"] = BACKGROUND + return request_meta(raw) + + +# ---------- refusals ---------- +def refuse(message: str, **teach) -> str: + """A refusal as a tool answers it: {"error": message, ...teach}, where `teach` is whatever lets a model correct its call once, from + the error alone (the names it could have sent, the forms of a period, the interval that fits).""" + if "error" in teach: + raise ValueError("a refusal's message is its `error`") + return json_result({"error": message, **teach}) + + +class Refusal(ValueError): + """A call refused, with what teaches the right one. Raised anywhere in a handler, it becomes the tool's answer (`text`).""" + + def __init__(self, message: str, **teach): + super().__init__(message) + self.message, self.teach = message, teach + + @property + def text(self) -> str: + return refuse(self.message, **self.teach) + + @classmethod + def of_period(cls, e: PeriodError) -> "Refusal": + """A period that can't be read: its message (which ends with the time now) and, when the words were none of the forms, each form + with what it means now, as {form: meaning}.""" + return cls(e.message, **({"forms": dict(e.forms)} if e.forms else {})) + + +def refuse_period(e: PeriodError) -> str: + """A PeriodError as a tool answers it: {"error": message, ["forms": {form: what it means now}]}.""" + return Refusal.of_period(e).text + + +# ---------- a tool ---------- +Handler = Callable[[dict, dict], Awaitable[str] | str] + + +@dataclass +class ServiceTool: + """A tool of the service: its name, the description a model reads, its input schema, and `handler(args, meta)`, which answers with + a string (`answer`, `refuse`) or raises Refusal. It may be a coroutine function. It is sent nothing else about the question.""" + name: str + description: str + parameters: dict # the input schema: {"type": "object", "properties": {...}, "required": [...]} + handler: Handler + read_only: bool = True # MCP's readOnlyHint: every tool of the service only reads + open_world: bool = False # MCP's openWorldHint: it asks a device or a cloud for what the file lacks (unless meta `fetch` is False) + + @property + def annotations(self) -> dict: + return {"readOnlyHint": self.read_only, "openWorldHint": self.open_world} + + async def call(self, args: dict | None = None, meta: dict | None = None) -> str: + """Run it with these arguments and this request metadata (request_meta fills in the rest); a Refusal comes back as its JSON.""" + if args is not None and not isinstance(args, dict): + return refuse("The arguments must be a JSON object of the tool's parameters.") + try: + out = self.handler(dict(args or {}), request_meta(meta)) + return await out if inspect.isawaitable(out) else out + except Refusal as e: + return e.text + + def tool(self) -> Tool: + """The tool as the bot's Tools runs it: its handler reads only the Turn's metadata (turn_meta).""" + async def handle(args: dict, turn: Turn | None = None) -> str: + return await self.call(args, turn_meta(turn)) + return Tool(self.name, self.description, self.parameters, handle) + + +# ---------- periods ---------- +PERIOD_FORMS = ("today, yesterday, last N hours/days/weeks/months/years (or Nh, Nd, Nw, Nm, Ny), this week, last week, week to date, " + "this month, last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, " + "2026-09-05), a weekday (Saturday), this morning, yesterday afternoon, last night, since 6am, a public holiday " + "(Christmas Day), on record, A to B (June to August)") +WHOLE_DAY_FORMS = ("yesterday, last N days/weeks/months/years (or Nd, Nw, Nm, Ny), this week, last week, week to date, this month, " + "last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, 2026-09-05), " + "a weekday (Saturday), a public holiday (Christmas Day), on record, A to B (June to August)") + + +def period_properties(default: str, whole_days: bool = False) -> dict: + """The `period`, `start` and `end` of a tool's input schema, described for a model: the person's words passed on unchanged, the + forms the service reads, or else dates on the station's clock; for a whole-day tool, whole days up to yesterday. `default` is what + the description says is read when nothing is sent: usually the words given to read_period as its default ("last 24 hours", "on + record"), or more ("today; with a chart, the last 24 hours").""" + if whole_days: + forms, days = WHOLE_DAY_FORMS, (" Whole days only, up to yesterday, as today isn't over: a rolling period is that many whole days " + "to yesterday (\"last 7 days\" is the 7 days before today).") + start = "Instead of `period`, never with it: the first day, 'YYYY-MM-DD'." + end = "With `start`: the last day, 'YYYY-MM-DD', up to yesterday. Default: yesterday." + else: + forms, days = PERIOD_FORMS, "" + start = ("Instead of `period`, never with it: when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " + "'YYYY-MM-DD HH:MM'.") + end = "With `start`: when it ends, local time, 'YYYY-MM-DD' (to the end of that day) or 'YYYY-MM-DD HH:MM'. Default: now." + return { + "period": {"type": "string", "description": "The period in the person's own words, passed on unchanged (\"this week\", \"in the " + "last year\", \"past two years\"): the service reads them, and the result says how. " + f"Forms: {forms}.{days} Default: {default}."}, + "start": {"type": "string", "description": start}, + "end": {"type": "string", "description": end}, + } + + +def read_period(args: dict, *, tz: tzinfo, now: datetime, default: str, whole_days: bool = False, + first_held: date | datetime | None = None) -> Period: + """The period a call asks for, from its `period`, or `start` and `end`, else `default` (words), read by lib/periods_text.py at `now` + (aware, or naive on the station's clock) in the station's zone. `first_held`: the first reading held for the readings asked about + ("on record"). Raises Refusal (refuse_period) when it can't be read.""" + try: + return read_words(args.get("period"), args.get("start"), args.get("end"), now=now, tz=tz, default=default, whole_days=whole_days, + first_held=first_held) + except PeriodError as e: + raise Refusal.of_period(e) from None + + +# ---------- an answer ---------- +FRESH = ("These figures are as of `as_of`. A follow-up or a challenge (\"that's wrong, it was cooler\") needs this tool called again: " + "never answer it from these.") +HEAD = ("period", "as_of", "fresh") # the keys every answer starts with (a tool's own fields can't take them) + + +def iso(t: datetime | int | float, tz: tzinfo | None = None) -> str: + """A time as the service writes it for an application: ISO local time with its UTC offset, to the second ("2026-11-10T14:05:00+11:00"). + `t` is an aware datetime (written in its own zone), or an epoch written in `tz`.""" + if isinstance(t, datetime): + if t.tzinfo is None: + raise ValueError(f"a time needs its zone: {t!r}") + return t.isoformat(timespec="seconds") + if tz is None: + raise ValueError("an epoch needs the zone to write it in") + return datetime.fromtimestamp(t, tz).isoformat(timespec="seconds") + + +def period_field(period: Period) -> dict: + """{"asked", "text", "start", "end", ["cut"]}: how the period was read.""" + out = {"asked": period.asked, "text": period.text, "start": iso(period.start), "end": iso(period.end)} + if period.cut: + out["cut"] = period.cut + return out + + +def as_of_field(as_of: datetime) -> dict: + """{"text": "Tue 10 Nov 2026 2:05pm", "time": ISO}: the time of the figures (aware, written in its own zone: the station's).""" + return {"text": f"{day_text(as_of)} {clock_text(as_of)}", "time": iso(as_of)} + + +def answer(*, period: Period | None, as_of: datetime | None, **fields) -> str: + """A tool's answer as compact JSON: `period` (period_field) and `as_of` (as_of_field) with the FRESH line, then the tool's own fields + in the order given. A tool with no period (current, outlook) passes None, and one with no figures (about) None for `as_of`.""" + if clash := set(HEAD) & set(fields): + raise ValueError(f"an answer's own fields can't be named {', '.join(sorted(clash))}") + head = {} + if period is not None: + head["period"] = period_field(period) + if as_of is not None: + head["as_of"], head["fresh"] = as_of_field(as_of), FRESH + return json_result({**head, **fields}) + + +# ---------- charts ---------- +CHART_NOTE = "The chart's data is in `charts`: draw it if you can, and keep your text to the figures. Don't describe the chart." + + +def charts_field(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> list[dict]: + """The charts as data (specs.to_json, schemas/chart.json), each line bucketed to the request's `chart_points` (default CHART_POINTS, + at most MAX_CHART_POINTS), times local to `tz`.""" + points = request_meta(meta)["chart_points"] + return [specs.to_json(chart, tz, max_points=points) for chart in charts] + + +def with_charts(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> dict: + """The fields an answer with charts ends with, {"chart_note": CHART_NOTE, "charts": charts_field(...)}; {} with no chart: + answer(..., **with_charts(charts, tz, meta)).""" + return {"chart_note": CHART_NOTE, "charts": charts_field(charts, tz, meta)} if charts else {} + + +def complete(reply: str) -> dict: + """The fields of an answer that is complete (3.7: `chart_answers_it` set and a chart made, with no error and no note that needs + the model's words): {"reply": the finished reply for the person, "complete": True}. A client may send `reply` with the chart and end + the turn; over MCP the server sends it as a text block for the user and marks the result `ecobot/complete`.""" + return {"reply": reply, "complete": True} + + +__all__ = ["BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", + "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_field", "complete", "iso", "period_field", "period_properties", + "read_period", "refuse", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/service/daylook.py b/lib/service/daylook.py new file mode 100644 index 00000000..b8374c02 --- /dev/null +++ b/lib/service/daylook.py @@ -0,0 +1,102 @@ +"""A day's look: one word and an emoji for that day's outdoor weather, worked out from its figures (docs/mcp-service.md 3.2, "Answers +ready to pass on"), so a model quotes `day_look: {word: "wet", emoji: "🌧️"}` beside a day and never guesses it. + +The rule takes the first that holds: + 1. stormy ⛈️ heavy rain and strong gusts together: rain >= STORMY_RAIN_MM and a gust >= STORMY_GUST_KMH (the station has no + lightning sensor, so a storm is told by what it does); + 2. wet 🌧️ rain >= WET_MM; + 3. showery 🌦️ rain >= RAINY_DAY_MM, the rainy day of the days tool and the bot's prompt (rain >= 1): every day counted as rainy + looks rainy, and a trace (under 1 mm, often dew or drizzle) doesn't; + 4. windy 💨 a gust >= WINDY_GUST_KMH; + 5. very hot 🥵 the high >= VERY_HOT_C; + 6. very cold 🥶 the high under VERY_COLD_HIGH_C, or a frost: the low at or below FROST_C; + 7. by how sunny it was: the day's mean solar radiation over a clear sky's for that date and latitude (clear_sky_mean): sunny ☀️ from + SUNNY, mostly sunny 🌤️ from MOSTLY_SUNNY, partly cloudy ⛅ from PARTLY_CLOUDY, else overcast ☁️. +A step whose figure is missing is passed over. With no solar radiation (or no latitude), step 7 gives nothing, so a day that none of +1 to 6 fits has no look: None, and the day goes without an emoji rather than with a guess. Fog 🌫️, which the prompt also lists, can't +be told from these figures, so it is never given. + +The thresholds are for a temperate climate such as Melbourne's: there, 35 °C is a day people count, a high under 10 °C one of the +coldest days of a winter, gusts of 50 km/h a day people call windy (the gust alert is at 40), and 10 mm in a day heavy rain. +""" + +import math +from collections.abc import Mapping +from datetime import date + +STORMY_RAIN_MM = 10.0 # heavy rain, with ... +STORMY_GUST_KMH = 60.0 # ... strong gusts: a storm +WET_MM = 5.0 # more than showers +RAINY_DAY_MM = 1.0 # a rainy day (daytable and the prompt: rain >= 1); below it a trace +WINDY_GUST_KMH = 50.0 +VERY_HOT_C = 35.0 # the high +VERY_COLD_HIGH_C = 10.0 # the high stays under it +FROST_C = 0.0 # or the low falls to it (on the ground it is colder still) +SUNNY = 0.80 # the day's solar radiation as a share of a clear sky's: the sensor and the model each err by up to about a +MOSTLY_SUNNY = 0.60 # tenth, so sunny starts below 1; an overcast day lets through a fifth to a third of a clear sky's +PARTLY_CLOUDY = 0.35 + +# The look of a day: its word and its emoji, from the prompt's WEATHER EMOJIS +LOOKS = {"stormy": "⛈️", "wet": "🌧️", "showery": "🌦️", "windy": "💨", "very hot": "🥵", "very cold": "🥶", + "sunny": "☀️", "mostly sunny": "🌤️", "partly cloudy": "⛅", "overcast": "☁️"} +FIGURES = ("rain", "wind_gust", "temp_max", "temp_min", "solar_avg") # what day_look reads: the days tool's names for them + +# The clear sky (Haurwitz, 1945): on a cloudless day the sun gives a level surface 1098 cos(z) e^(-0.057 / cos(z)) W/m², z the sun's +# angle from overhead, which depends on the latitude, the sun's declination that day (Cooper, 1969) and the hour. It needs nothing but +# the date and the latitude, and over a day comes within about a tenth of what a cloudless sky gives where the air is clean. +HAURWITZ_W, HAURWITZ_K = 1098.0, 0.057 +STEPS = 288 # the day's 24 hours in 5-minute steps of the sun's hour angle + + +def clear_sky_mean(day: date, latitude: float) -> float: + """The mean solar radiation of a cloudless `day` at this latitude (degrees, south negative) over its 24 hours, W/m²: what a day's + mean solar radiation (its `solar_avg`) is set against. 0 when the sun never rises.""" + declination = math.radians(23.45) * math.sin(2 * math.pi * (284 + day.timetuple().tm_yday) / 365) + lat = math.radians(latitude) + a, b = math.sin(lat) * math.sin(declination), math.cos(lat) * math.cos(declination) + total = 0.0 + for k in range(STEPS): + up = a + b * math.cos(math.pi * (2 * (k + 0.5) / STEPS - 1)) # the cosine of the sun's angle from overhead + if up > 0: + total += HAURWITZ_W * up * math.exp(-HAURWITZ_K / up) + return total / STEPS + + +def day_look(figures: Mapping, *, latitude: float | None, day: date, so_far: bool = False) -> dict | None: + """{"word": "wet", "emoji": "🌧️"} for a day from its figures, by the rule above, or None when none of it can be told. `figures` are + the day's, named as the days tool names them: rain (mm that fell), wind_gust (its highest, km/h), temp_max and temp_min (outdoor, + °C), solar_avg (its mean solar radiation over the whole day, W/m²); a missing one, or None, passes its steps over. `latitude`: the + station's. `so_far`: the day isn't over (today): its figures run to now, so its solar mean is no whole day's and the cloud step is + passed over.""" + rain, gust, high, low, solar = (_number(figures.get(name)) for name in FIGURES) + word = ("stormy" if rain is not None and gust is not None and rain >= STORMY_RAIN_MM and gust >= STORMY_GUST_KMH else + "wet" if rain is not None and rain >= WET_MM else + "showery" if rain is not None and rain >= RAINY_DAY_MM else + "windy" if gust is not None and gust >= WINDY_GUST_KMH else + "very hot" if high is not None and high >= VERY_HOT_C else + "very cold" if (high is not None and high < VERY_COLD_HIGH_C) or (low is not None and low <= FROST_C) else + None if so_far else _sky(solar, latitude, day)) + return {"word": word, "emoji": LOOKS[word]} if word else None + + +def _sky(solar: float | None, latitude: float | None, day: date) -> str | None: + """How sunny the day was, from its mean solar radiation against a clear sky's.""" + if solar is None or latitude is None or (clear := clear_sky_mean(day, latitude)) <= 0: + return None + share = solar / clear + return "sunny" if share >= SUNNY else "mostly sunny" if share >= MOSTLY_SUNNY else "partly cloudy" if share >= PARTLY_CLOUDY else \ + "overcast" + + +def _number(value) -> float | None: + """A figure as a number (one written as text, "12.3", too); None for none.""" + if value is None or isinstance(value, bool): + return None + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +__all__ = ["FIGURES", "LOOKS", "clear_sky_mean", "day_look"] diff --git a/lib/service/names.py b/lib/service/names.py new file mode 100644 index 00000000..6caa53d3 --- /dev/null +++ b/lib/service/names.py @@ -0,0 +1,318 @@ +"""The readings the service has, one name each, and the words people use for them (docs/mcp-service.md 3.2, "One naming scheme"). + +A reading's name is `sensor.reading`: the weather station's Ecowitt group and the reading's column (`outdoor.temperature`, +`indoor.humidity`, `pressure.relative`, `wind.wind_gust`), with rain as `rainfall.rain`, the mm that fell (the file keeps the running +daily total), and the air sensor's as `air.pm2_5` … `air.nox_index`, its own temperature and humidity `air.temperature` and +`air.humidity`. The catalogue holds the readings the file holds (lib/history.py's station_metrics and air_metrics, from the fields the +station has sent): `Catalogue.open(eco, air)`, or `CATALOGUE`, every reading the service knows, before any file is read (the evals). + +`resolve` reads the names a tool is sent, the full names or the words people use: + - a bare reading is the weather station's: `temperature` and `humidity` are outdoor and indoor, never the air sensor's (that is only + ever `air.temperature`, `air.humidity`, or the AirGradient named: "airgradient humidity"); `dew point`, `feels like` and `vpd` + are outdoor's; `outdoor humidity`, `indoor temp` name the side; + - `pressure` is relative pressure, `rain` the main gauge, `uv`, `solar`, `gust`, `rain rate`, the air sensor's `pm2.5`, `co2` …; + - `wind` is its speed shaded up to the gusts (the entry's `band`), and its direction, the compass rose on a chart; + - a sensor's name (`outdoor`, `indoor`, `wind`, `rainfall`, `air` …) is its usual set (SENSOR_SETS); `all` is every weather-station + reading, in the station's usual chart order (in_all); the devices' nicknames are their readings ("ecowitt": all; "ag": `air`). +A name or word it can't read raises UnknownReading, a Refusal that lists the names and the words with what each stands for. +""" + +import re +from collections.abc import Iterable +from dataclasses import dataclass + +from ..history import AIR_SENSOR, RAIN, Metric, air_metrics, station_fields, station_metrics +from ..series import AIR, AIR_EXTRA, INDOOR_READINGS, WEATHER +from ..storage.catalogue import label_of +from .common import Refusal + +STATION, AIR_DEVICE = "station", "air" # the two devices: the Ecowitt weather station, the AirGradient air sensor + +# ---------- "all" ---------- +# The settings "all" follows: the panels of "weather all week", top to bottom, as lib/series.py names the readings. intent.chart_fields +# reads them here too. ecobot.py sets the two flags from the config (CHART_ALL_FEELS_LIKE, CHART_ALL_VPD) at startup. +ALL_ORDER = ("temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "uv", "wind") +LEFT_OUT_OF_ALL = ("uv",) # the UV index has the same shape as solar radiation +FEELS_LIKE_IN_ALL = False # the feels-like panel: off, as it nearly repeats temperature +VPD_IN_ALL = False # the vapour pressure deficit panel: off, as it is temperature and humidity combined + + +def in_all() -> list[str]: + """The readings "all" is, as lib/series.py names them, in the station's usual chart order, with the settings applied.""" + return [n for n in ALL_ORDER if n not in LEFT_OUT_OF_ALL and (FEELS_LIKE_IN_ALL or n != "feels_like") and (VPD_IN_ALL or n != "vpd")] + + +# ---------- the words ---------- +# A reading named bare (lib/series.py's names): the weather station's. Temperature and humidity are both sides; the others outdoor's. +BARE = {"temperature": ("outdoor.temperature", "indoor.temperature"), "humidity": ("outdoor.humidity", "indoor.humidity"), + "pressure": ("pressure.relative",), "wind": ("wind.wind_speed", "wind.wind_direction"), "rain": ("rainfall.rain",), + "dew_point": ("outdoor.dew_point",), "feels_like": ("outdoor.feels_like",), "vpd": ("outdoor.vpd",), + "solar": ("solar_and_uvi.solar",), "uv": ("solar_and_uvi.uvi",)} +# A sensor named: its usual set, what the station's gauges show for it (lib/ecowitt/dashboard.py GAUGES), wind with its direction; the +# air sensor's six air-quality readings (its own temperature and humidity are named, never part of a set). +SENSOR_SETS = {"outdoor": ("outdoor.temperature", "outdoor.humidity", "outdoor.dew_point", "outdoor.feels_like"), + "indoor": ("indoor.temperature", "indoor.humidity"), + "pressure": ("pressure.relative",), + "wind": BARE["wind"], + "rainfall": ("rainfall.rain", "rainfall.rain_rate"), + "rainfall_piezo": ("rainfall_piezo.rain", "rainfall_piezo.rain_rate"), + "solar_and_uvi": ("solar_and_uvi.solar", "solar_and_uvi.uvi"), + AIR_SENSOR: tuple(f"air.{n}" for n in AIR)} +ALL = ("all",) # (stands for in_all(), read when resolved: the settings can change) +# The words people use, after _key (lower case, "_" and "-" as spaces) -> the names they stand for +ALIASES: dict[str, tuple[str, ...]] = { + **{_name.replace("_", " "): _names for _name, _names in SENSOR_SETS.items()}, + "outside": SENSOR_SETS["outdoor"], "outdoors": SENSOR_SETS["outdoor"], "inside": SENSOR_SETS["indoor"], "indoors": SENSOR_SETS["indoor"], + "piezo": ("rainfall_piezo.rain",), "piezo rain": ("rainfall_piezo.rain",), "piezo rain rate": ("rainfall_piezo.rain_rate",), + "air quality": SENSOR_SETS[AIR_SENSOR], "aq": SENSOR_SETS[AIR_SENSOR], + # the devices: the weather station is all its readings, the air sensor its usual set + "all": ALL, "everything": ALL, "every reading": ALL, "weather": ALL, "ecowitt": ALL, "weather station": ALL, "station": ALL, + "ag": SENSOR_SETS[AIR_SENSOR], "airgradient": SENSOR_SETS[AIR_SENSOR], "air gradient": SENSOR_SETS[AIR_SENSOR], + "air sensor": SENSOR_SETS[AIR_SENSOR], + # the weather station's readings, named bare + **{_w: BARE["temperature"] for _w in ("temperature", "temp", "temperatures")}, + "humidity": BARE["humidity"], + **{_w: BARE["pressure"] for _w in ("barometer", "barometric pressure", "relative pressure", "air pressure")}, + "absolute pressure": ("pressure.absolute",), "station pressure": ("pressure.absolute",), + "wind": BARE["wind"], "wind speed": ("wind.wind_speed",), "windspeed": ("wind.wind_speed",), + **{_w: ("wind.wind_gust",) for _w in ("gust", "gusts", "wind gust", "wind gusts")}, + "wind direction": ("wind.wind_direction",), "direction": ("wind.wind_direction",), + "rain": BARE["rain"], "precipitation": BARE["rain"], + "rain rate": ("rainfall.rain_rate",), "rainrate": ("rainfall.rain_rate",), "rain intensity": ("rainfall.rain_rate",), + "dew point": BARE["dew_point"], "dewpoint": BARE["dew_point"], + "feels like": BARE["feels_like"], "feelslike": BARE["feels_like"], + "apparent temperature": ("outdoor.app_temp",), "app temp": ("outdoor.app_temp",), + **{_w: BARE["vpd"] for _w in ("vpd", "vapour pressure deficit", "vapor pressure deficit")}, + **{_w: BARE["solar"] for _w in ("solar", "solar radiation", "radiation", "sunshine")}, + **{_w: BARE["uv"] for _w in ("uv", "uvi", "uv index", "ultraviolet")}, + # the air sensor's + **{_w: ("air.pm2_5",) for _w in ("pm2.5", "pm25", "pm 2.5", "pm2 5", "pm 25")}, + **{_w: ("air.pm10",) for _w in ("pm10", "pm 10")}, + **{_w: ("air.pm1",) for _w in ("pm1", "pm 1", "pm1.0", "pm 1.0")}, + **{_w: ("air.co2",) for _w in ("co2", "co₂", "co 2", "carbon dioxide")}, + **{_w: ("air.voc_index",) for _w in ("voc", "vocs", "tvoc", "voc index")}, + **{_w: ("air.nox_index",) for _w in ("nox", "nox index")}, +} +CLIMATE_WORDS = {"temperature": "temperature", "temp": "temperature", "humidity": "humidity", "dew point": "dew_point", + "dewpoint": "dew_point", "feels like": "feels_like", "apparent temperature": "app_temp", "app temp": "app_temp", + "vpd": "vpd", "vapour pressure deficit": "vpd", "vapor pressure deficit": "vpd"} # after "outdoor", "indoor" +AIR_OWN = {"temperature": "air.temperature", "temp": "air.temperature", "humidity": "air.humidity"} # after "air.", "airgradient" +SIDE = re.compile(r"(?Poutdoors?|outside|indoors?|inside)[. ](?P.+)") +DEVICE = re.compile(r"(?:air\.|(?:airgradient|air gradient|ag)[. ])(?P.+)") +LEGACY = {"air.air_temperature": "air.temperature", "air.air_humidity": "air.humidity", "air_temperature": "air.temperature", + "air_humidity": "air.humidity", "rainfall.daily": "rainfall.rain", "rainfall_piezo.daily": "rainfall_piezo.rain"} # today's names +AMBIGUOUS = {"air temperature": ("outdoor.temperature", "air.temperature"), "air temp": ("outdoor.temperature", "air.temperature"), + "air humidity": ("outdoor.humidity", "air.humidity")} # plain English for the weather, or the air sensor's own +# The words a description and a refusal list, one for each meaning, in this order +WORDS = ("temperature", "humidity", "dew point", "feels like", "vpd", "pressure", "wind", "gust", "wind direction", "rain", "rain rate", + "solar", "uv", "pm2.5", "pm10", "pm1", "co2", "voc", "nox", "outdoor", "indoor", "rainfall", "air", "all", "ecowitt", + "weather station", "ag", "airgradient", "air gradient") + + +def _key(word: str) -> str: + return " ".join(str(word).lower().replace("_", " ").replace("-", " ").split()) + + +# ---------- a reading ---------- +CLIMATE_LABELS = {"temperature": "temperature", "humidity": "humidity", "dew_point": "dew point", "feels_like": "feels like", + "app_temp": "apparent temperature", "vpd": "vapour pressure deficit"} +LABELS = {"pressure.relative": "Pressure", "pressure.absolute": "Absolute pressure", "wind.wind_speed": "Wind speed", + "wind.wind_gust": "Wind gust", "wind.wind_direction": "Wind direction", "rainfall.rain": "Rain", "rainfall.rain_rate": "Rain rate", + "rainfall_piezo.rain": "Piezo rain", "rainfall_piezo.rain_rate": "Piezo rain rate", "solar_and_uvi.solar": "Solar radiation", + "solar_and_uvi.uvi": "UV index"} +UNITS = {"wind_gust": "km/h"} # where the file names no unit and lib/history.py has none either +AIR_NAMES = {"air_temperature": "temperature", "air_humidity": "humidity"} # the air sensor's own: its column -> its reading's name +SERIES = {**{f"{r.group}.{RAIN if r.field == 'daily' else r.field}": name for name, r in WEATHER.items()}, + **{f"indoor.{WEATHER[name].field}": name for name in INDOOR_READINGS}} # a name -> lib/series.py's (station readings) + + +@dataclass(frozen=True) +class Reading: + """One reading of the catalogue.""" + name: str # "outdoor.temperature": `sensor.reading` + label: str # "Outdoor temperature", "Rain", "PM2.5", "AirGradient temperature" + unit: str # "°C", "mm", "µg/m³"; "" for an index (UV, VOC, NOx) + device: str # STATION or AIR_DEVICE + combine: str # how a stretch of readings is told as one: "mean" (over time), "max" (gusts: the highest), "last" (wind + # direction: the reading at its end), "rain" (the mm that fell, summed) + metric: Metric # how lib/history.py reads it (read_intervals, read_days): metric.kind, metric.column, metric.sensor + band: str | None = None # the reading its line is shaded up to, whose highest goes with it (wind speed: "wind.wind_gust") + series: str | None = None # its name in lib/series.py and lib/panels.py ("temperature" for both sides, "wind", "rain", "pm2_5") + + @property + def sensor(self) -> str: + """"outdoor", "rainfall", "air": the Ecowitt group, or the air sensor.""" + return self.name.split(".", 1)[0] + + @property + def reading(self) -> str: + return self.name.split(".", 1)[1] + + @property + def kind(self) -> str: + """The storage table it is in ("climate", "rain", "air" …).""" + return self.metric.kind + + @property + def column(self) -> str: + """The storage column read: rain's is "daily", the running daily total; the air sensor's own temperature "air_temperature".""" + return self.metric.column.name + + @property + def drawn(self) -> str: + """How a chart shows it: "bars" (rain), "rose" (wind direction, the compass rose beside the wind) or "line".""" + return "bars" if self.combine == RAIN else "rose" if self.reading == "wind_direction" else "line" + + +def _reading(m: Metric, held: set[str]) -> Reading: + if m.air: + reading = AIR_NAMES.get(m.reading, m.reading) + about = AIR.get(m.reading) or AIR_EXTRA[m.reading] + return Reading(f"air.{reading}", about.label, about.unit, AIR_DEVICE, m.how, m, series=m.reading) + name = m.name + label = f"{label_of(m.sensor)} {CLIMATE_LABELS[m.reading]}" if m.kind == "climate" else LABELS.get(name) or \ + f"{label_of(m.sensor)} {m.reading.replace('_', ' ')}" + band = "wind.wind_gust" if name == "wind.wind_speed" and "wind.wind_gust" in held else None + return Reading(name, label, m.unit or UNITS.get(m.reading, ""), STATION, m.how, m, band, SERIES.get(name)) + + +class UnknownReading(Refusal): + """A reading name or word the catalogue can't read: a Refusal listing the names it holds and the words with what each stands for.""" + + +# ---------- the catalogue ---------- +class Catalogue: + """The readings the service has, by name, in the order the file's groups and the air sensor's metrics come.""" + + def __init__(self, readings: Iterable[Reading]): + self.readings = {r.name: r for r in readings} + self._by_key = {_key(name): name for name in self.readings} + + @classmethod + def of(cls, sent: dict[str, dict[str, str]] | None = None, *, station: bool = True, air: bool = True) -> "Catalogue": + """The readings of the devices there are: the station's those its sensors have sent (`sent`: {group: {field: unit}}, as the + file's fields table has them; a group with nothing sent yet has every reading of its kind), and the air sensor's.""" + metrics = [*(station_metrics(sent) if station else []), *(air_metrics(extra=True) if air else [])] + held = {m.name for m in metrics} + return cls(_reading(m, held) for m in metrics) + + @classmethod + async def open(cls, eco=None, air=None) -> "Catalogue": + """The readings the file holds for these sources (Ecowitt, AirGradient; either may be None), as the readings tool reads them.""" + return cls.of(await station_fields(eco) if eco else None, station=eco is not None, air=air is not None) + + @property + def names(self) -> list[str]: + return list(self.readings) + + def get(self, name: str) -> Reading | None: + return self.readings.get(name) + + def __contains__(self, name: str) -> bool: + return name in self.readings + + def __iter__(self): + return iter(self.readings.values()) + + def resolve(self, names, *, default) -> list[Reading]: + """The readings these names stand for, in the order named, each once. `names`: a name or words, a list of them, or a string of + them separated by commas or "and"; none (None, "", []) is `default`, read the same way. Raises UnknownReading.""" + words = _split(names) or _split(default) + out: dict[str, Reading] = {} + for word in words: + for r in self._one(word): + out.setdefault(r.name, r) + return list(out.values()) + + def words(self) -> dict[str, list[str]]: + """{word: the names it stands for here}, one word for each meaning (WORDS), those standing for nothing held left out.""" + found = {word: self._lookup(word) for word in WORDS} + return {word: [r.name for r in readings] for word, readings in found.items() if not isinstance(readings, str)} + + def description(self) -> str: + """What a tool's readings property says: the full names, the words, and the rule for bare names.""" + air = any(r.device == AIR_DEVICE for r in self) + station = any(r.device == STATION for r in self) + parts = [f"Readings, as `sensor.reading`: {', '.join(self.names)}."] + if station: + parts.append("Or the words people use. A bare reading is the weather station's: temperature and humidity are outdoor and " + "indoor" + (" (the AirGradient's own are only ever air.temperature and air.humidity)" if air else "") + "; " + "dew point, feels like and vpd are outdoor's; pressure is relative pressure; rain is the main gauge, the mm " + "that fell; also rain rate, gust, uv, solar, wind (its speed shaded up to the gusts, with its direction: the " + "compass rose on a chart).") + if air: + parts.append("The air sensor's: pm2.5, pm10, pm1, co2, voc, nox.") + sets = [s for s in ("outdoor", "indoor", "wind", "rainfall", AIR_SENSOR) if any(r.sensor == s for r in self)] + parts.append(f"A sensor's name ({', '.join(sets)}) is its usual set" + + ("; all is every weather-station reading" if station else "") + ".") + devices = [*(["ecowitt and weather station mean the weather station"] if station else []), + *(["ag, airgradient and air gradient the AirGradient air sensor"] if air else [])] + if devices: + parts.append(f"The devices: {', '.join(devices)}.") + return " ".join(parts) + + # ---------- one name ---------- + def _one(self, word: str) -> list[Reading]: + """The readings one name or word stands for; UnknownReading, with the names and the words, when it stands for none held.""" + found = self._lookup(word) + if isinstance(found, str): + raise UnknownReading(found, names=self.names, words=self.words()) + return found + + def _lookup(self, word: str) -> list[Reading] | str: + """The readings a name or word stands for, or why there are none.""" + exact = " ".join(str(word).lower().split()) + if exact in self.readings: + return [self.readings[exact]] + key = _key(exact) + if key in self._by_key: + return [self.readings[self._by_key[key]]] + if key in AMBIGUOUS and exact not in LEGACY: # ("air_temperature", today's name, is the air sensor's) + station, own = AMBIGUOUS[key] + return f"{word!r} could be the weather station's ({station}) or the AirGradient's own ({own}): send the one meant." + targets = (LEGACY[exact],) if exact in LEGACY else ALIASES.get(key) or _prefixed(key) + if targets is None: + return (f"{word!r} isn't a reading this service knows. Send names from `names`, or words from `words` (each with the names " + f"it stands for).") + if targets == ALL: + targets = tuple(n for name in in_all() for n in BARE[name]) + return [self.readings[t] for t in targets if t in self.readings] or \ + f"{word!r} means {', '.join(targets)}, which this service doesn't hold." + + +def _prefixed(key: str) -> tuple[str, ...] | None: + """"outdoor humidity", "indoor.temp", "airgradient humidity", "air.temp", "ag pm2.5": a reading on the sensor named.""" + if m := SIDE.fullmatch(key): + column = CLIMATE_WORDS.get(m["rest"]) + return (f"{'outdoor' if m['side'].startswith('out') else 'indoor'}.{column}",) if column else None + if m := DEVICE.fullmatch(key): + if m["rest"] in AIR_OWN: + return (AIR_OWN[m["rest"]],) + found = ALIASES.get(m["rest"]) + return found if found and found != ALL and all(n.startswith("air.") for n in found) else None + return None + + +def _split(names) -> list[str]: + """Names as sent: a string (commas, semicolons, "+", "&" or "and" between them) or a list of such strings.""" + if names is None: + return [] + items = names if isinstance(names, (list, tuple)) else [names] + return [w for item in items for w in (part.strip() for part in re.split(r"[,;+&]| and ", str(item))) if w] + + +CATALOGUE = Catalogue.of() # every reading the service knows, before any file is read: for descriptions and the evals + + +def resolve(names, *, default, catalogue: Catalogue | None = None) -> list[Reading]: + """Catalogue.resolve on `catalogue` (default CATALOGUE).""" + return (catalogue or CATALOGUE).resolve(names, default=default) + + +def names_description(catalogue: Catalogue | None = None) -> str: + """Catalogue.description of `catalogue` (default CATALOGUE).""" + return (catalogue or CATALOGUE).description() + + +__all__ = ["ALIASES", "ALL_ORDER", "AIR_DEVICE", "BARE", "CATALOGUE", "Catalogue", "FEELS_LIKE_IN_ALL", "LEFT_OUT_OF_ALL", "Reading", + "SENSOR_SETS", "STATION", "UnknownReading", "VPD_IN_ALL", "WORDS", "in_all", "names_description", "resolve"] diff --git a/lib/tools.py b/lib/tools.py index 416cf56c..6df22636 100644 --- a/lib/tools.py +++ b/lib/tools.py @@ -42,6 +42,8 @@ class Turn: forecast_shown: list = field(default_factory=list) # the forecast days the answer includes, remembered once it is sent times: dict = field(default_factory=dict) # seconds spent by step ("data", "draw", "png"), for the reply's timing line in the log ahead: bool = False # a chart drawn ahead, nobody waiting: its requests wait their turn + meta: dict = field(default_factory=dict) # the request's metadata, all a service tool reads (lib/service/common.py: chart_points, + # fetch, priority); over MCP, the request's _meta @classmethod def of(cls, read, text: str, **more) -> "Turn": diff --git a/tests/test_intent.py b/tests/test_intent.py index b0732e87..49c2fb27 100644 --- a/tests/test_intent.py +++ b/tests/test_intent.py @@ -1,6 +1,7 @@ from datetime import datetime, timedelta from lib import intent +from lib.service import names as service_names from tests.fakes import EVERY_SOURCE NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday @@ -313,11 +314,11 @@ def test_dew_point_feels_like_and_vpd_are_charted_readings_that_outrank_temperat def test_weather_all_week_leaves_out_uv_feels_like_and_vpd_unless_configured(monkeypatch): every = ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "wind"] # solar third, wind last; no UV (same shape as solar), feels like or VPD assert intent.chart_fields("weather all week") == every - monkeypatch.setattr(intent, "FEELS_LIKE_IN_ALL", True) - monkeypatch.setattr(intent, "VPD_IN_ALL", True) + monkeypatch.setattr(service_names, "FEELS_LIKE_IN_ALL", True) + monkeypatch.setattr(service_names, "VPD_IN_ALL", True) assert intent.chart_fields("weather all week") == ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "wind"] - monkeypatch.setattr(intent, "FEELS_LIKE_IN_ALL", False) - monkeypatch.setattr(intent, "VPD_IN_ALL", False) + monkeypatch.setattr(service_names, "FEELS_LIKE_IN_ALL", False) + monkeypatch.setattr(service_names, "VPD_IN_ALL", False) assert intent.chart_fields("plot feels like and humidity") in (["humidity", "feels_like"], ["feels_like", "humidity"]) # named: still charted assert intent.chart_fields("plot solar and uv") == ["solar", "uv"] and intent.chart_fields("plot vpd and humidity") != [] assert intent.chart_field("feels 90d") == intent.chart_field("feel 90d") == intent.chart_field("feels-like 90d") == "feels_like" diff --git a/tests/test_service_base.py b/tests/test_service_base.py new file mode 100644 index 00000000..40bc5e46 --- /dev/null +++ b/tests/test_service_base.py @@ -0,0 +1,388 @@ +"""What the service's tools stand on (lib/service): the request's metadata, answers and refusals, periods read from words, the chart +budget, the reading names and the words for them, and a day's look.""" + +import json +from datetime import date, datetime + +import pytest + +from lib import intent +from lib.periods_text import PeriodError +from lib.prompt import PROMPT +from lib.service import common, daylook, names +from lib.service.common import (CHART_NOTE, FRESH, Refusal, ServiceTool, answer, charts_field, period_properties, read_period, refuse, + refuse_period, request_meta, with_charts) +from lib.service.daylook import LOOKS, clear_sky_mean, day_look +from lib.service.names import CATALOGUE, Catalogue, UnknownReading, resolve +from lib.specs import Chart, Line, Panel, from_json +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.tools import Tools, Turn +from tests.fakes import TZ + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm, as the plan's periods table is asked +MELBOURNE = -37.8 + + +def got(text: str) -> dict: + return json.loads(text) + + +def named(*words, default="temperature", catalogue: Catalogue | None = None) -> list[str]: + return [r.name for r in resolve(list(words), default=default, catalogue=catalogue)] + + +# ---------- the request's metadata ---------- +def test_the_metadata_a_handler_reads_has_its_defaults_and_is_checked(): + assert request_meta() == request_meta({}) == {"chart_points": 150, "fetch": True, "priority": "normal"} + assert request_meta({"chart_points": 500})["chart_points"] == 500 and request_meta({"chart_points": 10000})["chart_points"] == 500 + assert request_meta({"chart_points": 1})["chart_points"] == 2 and request_meta({"chart_points": "300"})["chart_points"] == 300 + assert request_meta({"chart_points": "lots"})["chart_points"] == request_meta({"chart_points": True})["chart_points"] == 150 + assert request_meta({"fetch": False})["fetch"] is False and request_meta({"fetch": "false"})["fetch"] is False + assert request_meta({"fetch": None})["fetch"] is True and request_meta({"fetch": True})["fetch"] is True + assert request_meta({"priority": "Background"})["priority"] == "background" and request_meta({"priority": "soon"})["priority"] == "normal" + assert request_meta({"progressToken": 7})["progressToken"] == 7 # what it doesn't read is passed on as it came + + +def test_a_turn_carries_its_own_metadata(): + a, b = Turn(), Turn() + a.meta["fetch"] = False + assert b.meta == {} + + +async def test_a_service_tool_is_sent_its_arguments_and_the_requests_metadata_and_nothing_else(): + seen = [] + + async def handler(args, meta): + seen.append((args, meta)) + return answer(period=None, as_of=None, ok=True) + tool = ServiceTool("probe", "A probe.", {"type": "object", "properties": {}}, handler, open_world=True) + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + tools = Tools([tool.tool()]) + assert got(await tools.call("probe", '{"x": 1}', Turn(text="plot it", chart_asked=True, meta={"chart_points": 500}))) == {"ok": True} + assert seen[-1] == ({"x": 1}, {"chart_points": 500, "fetch": True, "priority": "normal"}) # the Turn's words never reach it + await tools.call("probe", "{}", Turn(ahead=True)) # a chart drawn ahead is a background request + assert seen[-1][1]["priority"] == "background" + await tools.call("probe", "{}", Turn(ahead=True, meta={"priority": "normal"})) # (the request's own metadata wins) + assert seen[-1][1]["priority"] == "normal" + await tools.call("probe", "{}") + assert seen[-1] == ({}, {"chart_points": 150, "fetch": True, "priority": "normal"}) + assert tools.schemas[0]["function"]["parameters"] == {"type": "object", "properties": {}} # (no `source` argument: charts name theirs) + + +async def test_a_refusal_raised_in_a_handler_is_the_tools_answer_and_a_plain_function_will_do(): + def handler(args, meta): + if "reading" not in args: + raise Refusal("Which reading?", names=["outdoor.temperature"]) + return refuse("not yet") + tool = ServiceTool("probe", "A probe.", {"type": "object", "properties": {}}, handler) + assert got(await tool.call({})) == {"error": "Which reading?", "names": ["outdoor.temperature"]} + assert got(await tool.call({"reading": "x"})) == {"error": "not yet"} + assert "error" in got(await tool.call(["not", "an", "object"])) + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": False} + + +# ---------- answers and refusals ---------- +def test_an_answer_starts_with_its_period_and_the_time_of_its_figures(): + period = read_period({"period": "this week"}, tz=TZ, now=NOW, default="today") + out = got(answer(period=period, as_of=NOW, series={"outdoor.temperature": {}}, missing=[])) + assert list(out) == ["period", "as_of", "fresh", "series", "missing"] + assert out["period"] == {"asked": "this week", "text": "the last 7 days: Wed 4 – Tue 10 Nov 2026", + "start": "2026-11-04T00:00:00+11:00", "end": "2026-11-10T14:05:00+11:00"} + assert out["as_of"] == {"text": "Tue 10 Nov 2026 2:05pm", "time": "2026-11-10T14:05:00+11:00"} + assert out["fresh"] == FRESH and "as_of" in FRESH and "called again" in FRESH + cut = got(answer(period=read_period({"period": "this week"}, tz=TZ, now=NOW, default="on record", whole_days=True), as_of=NOW)) + assert cut["period"]["cut"] == "to Mon 9 Nov: today isn't over" and cut["period"]["end"] == "2026-11-10T00:00:00+11:00" + assert got(answer(period=None, as_of=None, verdict="likely")) == {"verdict": "likely"} # no period (outlook), no figures (about) + assert "°" in answer(period=None, as_of=None, unit="°C") and " " not in answer(period=None, as_of=None, a=1, b=2) # compact, unescaped + finished = got(answer(period=None, as_of=NOW, series={}, **common.complete("Pressure, the last 7 days: …"))) + assert list(finished)[-2:] == ["reply", "complete"] and finished["complete"] is True # a chart that is the whole answer (3.7) + assert common.iso(int(NOW.timestamp()), TZ) == common.iso(NOW) == "2026-11-10T14:05:00+11:00" + with pytest.raises(ValueError): + answer(period=None, as_of=NOW, fresh="mine") + with pytest.raises(ValueError): + answer(period=None, as_of=datetime(2026, 11, 10, 14, 5)) # a time without its zone can't be written + + +def test_a_refusal_is_its_error_and_what_teaches_the_right_call(): + assert got(refuse("too many rows", fits="1hour", max_rows=300)) == {"error": "too many rows", "fits": "1hour", "max_rows": 300} + assert list(got(refuse("x", a=1))) == ["error", "a"] + with pytest.raises(ValueError): + refuse("x", error="y") + plain = got(refuse_period(PeriodError("Not now."))) + assert plain == {"error": "Not now."} + + +# ---------- periods ---------- +def test_a_period_is_read_from_the_words_or_dates_or_else_the_default(): + assert read_period({}, tz=TZ, now=NOW, default="last 24 hours").text == "the last 24 hours: Mon 9 Nov 2:05pm – Tue 10 Nov 2026 2:05pm" + assert read_period({"period": " "}, tz=TZ, now=NOW, default="today").asked == "today" + assert read_period({"period": "in the last year"}, tz=TZ, now=NOW, default="today").text == \ + "the last 365 days: Tue 11 Nov 2025 – Tue 10 Nov 2026" + dated = read_period({"start": "2026-11-01", "end": "2026-11-02"}, tz=TZ, now=NOW, default="today") + assert dated.asked == "start/end" and (dated.start.day, dated.end.day) == (1, 3) + first = read_period({"period": "on record"}, tz=TZ, now=NOW, default="today", first_held=date(2024, 3, 1)) + assert first.start.date() == date(2024, 3, 1) + + +def test_words_that_are_no_form_are_refused_with_every_form_and_what_it_means_now(): + with pytest.raises(Refusal) as e: + read_period({"period": "the other week"}, tz=TZ, now=NOW, default="today") + out = got(e.value.text) + assert "'the other week' isn't a period" in out["error"] and out["error"].endswith("It is now Tue 10 Nov 2026 2:05pm.") + assert out["forms"]["today"] == "today: Tue 10 Nov 2026" + assert out["forms"]["this week, past week, the last week, week, 1w"] == "the last 7 days: Wed 4 – Tue 10 Nov 2026" + assert "since 6am, since Monday" in out["forms"] + with pytest.raises(Refusal) as e: + read_period({"period": "next week"}, tz=TZ, now=NOW, default="today") + assert "use forecast" in e.value.message and "forms" not in got(e.value.text) + with pytest.raises(Refusal) as e: + read_period({"period": "this week", "start": "2026-11-01"}, tz=TZ, now=NOW, default="today") + assert "not both" in e.value.message + + +def test_a_whole_day_tool_refuses_what_leaves_no_whole_day_and_points_elsewhere(): + for asked in ({"period": "today"}, {"period": "last 5 hours"}, {"period": "this morning"}, {"start": "2026-11-09 06:00"}): + with pytest.raises(Refusal) as e: + read_period(asked, tz=TZ, now=NOW, default="on record", whole_days=True, first_held=date(2024, 1, 1)) + assert "use summary or readings" in e.value.message, asked + with pytest.raises(Refusal) as e: + read_period({"period": "fortnightly"}, tz=TZ, now=NOW, default="on record", whole_days=True) + assert "today" not in got(e.value.text)["forms"] and "yesterday" in got(e.value.text)["forms"] # only the forms it takes + week = read_period({"period": "last 7 days"}, tz=TZ, now=NOW, default="on record", whole_days=True) + assert week.text == "the last 7 days: Tue 3 – Mon 9 Nov 2026" and week.cut == "to Mon 9 Nov: today isn't over" + + +def test_the_period_properties_tell_a_model_the_forms_the_dates_and_the_default(): + props = period_properties("last 24 hours") + assert list(props) == ["period", "start", "end"] and all(p["type"] == "string" for p in props.values()) + words = props["period"]["description"] + for form in ("today", "yesterday", "last N hours/days/weeks/months/years", "this week", "last week", "week to date", "this month", + "last month", "this year", "last year", "a month or a year", "5 Sep", "a weekday", "this morning", + "yesterday afternoon", "last night", "since 6am", "Christmas Day", "on record", "A to B"): + assert form in words, form + assert "own words" in words and "unchanged" in words and words.endswith("Default: last 24 hours.") + assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "never with it" in props["start"]["description"] + assert "Default: now." in props["end"]["description"] + whole = period_properties("on record", whole_days=True) + assert "yesterday" in whole["period"]["description"] and whole["period"]["description"].endswith("Default: on record.") + assert not any(form in whole["period"]["description"] for form in ("today,", "hours", "this morning", "since 6am")) + assert "HH:MM" not in whole["start"]["description"] and "Default: yesterday." in whole["end"]["description"] + + +# ---------- charts ---------- +def a_chart(points: int) -> Chart: + start = int(NOW.timestamp()) - points * 60 + x = [start + 60 * i for i in range(points)] + return Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", x, [15 + (i % 50) / 10 for i in range(points)])], + reading="temperature")]) + + +def test_a_chart_is_sent_as_data_within_the_requests_budget(): + chart = a_chart(1200) + lengths = lambda out: [len(s["points"]) for c in out for p in c["panels"] for s in p["series"]] + assert max(lengths(charts_field([chart], TZ))) <= 150 + assert 150 < max(lengths(charts_field([chart], TZ, {"chart_points": 500}))) <= 500 + assert max(lengths(charts_field([chart], TZ, {"chart_points": 5000}))) <= 500 # (at most today's budget) + assert lengths(charts_field([a_chart(40)], TZ)) == [40] # a short line as it is + sent = charts_field([chart], TZ)[0] + assert sent["panels"][0]["series"][0]["records"]["high"][1] == 19.9 # the true extremes stay + assert sent["panels"][0]["series"][0]["points"][0][0].endswith("+11:00") # local times with their offset + from_json(sent) # and it reads back as a chart + assert with_charts([], TZ) == {} + fields = with_charts([chart], TZ) + assert list(fields) == ["chart_note", "charts"] and fields["chart_note"] == CHART_NOTE and len(fields["charts"]) == 1 + assert "draw it" in CHART_NOTE and "describe" in CHART_NOTE + + +# ---------- reading names ---------- +def test_every_word_stands_for_the_readings_it_lists(): + for word, targets in names.ALIASES.items(): + expected = [n for n in (sum((names.BARE[r] for r in names.in_all()), ()) if targets == names.ALL else targets)] + assert named(word) == expected, word + + +def test_the_words_people_use(): + assert named("pressure") == named("barometer") == ["pressure.relative"] + assert named("uv") == named("UV index") == ["solar_and_uvi.uvi"] and named("solar") == ["solar_and_uvi.solar"] + assert named("rain") == ["rainfall.rain"] and named("rain rate") == named("rain_rate") == ["rainfall.rain_rate"] + assert named("gust") == named("gusts") == named("Wind Gusts") == ["wind.wind_gust"] + assert named("dew point") == named("dew_point") == named("dewpoint") == ["outdoor.dew_point"] + assert named("feels like") == named("feels-like") == ["outdoor.feels_like"] and named("vpd") == ["outdoor.vpd"] + for word in ("pm2.5", "pm25", "PM 2.5", "pm2_5", "air.pm2.5", "ag pm2.5"): + assert named(word) == ["air.pm2_5"], word + assert named("pm10") == ["air.pm10"] and named("pm1") == ["air.pm1"] and named("PM1.0") == ["air.pm1"] + assert named("co2") == named("CO₂") == ["air.co2"] and named("voc") == ["air.voc_index"] and named("nox") == ["air.nox_index"] + assert named("outdoor humidity") == named("outside humidity") == named("outdoor.humidity") == ["outdoor.humidity"] + assert named("indoor temp") == named("inside temperature") == ["indoor.temperature"] + assert named("rainfall.daily") == ["rainfall.rain"] and named("air_humidity") == ["air.humidity"] # today's names + + +def test_wind_is_its_speed_shaded_up_to_the_gusts_with_its_direction(): + speed, direction = resolve("wind", default="all") + assert (speed.name, speed.band, speed.drawn) == ("wind.wind_speed", "wind.wind_gust", "line") + assert (direction.name, direction.drawn, direction.combine) == ("wind.wind_direction", "rose", "last") + assert CATALOGUE.get("wind.wind_gust").combine == "max" and CATALOGUE.get("wind.wind_gust").unit == "km/h" + assert Catalogue.of({"wind": {"wind_speed": "km/h"}}, air=False).get("wind.wind_speed").band is None # no gusts held: no band + + +def test_a_bare_temperature_or_humidity_is_the_stations_outdoor_and_indoor_never_the_air_sensors(): + assert named("temperature") == named("temp") == ["outdoor.temperature", "indoor.temperature"] + assert named("humidity") == ["outdoor.humidity", "indoor.humidity"] + assert named("air.temperature") == named("airgradient temperature") == named("ag temp") == named("air.temp") == ["air.temperature"] + assert named("air gradient humidity") == ["air.humidity"] + with pytest.raises(UnknownReading) as e: + resolve("air temperature", default="all") + assert "outdoor.temperature" in e.value.message and "air.temperature" in e.value.message + + +def test_a_sensors_name_is_its_usual_set(): + assert named("outdoor") == ["outdoor.temperature", "outdoor.humidity", "outdoor.dew_point", "outdoor.feels_like"] + assert named("indoor") == named("inside") == ["indoor.temperature", "indoor.humidity"] + assert named("wind") == ["wind.wind_speed", "wind.wind_direction"] + assert named("rainfall") == ["rainfall.rain", "rainfall.rain_rate"] + six = ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"] + assert named("air") == named("air quality") == six + assert named("ag") == named("airgradient") == named("air gradient") == six # the devices' nicknames + assert named("ecowitt") == named("weather station") == named("all") + + +def test_all_is_every_station_reading_in_the_usual_chart_order_with_the_settings(monkeypatch): + usual = ["outdoor.temperature", "indoor.temperature", "outdoor.humidity", "indoor.humidity", "solar_and_uvi.solar", "pressure.relative", + "rainfall.rain", "outdoor.dew_point", "wind.wind_speed", "wind.wind_direction"] + assert named("all") == usual and not any(n.startswith("air.") for n in named("all")) + monkeypatch.setattr(names, "FEELS_LIKE_IN_ALL", True) + monkeypatch.setattr(names, "VPD_IN_ALL", True) + assert named("all") == [*usual[:8], "outdoor.feels_like", "outdoor.vpd", *usual[8:]] + assert intent.chart_fields("weather all week") == ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", + "vpd", "wind"] # the bot's "weather all week" reads the same settings + held = Catalogue.of({"outdoor": {"temperature": "℃"}, "indoor": {"temperature": "℃"}, "pressure": {"relative": "hPa"}, + "wind": {"wind_speed": "km/h"}, "rainfall": {"daily": "mm"}, "rainfall_piezo": {"daily": "mm"}, + "solar_and_uvi": {"uvi": ""}}, air=False) + assert named("weather station", catalogue=held) == ["outdoor.temperature", "indoor.temperature", "pressure.relative", "rainfall.rain", + "wind.wind_speed"] # what is held of it + + +def test_names_come_in_the_order_asked_each_once_and_none_is_the_default(): + assert named("rain, temperature and pressure") == ["rainfall.rain", "outdoor.temperature", "indoor.temperature", "pressure.relative"] + assert named("outdoor.temperature", "temperature") == ["outdoor.temperature", "indoor.temperature"] + assert named(default="outdoor") == [r.name for r in resolve(None, default="outdoor")] == named("outdoor") + assert named() == named("temperature") + assert [r.name for r in resolve("", default=["temperature", "humidity"])] == named("temperature", "humidity") + + +def test_an_unknown_name_is_refused_with_the_names_and_the_words(): + with pytest.raises(UnknownReading) as e: + resolve(["temperature", "sunniness"], default="all") + out = got(e.value.text) + assert "'sunniness' isn't a reading" in out["error"] + assert out["names"] == CATALOGUE.names and "air.temperature" in out["names"] + assert out["words"]["temperature"] == ["outdoor.temperature", "indoor.temperature"] and out["words"]["pm2.5"] == ["air.pm2_5"] + assert isinstance(e.value, Refusal) # (so a tool answers with it) + + +def test_the_catalogue_is_what_the_file_holds(): + station = Catalogue.of({"outdoor": {"temperature": "℃", "humidity": "%"}, "rainfall": {"daily": "mm"}}, air=False) + assert station.names[:3] == ["outdoor.temperature", "outdoor.humidity", "indoor.temperature"] # (indoor sent nothing: all its kind) + assert "outdoor.dew_point" not in station and "air.pm2_5" not in station + assert [r.name for r in station.resolve("rainfall", default="all")] == ["rainfall.rain"] # (no rain rate held) + with pytest.raises(UnknownReading) as e: + station.resolve("pm2.5", default="all") + assert "doesn't hold" in e.value.message + air = Catalogue.of(station=False) + assert all(r.device == "air" for r in air) + with pytest.raises(UnknownReading): + air.resolve("humidity", default="all") # a bare humidity is never the air sensor's + assert "pm2.5" not in names.names_description(station) and "ecowitt" not in names.names_description(air) + + +async def test_the_catalogue_reads_the_stations_fields_from_the_file(tmp_path): + from types import SimpleNamespace + storage = Storage(tmp_path / "ecobot.sqlite", TZ) + try: + def write(w): + sensor = w.ecowitt_sensor("M", "outdoor") + w.fields(sensor, "5min", {"temperature": "℃", "humidity": "%"}) + w.put(sensor, "5min", [{"ts": int(NOW.timestamp()) // 300 * 300, "temperature": 15.0, "humidity": 50.0}], CLOUD) + storage.writer.run(write, ()) + found = await Catalogue.open(SimpleNamespace(storage=storage, mac="M"), None) + assert [n for n in found.names if n.startswith("outdoor.")] == ["outdoor.temperature", "outdoor.humidity"] + assert not any(n.startswith("air.") for n in found.names) + finally: + storage.close() + + +def test_each_reading_says_what_it_is_and_how_it_is_read(): + t = CATALOGUE.get("outdoor.temperature") + assert (t.label, t.unit, t.device, t.kind, t.column, t.combine, t.series, t.sensor, t.reading) == \ + ("Outdoor temperature", "°C", "station", "climate", "temperature", "mean", "temperature", "outdoor", "temperature") + rain = CATALOGUE.get("rainfall.rain") + assert (rain.label, rain.unit, rain.kind, rain.column, rain.combine, rain.drawn, rain.series) == \ + ("Rain", "mm", "rain", "daily", "rain", "bars", "rain") + own = CATALOGUE.get("air.temperature") + assert (own.label, own.unit, own.device, own.column, own.series) == ("AirGradient temperature", "°C", "air", "air_temperature", + "air_temperature") + assert CATALOGUE.get("air.voc_index").unit == "" and CATALOGUE.get("solar_and_uvi.uvi").label == "UV index" + assert CATALOGUE.get("pressure.relative").metric.name == "pressure.relative" # (what lib/history.py reads it with) + assert set(names.BARE) == set(names.ALL_ORDER) and set(names.SENSOR_SETS) <= {*(r.sensor for r in CATALOGUE)} + + +def test_the_names_description_lists_the_names_the_words_and_the_rule_for_bare_names(): + text = names.names_description() + assert all(name in text for name in CATALOGUE.names) + for words in ("temperature and humidity are outdoor and indoor", "only ever air.temperature and air.humidity", "pressure is relative", + "rain is the main gauge", "pm2.5", "co2", "wind (its speed shaded up to the gusts", "usual set", "all is every", + "ecowitt", "weather station", "airgradient", "air gradient"): + assert words in text, words + + +# ---------- a day's look ---------- +SUMMER = date(2026, 12, 21) + + +def look(day=SUMMER, latitude=MELBOURNE, **figures) -> str | None: + found = day_look({"rain": 0.0, "wind_gust": 20.0, "temp_max": 24.0, "temp_min": 12.0} | figures, latitude=latitude, day=day) + return found and f"{found['word']} {found['emoji']}" + + +def test_a_days_look_takes_the_first_of_its_rules_that_holds(): + clear = clear_sky_mean(SUMMER, MELBOURNE) + assert look(rain=12.0, wind_gust=65.0, solar_avg=clear) == "stormy ⛈️" + assert look(rain=12.0, wind_gust=40.0) == look(rain=5.0) == "wet 🌧️" # heavy rain with no strong gust is wet + assert look(rain=1.0, solar_avg=clear) == look(rain=4.9, wind_gust=70.0) == "showery 🌦️" + assert look(rain=0.9, wind_gust=50.0) == "windy 💨" # a trace is no rainy day + assert look(temp_max=35.0, solar_avg=clear) == "very hot 🥵" + assert look(day=date(2026, 6, 21), temp_max=9.5) == look(temp_min=0.0, solar_avg=clear) == "very cold 🥶" + assert look(solar_avg=0.9 * clear) == "sunny ☀️" and look(solar_avg=0.7 * clear) == "mostly sunny 🌤️" + assert look(solar_avg=0.4 * clear) == "partly cloudy ⛅" and look(solar_avg=0.2 * clear) == "overcast ☁️" + winter = clear_sky_mean(date(2026, 6, 21), MELBOURNE) + assert look(day=date(2026, 6, 21), temp_max=14.0, temp_min=4.0, solar_avg=0.9 * winter) == "sunny ☀️" # set against its own date's sky + + +def test_a_day_with_no_solar_radiation_has_no_cloud_step(): + assert look() is None and look(latitude=None, solar_avg=300.0) is None + assert look(rain=6.0) == "wet 🌧️" # (the other steps still hold) + assert day_look({}, latitude=MELBOURNE, day=SUMMER) is None + assert day_look({"rain": None, "solar_avg": "350.0"}, latitude=MELBOURNE, day=SUMMER) == {"word": "sunny", "emoji": "☀️"} + today = {"rain": 0.0, "temp_max": 24.0, "solar_avg": 350.0} + assert day_look(today, latitude=MELBOURNE, day=SUMMER, so_far=True) is None # a day not over: its solar mean is no whole day's + assert day_look(today | {"temp_max": 36.0}, latitude=MELBOURNE, day=SUMMER, so_far=True)["word"] == "very hot" + + +def test_a_days_look_uses_only_the_prompts_weather_emojis(): + allowed = next(line for line in PROMPT.splitlines() if "Use only these" in line) + assert all(emoji in allowed for emoji in LOOKS.values()) + assert daylook.FIGURES == ("rain", "wind_gust", "temp_max", "temp_min", "solar_avg") # the days tool's names + + +def test_a_clear_sky_follows_the_season_and_the_latitude(): + summer, winter = clear_sky_mean(SUMMER, MELBOURNE), clear_sky_mean(date(2026, 6, 21), MELBOURNE) + assert 29 < summer * 86400 / 1e6 < 34 and 8 < winter * 86400 / 1e6 < 12 # MJ/m² a day: Melbourne's clear days, about 32 and 10 + assert clear_sky_mean(date(2026, 6, 21), -80.0) == 0.0 # the polar night + assert clear_sky_mean(date(2026, 6, 21), 37.8) == pytest.approx(summer, rel=0.02) # the other hemisphere's summer + assert day_look({"solar_avg": 10.0}, latitude=-80.0, day=date(2026, 6, 21)) is None + + +def test_the_service_modules_say_what_they_offer(): + for module in (common, names, daylook): + assert all(hasattr(module, name) for name in module.__all__), module.__name__ From 5963f73a68e0d29afbbe16405bfc96b55858102b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:04:37 +0000 Subject: [PATCH 026/125] lib/service/context.py: what each of the ten tools is built over The sources that started, the file, the catalogue, the station's zone and the clock, so each tool module exposes tools(ctx) and the ten are built the same way. Nothing uses it yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/service/context.py | 48 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 lib/service/context.py diff --git a/lib/service/context.py b/lib/service/context.py new file mode 100644 index 00000000..6b80297b --- /dev/null +++ b/lib/service/context.py @@ -0,0 +1,48 @@ +"""What the service's tools are built over: the sources that started, the file, the catalogue of readings, the station's zone and the +clock. Each tool module has `tools(ctx) -> list[ServiceTool]`, so the ten are built the same way, here today and behind MCP later.""" + +import time +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import datetime, tzinfo + +from ..timeutil import to_local +from .names import Catalogue + + +@dataclass +class Context: + eco: object | None = None # the weather station (lib.ecowitt.Ecowitt), started; None when it isn't configured + air: object | None = None # the air sensor (lib.airgradient.AirGradient), started; None when it isn't configured + composer: object | None = None # the charts and comparisons across the two (lib.compose.Composer), when both are there + forecast: object | None = None # lib.forecast.Forecast, when switched on + pollen: object | None = None # lib.pollen.Pollen, when switched on + catalogue: Catalogue | None = None # the readings the file holds (names.Catalogue.open); None: every reading the service knows + tz: tzinfo | None = None # the station's zone (the station's own, once it has named it) + clock: Callable[[], float] = field(default=time.time) # the time now, as an epoch (a test's own) + + @property + def storage(self): + """The readings file the sources share.""" + return self.eco.storage if self.eco else self.air.store.storage if self.air else None + + @property + def zone(self) -> tzinfo: + return self.tz or (self.eco.tz if self.eco else self.air.tz) + + def now(self) -> datetime: + """The time now, aware, in the station's zone.""" + return to_local(int(self.clock()), self.zone) + + def readings(self) -> Catalogue: + from .names import CATALOGUE + return self.catalogue or CATALOGUE + + @classmethod + async def open(cls, *, eco=None, air=None, composer=None, forecast=None, pollen=None, **more) -> "Context": + """The context with the catalogue read from the file.""" + return cls(eco=eco, air=air, composer=composer, forecast=forecast, pollen=pollen, + catalogue=await Catalogue.open(eco, air), **more) + + +__all__ = ["Context"] From 05d2c3d2b504220becc7684a59097d09101ec483 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:25:44 +0000 Subject: [PATCH 027/125] lib/service/days.py: the days tool, over both sensors and part of each day `days` (docs/mcp-service.md 3.3), in place of weather_days and air_days, on their engines: one field list (the station's and the air sensor's day fields), routed by the sensor of the fields named, the merged rule for a question mixing the two (days_checked counts the days both have; days whose station figures are Ecowitt's daily records are left out and counted), `hours` over lib/partday's stretches (today once its stretch is over; at most 400 days), `only` as the model sends it. The result in 3.2's shape: each listed day with its day_look, the bot's days-lookup line as `answer` (same words), the notes of both tools, the bars with drawn_by (per month: 3m, 1y, on record; per year: none) and the finished reply when chart_answers_it is set and no note needs the model's words. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/service/days.py | 593 +++++++++++++++++++++++++++++++++++++ tests/test_service_days.py | 415 ++++++++++++++++++++++++++ 2 files changed, 1008 insertions(+) create mode 100644 lib/service/days.py create mode 100644 tests/test_service_days.py diff --git a/lib/service/days.py b/lib/service/days.py new file mode 100644 index 00000000..fdaa280c --- /dev/null +++ b/lib/service/days.py @@ -0,0 +1,593 @@ +"""The `days` tool (docs/mcp-service.md 3.3): days found, ranked, counted or totalled by their figures, over the weather station's and +the air sensor's day figures, or over part of each day (`hours`). It replaces weather_days and air_days, on their engines: + + - the fields are theirs: the station's (lib/ecowitt/days.py FIELDS: temp_max, rain, humidity_avg, indoor_temp_min ...) and the air + sensor's (lib/airgradient/days.py: pm2_5_max, co2_avg ...), in one list; + - a whole day's figures are its day rows, read as those tools read them (ecowitt.days.day_values_on, AirReadings.day_figures); part of + each day's are lib/partday.stretch_figures, mapped to the same fields (temp_max is the stretch's highest, temp_avg its mean, rain the + mm that fell in it); + - finding, ranking, counting, grouping and the bars are lib/daytable.py's (prepare, analyse), and the notes are the two tools' own. + +Which sensor: the fields named (`where`, `sort_by`, `of`) say. Station fields read as weather_days did; air fields as air_days did; both +(a question mixing the two) by the merged rule of 3.3: the fields shown and the default sort come from the sensors named, `days_checked` +counts the days every named sensor has, and the days whose station figures come only from Ecowitt's daily records (10am to 10am, not +the air sensor's midnight to midnight) are left out and counted. + +The result is today's day-tool result in 3.2's shape (period, as_of, then its fields), each listed day with its `day_look`, and `answer`: +the line the bot writes today for a days lookup (lib/report.py `_days`, ported here with the same words), which is also the finished +reply when `chart_answers_it` is set and a chart drawn (unless a note needs the model's words). `group_by` draws the bar chart, which +carries the call that drew it (`drawn_by`, 3.7). + +It reads the file alone and never fetches, so the request's `fetch` and `priority` change nothing (and `chart_points` leaves bars as +they are: a bar per month or year is never bucketed). +""" + +import operator +import re +from collections.abc import Callable +from dataclasses import dataclass, field +from datetime import date, datetime, time, timedelta + +from ..airgradient.days import ALWAYS_SHOWN as AIR_SHOWN, FIELDS as AIR_UNITS +from ..daytable import MAX_LIMIT, OPS, STATS, analyse, lists_days, prepare +from ..ecowitt.api import daily_run, unit_text +from ..ecowitt.calendar import PublicHolidays +from ..ecowitt.days import ALWAYS_SHOWN as STATION_SHOWN, AVERAGED, COARSER, FIELDS as STATION_FIELDS, PARTS, day_values_on +from ..partday import ALLOWED, CLOCK_CHANGE, NOT_HELD, NOT_OVER, PartDays, Stretch, over, parse_stretch, stretch_figures +from ..specs import AIR_SOURCE, CHART_SOURCE, ECOWITT_SOURCE +from ..storage.catalogue import column_of +from ..storage.read import Reader +from ..timeutil import day_text +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, complete, period_properties, read_period, with_charts +from .context import Context +from .daylook import FIGURES as LOOK_FIGURES, day_look +from .names import AIR_DEVICE, STATION + +NAME = "days" +DEFAULT, DEFAULT_HOURS = "on record", "last 30 days" # the period read when none is sent: every day held; with hours, a month +MAX_HOURS_DAYS = 400 # the most days `hours` reads (3.3: a stretch costs far more than a day row) +STATION_UNITS = {name: f[3] for name, f in STATION_FIELDS.items()} +DEVICE_OF = {**dict.fromkeys(STATION_UNITS, STATION), **dict.fromkeys(AIR_UNITS, AIR_DEVICE)} +SHOWN = {STATION: STATION_SHOWN, AIR_DEVICE: AIR_SHOWN} # what every listed day shows, by the sensor named +DEVICES = (STATION, AIR_DEVICE) +ONLY = {"public_holiday": "public holidays only", "weekend": "weekends only"} # (the chart's subtitle says which) +ORDERS = ("desc", "asc") +OP_WORDS = {"==": "=", "≥": ">=", "≤": "<=", "=>": ">=", "=<": "<="} # ops written another way +ARGUMENTS = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "hours", "period", "start", "end", + "chart_answers_it") +OLD_NAMES = {"start_date": "start", "end_date": "end"} # weather_days' and air_days' names +CAPTIONED_NOTES = {"note_averaged"} # the notes the answer line passes on itself (" Older days use averages ..."): any other needs words +AIR_PART = {"max": "hi", "min": "lo", "avg": "mean"} # an air field's suffix -> where a day row keeps it +SOURCES = {STATION: ECOWITT_SOURCE, AIR_DEVICE: AIR_SOURCE} +# drawn_by.periods (3.7): a count or total per month over 3 months, a year and the whole record; per year, no other period +MONTH_PERIODS = (("3m", "3M"), ("1y", "1Y"), ("on record", "All")) +HOURS_HOW = ("Each day's figures are over this stretch of it, not the whole day: _max its highest, _min its lowest, _avg its mean, rain " + "the mm that fell in it. A stretch across midnight belongs to the day it ends on. day_look is still the whole day's look.") + +# the notes, worded as weather_days and air_days word them (lib/ecowitt/days.py, lib/airgradient/days.py) +NOTE_TRACE = ("These days rank higher but had less than {value:g} mm of rain (a trace), so they are not in \"days\". Mention the first " + "as a short footnote.") +NOTE_DAILY = ("Days marked \"daily\" come from daily readings that run {run}, so their rain and dates are approximate (a morning shower " + "can be counted on the day before). Say so briefly if any listed day is marked daily, or if the period reaches back before " + "exact_from.") +NOTE_AVERAGED = ("For these readings, days from 30-minute or daily data use each interval's average, so a day's true peak (or low) may " + "be a little beyond what is listed: a count of days at or past a limit can fall slightly short near the limit. Say so " + "briefly.") +NOTE_HOURLY = ("{n} of these days only exist as hourly averages, so their highs and lows are hourly averages and a short spike is " + "smoothed. Say so briefly if it matters.") +NOTE_MISSING = "{n} day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted." +NOTE_NOTHING = "No readings are held for this period yet (its history may still be downloading)." +NOTE_BEFORE = "No readings are held for this period: the record of what was asked about starts {first}." +NOTE_DAILY_LEFT_OUT = ("{n} day(s) are left out: their weather-station figures come only from Ecowitt's daily records, which run {run}, " + "not midnight to midnight as the air sensor's days do, so the two can't be set against each other. Say so " + "briefly.") +NOTE_LEFT_OUT = ("Some days aren't counted, as `left_out` says: \"not held finely enough\" (only Ecowitt's daily or 4-hour records, or " + "nothing, cover that stretch), \"no readings\" (the sensor was off), \"removed by the clock change\". Say so briefly " + "if it matters.") +LEFT_OUT = {NOT_HELD: "not held finely enough", CLOCK_CHANGE: CLOCK_CHANGE, NOT_OVER: NOT_OVER} + +# ---------- the description and the input schema ---------- +DESCRIPTION = ( + "Days found, ranked, counted or totalled by their figures, from the weather station's and the air sensor's (AirGradient's) days, " + "midnight to midnight. The wettest day: {sort_by: \"rain\"}. The hottest day it also rained: {where: [{field: \"rain\", op: \">=\", " + "value: 1}], sort_by: \"temp_max\"}. How many days over 35°C this year: {where: [{field: \"temp_max\", op: \">\", value: 35}], " + "period: \"this year\", count_only: true}. Rain per month: {stat: \"sum\", of: \"rain\", group_by: \"month\", period: \"past " + "year\"}. Days PM2.5 passed 25: {where: [{field: \"pm2_5_max\", op: \">\", value: 25}]}. The windiest weekend day: {sort_by: " + "\"wind_gust\", only: \"weekend\"}. One day's figures: {period: \"5 Sep\"}. Part of each day, with hours: nights below 5°C " + "{hours: \"night\", where: [{field: \"temp_min\", op: \"<\", value: 5}]}; the average 3pm temperature in October {hours: " + "\"15:00\", stat: \"avg\", of: \"temp_avg\", period: \"October\"}. No period: every day on record (with hours, the last 30 " + "days). Not for: a period's highest or lowest reading with when it happened, or a chart over time (summary); values at set " + "times (readings); rain against a reading (relate). Result: answer, a line ready to pass on; matching_days of days_checked; " + "days, the top ones, each with its day_look (the day's weather word and emoji: put it before the day); by_month or by_year, a " + "figure each, drawn as bars (charts); note_*: mention briefly. A rainy day is rain >= 1; above 0 is only a trace.") + +STATION_WHERE = ("Weather station: temp_max, temp_min, temp_avg (outdoor °C), rain (mm that fell), wind_gust (km/h, the highest); a " + "day's highest (_max), lowest (_min) and mean (_avg) of humidity, pressure, dew_point, feels_like, vpd, indoor_temp, " + "indoor_humidity; the _max and _avg of wind_speed, solar, uv, rain_rate.") +AIR_WHERE = "Air sensor: the _max, _min and _avg of pm2_5, pm10, pm1 (µg/m³), co2 (ppm), voc_index and nox_index." +HOURS = {"type": "string", "description": "Part of each day instead of the whole day: night (22:00-06:00, which belongs to the day it " + "ends on), morning (06:00-12:00), afternoon (12:00-18:00), evening (18:00-24:00), daytime " + "(06:00-18:00), two times on the half hour ('15:00-16:00', '22:30-06:00'), or a moment ('15:00'). " + "Each day's figures are then over that stretch: temp_max its highest, temp_min its lowest, " + "_avg its mean, rain the mm that fell in it. Today counts once its stretch is over. At most " + f"{MAX_HOURS_DAYS} days."} +CHART_ANSWERS_IT = {"type": "boolean", "description": "true only when the question is just to see this chart (a figure per month or " + "year) and its figures: nothing else to answer (\"rain per month this year\", " + "not \"rain per month: is it drier than last year?\"). The result then carries " + "the finished reply (`reply`, `complete`)."} + + +def parameters(fields: list[str]) -> dict: + """The input schema over these fields (those of the sensors there are).""" + devices = {DEVICE_OF[n] for n in fields} + where = " ".join([*([STATION_WHERE] if STATION in devices else []), *([AIR_WHERE] if AIR_DEVICE in devices else [])]) + default_sort = "temp_max" if STATION in devices else "pm2_5_max" + one = {"type": "string", "enum": fields} + return { + "type": "object", + "properties": { + "where": {"type": "array", "description": "Conditions that must ALL hold on the same day, e.g. rain >= 1 and temp_max > 30. " + f"Fields. {where}", + "items": {"type": "object", "properties": {"field": one, "op": {"type": "string", "enum": list(OPS)}, + "value": {"type": "number"}}, + "required": ["field", "op", "value"]}}, + "sort_by": {**one, "description": "Rank the days by this field. Default: the first condition's field, else `of`, else " + f"{default_sort}" + (" (pm2_5_max when only air fields are named)." + if len(devices) > 1 else ".")}, + "order": {"type": "string", "enum": list(ORDERS), "description": "desc: highest first (default); asc: lowest first."}, + "count_only": {"type": "boolean", "description": "true for \"how many days\": the counts alone, no days listed."}, + "group_by": {"type": "string", "enum": ["month", "year"], + "description": "A figure per month or year (those with none included), drawn as a bar chart: \"rain per " + "month\", \"days over 35°C per year\"."}, + "stat": {"type": "string", "enum": list(STATS), + "description": "What the period, or each month or year, gives: count (default: the matching days), or the max, min, " + "avg or sum of `of` over the matching days (\"rain per month\": sum of rain; \"the hottest day each " + "year\": max of temp_max; \"average humidity per year\": avg of humidity_avg)."}, + "of": {**one, "description": "The field stat takes the max, min, avg or sum of (not needed for count)."}, + "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always " + "counted."}, + "only": {"type": "string", "enum": list(ONLY), + "description": "Only the public holidays (the station's state's calendar) or only Saturdays and Sundays: days are " + "then found and counted among those alone."}, + "hours": HOURS, + **period_properties(f"{DEFAULT} (every day held); with hours, the {DEFAULT_HOURS}", whole_days=True), + "chart_answers_it": CHART_ANSWERS_IT, + }, + } + + +# ---------- the call, checked ---------- +@dataclass(frozen=True) +class Call: + """A call's arguments as the tool reads them, checked, with every default filled in.""" + where: list[dict] + sort_by: str | None + order: str + count_only: bool + group_by: str | None + stat: str + of: str | None + limit: int + only: str | None + stretch: Stretch | None + chart_answers_it: bool + + @property + def named(self) -> list[str]: + """The fields the call names, in order.""" + return list(dict.fromkeys([*(c["field"] for c in self.where), *filter(None, (self.sort_by, self.of))])) + + def engine(self, first: date, last: date) -> dict: + """The arguments as lib/daytable.py reads them.""" + return {"start_date": first.isoformat(), "end_date": last.isoformat(), "where": self.where, "order": self.order, + "count_only": self.count_only, "stat": self.stat, "limit": self.limit, + **{k: v for k, v in (("sort_by", self.sort_by), ("group_by", self.group_by), ("of", self.of)) if v}} + + +def _stretch_words(s: Stretch) -> str: + """A stretch as `hours` takes it: "night", "15:00-16:00", "15:00".""" + clock = lambda m: f"{m // 60:02d}:{m % 60:02d}" + return s.name or (clock(s.start) if s.moment else f"{clock(s.start)}-{clock(s.end)}") + + +def _flag(args: dict, name: str) -> bool: + value = args.get(name) + if value is None or isinstance(value, bool): + return bool(value) + if str(value).strip().lower() in ("true", "1", "yes"): + return True + if str(value).strip().lower() in ("false", "0", "no", ""): + return False + raise Refusal(f"`{name}` is true or false, not {value!r}.") + + +def _near(word: str, fields: list[str]) -> list[str]: + """The fields a name that isn't one may have meant ("temperature": temp_max, temp_min, temp_avg; "pm2.5": pm2_5_max ...).""" + key = re.sub(r"[^a-z0-9]+", "_", str(word).lower()).strip("_") + key = {"temperature": "temp", "outdoor_temp": "temp", "outdoor_temperature": "temp", "indoor_temperature": "indoor_temp", + "pm25": "pm2_5", "uvi": "uv", "uv_index": "uv", "gust": "wind_gust", "gusts": "wind_gust", "rainfall": "rain", + "precipitation": "rain", "voc": "voc_index", "nox": "nox_index", "wind": "wind"}.get(key, key) + for suffix in ("_max", "_min", "_avg", "_high", "_low", "_mean", "_total"): + key = key.removesuffix(suffix) + return [n for n in fields if n == key or n.startswith(key + "_")] + + +class DaysTool: + """The `days` tool over a Context: its fields are those of the sensors there are.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + self.units = {**(STATION_UNITS if ctx.eco else {}), **(AIR_UNITS if ctx.air else {})} + self.fields = list(self.units) + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, parameters(self.fields), self.handle) + + # ---------- reading the arguments ---------- + def _field(self, value, what: str) -> str: + name = str(value).strip() if value is not None else "" + if name in self.units: + return name + if name in DEVICE_OF: + device = "weather station" if DEVICE_OF[name] == STATION else "air sensor" + raise Refusal(f"{what} {name!r} is the {device}'s, and this service has no {device}.", fields=self.fields) + near = _near(name, self.fields) + hint = f" Did you mean {', '.join(near)}?" if near else "" + raise Refusal(f"{what} {value!r} isn't a field of days.{hint} Send one of `fields`.", fields=self.fields) + + def _condition(self, c) -> dict: + if not isinstance(c, dict) or not {"field", "op", "value"} <= set(c): + raise Refusal(f"A condition is {{\"field\", \"op\", \"value\"}}, such as {{\"field\": \"rain\", \"op\": \">=\", \"value\": 1}}, " + f"not {c!r}.", fields=self.fields, ops=list(OPS)) + name = self._field(c["field"], "Field") + op = OP_WORDS.get(str(c["op"]).strip(), str(c["op"]).strip()) + if op not in OPS: + raise Refusal(f"op {c['op']!r} isn't one of {' '.join(OPS)}.", ops=list(OPS)) + value = c["value"] + if isinstance(value, str): + try: + value = float(value) + except ValueError: + pass + if isinstance(value, bool) or not isinstance(value, int | float): + raise Refusal(f"A condition's value is a number, in the field's unit ({name}: {self.units[name] or 'an index'}), not " + f"{c['value']!r}.") + return {"field": name, "op": op, "value": value} + + def read(self, args: dict) -> Call: + """The call checked: a Refusal, saying what to send instead, for anything the tool can't use.""" + if unknown := [k for k in args if k not in ARGUMENTS]: + renamed = [f"`{k}` is `{OLD_NAMES[k]}`" for k in unknown if k in OLD_NAMES] + raise Refusal(f"{', '.join(map(repr, unknown))} {'is not an argument' if len(unknown) == 1 else 'are not arguments'} of days" + + (f" ({'; '.join(renamed)}, or send a `period` in words)" if renamed else "") + ".", arguments=list(ARGUMENTS)) + where = args.get("where") or [] + where = [where] if isinstance(where, dict) else where + if not isinstance(where, list): + raise Refusal("`where` is a list of conditions, such as [{\"field\": \"rain\", \"op\": \">=\", \"value\": 1}].", + fields=self.fields) + where = [self._condition(c) for c in where] + sort_by = self._field(args["sort_by"], "sort_by") if args.get("sort_by") else None + order = str(args.get("order") or "desc").strip().lower() + if order not in ORDERS: + raise Refusal(f"order is desc (highest first) or asc (lowest first), not {args['order']!r}.") + group_by = str(args["group_by"]).strip().lower() if args.get("group_by") else None + if group_by not in (None, "month", "year"): + raise Refusal(f"group_by is month or year, not {args['group_by']!r}.") + stat = str(args.get("stat") or "count").strip().lower() + if stat not in STATS: + raise Refusal(f"stat is one of {', '.join(STATS)}, not {args['stat']!r}.", stats=list(STATS)) + of = self._field(args["of"], "of") if args.get("of") else None + if stat != "count" and of is None: + raise Refusal(f"stat {stat} needs `of`: the field to take the {stat} of (\"rain per month\": stat sum, of rain).", + fields=self.fields) + try: + limit = max(1, min(int(args.get("limit") or 5), MAX_LIMIT)) + except (TypeError, ValueError): + raise Refusal(f"limit is a whole number of days to list, 1 to {MAX_LIMIT}, not {args['limit']!r}.") from None + only = str(args["only"]).strip().lower() if args.get("only") else None + if only not in (None, *ONLY): + raise Refusal(f"only is {' or '.join(ONLY)}, not {args['only']!r}.") + stretch = None + if args.get("hours") not in (None, ""): + try: + stretch = parse_stretch(args["hours"]) + except ValueError as e: + raise Refusal(str(e), hours=ALLOWED) from None + return Call(where, sort_by, order, _flag(args, "count_only"), group_by, stat, of, limit, only, stretch, + _flag(args, "chart_answers_it")) + + def devices(self, call: Call) -> list[str]: + """The sensors the call is about: those of the fields it names, else the station's (the air sensor's when there is no station).""" + named = {DEVICE_OF[n] for n in call.named} + return [d for d in DEVICES if d in named] or [STATION if self.ctx.eco else AIR_DEVICE] + + # ---------- the period ---------- + def period(self, args: dict, call: Call, now: datetime, first_held: date | None): + """(the Period, its first day, its last day): whole days to yesterday; with `hours`, today too once its stretch is over.""" + tz, today, stretch = self.ctx.zone, now.date(), call.stretch + read = lambda whole: read_period(args, tz=tz, now=now, default=DEFAULT_HOURS if stretch else DEFAULT, whole_days=whole, + first_held=first_held) + try: + whole, refused = read(True), None + except Refusal as e: + whole, refused = None, e + if stretch and (whole is None or whole.cut) and over(stretch, today, tz, now.timestamp()): + try: # the same words to now: whole days still, ending today + timed = read(False) + except Refusal: + timed = None + if timed and timed.start.time() == time() and timed.last_day == today: + return timed, timed.first_day, today + if refused: + raise refused + return whole, whole.first_day, whole.last_day + + # ---------- reading the file ---------- + def _station_sensors(self, r: Reader, shown: list[str]) -> dict: + """{group: its Sensor} of the groups these station fields are in, those the file has.""" + groups = dict.fromkeys(STATION_FIELDS[n][0] for n in shown if DEVICE_OF[n] == STATION) + return {g: s for g in groups if (s := r.sensor(self.ctx.eco.mac, g)) is not None} + + def _first_held(self, r: Reader, devices: list[str], shown: list[str]) -> date | None: + """The first day held by every sensor asked about ("on record"): the latest of their first day rows; None when one holds none.""" + firsts = [] + for device in devices: + sensors = list(self._station_sensors(r, shown).values()) if device == STATION else [self.ctx.air.store.sensor] + by_kind: dict[str, list[int]] = {} + for s in filter(None, sensors): + by_kind.setdefault(s.kind, []).append(s.id) + found = [r.db.execute(f"SELECT MIN(day) FROM {kind}_day WHERE sensor IN ({', '.join('?' * len(ids))})", ids).fetchone()[0] + for kind, ids in by_kind.items()] + found = [date.fromisoformat(d) for d in found if d] + if not found: + return None + firsts.append(min(found)) + return max(firsts) if firsts else None + + def _stretches(self, r: Reader, shown: list[str], first: date, last: date, stretch: Stretch, now: float) -> dict[str, PartDays]: + """{group (or "air"): its sensor's figures over the stretch of each day}, in the columns these fields need.""" + columns: dict[str, list[str]] = {} + for n in shown: + if DEVICE_OF[n] == STATION: + group, reading, _, _ = STATION_FIELDS[n] + columns.setdefault(group, []).append(column_of(group, reading)[0]) + else: + columns.setdefault(AIR_DEVICE, []).append(n.rsplit("_", 1)[0]) + sensors = {**(self._station_sensors(r, shown) if self.ctx.eco else {}), + **({AIR_DEVICE: self.ctx.air.store.sensor} if self.ctx.air and AIR_DEVICE in columns else {})} + return {key: stretch_figures(r, sensor.kind, sensor, first, last, stretch, list(dict.fromkeys(columns[key])), self.ctx.zone, now) + for key, sensor in sensors.items() if sensor is not None} + + async def _held(self, call: Call, shown: list[str], first: date, last: date, now: float) -> "Held": + """Each shown field's figure per day, and what is known of where they came from.""" + days = [first + timedelta(days=k) for k in range((last - first).days + 1)] + held = Held(values={n: {} for n in shown}) + station = [n for n in shown if DEVICE_OF[n] == STATION] + air = [n for n in shown if DEVICE_OF[n] == AIR_DEVICE] + storage = self.ctx.storage + if call.stretch is None: + if station: + values, held.station = await storage.read(day_values_on, self.ctx.eco.mac, station, days) + held.values.update(values) + if air: + figures = await self.ctx.air.store.day_figures(first, last, air) + held.values.update(figures.values) + held.hourly, held.counts = set(figures.hourly), figures.counts + else: + parts = await storage.read(self._stretches, shown, first, last, call.stretch, now) + for n in shown: + if DEVICE_OF[n] == STATION: + group, reading, kind, _ = STATION_FIELDS[n] + part, column = PARTS[kind], column_of(group, reading)[0] + else: + group, (column, suffix) = AIR_DEVICE, n.rsplit("_", 1) + part = AIR_PART[suffix] + got = parts.get(group) + if got is not None: + held.values[n] = {d: v for d, v in zip(got.days.day, getattr(got.days, part).get(column, ())) if v is not None} + for group, got in parts.items(): + for d, src in zip(got.days.day, got.days.source): + if group == AIR_DEVICE: + if src == "1hour": + held.hourly.add(d) + else: + held.station[d] = max(held.station.get(d, src), src, key=COARSER.get) + for d, why in got.left_out.items(): + held.left_out.setdefault(d, why) + held.missing.update(got.missing) + if got.note: + held.notes.append(got.note) + held.missing -= set(held.left_out) + if self.ctx.eco: # each day's look, from its whole day's figures + held.look = (await storage.read(day_values_on, self.ctx.eco.mac, list(LOOK_FIGURES), days))[0] + return held + + # ---------- the answer ---------- + async def handle(self, args: dict, meta: dict) -> str: + call = self.read(args) + devices = self.devices(call) # (each one the service has: read() refuses a field of a sensor it hasn't) + calendar = PublicHolidays(self.ctx.zone) + if call.only == "public_holiday" and not calendar.available: + raise Refusal(calendar.problem()) + tz, now = self.ctx.zone, self.ctx.now() + shown = list(dict.fromkeys([n for d in devices for n in SHOWN[d]] + call.named)) + first_held = await self.ctx.storage.read(self._first_held, devices, shown) + period, first, last = self.period(args, call, now, first_held) + if call.stretch and (last - first).days + 1 > MAX_HOURS_DAYS: + raise Refusal(f"With hours, a period is at most {MAX_HOURS_DAYS} days ({period.text} is {(last - first).days + 1}): send a " + "shorter one, such as \"past year\".", fits="past year") + asked = prepare(call.engine(first, last), self.units, tuple(n for d in devices for n in SHOWN[d]), + last + timedelta(days=1)) # ("today" for the engine: the day after the last, so it cuts nothing) + if isinstance(asked, str): # (the call was checked: the engine finds nothing more to refuse) + raise Refusal(asked) + held = await self._held(call, asked.shown, first, last, now.timestamp()) + merged = len(devices) > 1 + kind: Callable[[date], bool] = {None: lambda d: True, "weekend": lambda d: d.weekday() >= 5, + "public_holiday": lambda d: calendar.name(d) is not None}[call.only] + has = {device: {d for n in asked.shown if DEVICE_OF[n] == device for d in held.values[n]} for device in devices} + days = [d for d in asked.days if kind(d)] + both = [d for d in days if all(d in has[device] for device in devices)] + daily_out = {d for d in both if merged and held.station.get(d) == "daily"} + checked = [d for d in both if d not in daily_out] + + def row_extra(d: date) -> dict: + out = {} + if held.look is not None and (look := day_look({n: held.look[n].get(d) for n in LOOK_FIGURES}, latitude=self.ctx.eco.latitude, + day=d, so_far=d >= now.date())): + out["day_look"] = look + if call.only == "public_holiday": + out["holiday"] = calendar.name(d) + station = "daily" if held.station.get(d) == "daily" else "exact" + air = "hourly" if d in held.hourly else "exact" + out["source"] = {STATION: station, AIR_DEVICE: air} if merged else station if devices == [STATION] else air + return out + + turn = Turn() # (only its charts: the bars analyse draws) + scope = " · ".join(filter(None, [call.stretch.text if call.stretch else "", ONLY.get(call.only, "")])) + sourced = CHART_SOURCE.set(" and ".join(SOURCES[d] for d in devices)) + try: + got = analyse(held.values, asked, checked, tz, turn, row_extra, scope) + finally: + CHART_SOURCE.reset(sourced) + out = got.out + engine_period = out.pop("period") + out.pop("chart", None) # (the bot's hint: chart_note says what to do with a chart) + out.update(self._notes(call, asked, held, got, checked, days, daily_out, devices, merged, first_held)) + line = answer_line(out, engine_period, call.stretch) + fields = {"answer": line, **({"hours": {"text": call.stretch.text, "how_to_read": HOURS_HOW}} if call.stretch else {}), **out} + charts = with_charts(turn.charts, tz, meta) + if charts: + drawn = self.drawn_by(call, args, period, first, last, first_held, now.date()) + for chart in charts["charts"]: + chart["drawn_by"] = drawn + finished = complete(line) if call.chart_answers_it and charts and not needs_words(out) else {} + return answer(period=period, as_of=now, **fields, **charts, **finished) + + def _notes(self, call: Call, asked, held: "Held", got, checked: list[date], days: list[date], daily_out: set[date], + devices: list[str], merged: bool, first_held: date | None) -> dict: + """The notes weather_days and air_days add, in their order, and those of a question mixing the two and of part of each day.""" + out: dict = {} + where, values, sort_by = asked.where, held.values, asked.sort_by + station = STATION in devices + if station: + # Days that would have ranked higher had a trace of rain counted: the answer should mention them + trace: list[date] = [] + rain_cond = next((c for c in where if c["field"] == "rain" and c["op"] in (">", ">=") and c["value"] > 0), None) + if rain_cond and lists_days(asked.args): + relaxed = [{"field": "rain", "op": ">", "value": 0} if c is rain_cond else c for c in where] + matched = set(got.matches) + better = operator.lt if call.order == "asc" else operator.gt + for d in got.rank(d for d in checked if got.holds(d, relaxed)): + if d in matched: + break # from here on the real matches rank at least as high + if not got.ranked or better(values[sort_by][d], values[sort_by][got.ranked[0]]): # strictly ahead, not a tie + trace.append(d) + if len(trace) == 2: + break + if trace: + out["trace_rain_days"] = [got.row(d) for d in trace] + out["note_trace"] = NOTE_TRACE.format(value=rain_cond["value"]) + run = daily_run(self.ctx.zone, asked.first, asked.last) + if daily_out: + out["daily_left_out"] = len(daily_out) + out["note_daily_left_out"] = NOTE_DAILY_LEFT_OUT.format(n=len(daily_out), run=run) + elif any(held.station.get(d) == "daily" for d in checked): + exact = sorted(d for d in checked if held.station.get(d) != "daily") + out["exact_from"] = day_text(exact[0]) if exact else None + out["note_daily"] = NOTE_DAILY.format(run=run) + if AVERAGED & set(asked.shown) and any(held.station.get(d) != "5min" for d in checked): + out["note_averaged"] = NOTE_AVERAGED + if AIR_DEVICE in devices: + hourly = [d for d in checked if d in held.hourly] + if hourly and any(n.endswith(("_max", "_min")) for n in asked.shown if DEVICE_OF[n] == AIR_DEVICE): + out["note_hourly"] = NOTE_HOURLY.format(n=len(hourly)) + if call.stretch is None and (missing := sum(1 for d in days if not held.counts.get(d))): + out["note_missing"] = NOTE_MISSING.format(n=missing) + if call.stretch: + reasons = [LEFT_OUT[held.left_out[d]] for d in days if d in held.left_out] + ["no readings" for d in days if d in held.missing] + if reasons: + out["left_out"] = {why: reasons.count(why) for why in dict.fromkeys(reasons)} + out["note_left_out"] = NOTE_LEFT_OUT + if held.notes: + out["note_moment"] = " ".join(dict.fromkeys(held.notes)) + if not checked: + before = first_held is not None and asked.last < first_held # (what the data does reach: 3.2, errors that teach) + out["note"] = NOTE_BEFORE.format(first=day_text(first_held)) if before else NOTE_NOTHING + return out + + def drawn_by(self, call: Call, args: dict, period, first: date, last: date, first_held: date | None, today: date) -> dict: + """The call that drew the chart as the tool read it (3.7), every default filled in, the period in words, and the periods it is + worth drawing over: per month, 3 months, a year and the whole record (with hours, only while that is within its 400 days); per + year, none.""" + words = f"{first.isoformat()} to {last.isoformat()}" if args.get("start") else period.asked + arguments = {"where": call.where, "sort_by": self.sort_of(call), "order": call.order, "count_only": call.count_only, + "group_by": call.group_by, "stat": call.stat, **({"of": call.of} if call.of else {}), "limit": call.limit, + **({"only": call.only} if call.only else {}), **({"hours": _stretch_words(call.stretch)} if call.stretch else {}), + "period": words, "chart_answers_it": call.chart_answers_it} + periods = [] + if call.group_by == "month": + fits = not call.stretch or (first_held is not None and (today - first_held).days + 1 <= MAX_HOURS_DAYS) + periods = [{"period": p, "label": label} for p, label in MONTH_PERIODS if p != DEFAULT or fits] + return {"tool": NAME, "arguments": arguments, "periods": periods} + + def sort_of(self, call: Call) -> str: + """The field the days are ranked by: sort_by, else the first condition's field, else `of`, else the first shown (daytable).""" + return call.sort_by or (call.where[0]["field"] if call.where else call.of or SHOWN[self.devices(call)[0]][0]) + + +@dataclass +class Held: + """What DaysTool._held read: each shown field's figure per day; the station's source of each day ("5min", "30min", "daily"); the air + sensor's days held only as hourly averages, and (whole days) its readings per day; with `hours`, the days left out (and why) and + those with no readings in the stretch, and what a moment was on coarser days; and each day's figures for its look.""" + values: dict[str, dict[date, float]] + station: dict[date, str] = field(default_factory=dict) + hourly: set[date] = field(default_factory=set) + counts: dict[date, int | None] = field(default_factory=dict) + left_out: dict[date, str] = field(default_factory=dict) + missing: set[date] = field(default_factory=set) + notes: list[str] = field(default_factory=list) + look: dict[str, dict[date, float]] | None = None + + +def needs_words(out: dict) -> bool: + """Does the result carry a note the person should hear that the answer line leaves out (the older days held only as daily records + or hourly averages, a rarer day that nearly counted, days left out ...)? Then it is never complete (3.7).""" + notes = {k for k in out if k.startswith("note") or k.endswith("_note") or k in ("warning", "missing", "exact_from", "trace_rain_days")} + return bool(notes - CAPTIONED_NOTES) + + +# ---------- the answer line (lib/report.py's days lookup, ported with its words) ---------- +def period_words(text: str) -> str: + """"Tue 29 Sep 2026 - Tue 6 Oct 2026" -> "Tue 29 Sep – Tue 6 Oct 2026" (the first year is dropped only when it is the same year).""" + years = re.findall(r" (20\d\d)\b", text) + if len(years) == 2 and years[0] == years[1]: + text = re.sub(r" 20\d\d\b(?= - )", "", text) + return text.replace(" - ", " – ") + + +def answer_line(out: dict, period: str, stretch: Stretch | None = None) -> str: + """"137 of 1,454 days with UV index ≥ 10 (period).", or a total, average, highest or lowest over the period ("Total rain: 49.8 mm + over 30 days (period).") as the bot writes a days lookup today; `period` is the days' "first - last". Over part of each day the line + says which part first ("Each night (22:00–06:00): ...", "Each day at 15:00: ...").""" + when = period_words(period) + if out.get("stat") and out.get("value") is not None: + unit = unit_text(out["stat"].get("unit")) or "" + line = f"{out['stat']['what']}: {out['value']:g} {unit}".rstrip() + f" over {out['days_checked']:,} days ({when})." + else: + what = f" with {out['condition']}" if out.get("condition") else "" + note = " Older days use averages, so a count near the limit may fall slightly short." if out.get("note_averaged") else "" + line = f"{out['matching_days']:,} of {out['days_checked']:,} days{what} ({when}).{note}" + if stretch is None: + return line + each = f"Each {stretch.text}" if stretch.name else f"Each day at {stretch.text}" if stretch.moment else f"Each day {stretch.text}" + return f"{each}: {line}" + + +def tools(ctx: Context) -> list[ServiceTool]: + """The days tool, when there is a sensor to read.""" + return [DaysTool(ctx).tool()] if ctx.eco or ctx.air else [] + + +__all__ = ["DESCRIPTION", "DaysTool", "answer_line", "needs_words", "parameters", "tools"] diff --git a/tests/test_service_days.py b/tests/test_service_days.py new file mode 100644 index 00000000..cdee7a2d --- /dev/null +++ b/tests/test_service_days.py @@ -0,0 +1,415 @@ +"""The `days` tool (lib/service/days.py): its arguments and defaults, its result, its refusals, its periods, its charts and their +`drawn_by`, the merged rule over both sensors, part of each day (`hours`), and its answer line, against today's weather_days and air_days +(which it replaces) and lib/report.py's days lookup (whose words it keeps), on the fake station's archive with an air sensor added.""" + +import copy +import json +import shutil +from datetime import date, datetime, time, timedelta + +import pytest + +from lib import report +from lib.airgradient.days import find_air_days +from lib.airgradient.readings import AirReadings +from lib.ecowitt.days import find_days +from lib.partday import over, parse_stretch +from lib.service import days as days_tool +from lib.service.common import CHART_NOTE, FRESH +from lib.service.context import Context +from lib.service.daylook import LOOKS +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.timeutil import day_bounds, day_text, local_epoch, now_local +from lib.tools import Turn +from tests.fakes import TZ, archived_station, rain_day, temp +from tests.test_chart_json import errors as schema_errors + +LOC = "42" +AIR_DAYS = 40 # the air sensor's 5-minute readings: the last 40 days +OLD_AIR = (390, 375) # ... and hourly averages of days this long ago, before the station's 30-minute archive (its daily records) + + +def pm(ts: int) -> float: + """PM2.5: a level for each day (2 to 32 µg/m³), a microgram higher from noon.""" + local = datetime.fromtimestamp(ts, TZ) + return 2.0 + local.toordinal() % 7 * 5 + (local.hour >= 12) + + +def air_row(ts: int) -> dict: + v = pm(ts) + return {"ts": ts, "pm2_5": v, "pm10": v * 1.5, "pm1": v * 0.7, "co2": 420.0, "voc_index": 100.0, "nox_index": 1.0, + "air_temperature": 18.0, "air_humidity": 60.0} + + +@pytest.fixture(scope="module") +def air_cache(archived_cache, tmp_path_factory): + """The archive with an air sensor's readings added (built once for these tests): the last AIR_DAYS days at 5 minutes, and OLD_AIR's + days as hourly averages.""" + path = tmp_path_factory.mktemp("days") / "ecobot.sqlite" + shutil.copy(archived_cache, path) + storage = Storage(path, TZ) + today = datetime.now(TZ).date() + + def write(w): + sensor = w.air_sensor(LOC) + start, end = day_bounds(today - timedelta(days=AIR_DAYS), TZ)[0], int(datetime.now(TZ).timestamp()) // 300 * 300 + w.put(sensor, "5min", [air_row(t) for t in range(start, end, 300)], CLOUD) + w.cover(sensor, "5min", start, end - 1) + start, end = day_bounds(today - timedelta(days=OLD_AIR[0]), TZ)[0], day_bounds(today - timedelta(days=OLD_AIR[1]), TZ)[1] + w.put(sensor, "1hour", [air_row(t) for t in range(start, end, 3600)], CLOUD) + w.cover(sensor, "1hour", start, end - 1) + storage.writer.run(write, ()) + storage.close() + return path + + +class Air: + """The part of the air source the tool uses: its readings in the file.""" + tz = TZ + + def __init__(self, storage): + self.store = AirReadings(storage, LOC, TZ) + + +@pytest.fixture +async def world(tmp_path, air_cache): + eco, fake = await archived_station(tmp_path, air_cache) + yield Context(eco=eco, air=Air(eco.storage)) + await eco.close() + assert fake.calls == [] # answered from the file alone + + +def tool(ctx): + (found,) = days_tool.tools(ctx) + return found + + +async def ask(ctx, meta=None, **args) -> dict: + return json.loads(await tool(ctx).call(args, meta)) + + +def ago(n: int) -> date: + return datetime.now(TZ).date() - timedelta(days=n) + + +def label(d: date) -> str: + return day_text(d) + + +def truth(d: date) -> tuple[float, float]: + """(temp_max, rain) of a local day, from the fake's functions alone.""" + ticks = range(day_bounds(d, TZ)[0], day_bounds(d, TZ)[1], 300) + return max(temp(t) for t in ticks), max(rain_day(t) for t in ticks) + + +def engine_part(out: dict) -> dict: + """A days result as weather_days and air_days had it: without the service's head, its answer line, charts, looks and sources.""" + out = {k: v for k, v in out.items() if k not in ("period", "as_of", "fresh", "answer", "chart_note", "charts", "reply", "complete", + "note", "chart")} + for key in ("days", "trace_rain_days"): + if key in out: + out[key] = [{k: v for k, v in row.items() if k not in ("day_look", "source")} for row in out[key]] + return out + + +# ---------- the tool ---------- +async def test_the_tool_offers_the_fields_of_the_sensors_there_are_and_says_what_it_is_for(world): + t = tool(world) + assert t.name == "days" and t.annotations == {"readOnlyHint": True, "openWorldHint": False} + props = t.parameters["properties"] + assert set(props) == set(days_tool.ARGUMENTS) + fields = props["where"]["items"]["properties"]["field"]["enum"] + assert {"temp_max", "rain", "indoor_humidity_min", "uv_max", "pm2_5_max", "co2_avg"} <= set(fields) + assert props["sort_by"]["enum"] == props["of"]["enum"] == fields + assert "on record" in props["period"]["description"] and "last 30 days" in props["period"]["description"] + assert "Whole days only" in props["period"]["description"] and "night (22:00-06:00" in props["hours"]["description"] + d = t.description + assert len(d) < 1500 and all(word in d for word in ("summary", "readings", "relate", "day_look", "hours", "only", "count_only")) + station_only = days_tool.tools(Context(eco=world.eco))[0].parameters["properties"] + assert "pm2_5_max" not in station_only["where"]["items"]["properties"]["field"]["enum"] + assert "Air sensor" not in station_only["where"]["description"] + air_only = days_tool.tools(Context(air=world.air))[0].parameters["properties"] + assert air_only["where"]["items"]["properties"]["field"]["enum"] == list(days_tool.AIR_UNITS) + assert days_tool.tools(Context()) == [] + + +async def test_with_nothing_sent_it_ranks_every_day_on_record_by_the_high_and_answers_ready_to_pass_on(world): + out = await ask(world) + assert list(out)[:4] == ["period", "as_of", "fresh", "answer"] and out["fresh"] == FRESH + first = await world.storage.read(lambda r: min(date.fromisoformat(d) for (d,) in r.db.execute("SELECT day FROM climate_day"))) + assert out["period"]["asked"] == "on record" and out["period"]["start"].startswith(first.isoformat()) + assert out["period"]["cut"] == f"to {day_text(ago(1), year=False)}: today isn't over" + assert out["days_checked"] == out["matching_days"] == (ago(1) - first).days + 1 # (no condition: every day held matches) + rows = out["days"] + assert len(rows) == 5 and [r["temp_max"] for r in rows] == sorted((r["temp_max"] for r in rows), reverse=True) + assert set(rows[0]) >= {"date", "day_look", "source", "temp_max", "temp_min", "rain"} + assert all(r["day_look"]["emoji"] == LOOKS[r["day_look"]["word"]] for r in rows) + assert out["answer"].startswith(f"{out['matching_days']:,} of {out['days_checked']:,} days (") + assert "charts" not in out and "complete" not in out and "note_daily" in out # (its oldest days are Ecowitt's daily records) + + +# ---------- the same answers as weather_days and air_days ---------- +STATION_CASES = [ + {"where": [{"field": "rain", "op": ">", "value": 0}], "sort_by": "temp_max", "limit": 3}, + {"where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "limit": 4}, # a trace day ranks higher + {"where": [{"field": "temp_max", "op": ">", "value": 18}], "count_only": True}, + {"sort_by": "temp_min", "order": "asc", "limit": 2}, + {"stat": "sum", "of": "rain", "group_by": "month"}, + {"where": [{"field": "humidity_min", "op": "<", "value": 60}], "stat": "avg", "of": "humidity_avg"}, # note_averaged + {"where": [{"field": "rain", "op": "=", "value": 0}], "only": "weekend", "limit": 20}, +] + + +@pytest.mark.parametrize("case", STATION_CASES) +async def test_station_fields_answer_as_weather_days_did(world, case): + first, last = ago(80), ago(2) + out = await ask(world, start=str(first), end=str(last), **case) + theirs = await find_days(world.storage, world.eco.mac, TZ, {"start_date": str(first), "end_date": str(last), **case}, now_local(TZ), + Turn()) + assert engine_part(out) == engine_part(theirs) + assert all(r["source"] == "exact" for r in out.get("days", [])) + assert out["answer"] == report.lookup("days", json.dumps(theirs), [], [], ago(0)) # the bot's words for the same data + + +async def test_the_older_days_say_they_come_from_daily_records_as_weather_days_did(world): + args = {"where": [{"field": "temp_max", "op": ">", "value": 0}], "limit": 20} + out = await ask(world, start=str(ago(540)), end=str(ago(2)), **args) + theirs = await find_days(world.storage, world.eco.mac, TZ, {"start_date": str(ago(540)), "end_date": str(ago(2)), **args}, + now_local(TZ), Turn()) + assert engine_part(out) == engine_part(theirs) and out["exact_from"] and "10am to 10am" in out["note_daily"] + old = await ask(world, start=str(ago(540)), end=str(ago(510)), **args) + assert old["days"] and all(r["source"] == "daily" for r in old["days"]) + + +AIR_CASES = [ + {"where": [{"field": "pm2_5_max", "op": ">", "value": 20}], "limit": 3}, + {"stat": "max", "of": "pm2_5_max", "group_by": "month"}, + {"sort_by": "pm10_avg", "order": "asc", "count_only": True}, +] + + +@pytest.mark.parametrize("case", AIR_CASES) +async def test_air_fields_answer_as_air_days_did(world, case): + first, last = ago(AIR_DAYS + 10), ago(2) + out = await ask(world, start=str(first), end=str(last), **case) + theirs = await find_air_days(world.air.store, TZ, {"start_date": str(first), "end_date": str(last), **case}, now_local(TZ), Turn()) + assert engine_part(out) == engine_part(theirs) and out["note_missing"] == theirs["note_missing"] # (the 10 days before the sensor) + assert out["answer"] == report.lookup("days", json.dumps(theirs), [], [], ago(0)) + for row in out.get("days", []): + assert row["source"] == "exact" and "day_look" in row # each day's weather, from the station + + +async def test_an_air_question_shows_and_ranks_by_pm2_5_and_its_days_carry_the_weather(world): + out = await ask(world, period="last 20 days", where=[{"field": "co2_avg", "op": ">", "value": 0}]) + assert out["units"] == {"pm2_5_max": "µg/m³", "co2_avg": "ppm"} and out["days_checked"] == 20 # (ranked by co2_avg, as named) + assert "temp_max" not in out["days"][0] and "day_look" in out["days"][0] + air_only = json.loads(await days_tool.tools(Context(air=world.air))[0].call({"period": "last 20 days"})) + assert [r["pm2_5_max"] for r in air_only["days"]] == sorted((r["pm2_5_max"] for r in air_only["days"]), reverse=True) + expected = max(pm(t) for d in (ago(n) for n in range(1, 21)) for t in range(*day_bounds(d, TZ), 300)) + assert air_only["days"][0]["pm2_5_max"] == expected and air_only["units"] == {"pm2_5_max": "µg/m³"} + assert "day_look" not in air_only["days"][0] # (no station: no weather to look at) + + +# ---------- the answer line ---------- +def test_the_answer_line_is_the_bots_days_lookup_word_for_word(): + data = {"period": "Tue 29 Sep 2026 - Tue 6 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"} + for out in (data, {**data, "note_averaged": "..."}, {**data, "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": 49.8}, + {**data, "stat": {"what": "Highest UV index", "of": "uv_max", "unit": ""}, "value": 11.0}, + {**data, "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": None}, {**data, "condition": None}): + mine = days_tool.answer_line({k: v for k, v in out.items() if k != "period"}, out["period"]) + assert mine == report.lookup("days", json.dumps(out), [], [], date(2026, 11, 10)) + assert days_tool.answer_line(data, data["period"]) == "137 of 1,454 days with UV index ≥ 10 (Tue 29 Sep – Tue 6 Oct 2026)." + night, three = parse_stretch("night"), parse_stretch("15:00") + assert days_tool.answer_line(data, data["period"], night).startswith("Each night (22:00–06:00): 137 of 1,454 days") + assert days_tool.answer_line(data, data["period"], three).startswith("Each day at 15:00: 137 of") + assert days_tool.answer_line(data, data["period"], parse_stretch("15:00-16:00")).startswith("Each day 15:00–16:00: 137 of") + + +# ---------- refusals ---------- +async def test_a_call_it_cant_use_is_refused_with_what_to_send_instead(world): + bad = await ask(world, where=[{"field": "temperature", "op": ">", "value": 30}]) + assert "Did you mean temp_max, temp_min, temp_avg?" in bad["error"] and "pm2_5_max" in bad["fields"] + assert "pm2_5_max, pm2_5_min, pm2_5_avg" in (await ask(world, sort_by="pm2.5"))["error"] + assert (await ask(world, where=[{"field": "rain", "op": "gt", "value": 1}]))["ops"] == [">", ">=", "<", "<=", "="] + assert "a number" in (await ask(world, where=[{"field": "rain", "op": ">", "value": "lots"}]))["error"] + assert "rain" in (await ask(world, where=["rain > 1"]))["error"] + assert "needs `of`" in (await ask(world, stat="sum"))["error"] + assert "month or year" in (await ask(world, group_by="week"))["error"] + assert "desc" in (await ask(world, order="up"))["error"] + assert "public_holiday or weekend" in (await ask(world, only="holiday"))["error"] + old = await ask(world, start_date="2026-01-01", end_date="2026-01-31") + assert "`start_date` is `start`" in old["error"] and "period" in old["arguments"] + hours = await ask(world, hours="dawn") + assert "isn't a part of the day" in hours["error"] or "not a part of the day" in hours["error"] + assert "night (22:00-06:00)" in hours["hours"] + for words in ("today", "last 5 hours", "this morning"): # whole days only: today isn't over + assert "use summary or readings" in (await ask(world, period=words))["error"], words + assert "use forecast" in (await ask(world, period="next week"))["error"] + forms = await ask(world, period="the other week") + assert "isn't a period" in forms["error"] and "on record, all time, ever (from the first reading held)" in forms["forms"] + assert "today" not in forms["forms"] # (a whole-day tool lists only the forms it reads) + long = await ask(world, hours="night", period="on record") + assert "at most 400 days" in long["error"] and long["fits"] == "past year" + no_air = days_tool.tools(Context(eco=world.eco))[0] + refused = json.loads(await no_air.call({"where": [{"field": "pm2_5_max", "op": ">", "value": 1}]})) + assert "this service has no air sensor" in refused["error"] + + +async def test_a_period_before_the_record_says_where_the_record_starts(world): + first = await world.storage.read(lambda r: min(date.fromisoformat(d) for (d,) in r.db.execute("SELECT day FROM air_day"))) + out = await ask(world, start=str(first - timedelta(days=30)), end=str(first - timedelta(days=1)), sort_by="pm2_5_max") + assert out["days_checked"] == 0 and out["note"] == f"No readings are held for this period: the record of what was asked about " \ + f"starts {day_text(first)}." + assert out["answer"].startswith("0 of 0 days (") and "days" in out and out["days"] == [] + + +async def test_the_holiday_and_weekend_filter_is_the_models_own(world): + out = await ask(world, period="last 8 weeks", only="weekend", limit=20) + days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] + assert out["days_checked"] == 16 and all(d.weekday() >= 5 for d in days) + holidays = await ask(world, period="past year", only="public_holiday", sort_by="rain") + assert 5 <= holidays["days_checked"] <= 15 and all(r["holiday"] for r in holidays["days"]) + + +# ---------- both sensors ---------- +async def test_a_question_over_both_sensors_counts_the_days_both_have(world): + first, last = ago(AIR_DAYS + 10), ago(2) + where = [{"field": "rain", "op": ">=", "value": 1}, {"field": "pm2_5_max", "op": ">", "value": 10}] + out = await ask(world, start=str(first), end=str(last), where=where, sort_by="temp_max", limit=20) + days = [first + timedelta(days=k) for k in range((last - first).days + 1)] + both = [d for d in days if d >= ago(AIR_DAYS)] + wet = [d for d in both if truth(d)[1] >= 1 and max(pm(t) for t in range(*day_bounds(d, TZ), 300)) > 10] + assert out["days_checked"] == len(both) and out["matching_days"] == len(wet) + assert sorted(r["date"] for r in out["days"]) == sorted(label(d) for d in wet) + assert [r["temp_max"] for r in out["days"]] == sorted((r["temp_max"] for r in out["days"]), reverse=True) + assert out["units"] == {"temp_max": "°C", "temp_min": "°C", "rain": "mm", "pm2_5_max": "µg/m³"} # both sensors' shown fields + row = out["days"][0] + assert row["source"] == {"station": "exact", "air": "exact"} and row["day_look"]["word"] in ("wet", "showery", "stormy") + assert out["condition"] == "rain ≥ 1 mm and PM2.5 > 10 µg/m³" and out["note_missing"].startswith("10 day(s)") + when = days_tool.period_words(f"{day_text(first)} - {day_text(last)}") + assert out["answer"] == f"{len(wet)} of {len(both)} days with rain ≥ 1 mm and PM2.5 > 10 µg/m³ ({when})." + + +async def test_days_whose_station_figures_are_daily_records_are_left_out_of_a_mixed_question_and_counted(world): + first, last = ago(OLD_AIR[0]), ago(OLD_AIR[1]) + out = await ask(world, start=str(first), end=str(last), where=[{"field": "pm2_5_max", "op": ">", "value": 0}], sort_by="rain") + assert out["days_checked"] == 0 and out["daily_left_out"] == OLD_AIR[0] - OLD_AIR[1] + 1 + assert "daily records, which run 1" in out["note_daily_left_out"] and "note_daily" not in out and "note" in out + alone = await ask(world, start=str(first), end=str(last), where=[{"field": "pm2_5_max", "op": ">", "value": 0}]) + assert alone["days_checked"] == OLD_AIR[0] - OLD_AIR[1] + 1 and "note_hourly" in alone # the air sensor alone: every day + assert all(r["source"] == "hourly" for r in alone["days"]) + + +# ---------- part of each day ---------- +async def test_hours_works_out_each_days_figures_over_the_stretch(world): + afternoon = await ask(world, hours="afternoon", period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 1}], + sort_by="rain", limit=20) + morning = await ask(world, hours="morning", period="last 30 days", where=[{"field": "rain", "op": ">", "value": 0}]) + whole = await ask(world, period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 1}], limit=20) + assert morning["matching_days"] == 0 # the fake's rain falls from 2pm + assert afternoon["matching_days"] == whole["matching_days"] > 0 # ... all of it in the afternoon + assert {r["date"]: r["rain"] for r in afternoon["days"]} == {r["date"]: r["rain"] for r in whole["days"]} + assert afternoon["hours"]["text"] == "afternoon (12:00–18:00)" and "mm that fell in it" in afternoon["hours"]["how_to_read"] + assert afternoon["answer"].startswith("Each afternoon (12:00–18:00): ") + assert afternoon["period"]["asked"] == "last 30 days" + + +async def test_a_moment_is_the_reading_at_that_time_each_day(world): + out = await ask(world, hours="15:00", start=str(ago(10)), end=str(ago(2)), stat="avg", of="temp_avg") + at_three = [round(temp(local_epoch(datetime.combine(d, time(15)), TZ)), 1) for d in (ago(n) for n in range(2, 11))] + assert out["days_checked"] == 9 and out["value"] == round(sum(at_three) / len(at_three), 1) + assert out["answer"] == f"Each day at 15:00: Average temperature: {out['value']:g} °C over 9 days " \ + f"({days_tool.period_words(f'{day_text(ago(10))} - {day_text(ago(2))}')})." + + +async def test_a_night_across_midnight_belongs_to_the_day_it_ends_on_and_today_counts_once_it_is_over(world): + out = await ask(world, hours="night", period="this week", sort_by="temp_min", order="asc", limit=20) + over_now = over(parse_stretch("night"), ago(0), TZ, datetime.now(TZ).timestamp()) + days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] + assert out["days_checked"] == 7 and (ago(0) in days) == over_now and (ago(7) in days) == (not over_now) + assert ("cut" in out["period"]) == (not over_now) + d = days[0] + night = range(local_epoch(datetime.combine(d - timedelta(days=1), time(22)), TZ), local_epoch(datetime.combine(d, time(6)), TZ), 300) + assert out["days"][0]["temp_min"] == pytest.approx(min(temp(t) for t in night), abs=0.06) + + +async def test_a_whole_day_stretch_gives_the_day_rows_figures_and_leaves_out_days_held_only_as_daily_records(world): + first, last = ago(374), ago(356) # across the start of the station's 30-minute archive: every day listed + args = {"start": str(first), "end": str(last), "sort_by": "temp_max", "limit": 20, "where": [{"field": "rain", "op": ">=", "value": 0}]} + whole, stretch = await ask(world, **args), await ask(world, hours="00:00-24:00", **args) + figures = lambda rows: {r["date"]: (r["temp_max"], r["temp_min"], r["rain"]) for r in rows} + exact = figures(r for r in whole["days"] if r["source"] == "exact") + assert whole["days_checked"] == 19 and 0 < len(exact) < 19 + assert figures(stretch["days"]) == exact and stretch["days_checked"] == len(exact) + assert stretch["left_out"] == {"not held finely enough": 19 - len(exact)} and "note_left_out" in stretch and "note_daily" not in stretch + assert stretch["hours"]["text"] == "00:00–24:00" + + +# ---------- charts ---------- +def chart_of(out: dict) -> dict: + (chart,) = out["charts"] + return chart + + +async def test_a_figure_per_month_is_drawn_and_its_drawn_by_redraws_it_over_each_period_it_lists(world): + out = await ask(world, period="last 6 months", stat="sum", of="rain", group_by="month", chart_answers_it=True) + chart = chart_of(out) + assert out["chart_note"] == CHART_NOTE and "chart" not in out and out["by_month"] + assert chart["title"] == "Total rain" and chart["source"] == "Ecowitt weather station" + assert schema_errors({k: v for k, v in chart.items() if k != "drawn_by"}) == [] + drawn = chart["drawn_by"] + assert drawn == {"tool": "days", "arguments": {"where": [], "sort_by": "rain", "order": "desc", "count_only": False, "group_by": "month", + "stat": "sum", "of": "rain", "limit": 5, "period": "last 6 months", "chart_answers_it": True}, + "periods": [{"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}, {"period": "on record", "label": "All"}]} + again = await ask(world, **drawn["arguments"]) + assert chart_of(again) == chart + for p in drawn["periods"]: + redrawn = await ask(world, **{**drawn["arguments"], "period": p["period"]}) + assert "error" not in redrawn and chart_of(redrawn)["drawn_by"]["arguments"]["period"] == p["period"], p + assert chart_of(redrawn)["title"] == chart["title"] + assert out["reply"] == out["answer"] and out["complete"] is True # the chart is the whole answer (3.7) + assert out["answer"].startswith("Total rain: ") and " mm over 182 days (" in out["answer"] + + +async def test_a_chart_drawn_with_dates_names_them_as_its_period_and_per_year_it_lists_no_other(world): + out = await ask(world, start=str(ago(200)), end=str(ago(2)), where=[{"field": "rain", "op": ">=", "value": 1}], group_by="year") + drawn = chart_of(out)["drawn_by"] + assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to {ago(2).isoformat()}" and drawn["periods"] == [] + assert chart_of(await ask(world, **drawn["arguments"])) == chart_of(out) + assert "complete" not in out # (chart_answers_it wasn't set) + + +async def test_a_chart_is_not_the_whole_answer_when_a_note_needs_the_models_words(world): + out = await ask(world, period="on record", stat="max", of="temp_max", group_by="month", chart_answers_it=True) + assert "charts" in out and "note_daily" in out and "complete" not in out and "reply" not in out + averaged = await ask(world, period="last 6 months", where=[{"field": "humidity_max", "op": ">", "value": 70}], group_by="month", + chart_answers_it=True) + assert "note_averaged" in averaged and averaged["complete"] is True # (the answer line says it) + assert averaged["reply"].endswith("Older days use averages, so a count near the limit may fall slightly short.") + plain = await ask(world, period="past year", where=[{"field": "rain", "op": ">=", "value": 1}], chart_answers_it=True) + assert "charts" not in plain and "complete" not in plain # no chart, nothing complete + + +async def test_a_chart_of_part_of_each_day_lists_the_whole_record_only_while_it_is_within_400_days(world): + out = await ask(world, hours="night", period="3m", where=[{"field": "temp_min", "op": "<", "value": 12}], group_by="month") + drawn = chart_of(out)["drawn_by"] + assert drawn["arguments"]["hours"] == "night" and [p["period"] for p in drawn["periods"]] == ["3m", "1y"] # (548 days held) + assert "night (22:00–06:00)" in chart_of(out)["subtitle"] + for p in drawn["periods"]: + assert "error" not in await ask(world, **{**drawn["arguments"], "period": p["period"]}) + air = await ask(world, hours="afternoon", period="last 30 days", stat="avg", of="pm2_5_avg", group_by="month") + assert [p["period"] for p in chart_of(air)["drawn_by"]["periods"]] == ["3m", "1y", "on record"] # the air sensor's record is short + assert chart_of(air)["source"] == "AirGradient sensor" + for p in chart_of(air)["drawn_by"]["periods"]: + assert "error" not in await ask(world, **{**chart_of(air)["drawn_by"]["arguments"], "period": p["period"]}) + + +async def test_charts_are_sent_to_the_requests_budget(world): + args = {"period": "on record", "stat": "sum", "of": "rain", "group_by": "month"} + assert chart_of(await ask(world, {"chart_points": 500}, **args)) == chart_of(await ask(world, **args)) # (bars aren't bucketed) + both = await ask(world, period="last 30 days", where=[{"field": "rain", "op": ">=", "value": 0}, + {"field": "pm2_5_max", "op": ">", "value": 0}], group_by="month") + assert chart_of(both)["source"] == "Ecowitt weather station and AirGradient sensor" + replay = copy.deepcopy(chart_of(both)["drawn_by"]["arguments"]) + assert chart_of(await ask(world, **replay)) == chart_of(both) From 40d5113ed2873ca796252bed600ddf4467f295b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:34:27 +0000 Subject: [PATCH 028/125] lib/service/summary.py: the summary tool (3.3), over today's engines A period's figures from the weather station and the air sensor, and a chart of any readings from either or both, in place of weather_history, air_quality with dates and plot_chart. Not registered anywhere yet: tools(ctx) -> [ServiceTool]. - Arguments: readings (default outdoor and indoor temperature and humidity), period/start/end (default today; chart true alone, the last 24 hours), average, every_day, chart (on from 3 days), chart_readings (default all of readings; "all"; "air.pm2_5:rating"), layout (auto|panels|two_axes|same_axis), invert_second_axis, chart_answers_it. Unknown arguments, names, periods and layouts are refused with what to send instead. - Engines, given a Turn built from the arguments alone: HistoryQuery for the station (a subclass keeps its chart to the readings drawn, and works out the rain's bars when no chart did, so rain_total_mm is always the chart's total); AirGradient.history for the air sensor; Composer.plot_chart for a chart that mixes the sensors, draws a rating or uses same_axis (whole days to yesterday, said in a note and in the caption when the period is cut). Request _meta: background asks Ecowitt after the rest, fetch false asks it nothing, chart_points sizes the charts. - Result: series by service name, each record with low_text, low_when, low_date and that day's look (daylook over the day rows), averages, rows by day or month, wind direction, rain as the mm that fell (total, wettest day, rows), the air's ratings and AQI, notes, missing/warning; `caption` under a chart and `text` without one, in lib/report.py's words (chart_caption, the "extremes" lookup), ported; reply and complete when the chart answers it and no note needs the model's words. - Every chart carries drawn_by: the call as read (full names, every default, the period in words; whole-day dates as "A to B") and its periods (1D to 1Y; from 7D for each day's average; none for a time). lib/airgradient/source.py: history(daily=True) draws each whole day's average (the summary's `average`), off by default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/airgradient/source.py | 17 +- lib/service/summary.py | 863 ++++++++++++++++++++++++++++++++++ tests/test_service_summary.py | 464 ++++++++++++++++++ 3 files changed, 1337 insertions(+), 7 deletions(-) create mode 100644 lib/service/summary.py create mode 100644 tests/test_service_summary.py diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index d4f438bb..55743019 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -670,7 +670,8 @@ async def _with_spreads(self, rows: list[dict], day: date) -> list[dict]: return [{**r, "_range": {**ranges[r["ts"]], **r.get("_range", {})}} if r["ts"] in ranges else r for r in rows] async def history(self, start: str | None, end: str | None, chart: bool = False, - metrics: list[str] | None = None, turn: Turn | None = None) -> dict: + metrics: list[str] | None = None, turn: Turn | None = None, daily: bool = False) -> dict: + """daily: the chart draws each whole day's average, one point a day (an average was asked for: the summary tool's `average`).""" turn = turn or Turn() now = self.now() try: # a date the model sends, with or without an offset; a bad one is its mistake, not the sensor's @@ -710,7 +711,7 @@ async def history(self, start: str | None, end: str | None, chart: bool = False, if chart and rows: asked = metrics or turn.air_named or ["pm2_5"] # unnamed: the reading the person is asking about chart_spec = self._chart([m for m in (*ALL_METRICS, *EXTRA) if m in asked] or ["pm2_5"], rows, out["period"], - (t0.date(), t1.date())) + (t0.date(), t1.date()), daily) if chart_spec: turn.charts.append(chart_spec) out["chart"] = CHART_HINT @@ -731,7 +732,7 @@ def _entry(self, name: str, pts: list[tuple[int, float]], unit: str, span: tuple entry["average_aqi_us"], entry["average_band"] = pm25_aqi(entry["average"]) return entry - def _line(self, name: str, rows: list[dict]) -> tuple[Line, Plotted] | None: + def _line(self, name: str, rows: list[dict], daily: bool = False) -> tuple[Line, Plotted] | None: """One metric as a chart line, in its own units, and how it was drawn. The record high/low are the true readings. The readings themselves while they fit the point budget; more than that are bucketed (30 minutes ... a day): each bucket's mean, its range shaded.""" @@ -741,19 +742,21 @@ def _line(self, name: str, rows: list[dict]) -> tuple[Line, Plotted] | None: gap = max(60, round(statistics.median(b[0] - a[0] for a, b in pairwise(pts)))) spread = {r["ts"]: r["_range"][name] for r in rows if name in r and name in r.get("_range", {})} # what the bot saw in a bucket it recorded plotted = build_line([Sample(t, v, *(((min(spread[t][0], v), max(spread[t][1], v)) if t in spread else (None, None))), gap) - for t, v in pts], self.tz, pts[-1][0] - pts[0][0]) + for t, v in pts], self.tz, pts[-1][0] - pts[0][0], force_daily=daily, + until=self.now().date() if daily else None) if plotted is None: return None lo, hi = min(pts, key=lambda p: p[1]), max(pts, key=lambda p: p[1]) line = plotted.spec(LABELS.get(name) or EXTRA_LABELS[name], {"high": hi, **({"low": lo} if name in MARK_LOW else {})}, name) - line.on_line = True # the readings themselves marked where they peak, as the answer gives them, not the top of the shading (one sample inside a reading) + line.on_line = not daily # the readings themselves marked where they peak, as the answer gives them, not the top of the shading (one sample inside a reading); a day's average has the day's range as its band return line, plotted - def _chart(self, names: list[str], rows: list[dict], period: str, days: tuple[date, date] | None = None) -> Chart | None: + def _chart(self, names: list[str], rows: list[dict], period: str, days: tuple[date, date] | None = None, + daily: bool = False) -> Chart | None: """These metrics as one chart. One metric is drawn large, with its rating zones. Several go into panels on a shared time axis, grouped by AIR_PANELS (the particles together, the rest each alone). `period` is the subtitle's text for it, `days` its first and last day (for the caption).""" - drawn = {n: got for n in names if (got := self._line(n, rows))} + drawn = {n: got for n in names if (got := self._line(n, rows, daily))} if not drawn: return None if len(drawn) == 1: diff --git a/lib/service/summary.py b/lib/service/summary.py new file mode 100644 index 00000000..a993a420 --- /dev/null +++ b/lib/service/summary.py @@ -0,0 +1,863 @@ +"""The `summary` tool (docs/mcp-service.md 3.3): a period's figures from the weather station and the air sensor, each reading's lowest +and highest with when and that day's look, averages, a breakdown by day or by month, wind direction, the rain that fell, the air's +ratings and AQI, and a chart of any readings from either sensor or both. It replaces weather_history, air_quality with dates and +plot_chart, and wraps their engines, each given only what this tool's arguments say (a Turn built from them, never from words): + + - the station's readings: lib/ecowitt/query.py's HistoryQuery, as Ecowitt._history runs it (`_Query` keeps its chart to the readings + drawn, and works out the rain that fell when no chart did); + - the air sensor's: AirGradient.history (air_quality with dates); + - a chart that mixes the two sensors, draws a rating (`air.pm2_5:rating`) or puts readings on one axis (`same_axis`): + Composer.plot_chart, which draws whole days up to yesterday. + +The result (3.3): {period, as_of, fresh, series: {"outdoor.temperature": {unit, low, low_text, low_when, low_date, low_day_look, +[low_note], high…, [average, average_text], [daily|monthly]}, "air.pm2_5": {…, average, high_rating, average_rating, high_aqi_us, +high_band, average_aqi_us, average_band}, "wind.wind_direction": {most_common, then, steadiness, [daily]}, "rainfall.rain": {unit, +total, total_text, [wettest_day], [daily|monthly]}}, [rain_total_mm], [monthly_note], [note_no_readings], [note_chart], [notes], +[missing, warning], [caption] or [text], [chart_note, charts], [reply, complete]}. + +Words for the person, as the bot writes them today from weather_history's and air_quality's results (lib/report.py, its wording ported +here, as the bot's code goes): `caption` under a chart (report.chart_caption), and `text` when there is none (report.lookup's +"extremes"). Each chart carries `drawn_by`, the call that draws it again, and the periods it is worth drawing over (3.7). +""" + +import json +import re +from collections.abc import Callable +from dataclasses import dataclass +from datetime import date, datetime, time, timedelta + +from ..captions import CHART_MIN_DAYS +from ..compose import MAX_PANELS, Composer +from ..ecowitt.api import CYCLES, daily_run, kept_from, unit_text +from ..ecowitt.days import day_values_on +from ..ecowitt.fetch import Fetcher +from ..ecowitt.query import DERIVED, HistoryQuery +from ..ecowitt.reads import Held, readings_on, slot_values_on +from ..periods_text import Period +from ..series import AIR, WEATHER, find +from ..specs import AIR_SOURCE, ECOWITT_SOURCE, Bars, Chart +from ..storage.catalogue import KINDS, field_of +from ..timeutil import clock_text, day_text, local_date, to_local +from ..tools import Turn +from .common import BACKGROUND, Refusal, ServiceTool, answer, complete, period_properties, read_period, with_charts +from .context import Context +from .daylook import FIGURES, day_look +from .names import AIR_DEVICE, STATION, Reading + +NAME = "summary" +DEFAULT_READINGS = ("temperature", "humidity") # the station's usual set: outdoor and indoor temperature and humidity +LAYOUTS = ("auto", "panels", "two_axes", "same_axis") +RATING = ":rating" +AIR_QUALITY = tuple(AIR) # the air sensor's readings that have a rating (its own temperature and humidity have none) +# The periods a chart of readings over time is worth drawing over (3.7); one of each day's average needs two whole days at least +OVER_TIME = ({"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}, {"period": "1m", "label": "1M"}, + {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) +DAILY_MEANS = OVER_TIME[1:] +DAILY_ALL_DAYS = 7 # as HistoryQuery: a longer period lists only the days of its records, unless every_day +# The notes a caption carries itself (lib/bot.py CAPTIONED_NOTES for weather_history and air_quality): any other needs the model's words +CAPTIONED = {"missing", "warning"} +AIR_CAPTIONED = {"missing"} +DATE = re.compile(r"\d{4}-\d\d-\d\d") + +DESCRIPTION = ( + "A period's figures from the Ecowitt weather station and the AirGradient air sensor: each reading's lowest and highest with " + "when they happened and that day's look, averages, a breakdown by day (up to 31 days) or by month, wind direction, the rain " + "that fell, air ratings and AQI; and a chart of any readings from either sensor or both.\n" + "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; \"coldest on record\" " + "{readings: [\"outdoor.temperature\"], period: \"on record\"}; \"average humidity last month\" {readings: [\"humidity\"], " + "period: \"last month\", average: true}; \"rain since Monday\" {readings: [\"rain\"], period: \"since Monday\"}; \"plot " + "pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, chart_answers_it: true}; \"PM2.5 and rain, " + "3 months\" {readings: [\"pm2.5\", \"rain\"], period: \"3m\", chart: true}; \"weather all week\" {readings: [\"all\"], period: " + "\"this week\", chart: true}.\n" + "Not for: days ranked, counted or filtered by a day's figures (the wettest day, days over 35°C, rain per month): days. " + "Values at set times: readings. Rain against a reading: relate. Now: current. Ahead: forecast.\n" + "Reading it: `series` by reading name; quote low_text and high_text with their low_when and low_date as given, and a day's " + "day_look emoji beside it. rain_total_mm is the rain that fell. A note says what the figures lack. With a chart, `caption` is " + "its caption, ready; with complete: true, `reply` is the whole answer.") + + +def _boolean(description: str) -> dict: + return {"type": "boolean", "description": description} + + +ARGUMENTS = { # every argument but the readings and the period, as a model reads them + "average": _boolean("true when the question asks for an average or mean: adds each reading's average over the period (weighted " + "by time) and per day or month, and draws the chart as each day's average. Air readings always have theirs. " + "Default false."), + "every_day": _boolean("true to list every day of a period of up to 31 days; otherwise a period over 7 days lists only the days of " + "its lows and highs. Default false."), + "chart": _boolean("Draw a chart. Default: on for periods of 3 days or more."), + "chart_readings": {"type": "array", "items": {"type": "string"}, + "description": "What to draw, top to bottom, when not all of `readings`: names or words as for readings; \"all\" " + "is every weather-station reading in the station's usual order; add \":rating\" to an air-quality " + "reading to draw its traffic-light rating (\"air.pm2_5:rating\"). Default: all of readings."}, + "layout": {"type": "string", "enum": list(LAYOUTS), + "description": "auto (or panels): one reading as a line for each sensor that has it (wind with its compass rose), several " + "as a panel each on one time axis. two_axes: two readings on one panel, a scale each (or more in exactly two " + "units). same_axis: readings in one unit over each other. Default auto."}, + "invert_second_axis": _boolean("With layout two_axes: the right-hand scale runs top to bottom."), + "chart_answers_it": _boolean("true only when the question is just to see this chart and its figures: nothing else to answer (\"plot " + "pressure this week\", not \"plot pressure this week: is a storm coming?\"). Then the result carries the " + "finished reply (`reply`, `complete`: true)."), +} + + +def tools(ctx: Context) -> list[ServiceTool]: + return [Summary(ctx).tool] + + +# ---------- the call as read ---------- +@dataclass +class Call: + """A call as the tool read it: every argument resolved and every default filled in.""" + readings: list[Reading] + drawn: list[tuple[Reading, bool]] # chart_readings: each reading, and whether it is drawn as its rating + period: Period + when: dict # the period as drawn_by states it: {"period": words} or {"start", ["end"]} + average: bool + every_day: bool + chart: bool + layout: str + invert: bool + answers: bool # chart_answers_it + + @property + def replays(self) -> bool: + """Can the period be swapped for another (drawn_by.periods)? Words can; a start or end with a time can't.""" + return "period" in self.when + + def arguments(self) -> dict: + """The call as drawn_by states it: the readings' full names, the period in words, every default filled in.""" + return {"readings": [r.name for r in self.readings], **self.when, "average": self.average, "every_day": self.every_day, + "chart": True, "chart_readings": [r.name + (RATING if rating else "") for r, rating in self.drawn], + "layout": self.layout, "invert_second_axis": self.invert, "chart_answers_it": self.answers} + + +def _flag(args: dict, name: str) -> bool | None: + """A true-or-false argument: None when it isn't sent.""" + value = args.get(name) + if value is None or isinstance(value, bool): + return value + if str(value).strip().lower() in ("true", "false"): + return str(value).strip().lower() == "true" + raise Refusal(f"`{name}` is true or false, not {value!r}.") + + +def _words(raw) -> list[str]: + """The names in a readings argument: a list of them, or one string of them separated by commas or "and".""" + if raw is None: + return [] + items = raw if isinstance(raw, (list, tuple)) else [raw] + return [w for item in items for w in (part.strip() for part in re.split(r"[,;+&]| and ", str(item))) if w] + + +def _period_words(args: dict) -> dict: + """The period as drawn_by states it: words as sent; whole days ('YYYY-MM-DD' start and end, or a start alone) as words too ("2026-11-01 + to 2026-11-05", "2026-11-01 to now"), so another period can be swapped in; a start or end with a time as it came.""" + period, start, end = (str(args[k]).strip() if args.get(k) is not None and str(args[k]).strip() else None + for k in ("period", "start", "end")) + if start is None: + return {"period": period} + if DATE.fullmatch(start) and (end is None or DATE.fullmatch(end)): + return {"period": f"{start} to {end or 'now'}"} + return {"start": start, **({"end": end} if end else {})} + + +# ---------- what each engine calls a reading ---------- +def _engine_key(r: Reading) -> str: + """HistoryQuery's name for a station reading: its "group.field", as the group names it (rain is the running daily total, + "rainfall.daily"; indoor's apparent temperature "indoor.app_tempin").""" + return f"{r.sensor}.{field_of(r.sensor, r.column)}" + + +def _station_series(r: Reading) -> str | None: + """The station reading as HistoryQuery charts it (lib/series.py's name: temperature for both sides, wind for its speed, gusts and + direction), None for one it draws only alone (rain rate, absolute pressure, apparent temperature).""" + if r.sensor == "wind": + return "wind" + if r.combine == "rain": + return "rain" if r.sensor == "rainfall" else None + return r.series if r.series in WEATHER else None + + +def _composer_series(r: Reading) -> str | None: + """The reading as plot_chart names it, None when it can't draw it: the station's outdoor readings only (WEATHER), the air sensor's + all.""" + if r.device == AIR_DEVICE: + return r.column + if r.sensor == "wind": + return "wind" + if r.name == "rainfall.rain": + return "rain" + return r.series if r.series in WEATHER and WEATHER[r.series].group == r.sensor else None + + +def _number(raw): + """A figure as the station writes it ("12.3", "62") as a number.""" + try: + value = float(raw) + except (TypeError, ValueError): + return raw + return int(value) if str(raw).lstrip("-").isdigit() else value + + +def _text(value, unit: str) -> str: + return f"{value} {unit}".strip() + + +# ---------- the station's engine ---------- +class _HeldOnly(Fetcher): + """A Fetcher that asks Ecowitt for nothing: request _meta fetch false answers from what is held.""" + + async def _fetch(self, cycle, start, end, groups): + return None + + def sibling(self, groups: list[str]) -> "Fetcher": + return _HeldOnly(self.api, self.storage, self.recent, self.mac, groups, self.tz, self.urgent, self.has_minutes) + + +def _rain_on(r, mac: str, plan: list[tuple[str, int, int]], start: int, end: int) -> Held: + """The rain counter's reads for its bars, as history_on makes them when a chart has rain: its readings of the plan, its settled + 30-minute readings and its daily records.""" + held = Held({}, {}) + for cycle, a, b in plan: + readings_on(r, mac, ["rainfall"], cycle, a, b, held.store, ["daily"]) + held.rain = slot_values_on(r, mac, "rainfall", "daily", "30min", start, end)[0] + held.rain_daily = slot_values_on(r, mac, "rainfall", "daily", "1day", start - 86400, end + 86400)[0] + return held + + +class _Query(HistoryQuery): + """HistoryQuery as summary runs it: a chart only when the call draws one here (`drawn`), of the readings drawn alone (`keys`, its + "group.field" names; a reading that isn't drawn gives no line), and the rain's bars whenever rain is summarised, chart or not.""" + + def __init__(self, fetcher: Fetcher, args: dict, turn: Turn, *, drawn: bool, keys: set[str] | None): + super().__init__(fetcher, args, turn) + self.drawn, self.keys = drawn, keys + self.plan: list[tuple] = [] + + async def _hold_period(self): + self.plan = await super()._hold_period() + return self.plan + + def _drawing(self, plan): + return super()._drawing(plan) if self.drawn else ("none", 0) + + def _add_charts(self, out: dict, plottable: dict): + if self.drawn: + super()._add_charts(out, plottable) + + def _series_entry(self, k: str): + return None if self.keys is not None and k not in self.keys else super()._series_entry(k) + + async def rain(self) -> Bars: + """The rain that fell, in the bars a chart of the period draws (rain_bars): the chart's own, else worked out the same way.""" + if not self.rain_bars.x: + f = self.f + plan = [(cycle, f.epoch(a), f.epoch(b)) for cycle, a, b in self.plan] + held = await f.stored(_rain_on, f.mac, plan, f.epoch(self.start), f.epoch(self.end)) + self.store.setdefault("rainfall.daily", held.store.get("rainfall.daily", {"unit": "mm", "pts": {}})) + self.rain_bars = self._rain_bars(held) + return self.rain_bars + + +# ---------- the caption (lib/report.py's chart_caption, its wording kept) ---------- +def _year(text: str | None) -> str: + """"Tue 29 Sep 2026" -> "Tue 29 Sep".""" + return re.sub(r" 20\d\d\b", "", text or "") + + +def _period_line(text: str) -> str: + """"Tue 29 Sep 2026 - Tue 6 Oct 2026" -> "Tue 29 Sep – Tue 6 Oct 2026" (the first year is dropped only when it is the same year).""" + years = re.findall(r" (20\d\d)\b", text) + if len(years) == 2 and years[0] == years[1]: + text = re.sub(r" 20\d\d\b(?= - )", "", text) + return text.replace(" - ", " – ") + + +def _at(entry: dict, which: str) -> str: + """"24.3 °C, Tue 29 Sep around 3pm" for one record of a series.""" + when = _year(f"{entry.get(f'{which}_date', '')} {entry.get(f'{which}_when', '')}".strip()) + return f"{entry[which]} {unit_text(entry.get('unit')) or ''}".strip() + (f", {when}" if when else "") + + +def _range(label: str, entry: dict, average: bool) -> str: + unit = unit_text(entry.get("unit")) or "" + if average and entry.get("average"): + return f"{label}: average {entry['average']} {unit} (low {entry['low']}, high {entry['high']})".replace(" )", ")") + return f"{label}: low {_at(entry, 'low')} · high {_at(entry, 'high')}" + + +def _rain_line(charts: list[Chart], tz, bars: Bars | None = None) -> list[str]: + """Least and most rain in a period (the chart's own bars, else `bars`: those a chart of the period would draw).""" + bars = next((p.bars for c in charts for p in c.panels if p.bars and p.bars.x), bars) + if not bars or not bars.x: + return [] + + def day(i: int) -> str: + start = to_local(bars.x[i], tz) + return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") + lo, hi = min(range(len(bars.y)), key=bars.y.__getitem__), max(range(len(bars.y)), key=bars.y.__getitem__) + per = f" per {bars.per}" if bars.per else "" + return [f"☔ Rain{per}: least {bars.y[lo]:g} mm ({day(lo)}) · most {bars.y[hi]:g} mm ({day(hi)}) · {sum(bars.y):.1f} mm in all"] + + +def _weather_lines(series: dict, names: list[str], average: bool, charts: list[Chart], tz) -> list[str]: + """A line per series of each reading drawn (HistoryQuery's series: "group.field" names, figures as the station writes them).""" + lines: list[str] = [] + for name in [n for n in dict.fromkeys(names) if find(n)]: + reading = find(name) + keys = [k for k in series if k.split(".", 1)[1] == reading.field] + if reading.field == "daily": # rain: the amounts the chart draws + lines += _rain_line(charts, tz) + continue + for key in keys: + group = key.split(".", 1)[0] + label = reading.label + (f" ({group})" if len(keys) > 1 and group in ("outdoor", "indoor") else "") + if reading.field == "wind_speed": + gust = series.get(f"{group}.wind_gust") or series.get("wind.wind_gust") + lines.append(f"🌬️ Wind: strongest gust {_at(gust, 'high')}" if gust else _range(label, series[key], average)) + else: + lines.append(_range(label, series[key], average)) + if reading.field == "wind_speed" and (d := series.get("wind.wind_direction")): + lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) + return lines + + +def _air_lines(result: dict, metrics: list[str]) -> list[str]: + """A line per air-quality metric drawn (AirGradient.history's result): its peak, the peak's rating and the average.""" + lines = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = result.get(key) + if key not in (metrics or ["pm2_5"]) or not isinstance(entry, dict): + continue + unit = unit_text(entry.get("unit")) or "" + rating = entry.get("high_rating") + lines.append(f"• {label}: peak {entry['high']} {unit} ({_year(entry.get('high_time'))})".replace(" )", ")") + + (f" · {rating}" if rating else "") + f" · average {entry['average']}") + return lines + + +def _series_label(field: str) -> str: + """A series' name: its reading's label ("Temperature"), the gusts their own ("Wind gust").""" + if field == "wind_gust": + return "Wind gust" + return reading.label if (reading := find(field)) else field.replace("_", " ").capitalize() + + +def _extremes_lines(series: dict, names: list[str]) -> list[str]: + """The low and high (or the average) of each reading named, each with its day and time: wind, its speed and its gusts. A reading on + both sides (indoor, outdoor) has a line for each (lib/report.py's plain lookup of a weather_history result, "extremes").""" + wanted = [f for r in filter(None, map(find, names)) for f in (r.field, r.band_field) if f] or ["temperature"] + keys = [k for k in series if k.split(".", 1)[1] in wanted and "low" in series[k]] + fields = [k.split(".", 1)[1] for k in keys] + lines = [] + for key in keys: + group, field = key.split(".", 1) + label = _series_label(field) + (f" ({group})" if fields.count(field) > 1 else "") + lines.append(f"• {_range(label, series[key], 'average' in series[key])}") + return lines + + +def _caption(period: str, lines: list[str], note_missing: bool, warning: bool, more: list[str] = ()) -> str | None: + """The caption: the period, a line per reading, and what the figures lack; None with no line to write.""" + if not lines: + return None + notes = (["(Older days are still downloading, so they are left out.)"] if note_missing else + ["(Some data couldn't be fetched, so this may be incomplete.)"] if warning else []) + return "\n".join([_period_line(period), *lines, *more, *notes]).strip() + + +# ---------- the tool ---------- +class Summary: + def __init__(self, ctx: Context): + self.ctx = ctx + self.tool = ServiceTool(NAME, DESCRIPTION, self.parameters(), self.handle, open_world=True) + + def parameters(self) -> dict: + names = self.ctx.readings().description() + return {"type": "object", "properties": { + "readings": {"type": "array", "items": {"type": "string"}, + "description": f"What to summarise. {names} Default: outdoor and indoor temperature and humidity."}, + **period_properties("today; with chart true and no period, the last 24 hours"), + **ARGUMENTS}} + + # ---------- reading the call ---------- + async def read(self, args: dict) -> Call: + """The call as read, or a Refusal that teaches the right one.""" + ctx = self.ctx + props = self.tool.parameters["properties"] + if unknown := [k for k in args if k not in props]: + hint = " Send the period as `period` (words) or `start` and `end`." if {"start_date", "end_date"} & set(unknown) else \ + " Send the readings as `readings`." if {"metrics", "groups", "metric"} & set(unknown) else "" + raise Refusal(f"summary doesn't take {', '.join(map(repr, unknown))}.{hint}", arguments=list(props)) + catalogue = ctx.readings() + default = list(DEFAULT_READINGS) if ctx.eco else "air" + readings = catalogue.resolve(args.get("readings"), default=default) + drawn = self._drawn(args.get("chart_readings"), readings) + for r in {r for r in [*readings, *(r for r, _ in drawn)]}: + if (r.device == STATION and ctx.eco is None) or (r.device == AIR_DEVICE and ctx.air is None): + device = "weather station" if r.device == STATION else "air sensor" + raise Refusal(f"There is no {device} here, so {r.name} can't be read.", names=catalogue.names) + layout = str(args.get("layout") or "auto").strip().lower() + if layout not in LAYOUTS: + raise Refusal(f"`layout` is one of {', '.join(LAYOUTS)}, not {args.get('layout')!r}.", layouts=list(LAYOUTS)) + chart = _flag(args, "chart") + asked = any(str(args.get(k) or "").strip() for k in ("period", "start", "end")) + period = read_period(args, tz=ctx.zone, now=ctx.now(), default="last 24 hours" if chart and not asked else "today", + first_held=await self._first_held([*readings, *(r for r, _ in drawn)])) + long = (period.last_day - period.first_day).days >= CHART_MIN_DAYS - 1 + when = _period_words(args) if asked else {"period": period.asked} + return Call(readings, drawn, period, when, bool(_flag(args, "average")), bool(_flag(args, "every_day")), + long if chart is None else chart, layout, bool(_flag(args, "invert_second_axis")), bool(_flag(args, "chart_answers_it"))) + + def _drawn(self, raw, readings: list[Reading]) -> list[tuple[Reading, bool]]: + """chart_readings as read: each reading named (words too; "all"), in order, each once, with whether it is drawn as its rating.""" + words = _words(raw) + if not words: + return [(r, False) for r in readings] + out: dict[tuple[str, bool], tuple[Reading, bool]] = {} + for word in words: + rating = word.lower().endswith(RATING) + base = word[:-len(RATING)].strip() if rating else word + for r in self.ctx.readings().resolve(base, default=base): + if rating and (r.device != AIR_DEVICE or r.column not in AIR_QUALITY): + raise Refusal(f"Only the air sensor's air-quality readings have a rating ({', '.join(f'air.{m}' for m in AIR_QUALITY)}): " + f"{r.name} can't be drawn as one. Draw it as it is: {r.name!r}.") + out.setdefault((r.name, rating), (r, rating)) + if not out: + raise Refusal(f"chart_readings names no reading: send names or words as for readings, such as \"pressure\" or " + f"\"air.pm2_5{RATING}\".", names=self.ctx.readings().names) + return list(out.values()) + + async def _first_held(self, readings: list[Reading]) -> date | None: + """The first day held of these readings' sensors ("on record" starts there).""" + ctx, storage = self.ctx, self.ctx.storage + if storage is None: + return None + groups = sorted({r.sensor for r in readings if r.device == STATION}) + air = any(r.device == AIR_DEVICE for r in readings) and ctx.air is not None + + def first(r) -> date | None: + sensors = [s for g in groups if ctx.eco and (s := r.sensor(ctx.eco.mac, g)) is not None and s.kind in KINDS] + if air and (s := ctx.air.store.sensor) is not None: + sensors.append(s) + days = [r.db.execute(f"SELECT MIN(day) FROM {s.kind}_day WHERE sensor = ?", (s.id,)).fetchone()[0] for s in sensors] + return min((date.fromisoformat(d) for d in days if d), default=None) + return await storage.read(first) + + def _route(self, call: Call) -> str | None: + """Which engine draws the chart: "station" (HistoryQuery), "air" (AirGradient.history), "composer" (plot_chart), or None + (no chart). Refuses a chart that can't be drawn as asked, saying what can.""" + if not call.chart: + return None + station = [r for r, _ in call.drawn if r.device == STATION] + air = [r for r, _ in call.drawn if r.device == AIR_DEVICE] + rating = any(rating for _, rating in call.drawn) + if call.invert and call.layout != "two_axes": + raise Refusal("invert_second_axis needs layout two_axes: it turns the right-hand scale upside down.") + lines = [(r, rating) for r, rating in call.drawn if r.reading != "wind_direction"] + if call.layout in ("two_axes", "same_axis") and (rating or any(r.combine == "rain" for r, _ in lines)): + raise Refusal(f"layout {call.layout} draws lines: rain (bars) and ratings can't share a panel. Use layout auto, a panel each.") + composer = (station and air) or rating or call.layout == "same_axis" or (air and call.layout == "two_axes") + if composer: + if self.ctx.eco is None: + raise Refusal(f"layout {call.layout} is drawn only where there is a weather station: use layout auto.") + if bad := [r.name for r, _ in lines if _composer_series(r) is None]: + drawable = [r.name for r in self.ctx.readings() if _composer_series(r)] + raise Refusal(f"{', '.join(bad)} can't go on a chart that mixes the two sensors, draws a rating or uses same_axis: such a " + f"chart draws only these readings. Draw {', '.join(bad)} in a call of its own.", drawable=drawable) + series = list(dict.fromkeys((_composer_series(r), rating) for r, rating in lines)) + if len(series) > MAX_PANELS: + raise Refusal(f"A chart that mixes the two sensors, draws a rating or uses same_axis takes at most {MAX_PANELS} readings, " + f"not {len(series)}: draw the rest in another call.") + if call.layout in ("two_axes", "same_axis") and len(series) < 2: + raise Refusal(f"layout {call.layout} needs two readings or more in chart_readings (it puts them on one panel).") + return "composer" + if station: + if any(r.sensor == "rainfall_piezo" for r in station): + raise Refusal("The piezo rain gauge isn't drawn: draw rainfall.rain, the main gauge.") + series = list(dict.fromkeys(_station_series(r) or r.name for r in station)) + alone = [r.name for r in station if _station_series(r) is None] + if alone and len(series) > 1: + raise Refusal(f"{', '.join(alone)} can only be drawn on a chart of its own: send it alone in chart_readings.") + if call.layout == "two_axes" and len(series) < 2: + raise Refusal("layout two_axes needs two readings or more in chart_readings (it puts them on one panel, a scale each); " + "outdoor and indoor of one reading are already one panel.") + return "station" + return "air" + + # ---------- answering ---------- + async def handle(self, args: dict, meta: dict) -> str: + ctx = self.ctx + call = await self.read(args) + route = self._route(call) + if route == "composer" and self._whole_days(call) is None: + yesterday = ctx.now().date() - timedelta(days=1) + raise Refusal(f"A chart that mixes the two sensors, draws a rating or uses same_axis is drawn over whole days, up to " + f"yesterday ({day_text(yesterday)}): {call.period.text} has none. Ask for a period with whole days ('last 24 " + f"hours' draws yesterday, 'last 7 days'), or leave the chart out.") + background, fetch = meta.get("priority") == BACKGROUND, meta.get("fetch", True) + station = [r for r in call.readings if r.device == STATION] + air = [r for r in call.readings if r.device == AIR_DEVICE] + drawn_station = [r for r, _ in call.drawn if r.device == STATION] if route in ("station", "composer") else [] + drawn_air = [r for r, _ in call.drawn if r.device == AIR_DEVICE] if route in ("air", "composer") else [] + charts: list[Chart] = [] + found: dict = {"missing": [], "warning": False, "notes": {}} + q = out = None + if station or drawn_station: + q, out = await self._station(call, station, drawn_station, route == "station", background, fetch, charts, found) + air_out = None + if air or drawn_air: + figures = list(dict.fromkeys([*air, *(drawn_air if route == "composer" else [])])) + air_out = await self._air(call, figures, drawn_air if route == "air" else [], charts, found) + if route == "composer": + await self._compose(call, charts, found) + looks = await self._looks(call.period.first_day, call.period.last_day) + series, no_readings = {}, [] + rain_total = None + for r in call.readings: + if r.device == STATION: + entry = await self._station_entry(r, q, out, looks, call) if q else None + if r.name == "rainfall.rain" and entry: + rain_total = entry["total"] + else: + entry = self._air_entry(r, air_out, looks) + if entry: + series[r.name] = entry + else: + no_readings.append(r.name) + if not series and not charts: + first = await self._first_held(call.readings) + raise Refusal(f"Nothing is held of {', '.join(no_readings)} for {call.period.text}." + + (f" What is held starts on {day_text(first)}." if first else ""), + **({"held_from": first.isoformat()} if first else {}), + **({"missing": found["missing"][:10]} if found["missing"] else {})) + fields: dict = {"series": series} + if rain_total is not None: + fields["rain_total_mm"] = rain_total + if out and out.get("monthly_note"): + fields["monthly_note"] = out["monthly_note"] + if no_readings: + fields["note_no_readings"] = (f"Nothing held of {', '.join(no_readings)} for this period: say so." if not series else + f"Nothing held of {', '.join(no_readings)} for this period; the others are summarised.") + if call.chart and not charts and "chart" not in found["notes"]: + fields["note_chart"] = ("No chart: an average chart draws each whole day's average, and this period has fewer than two whole " + "days before today." if call.average else "No chart: too few readings to draw for this period.") + if found["notes"]: + fields["notes"] = found["notes"] + if found["missing"]: + fields["missing"] = found["missing"][:10] + if found["warning"]: + fields["warning"] = "Some data could not be fetched; the answer may be incomplete. Say so." + caption = self._caption(call, route, charts, out, air_out, found) if charts else None + if caption: + fields["caption"] = caption + elif not charts and (text := self._text(call, q, out, air_out)): + fields["text"] = text + finished = call.answers and charts and caption and not self._needs_words(fields) + fields.update(self._charts(call, route, charts, meta)) + if finished: + fields.update(complete(caption)) + return answer(period=call.period, as_of=ctx.now(), **fields) + + async def _station(self, call: Call, station: list[Reading], drawn: list[Reading], here: bool, background: bool, fetch: bool, + charts: list[Chart], found: dict) -> tuple[_Query | None, dict | None]: + """HistoryQuery over the station's readings summarised and drawn, drawing its chart when `here`.""" + eco = self.ctx.eco + every = [*station, *drawn] + groups = list(dict.fromkeys(r.sensor for r in every)) + named = [s for s in dict.fromkeys(_station_series(r) or r.column for r in drawn if here)] + series_names = list(dict.fromkeys(_station_series(r) or r.column for r in every)) + turn = Turn(chart_asked=here, chart_field=named[0] if len(named) == 1 else None, chart_fields=named if len(named) > 1 else [], + two_axes=here and call.layout == "two_axes", average_asked=call.average, per_day=call.every_day, + readings=series_names, text="", ahead=background) + start, end = call.period.as_naive_strings() + args = {"start_date": start, "end_date": end, "average": call.average, + "include_derived": sorted({r.column for r in every if r.column in DERIVED})} + make = Fetcher if fetch else _HeldOnly + fetcher = make(eco.api, eco.storage, eco.fetches, eco.mac, groups, eco.tz, not background, eco.has_minutes) + keys = {k for r in drawn for k in (("wind.wind_speed",) if r.sensor == "wind" else (_engine_key(r),))} if here else None + q = _Query(fetcher, args, turn, drawn=here, keys=keys) + text = await q.run() + if text.startswith("Error"): + if "within the last" in text: # (the period's start is checked against the history kept: only one before it all is refused) + start = kept_from("1day", self.ctx.now().date()) + raise Refusal(f"The weather station's history goes back {CYCLES['1day'].kept // 365} years, to {day_text(start)}: " + f"{call.period.text} is before it.", held_from=start.isoformat()) + if "Details: " in text: # nothing held, and what was asked for couldn't be fetched + found["missing"] += text.split("Details: ", 1)[1].split("; ") + found["warning"] = True + return None, None + out = json.loads(text) + for chart in turn.charts: + chart.source = chart.source or ECOWITT_SOURCE + if call.invert: + for panel in chart.panels: + panel.flip_right = panel.flip_right or any(line.right for line in panel.lines) + charts += turn.charts + if out.get("missing"): + found["missing"] += out["missing"] + found["warning"] = found["warning"] or bool(out.get("warning")) + if any(r.name == "rainfall.rain" for r in station): + await q.rain() + return q, out + + async def _air(self, call: Call, figures: list[Reading], drawn: list[Reading], charts: list[Chart], found: dict) -> dict | None: + """AirGradient.history over the air readings whose figures are wanted (and drawn, when the chart is the air sensor's alone). Its + `metrics` are what it draws, and bring in its own temperature and humidity: a reading summarised but not drawn that is one of + those takes a call of its own.""" + start, end = call.period.as_naive_strings() + metrics = [r.column for r in drawn] + wanted = [r.column for r in figures] + out: dict = {} + try: + if drawn: + turn = Turn(air_named=metrics) + out = await self.ctx.air.history(start, end, chart=True, metrics=metrics, turn=turn, daily=call.average) + for chart in turn.charts: + chart.source = chart.source or AIR_SOURCE + charts += turn.charts + if not drawn or (out.get("readings") and any(m not in out for m in wanted)): + more = await self.ctx.air.history(start, end, chart=False, metrics=wanted or None, turn=Turn()) + out = {**more, **out} if drawn else more + except Exception as e: # the sensor or its cloud is down: the station's figures still stand + found["missing"].append(f"air sensor: {type(e).__name__}: {e}") + found["warning"] = True + return None + if "error" in out: + found["missing"].append(f"air sensor: {out['error']}") + return None + notes = {k.removeprefix("note_") if k != "note" else "none": v for k, v in out.items() if k == "note" or k.startswith("note_")} + if notes: + found["notes"]["air"] = notes + return out + + async def _compose(self, call: Call, charts: list[Chart], found: dict): + """The chart plot_chart draws: whole days up to yesterday, so a period that runs into today is cut, and said so.""" + ctx = self.ctx + composer = ctx.composer or Composer(ctx.eco, ctx.air) + first, last = self._whole_days(call) + panels, seen = [], set() + for r, rating in call.drawn: + name = _composer_series(r) + if name is None or (r.reading == "wind_direction") or (name, rating) in seen: + continue + seen.add((name, rating)) + panels.append({"series": name, "style": "rating" if rating else "bars" if name == "rain" else "line"}) + args = {"panels": panels, "start_date": first.isoformat(), "end_date": last.isoformat(), + "two_axes": call.layout == "two_axes", "same_axis": call.layout == "same_axis", "invert_second_axis": call.invert} + turn = Turn() + result = json.loads(await composer.plot_chart(args, turn)) + if "error" in result: # (what plot_chart refuses is checked first: this is a reading it has nothing of) + found["notes"]["chart"] = f"No chart: {result['error'].rstrip('.')}." + return + for chart in turn.charts: # the devices its readings come from (plot_chart leaves out a rating's) + chart.source = " and ".join(name for name, device in ((ECOWITT_SOURCE, STATION), (AIR_SOURCE, AIR_DEVICE)) + if any(r.device == device for r, _ in call.drawn)) + charts += turn.charts + cut, early = last < call.period.last_day, call.period.start.time() != time() + if cut or early: # (the air sensor's own notes on the days it lacks are in its figures' notes already) + found["notes"]["chart"] = (f"The chart draws whole days, {day_text(first, year=False)} to {day_text(last, year=False)}" + + (": a chart that mixes the two sensors, draws a rating or uses same_axis is drawn over whole days " + "up to yesterday, as today isn't over" if cut else "") + ".") + + def _whole_days(self, call: Call) -> tuple[date, date] | None: + """The first and last day plot_chart draws for this period: its days up to yesterday (None when that leaves none).""" + first, last = call.period.first_day, min(call.period.last_day, self.ctx.now().date() - timedelta(days=1)) + return (first, last) if first <= last else None + + async def _looks(self, first: date, last: date) -> Callable[[date | None], dict | None]: + """day -> its look (daylook.day_look over its day row's figures), for the days of the period; nothing without the station.""" + eco = self.ctx.eco + if eco is None: + return lambda day: None + days = [first + timedelta(days=n) for n in range((last - first).days + 1)] + values, _ = await eco.storage.read(day_values_on, eco.mac, list(FIGURES), days) + today = self.ctx.now().date() + + def look(day: date | None) -> dict | None: + if day is None: + return None + return day_look({n: values[n].get(day) for n in FIGURES}, latitude=eco.latitude, day=day, so_far=day >= today) + return look + + # ---------- the figures ---------- + async def _station_entry(self, r: Reading, q: _Query, out: dict, looks, call: Call) -> dict | None: + """One station reading as the service gives it.""" + key = _engine_key(r) + if r.name == "rainfall.rain": + return await self._rain_entry(q, looks, call) if key in q.units else None + got = (out.get("series") or {}).get(key) or q.direction.get(key) + if not got: + return None + if r.combine == "rain": # the piezo gauge: its running daily total, whose highest is a day's total + got = {k: v for k, v in got.items() if not k.startswith("low")} | { + "how_to_read": "The gauge's running daily total: its high is the most rain in a day. Its total over the period is " + "rainfall.rain's, the main gauge."} + if r.reading == "wind_direction": + return {k: got[k] for k in ("most_common", "then", "average_direction", "steadiness", "calm", "note", "note_period", "daily") + if k in got} + unit = unit_text(got.get("unit")) or r.unit + entry = {"unit": unit} + for want in ("low", "high"): + if want not in got: + continue + ext = q.overall.get(key, {}).get(want) + entry[want] = _number(got[want]) + entry[f"{want}_text"] = _text(got[want], unit) + entry[f"{want}_when"] = got[f"{want}_when"] + if got.get(f"{want}_date"): + entry[f"{want}_date"] = got[f"{want}_date"] + if ext and (look := looks(local_date(ext.ts, q.tz))): + entry[f"{want}_day_look"] = look + if f"{want}_note" in got: + entry[f"{want}_note"] = got[f"{want}_note"] + if "average" in got: + entry["average"], entry["average_text"] = _number(got["average"]), _text(got["average"], unit) + if "how_to_read" in got: + entry["how_to_read"] = got["how_to_read"] + days = {q._label(d.day): d.day for d in q.period[key].days} if key in q.period else {} + if "daily" in got: + entry["daily"] = {label: {**{w: _number(v) for w, v in row.items() if w in ("low", "high")}, + **({"average": _number(row["avg"])} if "avg" in row else {}), + **({"day_look": look} if (look := looks(days.get(label))) else {})} + for label, row in got["daily"].items()} + if "monthly" in got: + monthly = {} + for label, row in got["monthly"].items(): + month = {w: _number(row[w]) for w in ("low", "high") if w in row} + for w in ("low", "high"): + if row.get(f"{w}_date"): + month[f"{w}_when"], month[f"{w}_date"] = row[f"{w}_when"], row[f"{w}_date"] + ext = q.monthly.get(key, {}).get(label, {}).get(w) + if ext and (look := looks(local_date(ext.ts, q.tz))): + month[f"{w}_day_look"] = look + if "avg" in row: + month["average"] = _number(row["avg"]) + monthly[label] = month + entry["monthly"] = monthly + return entry + + async def _rain_entry(self, q: _Query, looks, call: Call) -> dict: + """Rain as the mm that fell: the total, the wettest day, and a row per day or month (each the sum of the chart's bars in it).""" + bars = await q.rain() + total = round(sum(bars.y), 1) + per_day: dict[date, float] = {} + rows: dict[str, float] = {} + for t, mm in zip(bars.x, bars.y): + day = local_date(t, q.tz) + per_day[day] = per_day.get(day, 0.0) + mm + rows[q._label(day)] = rows.get(q._label(day), 0.0) + mm + entry: dict = {"unit": "mm", "total": total, "total_text": f"{total:.1f} mm"} + wettest = max(per_day, key=per_day.get) if per_day and max(per_day.values()) > 0 else None + if wettest: + mm = round(per_day[wettest], 1) + entry["wettest_day"] = {"date": day_text(wettest), "mm": mm, "text": f"{mm:.1f} mm", + **({"day_look": look} if (look := looks(wettest)) else {})} + if q.by_day: + keep = None if len(per_day) <= DAILY_ALL_DAYS or call.every_day else {wettest} + entry["daily"] = {q._label(day): {"total": round(mm, 1), **({"day_look": look} if (look := looks(day)) else {})} + for day, mm in per_day.items() if keep is None or day in keep} + else: + entry["monthly"] = {label: {"total": round(mm, 1)} for label, mm in rows.items()} + if q.rain_from_daily: + entry["note"] = (f"Older days come from Ecowitt's daily records, which run {daily_run(q.tz, q.start.date(), q.end.date())}, " + f"so their rain may fall on the day before.") + return entry + + def _air_entry(self, r: Reading, out: dict | None, looks) -> dict | None: + """One air reading as the service gives it: AirGradient.history's figures with their wording.""" + got = (out or {}).get(r.column) + if not isinstance(got, dict): + return None + unit = unit_text(got.get("unit")) or r.unit + entry = {"unit": unit} + for want in ("low", "high"): + entry[want] = got[want] + entry[f"{want}_text"] = _text(got[want], unit) + try: + at = datetime.strptime(got.get(f"{want}_time") or "", "%a %d %b %Y %I:%M%p") + except ValueError: + continue + entry[f"{want}_when"], entry[f"{want}_date"] = f"at {clock_text(at, whole_hours=True)}", day_text(at) + if look := looks(at.date()): + entry[f"{want}_day_look"] = look + entry["average"], entry["average_text"] = got["average"], _text(got["average"], unit) + for k in ("high_rating", "average_rating", "high_aqi_us", "high_band", "average_aqi_us", "average_band"): + if k in got: + entry[k] = got[k] + return entry + + # ---------- the chart's words and its replay ---------- + def _caption(self, call: Call, route: str, charts: list[Chart], out: dict | None, air_out: dict | None, found: dict) -> str | None: + """What lib/report.chart_caption writes under this chart today: the period, a line per reading drawn, and what the figures + lack. A chart plot_chart draws (no caption today) is written the same way, each reading's line as its own tool's, with the + chart's period when it is cut.""" + tz = self.ctx.zone + series = (out or {}).get("series") or {} + drawn_keys = {k for r, _ in call.drawn if r.device == STATION + for k in ((("wind.wind_speed", "wind.wind_gust", "wind.wind_direction") if r.sensor == "wind" else (_engine_key(r),)))} + series = {k: v for k, v in series.items() if k in drawn_keys} + lines: list[str] = [] + if route == "air": + lines = _air_lines(air_out or {}, [r.column for r, _ in call.drawn]) + elif route == "station": + names = list(dict.fromkeys(_station_series(r) or r.column for r, _ in call.drawn)) + lines = _weather_lines(series, names, call.average, charts, tz) + else: + for r, _ in call.drawn: + if r.device == AIR_DEVICE: + line = _air_lines(air_out or {}, [r.column]) + else: + line = _weather_lines(series, [_composer_series(r) or ""], call.average, charts, tz) + lines += [x for x in line if x not in lines] + period = (out or air_out or {}).get("period", "") + more = [f"({found['notes']['chart']})"] if route == "composer" and "chart" in found["notes"] else [] + return _caption(period, lines, bool(air_out and air_out.get("note_missing")), bool(found["warning"]), more) + + def _text(self, call: Call, q: _Query | None, out: dict | None, air_out: dict | None) -> str | None: + """The figures in words, ready to send, when no chart is drawn: the period, then each station reading's low and high (or its + average) with its day and time, as the bot writes a weather_history lookup today ("extremes"); rain as the least and most in a + day (or hour, or 6 hours) and its total, as under a rain chart; each air-quality reading's peak, rating and average.""" + station = [r for r in call.readings if r.device == STATION] + ranged = [r for r in station if r.combine != "rain" and r.reading != "wind_direction"] + names = list(dict.fromkeys(name for r in ranged if (name := _station_series(r)))) + series = (out or {}).get("series") or {} + lines = [] + if names: + keys = {k for r in ranged for k in (("wind.wind_speed", "wind.wind_gust") if r.name == "wind.wind_speed" else (_engine_key(r),))} + lines += _extremes_lines({k: v for k, v in series.items() if k in keys}, names) + if (any(r.reading == "wind_direction" for r in station) and not any(r.name == "wind.wind_speed" for r in station) + and (d := series.get("wind.wind_direction"))): # (with the speed, as under a wind chart, the direction is the chart's) + lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) + if q and any(r.name == "rainfall.rain" for r in station) and "rainfall.daily" in q.units: + lines += _rain_line([], q.tz, q.rain_bars) + if air_out: + lines += _air_lines(air_out, [r.column for r in call.readings if r.device == AIR_DEVICE]) + period = (out or air_out or {}).get("period", "") + return "\n".join([_period_line(period), *lines]) if lines else None + + @staticmethod + def _needs_words(fields: dict) -> bool: + """Does the result carry a note the caption leaves out (lib/bot.py _needs_words)? Then the model answers.""" + top = {k for k in fields if k != "notes" and (k.startswith("note") or k.endswith("_note") or k in ("warning", "missing"))} + notes = fields.get("notes") or {} + air = set(notes.get("air") or {}) + return bool(top - CAPTIONED or air - AIR_CAPTIONED or set(notes) - {"air", "chart"}) + + def _charts(self, call: Call, route: str | None, charts: list[Chart], meta: dict) -> dict: + """The charts as data (common.with_charts), each with drawn_by: the call that draws it again and the periods it is worth + drawing over (3.7): readings over time, 1D to 1Y (a chart of each day's average from 7D); none for a start or end with a time.""" + fields = with_charts(charts, self.ctx.zone, meta) + if not fields: + return {} + daily = call.average and route in ("station", "air") # (plot_chart draws its readings, average or not) + periods = list(DAILY_MEANS if daily else OVER_TIME) if call.replays else [] + drawn_by = {"tool": NAME, "arguments": call.arguments(), "periods": periods} + for chart in fields["charts"]: + chart["drawn_by"] = drawn_by + return fields + + +__all__ = ["DESCRIPTION", "Summary", "tools"] diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py new file mode 100644 index 00000000..aec73733 --- /dev/null +++ b/tests/test_service_summary.py @@ -0,0 +1,464 @@ +"""The `summary` tool (lib/service/summary.py): its arguments and defaults, the shape of what it answers, the refusals that teach, the +periods it reads, its charts with drawn_by (replayed, and over every period it lists), and the caption the bot writes today for the same +chart (lib/report.py), word for word.""" + +import json +from datetime import datetime, timedelta + +from lib import report +from lib.airgradient import AirGradient +from lib.bot import _as_drawn +from lib.compose import Composer +from lib.ecowitt.days import day_values_on +from lib.service import summary +from lib.service.common import FRESH, ServiceTool +from lib.service.context import Context +from lib.service.daylook import FIGURES, day_look +from lib.tools import Turn +from tests.fakes import TZ, air_transport, archived_station, config +from tests.test_chart_json import errors as schema_errors + + +async def make(tmp_path, archived_cache, air: bool = False, **air_options): + """(the tool, its Context, the fake Ecowitt): the archived station, and with `air` an AirGradient on the same file.""" + eco, fake = await archived_station(tmp_path, archived_cache) + source = None + if air: + transport, _ = air_transport(**{"rows_per_day": 288, **air_options}) + source = AirGradient(config(tmp_path), transport=transport, storage=eco.storage) + await source.start() + ctx = await Context.open(eco=eco, air=source, composer=Composer(eco, source) if source else None) + return summary.tools(ctx)[0], ctx, fake + + +async def close(ctx): + if ctx.air: + await ctx.air.close() + await ctx.eco.close() + + +async def ask(tool: ServiceTool, meta: dict | None = None, **args) -> dict: + return json.loads(await tool.call(args, meta)) + + +def without_drawn_by(chart: dict) -> dict: + return {k: v for k, v in chart.items() if k != "drawn_by"} + + +def days_ago(n: int) -> str: + return str(datetime.now(TZ).date() - timedelta(days=n)) + + +# ---------- the tool ---------- +async def test_the_tool_says_what_it_answers_what_it_is_not_for_and_how_to_read_it(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + assert tool.name == "summary" and tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + assert list(tool.parameters["properties"]) == ["readings", "period", "start", "end", "average", "every_day", "chart", "chart_readings", + "layout", "invert_second_axis", "chart_answers_it"] + text = tool.description + assert len(text) <= 1500 + for words in ("{readings: [\"temperature\"], period: \"this week\"}", "chart_answers_it: true", "average: true", "\"all\"", "pm2.5", + ": days", ": readings", ": relate", ": current", ": forecast", "low_text", "day_look", "rain_total_mm", "complete"): + assert words in text, words + readings = tool.parameters["properties"]["readings"]["description"] + assert "outdoor.temperature" in readings and "air.pm2_5" not in readings and readings.endswith( # (what this station holds) + "Default: outdoor and indoor temperature and humidity.") + assert tool.parameters["properties"]["period"]["description"].endswith("Default: today; with chart true and no period, the last 24 hours.") + assert tool.parameters["properties"]["layout"]["enum"] == ["auto", "panels", "two_axes", "same_axis"] + await close(ctx) + + +async def test_by_default_it_is_todays_outdoor_and_indoor_temperature_and_humidity_with_no_chart(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool) + assert list(out)[:4] == ["period", "as_of", "fresh", "series"] and out["fresh"] == FRESH + assert out["period"]["asked"] == "today" and out["period"]["text"].startswith("today: ") + assert list(out["series"]) == ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"] # (the fake's indoor has no humidity) + assert "charts" not in out and "caption" not in out and "complete" not in out + await close(ctx) + + +# ---------- the figures ---------- +async def test_each_record_comes_with_its_wording_its_day_and_that_days_look(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", chart=False) + assert list(out["series"]) == ["outdoor.temperature", "pressure.relative"] and "charts" not in out + values, _ = await ctx.eco.storage.read(day_values_on, ctx.eco.mac, list(FIGURES), + [ctx.now().date() - timedelta(days=n) for n in range(7)]) + today = ctx.now().date() + + def looked(day): + return day_look({n: values[n].get(day) for n in FIGURES}, latitude=-37.8, day=day, so_far=day == today) + temp = out["series"]["outdoor.temperature"] + assert temp["unit"] == "°C" and isinstance(temp["low"], float) and temp["low"] <= temp["high"] + for want in ("low", "high"): + assert temp[f"{want}_text"] == f"{temp[want]} °C" + assert temp[f"{want}_when"].startswith(("at ", "around ")) and temp[f"{want}_date"].endswith(" 2026") + day = datetime.strptime(temp[f"{want}_date"], "%a %d %b %Y").date() + assert temp.get(f"{want}_day_look") == looked(day) + rows = temp["daily"] + assert len(rows) == 7 and list(rows)[-1] == f"{today:%a} {today.day} {today:%b}" + for label, row in rows.items(): + day = next(d for d in (today - timedelta(days=n) for n in range(7)) if f"{d:%a} {d.day} {d:%b}" == label) + assert row.get("day_look") == looked(day) and row["low"] <= row["high"] + assert any(row.get("day_look", {}).get("word") == "wet" for row in rows.values()) # the fake's every 8th day is wet + assert "average" not in temp + await close(ctx) + + +async def test_an_average_is_by_time_and_comes_with_each_days(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature"], period="this week", average=True, chart=False) + temp = out["series"]["outdoor.temperature"] + assert temp["low"] < temp["average"] < temp["high"] and temp["average_text"] == f"{temp['average']} °C" + assert all("average" in row for row in temp["daily"].values()) + old = json.loads(await ctx.eco._history({"start_date": f"{days_ago(6)} 00:00:00", "end_date": datetime.now(TZ).strftime( + "%Y-%m-%d %H:%M:%S"), "groups": "outdoor", "average": True})) + assert float(old["series"]["outdoor.temperature"]["average"]) == temp["average"] # weather_history's own + await close(ctx) + + +async def test_a_period_over_a_week_lists_the_days_of_its_records_or_with_every_day_all_of_them(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + some = (await ask(tool, readings=["outdoor.temperature"], period="last 14 days", chart=False))["series"]["outdoor.temperature"] + assert 1 <= len(some["daily"]) <= 2 and {some["low_date"][:-5], some["high_date"][:-5]} == set(some["daily"]) + every = (await ask(tool, readings=["outdoor.temperature"], period="last 14 days", chart=False, every_day=True))["series"] + assert len(every["outdoor.temperature"]["daily"]) == 14 + longer = (await ask(tool, readings=["outdoor.temperature"], period="last 40 days", chart=False, every_day=True))["series"] + assert "monthly" in longer["outdoor.temperature"] and "daily" not in longer["outdoor.temperature"] # by month, past 31 days + await close(ctx) + + +async def test_rain_is_the_mm_that_fell_its_total_and_its_wettest_day(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["rain"], period="last 14 days", chart=False) + rain = out["series"]["rainfall.rain"] + assert "charts" not in out and out["rain_total_mm"] == rain["total"] > 0 and rain["total_text"] == f"{rain['total']:.1f} mm" + assert rain["wettest_day"]["mm"] == 5.0 and rain["wettest_day"]["day_look"]["word"] == "wet" # the fake's wet day: 5 mm + assert list(rain["daily"]) == [next(iter(rain["daily"]))] and "low" not in rain # 14 days: only the wettest listed + every = await ask(tool, readings=["rain"], period="last 14 days", chart=False, every_day=True) + assert len(every["series"]["rainfall.rain"]["daily"]) == 14 + assert round(sum(r["total"] for r in every["series"]["rainfall.rain"]["daily"].values()), 1) == rain["total"] + drawn = await ask(tool, readings=["rain"], period="last 14 days") # the chart's total is the same + old_turn = Turn() + old = json.loads(await ctx.eco._history({"start_date": f"{days_ago(13)} 00:00:00", "end_date": datetime.now(TZ).strftime( + "%Y-%m-%d %H:%M:%S"), "groups": "rainfall", "chart_field": "rain", "chart": True}, old_turn)) + assert drawn["rain_total_mm"] == old["rain_total_mm"] == rain["total"] + long = await ask(tool, readings=["rain"], period="3m", chart=False) + assert list(long["series"]["rainfall.rain"]["monthly"])[0].endswith(" 2026") + await close(ctx) + + +async def test_wind_is_its_speed_and_its_direction_by_compass_point(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["wind", "gust"], period="this week", chart=False) + assert list(out["series"]) == ["wind.wind_speed", "wind.wind_direction", "wind.wind_gust"] + direction = out["series"]["wind.wind_direction"] + assert direction["most_common"].startswith(("N ", "NNW", "NNE")) and direction["steadiness"] and "low" not in direction + assert "daily" in direction + await close(ctx) + + +async def test_the_air_sensors_figures_are_air_qualitys_with_their_wording(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + out = await ask(tool, readings=["pm2.5", "co2", "air.temperature"], period="last 2 days", chart=False) + assert list(out["series"]) == ["air.pm2_5", "air.co2", "air.temperature"] + start, end = (datetime.fromisoformat(out["period"][k]).strftime("%Y-%m-%d %H:%M:%S") for k in ("start", "end")) + old = json.loads(await ctx.air.handle({"start_date": start, "end_date": end, "metrics": ["air_temperature"]})) + pm = out["series"]["air.pm2_5"] + for k in ("low", "high", "average", "high_rating", "average_rating", "high_aqi_us", "high_band", "average_aqi_us", "average_band"): + assert pm[k] == old["pm2_5"][k], k + at = datetime.strptime(old["pm2_5"]["high_time"], "%a %d %b %Y %I:%M%p") # "Wed 4 Nov 2026 10:00am" + assert pm["high_text"] == f"{pm['high']} µg/m³" and pm["high_date"] == f"{at:%a} {at.day} {at:%b %Y}" + assert pm["high_when"] == f"at {at.hour % 12 or 12}{'' if not at.minute else f':{at:%M}'}{'am' if at.hour < 12 else 'pm'}" + assert out["series"]["air.temperature"]["average"] == old["air_temperature"]["average"] + assert "high_rating" not in out["series"]["air.temperature"] # its own temperature has no rating + await close(ctx) + + +# ---------- periods ---------- +async def test_a_chart_comes_for_three_days_or_more_and_chart_true_alone_is_the_last_24_hours(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + assert "charts" not in await ask(tool, readings=["pressure"], period="yesterday") + assert len((await ask(tool, readings=["pressure"], period="last 3 days"))["charts"]) == 1 + assert "charts" not in await ask(tool, readings=["pressure"], period="last 3 days", chart=False) + out = await ask(tool, readings=["pressure"], chart=True) + assert out["period"]["asked"] == "last 24 hours" and len(out["charts"]) == 1 + assert out["charts"][0]["drawn_by"]["arguments"]["period"] == "last 24 hours" + assert (await ask(tool, readings=["pressure"], chart="true"))["period"]["asked"] == "last 24 hours" # (as text too) + await close(ctx) + + +async def test_on_record_starts_at_the_first_day_held(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature"], period="on record", chart=False) + first = datetime.fromisoformat(out["period"]["start"]).date() + assert (ctx.now().date() - first).days in range(540, 560) # the fake station is 548 days old + assert "monthly" in out["series"]["outdoor.temperature"] + await close(ctx) + + +async def test_whole_days_sent_as_dates_are_drawn_by_as_words_and_a_time_lists_no_periods(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + dated = await ask(tool, readings=["pressure"], start=days_ago(9), end=days_ago(5)) + words = dated["charts"][0]["drawn_by"] + assert words["arguments"]["period"] == f"{days_ago(9)} to {days_ago(5)}" and "start" not in words["arguments"] + assert [p["period"] for p in words["periods"]] == ["1d", "7d", "1m", "3m", "1y"] + again = await ask(tool, **words["arguments"]) + assert without_drawn_by(again["charts"][0]) == without_drawn_by(dated["charts"][0]) and again["period"]["text"] == dated["period"]["text"] + since = await ask(tool, readings=["pressure"], start=days_ago(4)) + assert since["charts"][0]["drawn_by"]["arguments"]["period"] == f"{days_ago(4)} to now" + timed = await ask(tool, readings=["pressure"], start=f"{days_ago(4)} 06:00", chart=True) + by = timed["charts"][0]["drawn_by"] + assert by["arguments"]["start"] == f"{days_ago(4)} 06:00" and "period" not in by["arguments"] and by["periods"] == [] + assert without_drawn_by((await ask(tool, **by["arguments"]))["charts"][0]) == without_drawn_by(timed["charts"][0]) + await close(ctx) + + +# ---------- charts and drawn_by ---------- +async def replays(tool: ServiceTool, out: dict) -> dict: + """Check the result's chart: drawn_by draws it again, and draws a chart over each period it lists, never refused.""" + (chart,) = out["charts"] + by = chart["drawn_by"] + assert by["tool"] == "summary" and set(by) == {"tool", "arguments", "periods"} + assert schema_errors(without_drawn_by(chart)) == [] # the chart is schemas/chart.json's, with drawn_by beside it + again = await ask(tool, **by["arguments"]) + assert [without_drawn_by(c) for c in again["charts"]] == [without_drawn_by(chart)] and again["charts"][0]["drawn_by"] == by + for period in by["periods"]: + other = await ask(tool, **{**by["arguments"], "period": period["period"]}) + assert "error" not in other and len(other["charts"]) == 1, (period, other.get("error")) + assert other["charts"][0]["title"] == chart["title"], period + return by + + +async def test_a_station_chart_says_how_to_draw_it_again_and_over_which_periods(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, period="this week") # the usual set: a panel each, outdoor and indoor lines in each + chart = out["charts"][0] + assert [p["label"] for p in chart["panels"]] == ["Temperature", "Humidity"] and chart["source"] == "Ecowitt weather station" + assert [s["name"] for s in chart["panels"][0]["series"]] == ["Indoor", "Outdoor"] + by = await replays(tool, out) + assert by["arguments"] == {"readings": ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"], "period": "this week", + "average": False, "every_day": False, "chart": True, + "chart_readings": ["outdoor.temperature", "indoor.temperature", "outdoor.humidity"], "layout": "auto", + "invert_second_axis": False, "chart_answers_it": False} + assert by["periods"] == [{"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}, {"period": "1m", "label": "1M"}, + {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}] + assert out["chart_note"] and max(len(s["points"]) for p in chart["panels"] for s in p["series"]) <= 150 + await close(ctx) + + +async def test_wind_is_drawn_with_its_compass_and_one_reading_named_draws_only_that_one(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["wind"], period="this week") + chart = out["charts"][0] + assert chart["title"] == "Wind" and "compass" in chart["panels"][0] + await replays(tool, out) + outdoor = await ask(tool, readings=["temperature"], chart_readings=["indoor.temperature"], period="this week") + assert [s["name"] for s in outdoor["charts"][0]["panels"][0]["series"]] == ["Indoor"] # figures for both, the line asked for + assert list(outdoor["series"]) == ["outdoor.temperature", "indoor.temperature"] + everything = await ask(tool, readings=["all"], period="this week") + assert [p["label"] for p in everything["charts"][0]["panels"]] == ["Temperature", "Humidity", "Solar radiation", "Pressure", + "Dew point", "Wind"] # (rain behind the humidity) + await close(ctx) + + +async def test_an_average_draws_each_days_average_and_lists_no_one_day_period(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["pressure"], period="this week", average=True) + assert "daily averages" in out["charts"][0]["subtitle"] + by = await replays(tool, out) + assert [p["period"] for p in by["periods"]] == ["7d", "1m", "3m", "1y"] + short = await ask(tool, readings=["pressure"], period="today", average=True, chart=True) + assert "charts" not in short and "whole day" in short["note_chart"] + await close(ctx) + + +async def test_two_axes_and_the_second_axis_upside_down(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache) + out = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", layout="two_axes", invert_second_axis=True) + (panel,) = out["charts"][0]["panels"] + assert panel["flip_right"] is True and [s["right"] for s in panel["series"]] == [False, True] + await replays(tool, out) + plain = await ask(tool, readings=["outdoor.temperature", "pressure"], period="this week", layout="two_axes") + assert plain["charts"][0]["panels"][0]["flip_right"] is False + same = await ask(tool, readings=["outdoor.temperature", "dew point"], period="this week", layout="same_axis") + (panel,) = same["charts"][0]["panels"] + assert len(panel["series"]) == 2 and same["charts"][0]["period"][1] == days_ago(1) # plot_chart's: whole days to yesterday + await close(ctx) + + +async def test_an_air_chart_is_the_air_sensors_and_an_average_one_is_each_days(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, rows_per_day=24) + out = await ask(tool, readings=["pm2.5", "co2"], period="last 3 days") + chart = out["charts"][0] + assert chart["title"] == "Air quality" and [p["label"] for p in chart["panels"]] == ["PM2.5", "CO₂"] + assert chart["source"] == "AirGradient sensor" + await replays(tool, out) + daily = await ask(tool, readings=["pm2.5"], period="last 3 days", average=True) + assert "daily averages" in daily["charts"][0]["subtitle"] and len(daily["charts"][0]["panels"][0]["series"][0]["points"]) == 2 + await close(ctx) + + +async def test_a_chart_of_both_sensors_or_a_rating_is_drawn_over_whole_days_and_says_so(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, rows_per_day=24) + out = await ask(tool, readings=["pm2.5", "rain"], chart_readings=["air.pm2_5:rating", "rain"], period="this week") + chart = out["charts"][0] + assert chart["source"] == "Ecowitt weather station and AirGradient sensor" and chart["period"] == [days_ago(6), days_ago(1)] + assert chart["panels"][0]["series"][0]["kind"] == "rating" and chart["panels"][1]["series"][0]["kind"] == "bars" + assert "up to yesterday" in out["notes"]["chart"] and out["notes"]["chart"] in out["caption"] + assert list(out["series"]) == ["air.pm2_5", "rainfall.rain"] and out["rain_total_mm"] >= 0 + by = await replays(tool, out) + assert by["arguments"]["chart_readings"] == ["air.pm2_5:rating", "rainfall.rain"] + await close(ctx) + + +async def test_a_chart_of_both_sensors_has_each_readings_line_and_the_cut_in_its_caption(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + mixed = await ask(tool, readings=["outdoor.temperature", "pm2.5"], period="last 3 days", chart_answers_it=True) + assert [p["label"] for p in mixed["charts"][0]["panels"]] == ["Temperature", "PM2.5"] + lines = mixed["caption"].splitlines() + assert lines[1].startswith("Temperature: low ") and lines[2].startswith("• PM2.5: peak ") and lines[3].startswith("(The chart draws") + assert mixed["reply"] == mixed["caption"] and mixed["complete"] is True # the cut is in the caption: nothing left for the model + await close(ctx) + + +# ---------- the caption, as the bot writes it today ---------- +async def old_caption(ctx, out: dict, tool: str, args: dict) -> str: + """lib/report.chart_caption over today's tool (weather_history, air_quality) for the same period, as the bot calls it.""" + start, end = (datetime.fromisoformat(out["period"][k]) for k in ("start", "end")) + args = {"start_date": start.strftime("%Y-%m-%d %H:%M:%S"), "end_date": (end - timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"), + "chart": True, **args} + turn = Turn() + handler = ctx.eco._history if tool == "weather_history" else ctx.air.handle + result = await handler(args, turn) + drawn_args, drawn = _as_drawn(tool, args, turn) + return report.chart_caption(tool, drawn_args, result, drawn, TZ) + + +async def test_the_caption_is_the_one_the_bot_writes_today_word_for_word(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + for args, old in (({"readings": ["pressure"], "period": "this week"}, {"groups": "pressure", "chart_field": "pressure"}), + ({"period": "this week"}, {"groups": "outdoor,indoor", "chart_fields": ["temperature", "humidity"]}), + ({"readings": ["temperature"], "period": "this week", "average": True}, + {"groups": "outdoor,indoor", "chart_field": "temperature", "average": True}), + ({"readings": ["rain", "wind"], "period": "last 10 days"}, {"groups": "rainfall,wind", "chart_fields": ["rain", "wind"]}), + ({"readings": ["wind"], "period": "last 3 days"}, {"groups": "wind", "chart_field": "wind"}), + ({"readings": ["rain"], "period": "last 3 days"}, {"groups": "rainfall", "chart_field": "rain"})): + out = await ask(tool, **args) + assert out["caption"] == await old_caption(ctx, out, "weather_history", old), args + out = await ask(tool, readings=["pm2.5", "co2"], period="last 3 days") + assert out["caption"] == await old_caption(ctx, out, "air_quality", {"metrics": ["pm2_5", "co2"]}) + assert out["caption"].splitlines()[1].startswith("• PM2.5: peak ") + await close(ctx) + + +async def test_with_no_chart_the_figures_come_in_the_words_the_bot_writes_for_a_lookup_today(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + for args, old, names in (({"period": "yesterday"}, {"groups": "outdoor,indoor"}, ["temperature", "humidity"]), + ({"readings": ["temperature"], "period": "yesterday", "average": True}, + {"groups": "outdoor,indoor", "average": True}, ["temperature"]), + ({"readings": ["wind"], "period": "yesterday"}, {"groups": "wind"}, ["wind"]), + ({"readings": ["outdoor.humidity", "pressure"], "period": "yesterday"}, {"groups": "outdoor,pressure"}, + ["humidity", "pressure"])): + out = await ask(tool, **args) + start, end = (datetime.fromisoformat(out["period"][k]) for k in ("start", "end")) + result = await ctx.eco._history({"start_date": start.strftime("%Y-%m-%d %H:%M:%S"), + "end_date": (end - timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"), **old}) + assert "charts" not in out and out["text"] == report.lookup("extremes", result, names, [], ctx.now().date()), args + rain = await ask(tool, readings=["rain", "pm2.5"], period="yesterday") + lines = rain["text"].splitlines() + assert lines[1].startswith("☔ Rain per hour: least 0 mm") and lines[1].endswith(f" · {rain['rain_total_mm']:.1f} mm in all") + assert lines[2].startswith("• PM2.5: peak ") and len(lines) == 3 + direction = await ask(tool, readings=["wind direction"], period="yesterday") + assert direction["text"].splitlines()[1].startswith("🧭 Mostly from the N") + await close(ctx) + + +async def test_a_chart_that_answers_the_question_comes_with_its_reply_unless_a_note_needs_words(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True, hourly_before=datetime.now(TZ) - timedelta(days=3)) + out = await ask(tool, readings=["pressure"], period="this week", chart_answers_it=True) + assert out["reply"] == out["caption"] and out["complete"] is True and list(out)[-2:] == ["reply", "complete"] + assert out["charts"][0]["drawn_by"]["arguments"]["chart_answers_it"] is True + assert "complete" not in await ask(tool, readings=["pressure"], period="this week") # not asked + assert "complete" not in await ask(tool, readings=["pressure"], period="yesterday", chart_answers_it=True) # no chart + hourly = await ask(tool, readings=["pm2.5"], period="last 7 days", chart_answers_it=True) + assert "resolution" in hourly["notes"]["air"] and "caption" in hourly and "complete" not in hourly # the model words the note + assert summary.Summary._needs_words({"warning": "x", "missing": ["y"], "notes": {"air": {"missing": "z"}, "chart": "c"}}) is False + assert summary.Summary._needs_words({"monthly_note": "x"}) and summary.Summary._needs_words({"note_no_readings": "x"}) + await close(ctx) + + +# ---------- refusals that teach ---------- +async def test_a_call_that_cant_be_answered_is_refused_with_what_to_send_instead(tmp_path, archived_cache): + tool, ctx, _ = await make(tmp_path, archived_cache, air=True) + out = await ask(tool, start_date="2026-11-01") + assert "start_date" in out["error"] and "`start`" in out["error"] and "period" in out["arguments"] + out = await ask(tool, readings=["sunniness"]) + assert "'sunniness' isn't a reading" in out["error"] and "outdoor.temperature" in out["names"] and out["words"]["rain"] + out = await ask(tool, period="the other week") + assert "isn't a period" in out["error"] and "today" in out["forms"] + assert "use forecast" in (await ask(tool, period="next week"))["error"] + out = await ask(tool, readings=["pressure"], chart=True, layout="stacked") + assert out["layouts"] == ["auto", "panels", "two_axes", "same_axis"] + assert "needs layout two_axes" in (await ask(tool, readings=["pressure"], chart=True, invert_second_axis=True))["error"] + assert "two readings or more" in (await ask(tool, readings=["pressure"], chart=True, layout="two_axes"))["error"] + assert "rain (bars)" in (await ask(tool, readings=["pressure", "rain"], chart=True, layout="two_axes"))["error"] + assert "have a rating" in (await ask(tool, chart_readings=["temperature:rating"], chart=True))["error"] + out = await ask(tool, readings=["indoor.temperature", "pm2.5"], chart=True, period="this week") + assert "indoor.temperature can't go on a chart that mixes" in out["error"] and "air.pm2_5" in out["drawable"] + out = await ask(tool, readings=["pm2.5", "pm10", "co2", "voc", "rain"], chart=True, period="this week") + assert "at most 4 readings" in out["error"] + out = await ask(tool, readings=["pm2.5", "rain"], chart=True, period="today") + assert "whole days" in out["error"] and "'last 7 days'" in out["error"] + assert "true or false" in (await ask(tool, chart="maybe"))["error"] + assert "names no reading" in (await ask(tool, chart=True, chart_readings=[":rating"]))["error"] + every = summary.tools(Context(eco=ctx.eco))[0] # (every reading the service knows: rain rate is drawn only alone) + out = await ask(every, readings=["pressure", "rain rate"], chart=True) + assert "rainfall.rain_rate can only be drawn on a chart of its own" in out["error"] + assert "the piezo rain gauge" in (await ask(every, readings=["piezo"], chart=True))["error"].lower() + out = await ask(tool, readings=["pressure"], period="2021") + assert "goes back 4 years" in out["error"] and out["held_from"] + await close(ctx) + + +async def test_with_only_the_air_sensor_its_readings_are_the_default_and_no_day_has_a_look(tmp_path): + transport, _ = air_transport(rows_per_day=288) + air = AirGradient(config(tmp_path), transport=transport) + await air.start() + ctx = await Context.open(air=air) + tool = summary.tools(ctx)[0] + out = await ask(tool, period="last 2 days") + assert list(out["series"]) == ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"] + assert not any("low_day_look" in s or "high_day_look" in s for s in out["series"].values()) + assert out["text"].splitlines()[1].startswith("• PM2.5: peak ") and len(out["text"].splitlines()) == 7 + out = await ask(tool, readings=["pm2.5", "pm10"], chart=True, period="last 2 days", layout="two_axes") + assert "only where there is a weather station" in out["error"] + assert "doesn't hold" in (await ask(tool, readings=["temperature"]))["error"] # a bare temperature is the station's + await air.close() + + +async def test_nothing_held_is_refused_with_where_the_record_starts(tmp_path, archived_cache): + tool, ctx, fake = await make(tmp_path, archived_cache) + out = await ask(tool, {"fetch": False}, readings=["pressure"], period="June 2024") # before the fake station, asking nobody + assert out["error"].startswith("Nothing is held of pressure.relative for June 2024") and out["held_from"] + assert fake.calls == [] + await close(ctx) + + +# ---------- the request's metadata ---------- +async def test_a_chart_drawn_ahead_asks_after_the_rest_and_a_chart_points_budget_is_kept(tmp_path, archived_cache, monkeypatch): + tool, ctx, _ = await make(tmp_path, archived_cache) + urgent = [] + real = summary.Fetcher.__init__ + + def recorded(self, *args, **kwargs): + real(self, *args, **kwargs) + urgent.append(self.urgent) + monkeypatch.setattr(summary.Fetcher, "__init__", recorded) + await ask(tool, {"priority": "background"}, readings=["pressure"], period="this week") + await ask(tool, readings=["pressure"], period="this week") + assert urgent == [False, True] + big = await ask(tool, {"chart_points": 500}, readings=["pressure"], period="this week") + assert max(len(s["points"]) for s in big["charts"][0]["panels"][0]["series"]) > 150 + await close(ctx) From 547f5220757af5e06356b074c165277f0753cc39 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:48:40 +0000 Subject: [PATCH 029/125] lib/service/current.py, about.py: the current and about tools `current` (docs/mcp-service.md 3.3), in place of weather_now, air_quality without dates and the gauges' figures, on their engines: every reading the station and the air sensor have now (ctx.readings()), or those named; the station's live reading as dashboard() and weather_now read it (Ecowitt._live_data), each reading with value, unit, its text as weather_now writes it and its glance emoji; the air sensor's latest (AirGradient.latest: rating, US AQI and band); as_of the newest reading's time. With `context`, the gauges' figures (dashboard.figures over day_values_on's day rows, the live reading counted in), each high and low with when it happened and its day, rain's totals and wettest day, wind's highest gust. `lines` and `headings`: the report's, "weather now"'s and the plain lookups' words (lib/report.py weather_lines, air_lines, reading_lines, ported unchanged), so the bot can quote them. fetch false answers from the readings held; background priority asks the station behind the others. `about`: what the service measures and doesn't (the prompt's lists, copied), how far back each resolution is held (the file's coverage; the minutes from their rows), the alerts there are with their rules and thresholds (the rules' constants, the quiet hours and cooldown as settings), that alerts can't be added by asking, what each tool answers, and the Help list's words. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/service/about.py | 275 ++++++++++++++++ lib/service/current.py | 572 ++++++++++++++++++++++++++++++++++ tests/test_service_about.py | 166 ++++++++++ tests/test_service_current.py | 390 +++++++++++++++++++++++ 4 files changed, 1403 insertions(+) create mode 100644 lib/service/about.py create mode 100644 lib/service/current.py create mode 100644 tests/test_service_about.py create mode 100644 tests/test_service_current.py diff --git a/lib/service/about.py b/lib/service/about.py new file mode 100644 index 00000000..611d5ade --- /dev/null +++ b/lib/service/about.py @@ -0,0 +1,275 @@ +"""The `about` tool (docs/mcp-service.md 3.3): what the service measures and what it doesn't, how far back each kind of history goes, +the alerts there are with their thresholds, and that alerts can't be added or changed by asking. It replaces what the bot's prompt told +its model outside the tools (lib/prompt.py: NEVER_AVAILABLE, the capabilities, ALERT_WORDS), whose lists are copied here (the prompt +goes with the bot), and the bot's Help list (lib/templates.py MEASURES: `lines`, the same words). + + - measures: each device and service there is (the sources in the Context), in words and, for the sensors, the readings the catalogue + holds, each with its name, label and unit; + - history: for each sensor, from when to when each resolution is held, and on how many days, from the coverage of the file (the + minutes, which have none, from the readings themselves): what "on record" reaches, and how fine a record is in each stretch of it; + - alerts: each kind there is for the sources there are (lib/alerts/menu.py TYPES, copied), with what it is, its rule in words and its + thresholds as figures, from the alert rules' own constants and the settings (RAIN_QUIET_HOURS, ALERT_COOLDOWN_MINUTES). + +It takes no arguments and reads only what is held, so `fetch` and `priority` change nothing. +""" + +from datetime import datetime, tzinfo + +from ..alerts.forecast import DRY_BELOW_PCT, RAIN_FROM_PCT, TEMP_CHANGE_C +from ..alerts.particulates import CHECK_SECONDS, MASK_PM10, MASK_PM25, SAFE_PM10, SAFE_PM25 +from ..alerts.pollen_and_asthma import ALERT_FROM, WARN_FROM +from ..alerts.rules import CONFIRM_READINGS +from ..alerts.weather import CROSS_MARGIN, GUST_ALERT_KMH, GUST_REARM_SECONDS, UV_REARM_SECONDS +from ..airgradient.metrics import ALL_METRICS, CHART_UNITS, LABELS as AIR_LABELS +from ..ecowitt.api import daily_run +from ..ecowitt.glance import UVI_ALERT +from ..pollen.parse import LEVELS +from ..storage.catalogue import KINDS +from ..storage.coverage import merge +from ..storage.read import Reader +from ..storage.write import MINUTES_KEPT +from ..timeutil import clock_text, day_text, local_date +from .common import Refusal, ServiceTool, answer +from .context import Context +from .names import AIR_DEVICE, STATION + +NAME = "about" + +# ---------- the settings the alerts follow ---------- +# The rain alert's quiet hours and the alerts' cooldown are the service's config (RAIN_QUIET_HOURS, ALERT_COOLDOWN_MINUTES): set from it at +# startup, as names.FEELS_LIKE_IN_ALL is. These are the config's defaults. +RAIN_QUIET_HOURS: tuple[int, int] | None = (0, 6) # local hours with no rain alerts, a summary after; None: none +ALERT_COOLDOWN_MINUTES = 60 # dry this long before "the rain has stopped"; the temperature crossing's least gap + +# ---------- what the bot's prompt said (lib/prompt.py), copied: the prompt goes with the bot ---------- +NEVER_AVAILABLE = ["lightning", "soil or extra sensor channels", "indoor air quality", "other stations or places"] +WITHOUT = {"Pollen": "pollen and thunderstorm asthma", "Forecast": "forecasts (only a short read of the pressure trend)"} # a source that is off +ALERT_WORDS = {"rain": "rain starting or stopping", "gusts": f"wind gusts over {GUST_ALERT_KMH} km/h", + "uv": f"UV index of {UVI_ALERT} or more", "temps": "indoor/outdoor temperature crossing", + "particulates": "air-quality mask alerts", "pollen_and_asthma": "pollen or thunderstorm asthma risk reaching High", + "forecast": f"a forecast it sent being revised (rain, or max temperature over {TEMP_CHANGE_C:g} degrees)"} +# The alert kinds (lib/alerts/menu.py TYPES, copied, without the irrigation controller's: that is a server of its own): kind -> (its name, +# the source that sends it) +TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), + "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), + "forecast": ("forecast changes", "Forecast")} +# What each source measures, as the bot's Help lists it (lib/templates.py MEASURES) +MEASURES = {"Ecowitt": ["Temperature, humidity (indoor, outdoor)", "Dew point, vapour pressure deficit, pressure, wind speed", + "Rain, solar radiation, UV index"], + "AirGradient": ["PM1, PM2.5, PM10, CO₂, VOC, NOx"], + "Pollen": ["Pollen and thunderstorm asthma risk (October to December)"], + "Forecast": ["Forecast"]} +STATION_TEXT = ("Weather station (Ecowitt): outdoor and indoor temperature and humidity, dew point, feels-like, vapour pressure deficit, " + "pressure, wind speed, gust and direction, rain (daily total and rate), solar radiation and UV index.") +AIR_TEXT = ("Air quality (outdoor AirGradient): " + ", ".join(f"{AIR_LABELS[m]} ({CHART_UNITS[m] or 'index'})" for m in ALL_METRICS) + + ", each with a traffic-light rating, and PM2.5 with its US AQI; also the sensor's own temperature and humidity " + "(air.temperature, air.humidity).") +FORECAST_TEXT = "Forecast: today and the days ahead from Open-Meteo (summary, temperatures, chance of at least 1 mm of rain)." +POLLEN_TEXT = ("Pollen: Melbourne's grass pollen level and the thunderstorm asthma risk (Low, Moderate, High, Extreme). Both forecasts " + "only run from October to December.") +ALERTS_NOTE = ("Alerts can't be added or changed by asking (\"tell me when the wind reaches 100\", another threshold, another reading): " + "there are only these, at these thresholds. The service sends them to the apps that listen for them; which of them a " + "person gets is set where they receive them.") +NOT_NOTE = "A reading, a place or a chart style not listed here can't be had by asking: say so." + +# What each tool answers, for "what can you do": (tool, what, the sources it needs) +TOOLS = (("current", "the readings now, with today's, this month's and this year's highs and lows", ("Ecowitt", "AirGradient")), + ("summary", "a period's highs and lows with when, averages, rain totals, air ratings, and charts of any readings", + ("Ecowitt", "AirGradient")), + ("readings", "any reading's values at an interval, from a minute to a day, each with its time", ("Ecowitt", "AirGradient")), + ("days", "days found, ranked or counted by their figures (the wettest day, days over 35°C, rain per month), or over part of " + "each day (the overnight low)", ("Ecowitt", "AirGradient")), + ("relate", "whether rain comes with a change in pressure, humidity or wind, and whether the air is cleaner after rain", + ("Ecowitt",)), + ("scan", "which air readings go with which weather readings", ("Ecowitt+AirGradient",)), + ("outlook", "whether it will rain in the next few hours", ("Ecowitt",)), + ("forecast", "today and the days ahead", ("Forecast",)), + ("pollen", "grass pollen and thunderstorm asthma (October to December)", ("Pollen",))) + +# The resolutions each sensor's history is held at, finest first, and what each is called +STATION_HELD = (("1min", "minute readings"), ("5min", "5-minute readings"), ("30min", "30-minute readings"), ("4hour", "4-hour records"), + ("1day", "daily records")) +AIR_HELD = (("1min", "minute readings"), ("5min", "5-minute readings"), ("1hour", "hourly averages")) +MINUTE = "1min" # held as readings only, for MINUTES_KEPT, with no coverage of their own + +# ---------- the description ---------- +DESCRIPTION = ( + "What this service is: what it measures and what it doesn't (no lightning, soil sensors, indoor air quality or other places), how " + "far back each kind of history goes and how fine it is, which alerts there are with their thresholds, and what each tool answers. " + "For \"what can you do\", \"what do you measure\", \"can you measure lightning\", \"how far back does the history go\", \"what " + "alerts are there\", \"alert me when the wind reaches 100\": {} (no arguments). Alerts can't be added or changed by asking: there " + "are only those listed, at their thresholds; say so. Not for any reading or figure: current (now), summary (a period), days, " + "readings. Result: measures (each device in words, and its readings: each name with its label and unit); not_available and " + "not_note; history (each sensor's text, ready to pass on, and each resolution held: from, to, days); alerts (each with what it is, " + "its rule in words and its thresholds as figures) and alerts_note; tools (what each answers); lines (a short list of what is " + "measured, to pass on as it is).") +PARAMETERS = {"type": "object", "properties": {}} + + +# ---------- what is held ---------- +def _minutes(r: Reader, sensors: list) -> tuple[int, int] | None: + """(the first, the last) minute held of these sensors (epochs), None for none: one query per kind.""" + found = [] + for kind in dict.fromkeys(s.kind for s in sensors): + ids = [s.id for s in sensors if s.kind == kind] + found.append(r.db.execute(f"SELECT MIN(ts), MAX(ts) FROM {kind} WHERE sensor IN ({', '.join('?' * len(ids))}) AND res = ?", + (*ids, MINUTE)).fetchone()) + firsts, lasts = [a for a, _ in found if a is not None], [b for _, b in found if b is not None] + return (min(firsts), max(lasts)) if firsts else None + + +def held_on(r: Reader, sensors: list, resolutions: tuple) -> dict[str, tuple[int, int, int]]: + """{resolution: (first, last, whole days held)} of these sensors (epochs; merged over them), for the resolutions held.""" + out = {} + for res, _ in resolutions: + if res == MINUTE: + if span := _minutes(r, sensors): + out[res] = (*span, round((span[1] - span[0]) / 86400)) + continue + spans = merge([span for s in sensors for span in r.storage.coverage.of(s.id, res)]) + if spans: + out[res] = (spans[0][0], spans[-1][1], sum(e - s + 1 for s, e in spans) // 86400) + return out + + +def history_of(held: dict[str, tuple[int, int, int]], resolutions: tuple, device: str, tz: tzinfo) -> dict: + """{text, held: {resolution: {from, to, days}}} of one sensor: its text ready to pass on ("Weather station: 5-minute readings from + Mon 12 May 2025, ..."), and each resolution's first and last day held (ISO dates) and its days held.""" + if not held: + return {"text": f"{'Weather station' if device == STATION else 'Air sensor'}: nothing held yet.", "held": {}} + parts, out = [], {} + for res, what in resolutions: + if res not in held: + continue + first, last, days = held[res] + a, b = local_date(first, tz), local_date(last, tz) + out[res] = {"from": a.isoformat(), "to": b.isoformat(), "days": days} + if res == MINUTE: + parts.append(f"{what} from {day_text(a)} (kept {MINUTES_KEPT // 86400} days)") + elif res == "1day": + parts.append(f"{what} from {day_text(a)}, each {daily_run(tz, a, b)}") + else: + parts.append(f"{what} from {day_text(a)}") + name = "Weather station" if device == STATION else "Air sensor" + return {"text": f"{name}: {', '.join(parts)}. The tools use the finest held for each part of a period.", "held": out} + + +# ---------- the alerts ---------- +def _clock(hour: int, minute: int = 0) -> str: + """"12am", "7:30am": a time of day as the service writes one.""" + return clock_text(datetime(2000, 1, 1, hour % 24, minute), whole_hours=True) + + +def alert_rules() -> dict[str, tuple[str, dict]]: + """{kind: (its rule in words, its thresholds as figures)}, from the rules' constants and the settings.""" + cooldown, quiet = ALERT_COOLDOWN_MINUTES, RAIN_QUIET_HOURS + rain = (f"Started: the first tip of the gauge, told at once. Stopped: dry for {cooldown} minutes, with how much fell." + + (f" None from {_clock(quiet[0])} to {_clock(quiet[1])}: one summary of the rain in those hours after them." if quiet else "")) + return { + "rain": (rain, {"dry_minutes": cooldown, "quiet_hours": f"{quiet[0]:02d}:00-{quiet[1]:02d}:00" if quiet else None}), + "gusts": (f"A gust over {GUST_ALERT_KMH} km/h; then none until the gusts have stayed at or under it for " + f"{GUST_REARM_SECONDS // 60} minutes.", {"gust_kmh": GUST_ALERT_KMH, "rearm_minutes": GUST_REARM_SECONDS // 60}), + "uv": (f"A UV index of {UVI_ALERT} or more in {CONFIRM_READINGS} readings in a row; then none until it has stayed below {UVI_ALERT} " + f"for {UV_REARM_SECONDS // 60} minutes.", + {"uv_index": UVI_ALERT, "readings_in_a_row": CONFIRM_READINGS, "rearm_minutes": UV_REARM_SECONDS // 60}), + "temps": (f"Outdoor becoming warmer than indoor, or cooler, by more than {CROSS_MARGIN:g}°C; at most one every {cooldown} minutes.", + {"margin_c": CROSS_MARGIN, "cooldown_minutes": cooldown}), + "particulates": (f"Wear a mask: PM2.5 at {MASK_PM25:g} µg/m³ or more, or PM10 at {MASK_PM10:g} µg/m³ or more (US AQI 151 and up: " + f"unhealthy), in {CONFIRM_READINGS} readings in a row. Safe again: PM2.5 at {SAFE_PM25:g} or less and PM10 at " + f"{SAFE_PM10:g} or less (AQI 100 or better), in {CONFIRM_READINGS} readings in a row. Checked every " + f"{CHECK_SECONDS // 60} minutes.", + {"mask_pm2_5": MASK_PM25, "mask_pm10": MASK_PM10, "safe_pm2_5": SAFE_PM25, "safe_pm10": SAFE_PM10, + "readings_in_a_row": CONFIRM_READINGS, "check_minutes": CHECK_SECONDS // 60}), + "pollen_and_asthma": (f"Grass pollen or the thunderstorm asthma risk forecast {' or '.join(LEVELS[WARN_FROM:])}: once a day from " + f"{_clock(*ALERT_FROM)} while it stays there, and again when it rises. October to December only.", + {"from_level": LEVELS[WARN_FROM]}), + "forecast": (f"A day's forecast revised: its highest temperature by more than {TEMP_CHANGE_C:g}°C, or rain turning likely (a " + f"chance of at least 1 mm of {RAIN_FROM_PCT}% or more) from unlikely ({DRY_BELOW_PCT}% or less), or the reverse.", + {"max_change_c": TEMP_CHANGE_C, "rain_from_pct": RAIN_FROM_PCT, "dry_below_pct": DRY_BELOW_PCT}), + } + + +# ---------- the tool ---------- +class AboutTool: + """The about tool over a Context.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + + @property + def sources(self) -> list[str]: + """The sources there are, by the names the bot's lists use.""" + c = self.ctx + return [name for name, there in (("Ecowitt", c.eco), ("AirGradient", c.air), ("Pollen", c.pollen), ("Forecast", c.forecast)) if there] + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, PARAMETERS, self.handle) + + async def handle(self, args: dict, meta: dict) -> str: + if args: + raise Refusal(f"about takes no arguments, not {', '.join(map(repr, args))}: call it with {{}}.", arguments=[]) + sources = self.sources + return answer(period=None, as_of=None, measures=self.measures(), not_available=not_available(sources), not_note=NOT_NOTE, + history=await self.history(), alerts=alerts(sources), alerts_note=ALERTS_NOTE, + tools={name: what for name, what, needs in TOOLS if any(_has(sources, n) for n in needs)}, + lines=measure_lines(sources)) + + def measures(self) -> dict: + """Each device and service there is, in words; the sensors with their readings (name, label, unit).""" + catalogue = self.ctx.readings() + out = {} + for device, there, text in ((STATION, self.ctx.eco, STATION_TEXT), (AIR_DEVICE, self.ctx.air, AIR_TEXT)): + if there: + out[device] = {"text": text, "readings": {r.name: f"{r.label} ({r.unit})" if r.unit else r.label + for r in catalogue if r.device == device}} + if self.ctx.forecast: + out["forecast"] = {"text": FORECAST_TEXT} + if self.ctx.pollen: + out["pollen"] = {"text": POLLEN_TEXT} + return out + + async def history(self) -> dict: + """Each sensor's history: from when to when each resolution is held (history_of).""" + storage, tz, out = self.ctx.storage, self.ctx.zone, {} + if storage is None: + return out + if self.ctx.eco: + sensors = [s for s in storage.station(self.ctx.eco.mac).values() if s.kind in KINDS] + out[STATION] = history_of(await storage.read(held_on, sensors, STATION_HELD), STATION_HELD, STATION, tz) + if self.ctx.air: + sensor = self.ctx.air.store.sensor + held = await storage.read(held_on, [sensor], AIR_HELD) if sensor is not None else {} + out[AIR_DEVICE] = history_of(held, AIR_HELD, AIR_DEVICE, tz) + return out + + +def _has(sources: list[str], need: str) -> bool: + return all(n in sources for n in need.split("+")) + + +def not_available(sources: list[str]) -> list[str]: + """What the service can't give: never (NEVER_AVAILABLE), and what a source that is off leaves out (WITHOUT).""" + return [*NEVER_AVAILABLE, *(what for name, what in WITHOUT.items() if name not in sources), + *(["weather station readings"] if "Ecowitt" not in sources else []), *(["air quality"] if "AirGradient" not in sources else [])] + + +def alerts(sources: list[str]) -> list[dict]: + """The alerts there are for these sources, each {kind, name, what, rule, thresholds}.""" + rules = alert_rules() + return [{"kind": kind, "name": name, "what": ALERT_WORDS[kind], "rule": rules[kind][0], "thresholds": rules[kind][1]} + for kind, (name, source) in TYPES.items() if source in sources] + + +def measure_lines(sources: list[str]) -> list[str]: + """What is measured, as the bot's Help lists it (lib/templates.py capabilities_text): a short bullet each.""" + return [f"• {line}" for line in [*(line for name, measured in MEASURES.items() if name in sources for line in measured), + "History charts"]] + + +def tools(ctx: Context) -> list[ServiceTool]: + """The about tool: always there.""" + return [AboutTool(ctx).tool()] + + +__all__ = ["ALERT_COOLDOWN_MINUTES", "ALERT_WORDS", "AboutTool", "DESCRIPTION", "MEASURES", "NEVER_AVAILABLE", "RAIN_QUIET_HOURS", + "TYPES", "WITHOUT", "alert_rules", "alerts", "held_on", "history_of", "measure_lines", "not_available", "tools"] diff --git a/lib/service/current.py b/lib/service/current.py new file mode 100644 index 00000000..ecf50c31 --- /dev/null +++ b/lib/service/current.py @@ -0,0 +1,572 @@ +"""The `current` tool (docs/mcp-service.md 3.3): how it is now, from the weather station and the air sensor, every reading or the ones +named, and with `context` today's, this month's and this year's highs and lows beside each reading, as the gauges show them. It replaces +weather_now and air_quality without dates (and the gauges' figures), on their engines: + + - the station's reading is its live reading as Ecowitt.dashboard() and weather_now read it (Ecowitt._live_data: the kept reading while it + is fresh, else a request; raw {group: {field: {value, unit, time}}}), each reading with its value, unit, its text as weather_now writes + it ("12.3 °C") and its glance emoji (lib/ecowitt/glance.py), when the reading is one to notice; + - the air sensor's is AirGradient.latest(): value, unit, rating (held at the better level until two readings agree), PM2.5's US AQI and + band, and its text as the report writes it; + - `context` is the gauges' figures (lib/ecowitt/dashboard.py figures(), over the day rows as dashboard() reads them, + lib/ecowitt/days.day_values_on, the live reading counted in for today's highs and lows), each high and low with when it happened (the + day row's own time of it, worded as weather_history words a record) and its day; rain as its totals and its wettest day, wind as its + highest gust. + +`lines` are each device's readings as bullets, worded as the bot's report, "weather now" and plain lookups word them today +(lib/report.py weather_lines, air_lines, reading_lines, ported here with the same words): every reading (none named) in the report's +layout, else a line for each reading named. `headings` are the report's section headings, with the time of each device's reading. So a +client's report is current's headings and lines, then forecast's (today) and pollen's. + +The request's `fetch` False answers from the readings held (the station's kept live reading, whatever its age, and the air sensor's +latest); `priority` "background" asks the station behind the readings someone is waiting for. There are no charts. +""" + +import logging +import re +from dataclasses import dataclass, field, replace +from datetime import date, datetime, tzinfo + +from ..airgradient.metrics import EXTRA as AIR_OWN_METRICS +from ..ecowitt.api import MINUTE, unit_text +from ..ecowitt.dashboard import GAUGES, Gauge, figures, live_value, periods_of +from ..ecowitt.days import FIELDS, PARTS, day_values_on +from ..ecowitt.direction import point +from ..ecowitt.extremes import describe_time +from ..ecowitt.glance import glance, solar_band +from ..series import AIR, INDOOR_READINGS, WEATHER +from ..storage.catalogue import BY_NAME, column_of, kind_of, text as written +from ..storage.read import Reader +from ..timeutil import clock_text, day_text, to_local +from .common import BACKGROUND, Refusal, ServiceTool, answer +from .context import Context +from .names import AIR_DEVICE, STATION, Reading + +log = logging.getLogger(__name__) + +NAME = "current" +ARGUMENTS = ("readings", "context") +ANOTHER_TIME = ("period", "start", "end") # a call about another time than now: summary's or readings' +HEADINGS = {STATION: "Weather station", AIR_DEVICE: "Air quality"} # the report's sections (lib/report.py SECTIONS) +NOT_AVAILABLE = "• not available right now" # ... and a section whose device didn't answer +UNAVAILABLE = {STATION: "The weather station isn't answering right now.", AIR_DEVICE: "The air sensor isn't answering right now."} +NOTHING_HELD = {STATION: "No reading of the weather station is held (and `fetch` is off).", + AIR_DEVICE: "No reading of the air sensor is held (and `fetch` is off)."} +PERIODS = (("Daily", "today"), ("Monthly", "month"), ("Yearly", "year")) # a gauge's rows, as the result names them + +# ---------- the description and the input schema ---------- +DESCRIPTION = ( + "How it is now, from the weather station (Ecowitt) and the air sensor (AirGradient): every reading, or those named. Everything now " + "(\"weather now\", \"how's it outside\"): {}. How hot is it: {readings: [\"temperature\"]}. Is it raining: {readings: [\"rain\"]}. " + "The air now: {readings: [\"air\"]}. With today's, this month's and this year's highs and lows beside each reading, as gauges show " + "them (rain: its totals and wettest day; wind: its highest gust): {context: true}. A report, status or sitrep: current, forecast " + "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows, averages or a chart " + "(summary); values at set times (readings); the days ahead (forecast). Result: sensors.. (sensors.outdoor." + "temperature) with value, unit, text ready to quote (\"12.3 °C\") and emoji when the reading is one to notice (put it right " + "before the reading, copied; none otherwise); rainfall.rain is today's rain so far; wind_direction has its compass point; the air " + "sensor's have their rating (put it beside the value) and PM2.5 its US aqi_us and band. With context: today, month and year, each " + "with high and low (_text to quote, _when copied as written, \"at 3:05pm\" or \"around 3:30pm\", _date the day). lines: each " + "device's readings as bullet lines, to pass on as they are (headings: each one's heading for a report). missing: readings asked " + "for that aren't being read now; unavailable: a device not answering.") +CONTEXT = {"type": "boolean", "description": "true to add today's, this month's and this year's highs and lows beside each of the " + "weather station's readings that has them (temperature, humidity, pressure, dew point, " + "feels like, wind's highest gust, rain's totals and wettest day, rain rate, solar, UV, " + "indoor temperature and humidity). Default false."} + + +def parameters(description: str) -> dict: + """The input schema, its readings described by the catalogue the tool reads (`description`).""" + return {"type": "object", "properties": { + "readings": {"type": "array", "items": {"type": "string"}, + "description": f"{description} Default: every reading the station and the air sensor have now."}, + "context": CONTEXT}} + + +# ---------- the words, as lib/report.py writes them ---------- +def _zero(text: str | None) -> bool: + """Is this reading missing or zero ("0.0 W/m²", "0")?""" + try: + return not text or float(text.split()[0]) == 0 + except ValueError: + return False + + +def _band(solar: str | None) -> str: + """" (medium)" for a solar reading like "40.2 W/m²"; nothing when it can't be read.""" + try: + return f" ({solar_band(float(solar.split()[0]))})" + except (AttributeError, IndexError, ValueError): + return "" + + +def _join(parts: list[str | None], sep: str = ", ") -> str: + return sep.join(p for p in parts if p) + + +def _getters(now: dict): + """(get, tag) for a weather_now-shaped reading ({group: {field: "12.3 ℃"}, "emoji": {"group.field": emoji}}): a reading's text, and + the same with its emoji (if it has one) before it.""" + emoji = now.get("emoji") or {} + + def get(group: str, field: str) -> str | None: + return unit_text((now.get(group) or {}).get(field)) + + def tag(group: str, field: str, text: str | None = None) -> str | None: + text = text or get(group, field) + return f"{emoji[f'{group}.{field}']} {text}" if text and f"{group}.{field}" in emoji else text + return get, tag + + +def _rain(now: dict) -> str: + """Today's rain, the month's and, while it rains, the rate: "☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)".""" + get, tag = _getters(now) + rate, month = get("rainfall", "rain_rate"), get("rainfall", "monthly") + return _join([_join([tag("rainfall", "daily"), f"(month total {month})" if month else None], " "), + None if _zero(rate) else tag("rainfall", "rain_rate", f"raining ({rate})")], "; ") + + +def _wind(now: dict) -> str | None: + """The wind, where it comes from and its gusts: "14.0 km/h from 131°, gust 31.0 km/h"; None when it is calm.""" + get, tag = _getters(now) + if _zero(get("wind", "wind_speed")) and _zero(get("wind", "wind_gust")): + return None + direction, gust = get("wind", "wind_direction"), tag("wind", "wind_gust") + return _join([_join([tag("wind", "wind_speed"), f"from {direction}" if direction else None], " "), f"gust {gust}" if gust else None]) + + +def weather_lines(now: dict) -> list[str]: + """The weather station's bullets, the report's and "weather now"'s: an emoji sits right before the reading it is keyed to.""" + get, tag = _getters(now) + solar, uvi = get("solar_and_uvi", "solar"), get("solar_and_uvi", "uvi") + sun = _join([None if _zero(solar) else tag("solar_and_uvi", "solar", f"solar radiation {solar}{_band(solar)}"), # night: no sun line + None if _zero(uvi) else tag("solar_and_uvi", "uvi", f"UV index {uvi}")]) + bullets = [("Outdoor", _join([tag("outdoor", "temperature"), tag("outdoor", "humidity")])), # (dew point and VPD are there to ask for) + ("Indoor", _join([tag("indoor", "temperature"), tag("indoor", "humidity")])), + ("Pressure", tag("pressure", "relative")), + ("Rain today", _rain(now)), + ("Sun", sun), + ("Wind", _wind(now))] # calm: no line + return [f"• {name}: {text}" for name, text in bullets if text] + + +def air_shown(key: str, value: float, unit: str) -> str: + """An air reading as the report writes it: "1.4 µg/m³", "433 ppm", "88" (VOC), "1.0" (NOx); the sensor's own temperature and + humidity as the station's are ("18.5 °C", "60 %").""" + if key in AIR_OWN_METRICS: + return f"{value:.1f} {unit}" if unit == "°C" else f"{value:.0f} {unit}" + return (f"{value:.1f} {unit}" if unit.startswith("µg") else f"{value:.0f} {unit}" if unit == "ppm" + else f"{value:.1f}" if key == "nox_index" else f"{value:.0f}") + + +def air_lines(air: dict, only: list[str] | None = None) -> list[str]: + """The air sensor's bullets from its latest reading (AirGradient.latest()), those in `only` (all when None), as the report writes them.""" + out = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = air.get(key) if only is None or key in only else None + if not isinstance(entry, dict) or entry.get("value") is None: + continue + aqi = f" (AQI {entry['aqi_us']})" if key == "pm2_5" and "aqi_us" in entry else "" + out.append(f"• {label}: {_join([air_shown(key, entry['value'], entry.get('unit', '')), entry.get('rating')], ' ')}{aqi}") + return out + + +def reading_lines(now: dict, names: list[str], sides: list[str]) -> list[str]: + """Just the readings asked about (lib/series.py's names: "how hot is it": the temperature, indoors and out), as the bot's plain + lookup writes them.""" + get, tag = _getters(now) + lines = [] + for name in names: + reading = WEATHER[name] + if name in ("temperature", "humidity"): # a line for each side asked about; the temperature with what it feels like + for side in sides: + feels = get(side, "feels_like") if name == "temperature" else None + if text := _join([tag(side, reading.field), f"feels like {feels}" if feels else None]): + lines.append(f"• {side.capitalize()}: {text}") + elif name == "wind": + lines.append(f"• Wind: {_wind(now) or 'calm'}") + elif name == "rain": + lines.append(f"• Rain today: {_rain(now) or 'none'}") + else: + group = sides[0] if name in INDOOR_READINGS and len(sides) == 1 else reading.group # "indoor dew point": that sensor's + if text := tag(group, reading.field): + lines.append(f"• {reading.label}{' (indoor)' if group == 'indoor' else ''}: {text}") + return lines + + +def _stamp(at: datetime, today: date) -> str: + """"11:45pm", with its day when that isn't today ("Sat 10 Oct 11:45pm").""" + return clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" + + +def heading(device: str, at: datetime | None, today: date) -> str: + """"Weather station (2:21am)": the report's heading of a device's section, with the time of its reading when it has one.""" + return f"{HEADINGS[device]} ({_stamp(at, today)})" if at else HEADINGS[device] + + +# ---------- the station's live reading ---------- +def now_shaped(live: dict, tz: tzinfo) -> tuple[dict, int]: + """(weather_now's result from a live reading, {group: {field: "12.3 ℃"}, "emoji": {"group.field": emoji}}, as Ecowitt's + weather_now tool makes it; the time of the newest reading in it, an epoch, 0 for none).""" + out, newest, emoji = {}, 0, {} + for group, fields in live.items(): + for name, obj in (fields.items() if isinstance(fields, dict) else ()): + if isinstance(obj, dict) and "value" in obj: + out.setdefault(group, {})[name] = f"{obj['value']} {obj.get('unit', '')}".strip() + try: + if tag := glance(group, name, float(obj["value"])): + emoji[f"{group}.{name}"] = tag + except (TypeError, ValueError): + pass + try: + newest = max(newest, int(obj.get("time") or 0)) + except (TypeError, ValueError): + pass + return {**out, **({"emoji": emoji} if emoji else {})}, newest + + +def live_field(live: dict, reading: Reading) -> str | None: + """The live reading's own name for a catalogue reading in its group ("daily" for rainfall.rain, "app_tempin" for indoor.app_temp), + or None when the live reading lacks it.""" + for name, obj in (live.get(reading.sensor) or {}).items(): + if isinstance(obj, dict) and "value" in obj and column_of(reading.sensor, name) == (reading.column, "value"): + return name + return None + + +def _number(raw) -> float | int | None: + """A reading as a number ("94" -> 94, "12.3" -> 12.3); None when it isn't one.""" + try: + value = float(raw) + except (TypeError, ValueError): + return None + return int(value) if re.fullmatch(r"\s*-?\d+\s*", str(raw)) else value + + +def station_entry(live: dict, now: dict, reading: Reading, field: str) -> dict: + """{value, unit, text, [emoji], [compass]} of one of the station's readings now.""" + obj = live[reading.sensor][field] + entry = {"value": _number(obj["value"]), "unit": unit_text(obj.get("unit")) or "", # (as its text has it: the UV index has none) + "text": unit_text(now[reading.sensor][field])} + if emoji := (now.get("emoji") or {}).get(f"{reading.sensor}.{field}"): + entry["emoji"] = emoji + if reading.reading == "wind_direction" and entry["value"] is not None: + entry["compass"] = point(entry["value"]) + return entry + + +# ---------- the gauges' figures (context) ---------- +def gauge_of(name: str) -> Gauge | None: + """The gauge a reading's context comes from: the one whose live reading it is (rainfall.rain: the Rain gauge's "daily"); the gusts + get the Wind gauge's highest, with the live gust counted in.""" + if name == "wind.wind_gust": + return replace(next(g for g in GAUGES if g.live == ("wind", "wind_speed")), live=("wind", "wind_gust")) + group, reading = name.split(".", 1) + return next((g for g in GAUGES if g.live == (group, "daily" if reading == "rain" else reading)), None) + + +def _times_on(r: Reader, mac: str, names: list[str], days: list[date]) -> dict[str, dict[date, tuple[int, str]]]: + """{figure: {day: (when its high or low happened, the resolution that time is from)}}: the day rows' own times of the figures + day_values_on reads, for these days (one query per kind of sensor).""" + out: dict[str, dict[date, tuple[int, str]]] = {n: {} for n in names} + by_kind: dict[str, tuple[dict, set]] = {} + places = {} + for name in names: + group, field, which, _ = FIELDS[name] + sensor, place = r.sensor(mac, group), column_of(group, field) + if sensor is None or place is None or PARTS[which] == "mean": + continue + places[name] = (sensor, place[0], PARTS[which] + "_ts") + by_kind.setdefault(sensor.kind, ({}, set()))[0][sensor.id] = sensor + by_kind[sensor.kind][1].add(place[0]) + rows = {} + for kind, (sensors, columns) in by_kind.items(): + rows.update(r.days(kind, list(sensors), min(days), max(days), sorted(columns))) + wanted = set(days) + for name, (sensor, column, part) in places.items(): + got = rows.get(sensor.id) + if got is None or column not in getattr(got, part): + continue + for d, ts, timing in zip(got.day, getattr(got, part)[column], got.timing): + if ts is not None and d in wanted: + out[name][d] = (ts, timing) + return out + + +def context_on(r: Reader, mac: str, names: list[str], days: list[date]) -> tuple[dict, dict]: + """(the figures of these days as dashboard() reads them, day_values_on's {figure: {day: value}}; their times, _times_on's).""" + values, _ = day_values_on(r, mac, names, days) + return values, _times_on(r, mac, names, days) + + +def _figure_text(gauge: Gauge, figure: str, value: float, unit: str) -> str: + """A gauge's figure written as the station writes the reading (its column's decimals) with its unit: "24.3 °C", "62 %", "11".""" + group, field, _, _ = FIELDS[figure] + column = BY_NAME[kind_of(group)][column_of(group, field)[0]] + return f"{written(value, column.decimals, column.whole)} {unit}".strip() + + +class Live: + """The live reading of one gauge: its value and when it was read (an epoch, or None).""" + + def __init__(self, live: dict, gauge: Gauge): + self.value = live_value(live, gauge.live) + group, field = gauge.live + try: + self.ts = int(((live.get(group) or {}).get(field) or {}).get("time") or 0) or None + except (TypeError, ValueError): + self.ts = None + + +def _extreme(key: str, value: float, figure: str, days: list[date], values: dict, times: dict, live: Live | None, gauge: Gauge, + unit: str, tz: tzinfo, dated: bool) -> dict: + """{key, key_text, key_when, [key_date]} of one high or low: when it happened is the first day of these that had it (its day row's + time of it), else the live reading's (it counted in, and is higher or lower than any day's).""" + out = {key: value, f"{key}_text": _figure_text(gauge, figure, value, unit)} + day = next((d for d in days if values.get(figure, {}).get(d) == value), None) + if day is not None and day in times.get(figure, {}): + ts, timing = times[figure][day] + _, out[f"{key}_when"], on = describe_time(ts, timing, tz) + elif day is None and live is not None and live.value == value and live.ts: + _, out[f"{key}_when"], on = describe_time(live.ts, MINUTE, tz) + else: + return out + if dated and on: + out[f"{key}_date"] = on + return out + + +def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz: tzinfo) -> dict: + """{today, month, year} beside one reading: the figures its gauge's rows give (dashboard.figures, the live reading counted in for its + highs and lows, today's rain the gauge's own reading), each high and low with when it happened and its day; rain's totals and wettest + day; wind speed's highest as `high_gust`. {} for a reading with no gauge, or none of whose figures are held.""" + gauge = gauge_of(name) + if gauge is None: + return {} + days, unit = periods_of(today), gauge.unit + now = Live(live, gauge) + out = {} + for row, key in PERIODS: + got = figures(gauge, values, days[row], None if gauge.total else now.value) + if gauge.total and row == "Daily" and now.value is not None: # today's rain is the gauge's own reading (dashboard.sheet) + got = (None, now.value) + entry: dict = {} + if gauge.total: + wettest, total = got + if total is not None: + entry.update(total=total, total_text=_figure_text(gauge, gauge.highest, total, unit)) + if wettest is not None: + day = next(d for d in days[row] if values.get(gauge.highest, {}).get(d) == wettest) + entry["wettest_day"] = {"rain": wettest, "text": _figure_text(gauge, gauge.highest, wettest, unit), "date": day_text(day)} + else: + high = "high_gust" if name == "wind.wind_speed" else "high" + pairs = [(high, gauge.highest, got[0])] + ([("low", gauge.lowest, got[1])] if gauge.lowest else []) + for key_, figure, value in pairs: + if value is not None: + entry.update(_extreme(key_, value, figure, days[row], values, times, now, gauge, unit, tz, dated=row != "Daily")) + if entry: + out[key] = entry + return out + + +# ---------- the tool ---------- +class CurrentTool: + """The current tool over a Context: the station's and the air sensor's readings now.""" + + def __init__(self, ctx: Context): + self.ctx = ctx + + @property + def devices(self) -> list[str]: + return [*([STATION] if self.ctx.eco else []), *([AIR_DEVICE] if self.ctx.air else [])] + + def tool(self) -> ServiceTool: + return ServiceTool(NAME, DESCRIPTION, parameters(self.ctx.readings().description()), self.handle, open_world=True) + + # ---------- the call ---------- + def _asked(self, args: dict) -> tuple[list[Reading], bool, bool]: + """(the readings asked for, whether they were named, context): the call checked, a wrong one refused with what fixes it.""" + if unknown := [k for k in args if k not in ARGUMENTS]: + then = any(k in ANOTHER_TIME for k in unknown) + raise Refusal(f"{', '.join(map(repr, unknown))} {'is not an argument' if len(unknown) == 1 else 'are not arguments'} of " + "current" + (": it gives the readings now. For a period's highs, lows or averages call summary with that " + "period; for values at set times, readings" if then else "") + ".", arguments=list(ARGUMENTS)) + context = args.get("context") + if isinstance(context, str) and context.strip().lower() in ("true", "false"): + context = context.strip().lower() == "true" + if context is not None and not isinstance(context, bool): + raise Refusal(f"`context` is true or false, not {context!r}.") + catalogue = self.ctx.readings() + here = [r for r in catalogue if r.device in self.devices] + named = args.get("readings") not in (None, "", []) + asked = catalogue.resolve(args.get("readings"), default=[r.name for r in here]) + if named and (absent := [r for r in asked if r.device not in self.devices]): + device = "weather station" if absent[0].device == STATION else "air sensor" + raise Refusal(f"{absent[0].name} is the {device}'s, and this service has no {device}.", names=[r.name for r in here]) + return [r for r in asked if r.device in self.devices], named, bool(context) + + async def handle(self, args: dict, meta: dict) -> str: + asked, named, context = self._asked(args) + parts = [] + if station := [r for r in asked if r.device == STATION]: + parts.append(await self._station(station, named, context, meta)) + if air := [r for r in asked if r.device == AIR_DEVICE]: + parts.append(await self._air(air, named, meta)) + sensors: dict[str, dict] = {} + for part in parts: + for r, entry in part.entries: + sensors.setdefault(r.sensor, {})[r.reading] = entry + fields = {"sensors": sensors, "lines": {p.device: p.lines for p in parts}, "headings": {p.device: p.heading for p in parts}} + if missing := [name for p in parts for name in p.missing]: + fields["missing"] = missing + if unavailable := {p.device: p.unavailable for p in parts if p.unavailable}: + fields["unavailable"] = unavailable + times = [p.at for p in parts if p.at] + return answer(period=None, as_of=max(times) if times else self.ctx.now() if sensors else None, **fields) + + async def _station(self, station: list[Reading], named: bool, context: bool, meta: dict) -> "Part": + """The weather station's part: each reading asked for now (with the gauges' figures beside it, with `context`), its lines and + heading. A reading named that it isn't reading is missing; so is a gauge's, with `context`, shown with its figures alone.""" + tz, today = self.ctx.zone, self.ctx.now().date() + try: + live = await self._live(station, named, meta) + except NothingHeld: + return Part.down(STATION, NOTHING_HELD[STATION], today) + except Exception as e: + log.warning("current: the weather station's reading failed: %s", e) + return Part.down(STATION, UNAVAILABLE[STATION], today) + now, newest = now_shaped(live, tz) + at = to_local(newest, tz) if newest else None + gauges = await self._context(station) if context else None + part, shown = Part(STATION, at=at), [] + for r in station: + own = live_field(live, r) + beside = context_of(r.name, live, *gauges, today, tz) if gauges else {} + if own is not None: + part.entries.append((r, {**station_entry(live, now, r, own), **beside})) + shown.append(r) + continue + if named or beside: + part.missing.append(r.name) + if beside: # (a gauge drawn dimmed: no reading now, its figures still there) + part.entries.append((r, {"value": None, "unit": gauge_of(r.name).unit, **beside})) + part.lines = station_lines(now, shown) if named else weather_lines(now) + part.heading = heading(STATION, at, today) + return part + + async def _air(self, air: list[Reading], named: bool, meta: dict) -> "Part": + """The air sensor's part: each reading asked for now, its lines and heading. A reading named that it isn't reading is missing.""" + tz, today = self.ctx.zone, self.ctx.now().date() + try: + latest = await self._latest([r.column for r in air if r.column in AIR_OWN_METRICS], meta) + except NothingHeld: + return Part.down(AIR_DEVICE, NOTHING_HELD[AIR_DEVICE], today) + except Exception as e: + log.warning("current: the air sensor's reading failed: %s", e) + return Part.down(AIR_DEVICE, UNAVAILABLE[AIR_DEVICE], today) + reading, at = latest.reading, latest.at.astimezone(tz) if latest.at else None + part, shown = Part(AIR_DEVICE, at=at), [] + for r in air: + entry = reading.get(r.column) + if isinstance(entry, dict) and entry.get("value") is not None: + part.entries.append((r, air_entry(r.column, entry))) + shown.append(r) + elif named: + part.missing.append(r.name) + part.lines = own_air_lines(reading, shown) if named else air_lines(reading) + part.heading = heading(AIR_DEVICE, at, today) + return part + + async def _live(self, station: list[Reading], named: bool, meta: dict) -> dict: + """The station's live reading for every group "weather now" shows (the reading it keeps, while that is fresh) and, only when they + are named, those of other readings (the piezo gauge: a request of its own); with `fetch` off, the reading it keeps, whatever its + age (NothingHeld when it keeps none).""" + from ..ecowitt.source import LIVE_GROUPS # (lazy: the station's package is the engine; this module only reads it) + eco = self.ctx.eco + groups = list(dict.fromkeys([*LIVE_GROUPS, *(r.sensor for r in station if named)])) + if not meta["fetch"]: + kept = getattr(eco, "_live", None) + if not kept: + raise NothingHeld() + return {g: kept[1][g] for g in groups if g in kept[1]} + return await eco._live_data(groups, urgent=meta["priority"] != BACKGROUND) + + async def _latest(self, extras: list[str], meta: dict): + """The air sensor's latest reading (AirGradient.latest), with its own temperature and humidity when named; with `fetch` off, only + when it holds one (NothingHeld otherwise).""" + if not meta["fetch"] and getattr(self.ctx.air, "_current", None) is None: + raise NothingHeld() + return await self.ctx.air.latest(extras) + + async def _context(self, station: list[Reading]) -> tuple[dict, dict]: + """The gauges' figures for the readings that have a gauge (context_on): their day rows of the year so far, in one read.""" + names = sorted({n for r in station if (g := gauge_of(r.name)) for n in (g.highest, g.lowest) if n}) + if not names: + return {}, {} + eco = self.ctx.eco + return await eco.storage.read(context_on, eco.mac, names, periods_of(self.ctx.now().date())["Yearly"]) + + +@dataclass +class Part: + """One device's part of the answer: its readings (each with its entry), its lines and heading, what was named but isn't read now, + why it gave nothing (when it didn't answer), and the time of its reading.""" + device: str + entries: list[tuple[Reading, dict]] = field(default_factory=list) + lines: list[str] = field(default_factory=list) + heading: str = "" + missing: list[str] = field(default_factory=list) + unavailable: str | None = None + at: datetime | None = None + + @classmethod + def down(cls, device: str, why: str, today: date) -> "Part": + """A device that gave nothing: the report's section for it ("Weather station", "• not available right now").""" + return cls(device, lines=[NOT_AVAILABLE], heading=heading(device, None, today), unavailable=why) + + +class NothingHeld(Exception): + """With `fetch` off, a device whose reading isn't held.""" + + +def air_entry(key: str, entry: dict) -> dict: + """{value, unit, text, [rating], [rating_note], [aqi_us, band]} of an air reading (AirGradient.latest()'s), with its text.""" + unit = entry.get("unit", "") + return {"value": entry["value"], "unit": unit, "text": air_shown(key, entry["value"], unit), + **{k: entry[k] for k in ("rating", "rating_note", "aqi_us", "band") if k in entry}} + + +COVERED = {"wind.wind_gust": "wind", "wind.wind_direction": "wind", "rainfall.rain_rate": "rain"} # in the line of another reading + + +def station_lines(now: dict, readings: list[Reading]) -> list[str]: + """The lines of the station's readings named: the bot's plain lookup's (reading_lines) for each reading it words, each on the sides + asked for it (outdoor, indoor; both when it has neither), then a line of its own for each other reading not in one of those.""" + names = list(dict.fromkeys(r.series for r in readings if r.series in WEATHER)) + out = [] + for name in names: + sides = [s for s in ("outdoor", "indoor") if any(r.sensor == s and r.series == name for r in readings)] or ["outdoor", "indoor"] + out += reading_lines(now, [name], sides) + _, tag = _getters(now) + for r in readings: + if r.series in WEATHER or COVERED.get(r.name) in names: + continue + own = next((f for f in (now.get(r.sensor) or {}) if column_of(r.sensor, f) == (r.column, "value")), None) + if own and (shown := tag(r.sensor, own)): + out.append(f"• {r.label}: {shown}") + return out + + +def own_air_lines(reading: dict, readings: list[Reading]) -> list[str]: + """The lines of the air readings named: the report's (air_lines) for its six, then the sensor's own temperature and humidity.""" + keys = [r.column for r in readings] + own = [f"• {r.label}: {air_shown(r.column, reading[r.column]['value'], reading[r.column].get('unit', ''))}" + for r in readings if r.column in AIR_OWN_METRICS] + return air_lines(reading, [k for k in keys if k in AIR]) + own + + +def tools(ctx: Context) -> list[ServiceTool]: + """The current tool, when there is a sensor to read.""" + return [CurrentTool(ctx).tool()] if ctx.eco or ctx.air else [] + + +__all__ = ["CurrentTool", "DESCRIPTION", "air_lines", "context_of", "gauge_of", "heading", "now_shaped", "parameters", "reading_lines", + "station_lines", "tools", "weather_lines"] diff --git a/tests/test_service_about.py b/tests/test_service_about.py new file mode 100644 index 00000000..5ff42889 --- /dev/null +++ b/tests/test_service_about.py @@ -0,0 +1,166 @@ +"""The `about` tool (lib/service/about.py): what the service measures and doesn't, how far back each kind of history goes, the alerts +there are with their thresholds; the lists the bot's prompt and Help had, the same.""" + +import json +import time +from datetime import timedelta +from types import SimpleNamespace as NS + +from lib import prompt, templates +from lib.airgradient import AirGradient +from lib.alerts import forecast as forecast_alert, menu, particulates, weather +from lib.ecowitt.glance import UVI_ALERT +from lib.service import about as ab +from lib.service.about import AboutTool +from lib.service.common import request_meta +from lib.service.context import Context +from lib.service.names import AIR_DEVICE, STATION +from lib.storage.catalogue import BOT +from lib.storage.coverage import merge +from lib.timeutil import day_bounds, day_text, local_date +from tests.fakes import TZ, air_transport, archived_station, config + +EVERY = ["Ecowitt", "AirGradient", "Pollen", "Forecast"] + + +async def call(ctx: Context, args=None) -> dict: + return json.loads(await AboutTool(ctx).tool().call(args or {})) + + +async def world(tmp_path, archived_cache, *, air=True, others=True): + """A Context over the archived station, the fake air sensor's cloud beside it in the same file, and (others) stand-ins for the + forecast and the pollen sources (about only asks whether they are there).""" + eco, _ = await archived_station(tmp_path, archived_cache) + sensor = None + if air: + transport, _ = air_transport() + sensor = AirGradient(config(tmp_path), transport=transport, storage=eco.storage, owned=False) + return await Context.open(eco=eco, air=sensor, forecast=NS() if others else None, pollen=NS() if others else None) + + +async def close(ctx: Context): + if ctx.air: + await ctx.air.close() + await ctx.eco.close() + + +# ---------- the tool ---------- +def test_the_description_says_what_it_answers_and_that_alerts_cant_be_added_by_asking(): + d = ab.DESCRIPTION + assert len(d) < 1500 + for said in ("what can you do", "lightning", "how far back", "what alerts are there", "{} (no arguments)", + "can't be added or changed by asking", "current (now)", "summary (a period)", "history", "alerts_note", "lines"): + assert said in d, said + (tool,) = ab.tools(Context()) + assert tool.name == "about" and tool.parameters == {"type": "object", "properties": {}} + assert tool.annotations == {"readOnlyHint": True, "openWorldHint": False} + + +async def test_arguments_are_refused_with_how_to_call_it(): + got = json.loads(await AboutTool(Context()).tool().call({"topic": "alerts"})) + assert got == {"error": "about takes no arguments, not 'topic': call it with {}.", "arguments": []} + + +def test_the_lists_are_the_ones_the_bots_prompt_menu_and_help_had(): + assert ab.NEVER_AVAILABLE == prompt.NEVER_AVAILABLE and ab.WITHOUT == prompt.WITHOUT and ab.ALERT_WORDS == prompt.ALERT_WORDS + assert ab.TYPES == {kind: v for kind, v in menu.TYPES.items() if v[1] != "Irrigation"} # (irrigation: a server of its own) + assert ab.MEASURES == templates.MEASURES + for sources in (EVERY, ["Ecowitt"], ["AirGradient", "Pollen"], []): + assert "\n".join(ab.measure_lines(sources)) == templates.capabilities_text(sources) # the Help list, word for word + + +# ---------- what it measures ---------- +async def test_what_it_measures_and_doesnt_for_the_sources_there_are(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + got = await call(ctx) + assert "period" not in got and "as_of" not in got and "fresh" not in got # no figures of the weather, nothing to call again + m = got["measures"] + assert list(m) == [STATION, AIR_DEVICE, "forecast", "pollen"] + assert m[STATION]["text"].startswith("Weather station (Ecowitt): outdoor and indoor temperature") + assert m[STATION]["readings"]["outdoor.temperature"] == "Outdoor temperature (°C)" and m[AIR_DEVICE]["readings"]["air.voc_index"] == "VOC index" + assert set(m[STATION]["readings"]) | set(m[AIR_DEVICE]["readings"]) == set(ctx.readings().names) # the readings the file holds + assert got["not_available"] == ab.NEVER_AVAILABLE + assert list(got["tools"]) == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen"] + assert [a["kind"] for a in got["alerts"]] == list(ab.TYPES) + assert got["lines"] == templates.capabilities_text(EVERY).splitlines() + assert json.loads(await AboutTool(ctx).tool().call({}, request_meta({"fetch": False}))) == got # (it reads only what is held) + await close(ctx) + + (tmp_path / "alone").mkdir() + alone = await world(tmp_path / "alone", archived_cache, air=False, others=False) + got = await call(alone) + assert list(got["measures"]) == [STATION] + assert got["not_available"] == [*ab.NEVER_AVAILABLE, *prompt.WITHOUT.values(), "air quality"] + assert [a["kind"] for a in got["alerts"]] == ["rain", "gusts", "uv", "temps"] # the station's alerts alone + assert "scan" not in got["tools"] and "forecast" not in got["tools"] and "outlook" in got["tools"] + await close(alone) + + +# ---------- the alerts ---------- +def test_each_alert_has_its_rule_and_the_thresholds_the_rules_use(monkeypatch): + rules = {a["kind"]: a for a in ab.alerts(EVERY)} + assert rules["gusts"]["thresholds"]["gust_kmh"] == weather.GUST_ALERT_KMH and "over 40 km/h" in rules["gusts"]["rule"] + assert rules["uv"]["thresholds"] == {"uv_index": UVI_ALERT, "readings_in_a_row": 2, "rearm_minutes": weather.UV_REARM_SECONDS // 60} + assert rules["temps"]["thresholds"]["margin_c"] == weather.CROSS_MARGIN + p = rules["particulates"]["thresholds"] + assert (p["mask_pm2_5"], p["mask_pm10"], p["safe_pm2_5"], p["safe_pm10"]) == (particulates.MASK_PM25, particulates.MASK_PM10, + particulates.SAFE_PM25, particulates.SAFE_PM10) + assert "55.5 µg/m³" in rules["particulates"]["rule"] and "AQI 151" in rules["particulates"]["rule"] + assert rules["forecast"]["thresholds"]["max_change_c"] == forecast_alert.TEMP_CHANGE_C + assert rules["pollen_and_asthma"]["thresholds"] == {"from_level": "High"} and "from 7:30am" in rules["pollen_and_asthma"]["rule"] + assert rules["rain"]["thresholds"] == {"dry_minutes": 60, "quiet_hours": "00:00-06:00"} + assert rules["rain"]["rule"].endswith("None from 12am to 6am: one summary of the rain in those hours after them.") + assert all(a["what"] == prompt.ALERT_WORDS[a["kind"]] and a["name"] == menu.LABELS[a["kind"]] for a in rules.values()) + monkeypatch.setattr(ab, "RAIN_QUIET_HOURS", None) # the service's settings, as the config sets them + monkeypatch.setattr(ab, "ALERT_COOLDOWN_MINUTES", 90) + rules = {a["kind"]: a for a in ab.alerts(EVERY)} + assert rules["rain"]["thresholds"] == {"dry_minutes": 90, "quiet_hours": None} and "None from" not in rules["rain"]["rule"] + assert "at most one every 90 minutes" in rules["temps"]["rule"] + assert "can't be added or changed by asking" in ab.ALERTS_NOTE + + +# ---------- how far back ---------- +async def test_the_history_is_what_the_file_holds_at_each_resolution(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + eco, air = ctx.eco, ctx.air + now = time.time() + minutes = {"outdoor": {"temperature": {"unit": "℃", "list": {str(int(now) // 60 * 60 - 60 * k): "12.3" for k in range(5)}}}} + await eco.storage.write(lambda w: w.put_minutes(eco.mac, minutes, now)) + day = local_date(int(now), TZ) - timedelta(days=3) + start = day_bounds(day, TZ)[0] + await air.store.save_day(day, [{"ts": start + 300 * k, "pm2_5": 5.0} for k in range(288)]) # a day at 5 minutes + older = day - timedelta(days=200) + await air.store.save_day(older, [{"ts": day_bounds(older, TZ)[0] + 3600 * k, "pm2_5": 5.0} for k in range(24)]) # one of hourly averages + await air.store.add_minutes([{"ts": int(now) // 60 * 60, "pm2_5": 4.0}], BOT, now) + got = (await call(ctx))["history"] + + station = got[STATION] + sensors = list(eco.storage.station(eco.mac).values()) + for res in ("5min", "30min", "4hour", "1day"): + spans = merge([s for sensor in sensors for s in eco.storage.coverage.of(sensor.id, res)]) + assert station["held"][res] == {"from": local_date(spans[0][0], TZ).isoformat(), "to": local_date(spans[-1][1], TZ).isoformat(), + "days": sum(e - s + 1 for s, e in spans) // 86400}, res + first_5min = local_date(merge([s for sensor in sensors for s in eco.storage.coverage.of(sensor.id, "5min")])[0][0], TZ) + minute = local_date(int(now) // 60 * 60 - 240, TZ) + assert station["held"]["1min"]["from"] == minute.isoformat() + assert station["text"].startswith(f"Weather station: minute readings from {day_text(minute)} (kept 10 days), 5-minute readings from " + f"{day_text(first_5min)}, 30-minute readings from ") + assert "daily records from " in station["text"] and ", each 10am to 10am" in station["text"] + + sky = got[AIR_DEVICE] + assert sky["held"]["5min"] == {"from": day.isoformat(), "to": day.isoformat(), "days": (day_bounds(day, TZ)[1] - start) // 86400} + assert sky["held"]["1hour"]["from"] == older.isoformat() and "1min" in sky["held"] + today = local_date(int(now) // 60 * 60, TZ) + assert sky["text"] == (f"Air sensor: minute readings from {day_text(today)} (kept 10 days), 5-minute readings from {day_text(day)}, " + f"hourly averages from {day_text(older)}. The tools use the finest held for each part of a period.") + await close(ctx) + + +async def test_a_sensor_with_nothing_held_says_so(tmp_path, archived_cache): + ctx = await world(tmp_path, archived_cache) + assert (await call(ctx))["history"][AIR_DEVICE] == {"text": "Air sensor: nothing held yet.", "held": {}} + await close(ctx) + + +def test_the_module_says_what_it_offers(): + assert all(hasattr(ab, name) for name in ab.__all__) diff --git a/tests/test_service_current.py b/tests/test_service_current.py new file mode 100644 index 00000000..8891d502 --- /dev/null +++ b/tests/test_service_current.py @@ -0,0 +1,390 @@ +"""The `current` tool (lib/service/current.py): the readings now from both sensors, every one or those named, with the gauges' highs and +lows beside them on request, and the bot's own words for them (its report, "weather now" and plain lookups), unchanged.""" + +import json +import re +import time +from datetime import date, datetime + +import pytest + +from lib import report +from lib.airgradient import AirGradient +from lib.ecowitt.days import day_values_on +from lib.intent import NOW_GROUPS +from lib.service import current as cur +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.current import CurrentTool, heading +from lib.service.names import AIR_DEVICE, STATION, Catalogue +from lib.timeutil import clock_text, to_local +from tests.fakes import TZ, air_transport, archived_station, config + +WHEN = re.compile(r"^(at|around) \d{1,2}(:\d\d)?[ap]m$|^sometime between ") + + +def live(at: float, **changes) -> dict: + """A live reading as Ecowitt's real_time gives it ({group: {field: {time, unit, value}}}): the station's own on a wet night (what + tests/test_report.py's NOW was written from), with `changes` ("outdoor.temperature": "36.0", or None to leave a reading out).""" + t = str(int(at)) + data = {"outdoor": {"temperature": ("12.3", "℃"), "feels_like": ("12.3", "℃"), "app_temp": ("12.7", "℃"), "dew_point": ("11.3", "℃"), + "vpd": ("0.085", "kPa"), "humidity": ("94", "%")}, + "indoor": {"temperature": ("18.3", "℃"), "humidity": ("63", "%"), "dew_point": ("11.1", "℃"), "feels_like": ("18.3", "℃"), + "app_tempin": ("18.7", "℃")}, + "solar_and_uvi": {"solar": ("0.0", "W/m²"), "uvi": ("0", "")}, + "rainfall": {"rain_rate": ("1.8", "mm/hr"), "daily": ("6.3", "mm"), "event": ("49.8", "mm"), "1_hour": ("1.3", "mm"), + "weekly": ("49.8", "mm"), "monthly": ("49.8", "mm"), "yearly": ("5105.7", "mm")}, + "wind": {"wind_speed": ("0.0", "km/h"), "wind_gust": ("0.0", "km/h"), "wind_direction": ("131", "º")}, + "pressure": {"relative": ("1025.0", "hPa"), "absolute": ("1009.5", "hPa")}} + out = {g: {f: {"time": t, "unit": u, "value": v} for f, (v, u) in fields.items()} for g, fields in data.items()} + for name, value in changes.items(): + group, field = name.split(".") + if value is None: + out[group].pop(field, None) + else: + out[group][field] = {**out[group].get(field, {"time": t, "unit": ""}), "value": value} + return out + + +DAY = {"solar_and_uvi.solar": "612.5", "solar_and_uvi.uvi": "7", "wind.wind_speed": "14.0", "wind.wind_gust": "31.0"} # sunny and breezy +HOT = {"outdoor.temperature": "36.0", "outdoor.humidity": "90", "indoor.temperature": "29.0", "indoor.humidity": "20", + "pressure.relative": "1030.0", "rainfall.rain_rate": "2.0", "rainfall.daily": "3.0", "rainfall.monthly": "9.0", + "solar_and_uvi.solar": "800.0", "solar_and_uvi.uvi": "10", "wind.wind_speed": "55.0", "wind.wind_gust": "70.0", + "wind.wind_direction": "90"} # every emoji there is (tests/test_report.py) +DRY = {"rainfall.rain_rate": "0.0", "rainfall.daily": "0.0", "rainfall.monthly": "12.0", "wind.wind_speed": "12.0", + "wind.wind_gust": "20.0", "wind.wind_direction": "270"} + + +class Station: + """The archived fake station, its live reading what the test says (a request counted, and whether it was urgent).""" + + def __init__(self, eco, data: dict | None): + self.eco, self.data, self.asked = eco, data, [] + eco.api.realtime = self.realtime + + async def realtime(self, mac, groups, urgent=False): + self.asked.append(urgent) + if isinstance(self.data, Exception): + raise self.data + return json.loads(json.dumps(self.data)) + + def reads(self, data): + """A new live reading, asked for afresh (the kept one forgotten).""" + self.data, self.eco._live = data, None + + +async def world(tmp_path, archived_cache, data=None, *, air=True, station=True, catalogue=None): + """(the tool, the Station, the AirGradient or None): the archived station reading `data` now (default: the wet night), the fake air + sensor's cloud beside it in the same file. catalogue "file": the readings the file holds (Catalogue.open); None: every reading.""" + eco, _ = await archived_station(tmp_path, archived_cache) + stand_in = Station(eco, live(time.time()) if data is None else data) + sensor = None + if air: + transport, _ = air_transport() + sensor = AirGradient(config(tmp_path), transport=transport, storage=eco.storage, owned=False) + await sensor.start() + ctx = Context(eco=eco if station else None, air=sensor) + if catalogue == "file": + ctx.catalogue = await Catalogue.open(ctx.eco, ctx.air) + tool = CurrentTool(ctx) + tool.opened = [s for s in (sensor, eco) if s is not None] # (what close() closes: the station too, when the tool isn't given it) + return tool, stand_in, sensor + + +async def close(tool): + for source in tool.opened: + await source.close() + + +async def call(tool, meta=None, **args) -> dict: + return json.loads(await tool.tool().call(args, meta)) + + +# ---------- the tool ---------- +def test_the_description_says_what_it_answers_with_an_example_each_and_where_the_rest_goes(): + d = cur.DESCRIPTION + assert len(d) < 1500 + for said in ("{}", "{readings: [\"temperature\"]}", "{readings: [\"rain\"]}", "{context: true}", "report, status or sitrep", + "forecast", "pollen", "will it rain (outlook)", "(summary)", "(readings)", "lines", "missing", "unavailable"): + assert said in d, said + schema = cur.parameters("Readings, as `sensor.reading`.") + assert set(schema["properties"]) == {"readings", "context"} and "required" not in schema + assert schema["properties"]["readings"]["description"].endswith("Default: every reading the station and the air sensor have now.") + + +async def test_it_is_offered_with_a_sensor_and_says_it_asks_the_devices(tmp_path, archived_cache): + assert cur.tools(Context()) == [] + tool, _, _ = await world(tmp_path, archived_cache) + (made,) = cur.tools(tool.ctx) + assert made.name == "current" and made.annotations == {"readOnlyHint": True, "openWorldHint": True} + assert "outdoor.temperature" in made.parameters["properties"]["readings"]["description"] + await close(tool) + + +# ---------- the readings now ---------- +async def test_every_reading_now_with_its_value_unit_words_and_emoji(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache) + got = await call(tool) + assert "period" not in got and got["fresh"] == FRESH and "charts" not in got and "missing" not in got + s = got["sensors"] + assert s["outdoor"]["temperature"] == {"value": 12.3, "unit": "°C", "text": "12.3 °C", "emoji": "🧥"} + assert s["outdoor"]["humidity"] == {"value": 94, "unit": "%", "text": "94 %", "emoji": "💦"} + assert s["indoor"]["app_temp"]["text"] == "18.7 °C" # (the station calls it app_tempin) + assert s["outdoor"]["vpd"] == {"value": 0.085, "unit": "kPa", "text": "0.085 kPa"} # nothing to notice: no emoji + assert s["rainfall"]["rain"] == {"value": 6.3, "unit": "mm", "text": "6.3 mm", "emoji": "☔"} # today's rain so far + assert s["rainfall"]["rain_rate"]["text"] == "1.8 mm/h" and s["rainfall"]["rain_rate"]["emoji"] == "🌧️" + assert s["wind"]["wind_direction"] == {"value": 131, "unit": "°", "text": "131°", "compass": "SE"} + assert s["solar_and_uvi"]["uvi"] == {"value": 0, "unit": "", "text": "0"} + assert s["pressure"]["absolute"]["text"] == "1009.5 hPa" + assert "rainfall_piezo" not in s # every reading the sensors have now: this station has no piezo gauge + pm = s["air"]["pm2_5"] + assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and pm["aqi_us"] == 56 and pm["band"] == "moderate" + assert pm["rating"].endswith(("good", "poor")) + assert s["air"]["co2"]["text"] == "450 ppm" and s["air"]["nox_index"]["text"] == "1.0" and s["air"]["voc_index"]["text"] == "100" + assert s["air"]["temperature"]["unit"] == "°C" and "rating" not in s["air"]["temperature"] # the sensor's own: no rating + newest = datetime.fromisoformat(got["as_of"]["time"]) + assert abs(newest.timestamp() - time.time()) < 60 and got["as_of"]["text"].endswith(clock_text(newest)) + assert station.asked == [True] # someone is waiting: the station's request goes first + await close(tool) + + +async def test_named_readings_alone_each_once_in_the_order_named(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache) + got = await call(tool, readings=["rain", "temperature", "pm2.5", "gust"]) + assert [(g, list(r)) for g, r in got["sensors"].items()] == [("rainfall", ["rain"]), ("outdoor", ["temperature"]), + ("indoor", ["temperature"]), ("wind", ["wind_gust"]), ("air", ["pm2_5"])] + assert set(got["lines"]) == {STATION, AIR_DEVICE} and got["lines"][AIR_DEVICE] == ["• PM2.5: " + got["sensors"]["air"]["pm2_5"]["text"] + + f" {got['sensors']['air']['pm2_5']['rating']} (AQI 56)"] + assert (await call(tool, readings="indoor temperature, outdoor humidity"))["sensors"] == { + "indoor": {"temperature": {"value": 18.3, "unit": "°C", "text": "18.3 °C", "emoji": "🧥"}}, + "outdoor": {"humidity": {"value": 94, "unit": "%", "text": "94 %", "emoji": "💦"}}} # (a string of names will do) + only_air = await call(tool, readings=["air"]) + assert list(only_air["sensors"]) == ["air"] and list(only_air["sensors"]["air"]) == ["pm2_5", "pm10", "pm1", "co2", "voc_index", + "nox_index"] + assert set(only_air["lines"]) == {AIR_DEVICE} + await close(tool) + + +async def test_a_reading_named_that_isnt_being_read_now_is_missing(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, live(time.time(), **{"indoor.temperature": None})) + got = await call(tool, readings=["indoor temperature", "pressure", "piezo rain"]) + assert got["missing"] == ["indoor.temperature", "rainfall_piezo.rain"] and list(got["sensors"]) == ["pressure"] + with_context = await call(tool, readings=["indoor temperature"], context=True) # a gauge with no reading now: its figures, dimmed + entry = with_context["sensors"]["indoor"]["temperature"] + assert entry["value"] is None and entry["unit"] == "°C" and entry["year"]["high"] > entry["year"]["low"] + assert with_context["missing"] == ["indoor.temperature"] + await close(tool) + + +async def test_the_readings_listed_are_those_the_file_holds(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache, catalogue="file") # the fake station's history has no indoor humidity + got = await call(tool) + assert list(got["sensors"]["indoor"]) == ["temperature"] and "• Indoor: 🧥 18.3 °C, 63 %" in got["lines"][STATION] # (the report's words: as today) + await close(tool) + + +# ---------- the words: the bot's, unchanged ---------- +@pytest.mark.parametrize("changes", [{}, DAY, HOT, DRY], ids=["wet-night", "sunny", "every-emoji", "dry"]) +async def test_the_lines_are_the_reports_and_weather_nows_words(tmp_path, archived_cache, changes): + tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) + got = await call(tool) + eco, today = tool.ctx.eco, tool.ctx.now().date() + weather_now, air_quality = await eco._realtime({"groups": NOW_GROUPS}), await air.handle({}) # today's tools, on the same readings + written = "\n\n".join(f"{got['headings'][d]}\n" + "\n".join(got["lines"][d]) for d in (STATION, AIR_DEVICE)) + assert written == report.report({"weather_now": weather_now, "air_quality": air_quality}, today) + assert "\n".join(got["lines"][STATION]) == report.weather_now(weather_now) + assert got["lines"][AIR_DEVICE] == report.air_lines(json.loads(air_quality)) + await close(tool) + + +# (the bot's plain lookup: the readings the words name, and the sides) -> what a model sends for the same question +LOOKUPS = [(["temperature"], ["outdoor", "indoor"], ["temperature"]), # "how hot is it" + (["temperature"], ["indoor"], ["indoor temperature"]), # "indoor temperature" + (["humidity"], ["outdoor"], ["outdoor humidity"]), + (["rain"], ["outdoor", "indoor"], ["rain"]), # "is it raining" + (["wind"], ["outdoor", "indoor"], ["wind"]), + (["uv"], ["outdoor", "indoor"], ["uv"]), + (["pressure"], ["outdoor", "indoor"], ["pressure"]), + (["solar"], ["outdoor", "indoor"], ["solar"]), + (["dew_point"], ["outdoor", "indoor"], ["dew point"]), + (["dew_point"], ["indoor"], ["indoor dew point"]), + (["feels_like"], ["outdoor", "indoor"], ["feels like"]), + (["temperature", "rain"], ["outdoor", "indoor"], ["temperature", "rain"])] + + +@pytest.mark.parametrize("changes", [{}, DAY, DRY], ids=["wet-night", "sunny", "dry"]) +async def test_named_readings_are_worded_as_the_bots_plain_lookups(tmp_path, archived_cache, changes): + tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) + eco, today = tool.ctx.eco, tool.ctx.now().date() + weather_now = await eco._realtime({"groups": NOW_GROUPS}) + for names, sides, asked in LOOKUPS: + got = await call(tool, readings=asked) + assert "\n".join(got["lines"][STATION]) == report.lookup("reading", weather_now, names, sides, today), asked + air_quality = await air.handle({}) + for names, asked in ((["pm10"], ["pm10"]), (["co2", "pm2_5"], ["co2", "pm2.5"]), ([], ["air"]), ([], ["airgradient"])): + got = await call(tool, readings=asked) + assert "\n".join(got["lines"][AIR_DEVICE]) == report.lookup("air", air_quality, names, [], today), asked + await close(tool) + + +async def test_readings_the_bot_never_worded_have_a_line_of_their_own(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache, live(time.time(), **DAY)) + got = await call(tool, readings=["gust", "wind direction", "rain rate", "absolute pressure", "airgradient temperature"]) + assert got["lines"][STATION] == ["• Wind gust: 🌬️ 31.0 km/h", "• Wind direction: 131°", "• Rain rate: 🌧️ 1.8 mm/h", + "• Absolute pressure: 1009.5 hPa"] + assert got["lines"][AIR_DEVICE] == [f"• AirGradient temperature: {got['sensors']['air']['temperature']['text']}"] + wind = await call(tool, readings=["wind", "gust"]) # the gusts are in the wind's line already + assert wind["lines"][STATION] == ["• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h"] + await close(tool) + + +def test_the_heading_has_the_time_of_the_reading_with_its_day_when_that_isnt_today(): + today = date(2026, 11, 10) + assert heading(STATION, datetime(2026, 11, 10, 2, 21, tzinfo=TZ), today) == "Weather station (2:21am)" + assert heading(AIR_DEVICE, datetime(2026, 11, 9, 23, 45, tzinfo=TZ), today) == "Air quality (Mon 9 Nov 11:45pm)" + assert heading(STATION, None, today) == "Weather station" + old = json.dumps({"time": "Mon 9 Nov 2026 11:45pm", "pm2_5": {"value": 1.0, "unit": "µg/m³"}}) + assert report.report({"air_quality": old}, today).splitlines()[0] == "Air quality (Mon 9 Nov 11:45pm)" # (as the report writes it) + + +# ---------- context: the gauges' figures ---------- +async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache, live(time.time(), **DAY)) + got = await call(tool, context=True) + tiles = {t.title: t.rows for t in (await tool.ctx.eco.dashboard()).tiles} + s = got["sensors"] + for title, (sensor, reading) in (("Temperature", ("outdoor", "temperature")), ("Humidity", ("outdoor", "humidity")), + ("Atmospheric pressure", ("pressure", "relative")), ("Dew point", ("outdoor", "dew_point")), + ("Indoor temperature", ("indoor", "temperature"))): + entry = s[sensor][reading] + for row, key in cur.PERIODS: + assert (entry[key]["high"], entry[key]["low"]) == tiles[title][row], (title, row) + assert WHEN.match(entry[key]["high_when"]) and WHEN.match(entry[key]["low_when"]), entry[key] + assert ("high_date" in entry[key]) is (key != "today") + assert s["outdoor"]["temperature"]["year"]["high_text"] == f"{s['outdoor']['temperature']['year']['high']:.1f} °C" + assert s["outdoor"]["humidity"]["year"]["low_text"] == f"{s['outdoor']['humidity']['year']['low']:.0f} %" + wind = s["wind"]["wind_speed"] + assert [wind[k]["high_gust"] for _, k in cur.PERIODS] == [tiles["Wind"][row][0] for row, _ in cur.PERIODS] + assert s["wind"]["wind_gust"]["year"]["high"] == wind["year"]["high_gust"] # the gusts' own: the same figure + rain = s["rainfall"]["rain"] + assert rain["today"] == {"total": 6.3, "total_text": "6.3 mm"} # the gauge's own reading + for row, key in cur.PERIODS[1:]: + wettest, total = tiles["Rain"][row] + assert rain[key]["total"] == total and rain[key]["wettest_day"]["rain"] == wettest + assert s["solar_and_uvi"]["uvi"]["year"]["high_text"] == "11" # written as the station writes it + assert "today" not in s["outdoor"]["vpd"] and "today" not in s["air"]["pm2_5"] # no gauge, no context + await close(tool) + + +async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache) + got = await call(tool, readings=["outdoor temperature"], context=True) + year = got["sensors"]["outdoor"]["temperature"]["year"] + on = datetime.strptime(year["high_date"], "%a %d %b %Y").date() + eco = tool.ctx.eco + values, _ = await eco.storage.read(day_values_on, eco.mac, ["temp_max"], [on]) + assert values["temp_max"][on] == year["high"] # the day whose row has it + at = time.time() + station.reads(live(at, **{"outdoor.temperature": "45.0"})) # hotter than any day held + hot = (await call(tool, readings=["outdoor temperature"], context=True))["sensors"]["outdoor"]["temperature"] + clock = f"at {clock_text(to_local(int(at), TZ), whole_hours=True)}" + for key in ("today", "month", "year"): + assert hot[key]["high"] == 45.0 and hot[key]["high_when"] == clock and hot[key]["high_text"] == "45.0 °C" + assert hot["month"]["high_date"] == f"{to_local(int(at), TZ):%a} {to_local(int(at), TZ).day} {to_local(int(at), TZ):%b %Y}" + await close(tool) + + +# ---------- refusals that teach, and devices that don't answer ---------- +async def test_a_wrong_call_is_refused_with_what_fixes_it(tmp_path, archived_cache): + tool, _, _ = await world(tmp_path, archived_cache) + then = await call(tool, period="yesterday") + assert "summary" in then["error"] and "readings" in then["error"] and then["arguments"] == ["readings", "context"] + other = await call(tool, groups="outdoor") + assert other["error"] == "'groups' is not an argument of current." and other["arguments"] == ["readings", "context"] + unknown = await call(tool, readings=["lightning"]) + assert "isn't a reading" in unknown["error"] and "outdoor.temperature" in unknown["names"] and "rain" in unknown["words"] + assert "true or false" in (await call(tool, context="maybe"))["error"] + assert (await call(tool, context="true"))["sensors"]["outdoor"]["temperature"]["today"] # (true written as a word will do) + await close(tool) + + (tmp_path / "station").mkdir() + tool, _, _ = await world(tmp_path / "station", archived_cache, air=False) + no_air = await call(tool, readings=["pm2.5"]) + assert no_air["error"] == "air.pm2_5 is the air sensor's, and this service has no air sensor." and "air.pm2_5" not in no_air["names"] + assert "air" not in (await call(tool))["sensors"] # unnamed: just the sensors there are + await close(tool) + + +async def test_a_device_that_doesnt_answer_is_said_so_and_the_other_still_answers(tmp_path, archived_cache): + tool, station, air = await world(tmp_path, archived_cache, RuntimeError("Ecowitt: System is busy.")) + got = await call(tool) + assert got["unavailable"] == {STATION: "The weather station isn't answering right now."} + assert got["lines"][STATION] == ["• not available right now"] and got["headings"][STATION] == "Weather station" + assert list(got["sensors"]) == ["air"] and got["as_of"] + written = "\n\n".join(f"{got['headings'][d]}\n" + "\n".join(got["lines"][d]) for d in (STATION, AIR_DEVICE)) + assert written == report.report({"weather_now": "Error calling tool: busy", "air_quality": await air.handle({})}, + tool.ctx.now().date()) # the report's words for it + + async def down(extras=()): + raise RuntimeError("AirGradient current failed: HTTP 500") + air.latest = down + station.reads(live(time.time())) + got = await call(tool) + assert got["unavailable"] == {AIR_DEVICE: "The air sensor isn't answering right now."} and "air" not in got["sensors"] + assert f"{got['headings'][AIR_DEVICE]}\n{got['lines'][AIR_DEVICE][0]}" == "Air quality\n• not available right now" + neither = RuntimeError("down") + station.reads(neither) + nothing = await call(tool) + assert set(nothing["unavailable"]) == {STATION, AIR_DEVICE} and nothing["sensors"] == {} and "as_of" not in nothing + await close(tool) + + +# ---------- the request's metadata ---------- +async def test_without_fetching_it_answers_from_the_reading_held(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache) + nothing = await call(tool, {"fetch": False}, readings=["temperature"]) + assert nothing["unavailable"] == {STATION: "No reading of the weather station is held (and `fetch` is off)."} and station.asked == [] + await call(tool, readings=["temperature"]) + station.data = live(time.time(), **{"outdoor.temperature": "20.0"}) + tool.ctx.eco._live = (time.time() - 3600, tool.ctx.eco._live[1]) # an hour old: a question would ask again + held = await call(tool, {"fetch": False}, readings=["outdoor temperature"]) + assert held["sensors"]["outdoor"]["temperature"]["value"] == 12.3 and station.asked == [True] + assert (await call(tool, readings=["outdoor temperature"]))["sensors"]["outdoor"]["temperature"]["value"] == 20.0 + await close(tool) + + +async def test_the_kept_reading_answers_while_fresh_and_a_group_it_lacks_is_asked_for_when_named(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, air=False, catalogue="file") + assert "rainfall_piezo.rain" in tool.ctx.readings() # (a group that never sent anything is offered whole) + await call(tool) + await call(tool, context=True) + await call(tool, readings=["temperature", "rain"]) + assert station.asked == [True] # one request: the reading the station keeps answers the rest + await call(tool, readings=["piezo rain"]) + assert station.asked == [True, True] # a group "weather now" doesn't show: asked for when named + await close(tool) + + +async def test_a_background_request_asks_the_station_behind_those_someone_waits_for(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, air=False) + await call(tool, {"priority": "background"}) + station.reads(live(time.time())) + await call(tool) + assert station.asked == [False, True] + await close(tool) + + +async def test_the_air_sensor_alone_and_its_own_temperature(tmp_path, archived_cache): + tool, station, _ = await world(tmp_path, archived_cache, station=False) + got = await call(tool, readings=["airgradient temperature", "airgradient humidity"]) + t, h = got["sensors"]["air"]["temperature"], got["sensors"]["air"]["humidity"] + assert t["unit"] == "°C" and t["text"] == f"{t['value']:.1f} °C" and h["text"] == f"{h['value']:.0f} %" + assert got["lines"] == {AIR_DEVICE: [f"• AirGradient temperature: {t['text']}", f"• AirGradient humidity: {h['text']}"]} + everything = await call(tool) + assert list(everything["sensors"]) == ["air"] and list(everything["lines"]) == [AIR_DEVICE] and station.asked == [] + assert everything["headings"][AIR_DEVICE].startswith("Air quality (") + await close(tool) + + +def test_the_module_says_what_it_offers(): + assert all(hasattr(cur, name) for name in cur.__all__) From 36fb8434f7e3171cc5c977f22ae4bf44df5e17d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 04:52:23 +0000 Subject: [PATCH 030/125] lib/service: outlook, forecast and pollen, three of the ten tools (3.3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - outlook (no arguments): will it rain in the next few hours, by the prompt's outlook rules worked out in code from the station's last 3 hours of 5-minute readings (as Ecowitt.recent reads them) and its reading now: the pressure tendency from whether the high or the low came first (down more than 3 hPa likely, 1-3 possible, under 1 or rising unlikely), a step towards rain for each of unsettled pressure (under 1005 hPa), moist air (humidity 90% or more, or within 2 °C of the dew point) and wind picking up while pressure falls, a step away for settled pressure (over 1020 hPa), and rain now or in the last hour making it likely. Result: verdict, reason ready to quote, pressure, moisture, recent_rain, wind_trend, and the forecast's lines for today and tomorrow when the forecast is on. - forecast (`period`, default "the next 7 days"): the days ahead in words read here (today, tomorrow, next N days, this weekend, next week, a weekday, a date); the past is refused pointing to summary. Result: weather_forecast's lines, each day's figures, place, source, fetched_at, and `text`, the bot's forecast section word for word. - pollen (no arguments): pollen_asthma's lines, each level with its emoji and day, in_season, fetched_at, and `text`, the bot's pollen section word for word; out of season, pollen_asthma's own answer. Request _meta fetch false answers from what is held (today's cached); background priority makes the outlook's fetches wait their turn. Not registered anywhere yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/service/forecast.py | 243 +++++++++++++++++++++++++ lib/service/outlook.py | 309 +++++++++++++++++++++++++++++++ lib/service/pollen.py | 78 ++++++++ tests/test_service_forecast.py | 224 +++++++++++++++++++++++ tests/test_service_outlook.py | 320 +++++++++++++++++++++++++++++++++ tests/test_service_pollen.py | 90 ++++++++++ 6 files changed, 1264 insertions(+) create mode 100644 lib/service/forecast.py create mode 100644 lib/service/outlook.py create mode 100644 lib/service/pollen.py create mode 100644 tests/test_service_forecast.py create mode 100644 tests/test_service_outlook.py create mode 100644 tests/test_service_pollen.py diff --git a/lib/service/forecast.py b/lib/service/forecast.py new file mode 100644 index 00000000..3268867c --- /dev/null +++ b/lib/service/forecast.py @@ -0,0 +1,243 @@ +"""The `forecast` tool (docs/mcp-service.md 3.3): today and the days ahead, from the forecast source (lib/forecast, Open-Meteo), for a +period in words that look ahead ("tomorrow", "next 3 days", "this weekend"), read here: lib/periods_text.py reads only what has been +measured, and refuses the future by pointing to this tool. + +The answer is today's weather_forecast's, in the service's shape: the same `lines` (lib/forecast/source.py day_label and describe_day), +each day's figures in `days`, `place`, `source` and `fetched_at`, and `text`, the bot's forecast section ("Forecast (Melbourne, +6:00pm)" and a bullet per line, lib/report.py's report and lookup) written here so a client can send it as it is. +Request `_meta` `fetch: false` answers from the forecast held, fetching nothing (the report's `cached`). + +`section` writes a heading and bullets as the bot does for the sources that bring their own lines (pollen.py uses it too), and +`held_days` and `day_lines` are what outlook.py reads the forecast with. +""" + +import logging +import re +from datetime import date, datetime, time, timedelta, tzinfo + +from ..forecast.source import SOURCE, day_label, describe_day +from ..periods_text import NUMBER_WORDS, WEEKDAY_NAMES, Period, PeriodError, read_period as read_past +from ..timeutil import clock_text, day_text, to_local +from .common import Refusal, ServiceTool, answer, iso + +log = logging.getLogger(__name__) + +DEFAULT = "the next 7 days" # weather_forecast's default: today and the six days after it +HEADING = "Forecast" # the bot's heading for it (lib/report.py SECTIONS) +NO_FORECAST = "No forecast is available right now." # (weather_forecast's own words) +FOR_WHAT_WAS = "summary (or days, for days ranked or counted)" + +# ---------- the period, looking ahead ---------- +_N = rf"(?P\d+|{'|'.join(NUMBER_WORDS)})" +_WEEKDAYS = {name.lower(): i for i, name in enumerate(WEEKDAY_NAMES)} | { + "mon": 0, "tue": 1, "tues": 1, "wed": 2, "weds": 2, "thu": 3, "thur": 3, "thurs": 3, "fri": 4, "sat": 5, "sun": 6} +# "over the weekend", "for tomorrow", "in the next 3 days" (but not "in 3 days", which is one day) +LEAD = re.compile(r"(?:in (?=the |next |coming |upcoming )|(?:over|during|for|within|across|throughout|on|from) )(?P.+)") +TODAY = re.compile(r"today|(?:the )?rest of (?:the|to)day|later(?: today| on)?|tonight|this (?:afternoon|evening)") +TOMORROW = re.compile(r"tomorrow(?: (?:morning|afternoon|evening|night))?") +AFTER_TOMORROW = re.compile(r"(?:the )?day after tomorrow") +NEXT_DAYS = re.compile(rf"(?:(?:the )?(?:next|coming|upcoming|following) )?{_N} ?(?:days?|d)") +WEEK_AHEAD = re.compile(r"this week|(?:the )?week ahead|(?:the )?(?:coming|upcoming|following) week|(?:the )?week|1 ?w") +WEEKEND = re.compile(r"(?:this |the )?weekend") +NEXT_WEEK = re.compile(r"next week") +WEEKDAY = re.compile(rf"(?:(?Pnext|this|coming) )?(?P{'|'.join(sorted(_WEEKDAYS, key=len, reverse=True))})") +ISO_DAY = re.compile(r"\d{4}-\d\d-\d\d") +FORMS = ( # (form, an example read now): what a refusal lists + ("today (also tonight, later today: the forecast is by day)", "today"), + ("tomorrow", "tomorrow"), + ("the day after tomorrow", "the day after tomorrow"), + ("next N days, N days, Nd (N from 1: today and the N-1 days after it)", "next 3 days"), + ("the next 7 days, this week, the week ahead, the coming week", "the next 7 days"), + ("this weekend, the weekend (Saturday and Sunday; from today when it is one)", "this weekend"), + ("next week (Monday to Sunday)", "next week"), + ("Monday … Sunday, this Saturday, next Saturday (the next one; a bare weekday is today when it is one)", "Saturday"), + ("a date, YYYY-MM-DD", None), +) + + +def days_text(first: date, last: date) -> str: + """"Tue 10 Nov 2026", "Tue 10 – Mon 16 Nov 2026", "Mon 28 Dec 2026 – Sun 3 Jan 2027": days as the periods' texts write them.""" + if first == last: + return day_text(first) + if (first.year, first.month) == (last.year, last.month): + return f"{first:%a} {first.day} – {day_text(last)}" + return f"{day_text(first, year=first.year != last.year)} – {day_text(last)}" + + +def _ahead(p: str, today: date) -> tuple[str | None, date, date] | None: + """(its label, the first day, the last day) of words that look ahead, or None when they are none of the forms.""" + if TODAY.fullmatch(p): + return "today", today, today + if TOMORROW.fullmatch(p): + return "tomorrow", today + timedelta(days=1), today + timedelta(days=1) + if AFTER_TOMORROW.fullmatch(p): + return "the day after tomorrow", today + timedelta(days=2), today + timedelta(days=2) + if m := NEXT_DAYS.fullmatch(p): + n = int(m["n"]) if m["n"].isdigit() else NUMBER_WORDS[m["n"]] + if n < 1: + return None + return ("today" if n == 1 else f"the next {n} days"), today, today + timedelta(days=n - 1) + if WEEK_AHEAD.fullmatch(p): + return "the next 7 days", today, today + timedelta(days=6) + if WEEKEND.fullmatch(p): + saturday = today + timedelta(days=(5 - today.weekday()) % 7) if today.weekday() < 5 else today - timedelta(days=today.weekday() - 5) + return "this weekend", max(saturday, today), saturday + timedelta(days=1) + if NEXT_WEEK.fullmatch(p): + monday = today + timedelta(days=7 - today.weekday()) + return "next week", monday, monday + timedelta(days=6) + if m := WEEKDAY.fullmatch(p): + wd = _WEEKDAYS[m["wd"]] + ahead = (wd - today.weekday()) % 7 + if m["next"] == "next" and not ahead: + ahead = 7 + day = today + timedelta(days=ahead) + return WEEKDAY_NAMES[wd], day, day + if ISO_DAY.fullmatch(p): + try: + day = date.fromisoformat(p) + except ValueError: + return None + return None, day, day + return None + + +def _forms(today: date) -> dict[str, str]: + """{form: what it means now}: every form a refusal lists, read today.""" + out = {} + for form, example in FORMS: + example = example or (today + timedelta(days=2)).isoformat() + label, first, last = _ahead(example.lower(), today) + out[form] = f"{label}: {days_text(first, last)}" if label else days_text(first, last) + return out + + +def read_ahead(words: str | None, now: datetime, tz: tzinfo) -> Period: + """The days a forecast is asked for, from words that look ahead (DEFAULT when none), as a Period: `start` the first day's midnight, + `end` the midnight after the last, `text` how the words were read ("this weekend: Sat 14 – Sun 15 Nov 2026"). Raises Refusal: for + words that are in the past (pointing to summary), and for words that are none of the forms (listing each with what it means now).""" + asked = str(words).strip() if words is not None and str(words).strip() else DEFAULT + local = now.astimezone(tz) if now.tzinfo else now + today = local.date() + it_is_now = f"It is now {day_text(local)} {clock_text(local)}." + p = " ".join(asked.replace("’", "'").lower().split()) + lead = LEAD.fullmatch(p) + read = _ahead(p, today) or (lead and _ahead(lead["rest"], today)) + if read and read[1] < today: + raise Refusal(f"{asked!r} is in the past ({days_text(read[1], read[2])}): the forecast is for today and the days ahead. For what " + f"was measured, use {FOR_WHAT_WAS}. {it_is_now}", forms=_forms(today)) + if not read: + try: # words for what has been measured ("yesterday", "last week"): the tool for them is another + past = read_past(asked, None, None, now=now, tz=tz, default=asked) + except PeriodError: + past = None + if past is not None: + raise Refusal(f"{asked!r} reads as a period that has been measured ({past.text}), not days ahead: the forecast is for today " + f"and the days ahead. For what was measured, use {FOR_WHAT_WAS}. {it_is_now}", forms=_forms(today)) + raise Refusal(f"{asked!r} isn't a period the forecast can read. Send `period` as one of these forms, as a whole phrase (N is a " + f"number, in digits or a word up to twelve). {it_is_now}", forms=_forms(today)) + label, first, last = read + text = f"{label}: {days_text(first, last)}" if label else days_text(first, last) + return Period(asked, datetime.combine(first, time(), tzinfo=tz), datetime.combine(last + timedelta(days=1), time(), tzinfo=tz), text) + + +# ---------- the forecast held ---------- +async def held_days(forecast, today: date, fetch: bool) -> list[dict]: + """The forecast's days from today on, as held; when it holds none of them and `fetch` allows, it is fetched first (Forecast.warm, + which keeps to its own hours and pace), as weather_forecast does when nothing is held.""" + if fetch and not any(d["date"] >= today for d in forecast.days or []): + try: + await forecast.warm(True) + except Exception as e: + log.warning("Forecast not readable: %s", e) + return [d for d in forecast.days or [] if d["date"] >= today] + + +def day_lines(days: list[dict], today: date) -> list[str]: + """weather_forecast's lines for these days: "Today: 🌧️ Rain. 11–17°C, 90% chance of at least 1 mm", then each day by its + weekday.""" + return [f"{day_label(d['date'], today)}: {describe_day(d)}" for d in days] + + +def day_figures(d: dict) -> dict: + """A day of the forecast as figures: {date, min, max, summary, rain_chance, rain_1mm_pct} (°C and %; None where it has none).""" + return {"date": d["date"].isoformat(), "min": d.get("min_c"), "max": d.get("max_c"), "summary": d.get("summary") or None, + "rain_chance": d.get("rain_chance_pct"), "rain_1mm_pct": d.get("rain_1mm_pct")} + + +def section(heading: str, lines: list[str], *, place: str | None, fetched_at: float | None, tz: tzinfo, today: date) -> str: + """A source's lines as the bot writes them in the report and alone (lib/report.py _heading, _own_lines): "Forecast (Melbourne, + 6:00pm)", the place and the time it was fetched (with its day when that isn't `today`), then "• " and each line.""" + stamp = None + if fetched_at: + at = to_local(int(fetched_at), tz) + stamp = clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" + note = ", ".join(x for x in (place, stamp) if x) + return "\n".join([f"{heading} ({note})" if note else heading, *(f"• {line}" for line in lines)]) + + +# ---------- the tool ---------- +DESCRIPTION = ( + "The weather forecast (Open-Meteo) for the station's place: today and the days ahead, each day's summary with its emoji, its lowest " + "and highest temperature and the chance of at least 1 mm of rain. For \"what's tomorrow like\": {\"period\": \"tomorrow\"}; \"the " + "forecast for the weekend\": {\"period\": \"this weekend\"}; \"will it rain this week\", \"forecast\": {} (the next 7 days). A " + "report (\"report\", \"status\", \"sitrep\") is current, forecast {\"period\": \"today\"} and pollen, called together.\n" + "Not for: the next few hours from the station's own readings (\"will it rain soon\", \"do I need an umbrella\": outlook); what was " + "measured (summary; days, for days ranked or counted).\n" + "Result: `period` (how the words were read, with the dates); `text`, the whole answer for the person, ready to send; `lines`, one a " + "day, emoji included: copy them as they are, with the place in parentheses after the heading, e.g. Forecast (Melbourne); `days`, " + "each day's figures (min and max °C, rain_chance: Open-Meteo's chance of rain, rain_1mm_pct: the chance of at least 1 mm, the one " + "the lines give when there is one); `place`, `fetched_at`; `note` when the forecast doesn't reach the end of the period.") +PARAMETERS = {"type": "object", "properties": {"period": { + "type": "string", + "description": "The days ahead in the person's own words, passed on unchanged: today, tomorrow, the day after tomorrow, next N days " + "(N from 1: today and the N-1 days after it; also N days, Nd), the next 7 days or this week, this weekend, next week " + "(Monday to Sunday), a weekday (Saturday: the next one, today when it is one), or a date (YYYY-MM-DD). The " + f"forecast reaches 7 days from today. Default: {DEFAULT}."}}} + + +def tools(ctx) -> list[ServiceTool]: + """The `forecast` tool, when the forecast is switched on.""" + if ctx.forecast is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + fc = ctx.forecast + tz, now = clock_of(ctx, fc.tz) + today = now.date() + if args.get("start") or args.get("end"): + raise Refusal("The forecast takes `period` in words, not `start` and `end`: send one of these forms.", forms=_forms(today)) + period = read_ahead(args.get("period"), now, tz) + first, last = period.first_day, period.last_day + held = await held_days(fc, today, meta["fetch"]) + if not held: + raise Refusal(NO_FORECAST) + days = [d for d in held if first <= d["date"] <= last] + reaches = held[-1]["date"] + if not days: + raise Refusal(f"The days asked for ({period.text}) are beyond the forecast, which reaches {day_text(reaches)}: ask for days " + f"up to then (the next 7 days is all of it).", reaches=reaches.isoformat()) + lines = day_lines(days, today) + note = {"note": f"The forecast reaches only {day_text(reaches, year=False)}: the days after it aren't forecast yet."} \ + if reaches < last else {} + fetched = to_local(int(fc.fetched_at), tz) if fc.fetched_at else None + return answer(period=period, as_of=fetched, + text=section(HEADING, lines, place=fc.place, fetched_at=fc.fetched_at, tz=tz, today=today), + lines=lines, days=[day_figures(d) for d in days], **note, + **({"place": fc.place} if fc.place else {}), source=SOURCE, + **({"fetched_at": iso(fetched)} if fetched else {})) + + return [ServiceTool("forecast", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +def clock_of(ctx, fallback: tzinfo) -> tuple[tzinfo, datetime]: + """(the station's zone, the time now in it) from the context; the source's own zone when the context has no device to name one + (Context.zone asks the station or the air sensor).""" + try: + tz = ctx.zone + except AttributeError: + tz = fallback + return tz, to_local(int(ctx.clock()), tz) + + +__all__ = ["DEFAULT", "DESCRIPTION", "PARAMETERS", "clock_of", "day_figures", "day_lines", "days_text", "held_days", "read_ahead", + "section", "tools"] diff --git a/lib/service/outlook.py b/lib/service/outlook.py new file mode 100644 index 00000000..1a7bef1d --- /dev/null +++ b/lib/service/outlook.py @@ -0,0 +1,309 @@ +"""The `outlook` tool (docs/mcp-service.md 3.3): will it rain in the next few hours. No arguments. + +The bot's prompt told the model how to read the station for this (lib/prompt.py, its "outlook" block) and fetched the reading now and +the last 3 hours for it (intent.model_prefetch). Here the same rules are worked out in code, from the station's 5-minute readings of +the last 3 hours (as Ecowitt.recent reads them) and its reading now, so any model gets the same read: + + - Pressure tendency (relative pressure over the 3 hours): falling when its highest came before its lowest, rising when the lowest + came first; the change is the highest minus the lowest. Down more than 3 hPa: rain likely; down 1 to 3 hPa: possible; under + 1 hPa (steady) or rising: unlikely. + - Each of these moves that a step towards rain: pressure under 1005 hPa (unsettled); moist air, humidity 90% or more or the + temperature within 2 °C of the dew point; wind picking up while the pressure falls. Pressure over 1020 hPa (settled) moves it a + step away. The verdict stays between unlikely and likely. + - Recent rain, a rain rate above 0 now or rain in the last hour, makes it likely: showers tend to go on for a while. + +The answer: {as_of, fresh, verdict, reason ("pressure down 2.4 hPa in 3 hours, humidity 91%"), pressure {hpa, change_hpa, tendency, +level, text}, moisture {humidity, dew_point_spread, moist, text}, recent_rain {rained, raining_now, rate_mm_h, last_hour_mm, text}, +wind_trend {trend, first_hour_kmh, last_hour_kmh, text}, [missing: what the station had none of], [forecast: today's and tomorrow's +lines, when the forecast is on, with forecast_note when it has none], [warning: the newest reading is old], how_to_read}. `read` +works it out from the readings alone; the tool fetches them (`readings`). +""" + +import logging +import math +from collections.abc import Sequence + +from ..ecowitt.reads import rows_on +from ..ecowitt.source import LIVE_GROUPS +from ..timeutil import clock_text, day_text, naive_local, to_local +from .common import BACKGROUND, Refusal, ServiceTool, answer +from .forecast import day_lines, held_days + +log = logging.getLogger(__name__) + +HOURS = 3 # the station's last 3 hours +RECENT_SECONDS = 3600 # rain in the last hour counts as recent +LIKELY_FALL_HPA = 3.0 # pressure down more than this: likely +STEADY_HPA = 1.0 # a change under this is steady +UNSETTLED_HPA = 1005.0 # pressure under this is unsettled ... +SETTLED_HPA = 1020.0 # ... over this, settled +MOIST_HUMIDITY = 90.0 # humidity at or above this ... +MOIST_SPREAD_C = 2.0 # ... or the temperature within this of the dew point: moist air +WIND_CHANGE_KMH = 5.0 # the last hour's mean wind against the first hour's: picking up (or easing) by this much +STALE_SECONDS = 30 * 60 # a newest reading older than this is warned about +VERDICTS = ("unlikely", "possible", "likely") +GROUPS = ("outdoor", "pressure", "rainfall", "rainfall_piezo", "wind") # what the read needs (the prefetch's groups) +GAUGES = ("rainfall", "rainfall_piezo") # the rain gauges, the main one first + +Rows = Sequence[tuple[int, dict]] + + +# ---------- the read, from the readings ---------- +def read(rows: Rows, now_reading: dict | None, now_ts: int, live_ts: int | None = None) -> dict: + """The outlook's fields from the station's readings: `rows`, the last HOURS of 5-minute readings ([(epoch, {"group.field": value})], + oldest first, as Ecowitt.recent gives them), `now_reading` the reading now ({"group.field": value}, None when there is none) of + `live_ts`, and `now_ts` the time asked. The fields: verdict, reason, pressure, moisture, recent_rain, wind_trend, [missing], and + `newest`, the time of the newest reading read (None when there is none).""" + live = dict(now_reading or {}) if live_ts else {} + if live and rows and live_ts <= rows[-1][0]: # the reading now is older than the newest 5 minutes': the rows say it all + live = {} + last = rows[-1][1] if rows else {} + newest = max([ts for ts in (live_ts if live else None, rows[-1][0] if rows else None) if ts], default=None) + gauge = next((g for g in GAUGES if any(f"{g}.daily" in r or f"{g}.rain_rate" in r for r in (live, last))), GAUGES[0]) + + def points(key: str) -> list[tuple[int, float]]: + out = [(ts, float(r[key])) for ts, r in rows if _number(r.get(key))] + if _number(live.get(key)): + out.append((live_ts, float(live[key]))) + return out + + def latest(*keys: str) -> list[float | None]: + """These readings now, all from one reading: the reading now when it has them all, else the newest 5 minutes'.""" + for source in (live, last): + if all(_number(source.get(k)) for k in keys): + return [float(source[k]) for k in keys] + return [float(v) if _number(v := live.get(k, last.get(k))) else None for k in keys] + + pressure = _pressure(points("pressure.relative")) + moisture = _moisture(*latest("outdoor.temperature", "outdoor.humidity", "outdoor.dew_point")) + rain = _recent_rain(rows, live, live_ts, gauge, now_ts) + wind = _wind(points("wind.wind_speed"), now_ts) + + falling = pressure is not None and pressure["tendency"] == "falling" + score = 0 if not falling else 2 if -pressure["change_hpa"] > LIKELY_FALL_HPA else 1 + wind_counts = falling and wind is not None and wind["trend"] == "picking up" + up, down = [], [] # the readings behind the verdict, towards rain and away from it, the strongest first + if rain is not None and rain["rained"]: + up.append(rain["why"]) + if falling: + up.append(f"pressure {pressure['change']}") + if moisture is not None and moisture["moist"]: + score += 1 + up.append(moisture["why"]) + if pressure is not None and pressure["level"] == "unsettled": + score += 1 + up.append(f"low pressure ({pressure['hpa']:.1f} hPa)") + if wind_counts: + score += 1 + up.append("wind picking up") + if pressure is not None and not falling: + down.append(f"pressure {pressure['change']}") + if pressure is not None and pressure["level"] == "settled": + score -= 1 + down.append(f"high pressure ({pressure['hpa']:.1f} hPa)") + besides = [f"humidity {moisture['humidity']:.0f}%"] if moisture is not None and not moisture["moist"] and \ + moisture["humidity"] is not None else [] # (a figure to quote when one reading alone is behind the verdict) + score = 2 if rain is not None and rain["rained"] else min(max(score, 0), 2) + verdict = VERDICTS[score] + parts = (down + up if verdict == "unlikely" else up + down) + besides + out = {"verdict": verdict, "reason": ", ".join(parts[:2]) or "too few readings in the last 3 hours to tell", + "pressure": _public(pressure), "moisture": _public(moisture), "recent_rain": _public(rain), "wind_trend": wind} + if missing := [name for name, got in (("pressure", pressure), ("humidity and dew point", moisture), ("rain", rain), ("wind", wind)) + if got is None]: + out["missing"] = missing + out["newest"] = newest + return out + + +def _number(value) -> bool: + """Is it a reading's value: a finite number?""" + return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + + +def _public(fields: dict | None) -> dict | None: + """The fields an answer shows: those the read keeps for its reason (`change`, `why`) left out.""" + return None if fields is None else {k: v for k, v in fields.items() if k not in ("change", "why")} + + +def _over(seconds: float) -> str: + """"3 hours", "1.5 hours", "1 hour", "30 minutes": how long the readings span, to the half hour.""" + halves = max(1, round(seconds / 1800)) + return "30 minutes" if halves == 1 else "1 hour" if halves == 2 else f"{halves / 2:g} hours" + + +def _pressure(points: list[tuple[int, float]]) -> dict | None: + """{hpa, change_hpa, tendency, level, text}: the pressure now, its change over the readings (signed: down is negative), whether it + is falling (its highest came before its lowest), rising or steady (a change under STEADY_HPA), and its level.""" + if len(points) < 2: + return None + high = max(points, key=lambda p: p[1]) # (the first, where several are as high) + low = min(points, key=lambda p: p[1]) + size = round(high[1] - low[1], 1) + falling = high[0] < low[0] + tendency = "steady" if size < STEADY_HPA else "falling" if falling else "rising" + over = _over(points[-1][0] - points[0][0]) + change = (f"down {size:.1f} hPa in {over}" if tendency == "falling" else f"up {size:.1f} hPa in {over}" if tendency == "rising" + else "steady") + hpa = points[-1][1] + level = "unsettled" if hpa < UNSETTLED_HPA else "settled" if hpa > SETTLED_HPA else "normal" + steady = f"steady ({'no change' if not size else ('down ' if falling else 'up ') + f'{size:.1f} hPa'} in {over})" + where = {"unsettled": f"; under {UNSETTLED_HPA:g} hPa: unsettled", "settled": f"; over {SETTLED_HPA:g} hPa: settled"}.get(level, "") + text = f"{hpa:.1f} hPa, {steady if tendency == 'steady' else change}{where}" + return {"hpa": round(hpa, 1), "change_hpa": (-size if falling else size) or 0.0, "tendency": tendency, "level": level, "text": text, + "change": change} + + +def dew_point(temperature: float, humidity: float) -> float: + """The dew point (°C) of air at this temperature (°C) and relative humidity (%), by the Magnus formula: for a station that sends + no dew point of its own.""" + a, b = 17.62, 243.12 + gamma = math.log(max(humidity, 1.0) / 100) + a * temperature / (b + temperature) + return b * gamma / (a - gamma) + + +def _moisture(temperature: float | None, humidity: float | None, dew: float | None) -> dict | None: + """{humidity, dew_point_spread, moist, text}: the humidity now and how far the temperature is above the dew point; moist when the + humidity is MOIST_HUMIDITY or more or the spread MOIST_SPREAD_C or less.""" + if dew is None and temperature is not None and humidity is not None: + dew = dew_point(temperature, humidity) + spread = round(temperature - dew, 1) if temperature is not None and dew is not None else None + if humidity is None and spread is None: + return None + by_humidity = humidity is not None and humidity >= MOIST_HUMIDITY + by_spread = spread is not None and spread <= MOIST_SPREAD_C + gap = None if spread is None else "at the dew point" if spread <= 0 else f"{spread:.1f} °C above the dew point" + text = ", ".join(x for x in (f"humidity {humidity:.0f}%" if humidity is not None else None, gap) if x) + why = f"humidity {humidity:.0f}%" if by_humidity else "the temperature at the dew point" if by_spread and spread <= 0 else \ + f"temperature within {spread:.1f} °C of the dew point" if by_spread else None + return {"humidity": None if humidity is None else round(humidity), "dew_point_spread": spread, "moist": by_humidity or by_spread, + "text": text, "why": why} + + +def _recent_rain(rows: Rows, live: dict, live_ts: int | None, gauge: str, now_ts: int) -> dict | None: + """{rained, raining_now, rate_mm_h, last_hour_mm, text}: is it raining now (a rain rate above 0), and the rain of the last hour + (the daily total's rise, its midnight reset allowed for, and any rate above 0).""" + total, rate = f"{gauge}.daily", f"{gauge}.rain_rate" + seq = [*rows, *([(live_ts, live)] if live else [])] + if not any(_number(r.get(total)) or _number(r.get(rate)) for _, r in seq): + return None + since = now_ts - RECENT_SECONDS + fell, before = 0.0, None + for ts, r in seq: + if not _number(daily := r.get(total)): + continue + if ts >= since and before is not None: + fell += daily - before if daily >= before else daily # (a drop is the midnight reset) + before = daily + rate_now = next((float(r[rate]) for _, r in reversed(seq) if _number(r.get(rate))), None) + raining = rate_now is not None and rate_now > 0 + rate_seen = any(_number(r.get(rate)) and r[rate] > 0 for ts, r in seq if ts >= since) + rained = raining or fell > 0 or rate_seen + mm = round(fell, 1) + in_hour = (f"{mm:.1f} mm in the last hour" if mm else "a trace of rain in the last hour" if fell > 0 + else "rain in the last hour" if rate_seen else "no rain in the last hour") + now = f"raining now ({rate_now:.1f} mm/h)" if raining else None + text = now + (f", {mm:.1f} mm in the last hour" if mm else "") if raining else in_hour + return {"rained": rained, "raining_now": raining, "rate_mm_h": None if rate_now is None else round(rate_now, 1), + "last_hour_mm": mm, "text": text, "why": now or in_hour} + + +def _wind(points: list[tuple[int, float]], now_ts: int) -> dict | None: + """{trend, first_hour_kmh, last_hour_kmh, text}: the mean wind speed of the last hour against that of the first of the 3 hours; + picking up, or easing, when it differs by WIND_CHANGE_KMH or more. None without readings in both hours.""" + start = now_ts - HOURS * 3600 + first = [v for ts, v in points if start <= ts < start + 3600] + last = [v for ts, v in points if ts >= now_ts - 3600] + if not first or not last: + return None + a, b = sum(first) / len(first), sum(last) / len(last) + trend = "picking up" if b - a >= WIND_CHANGE_KMH else "easing" if a - b >= WIND_CHANGE_KMH else "steady" + return {"trend": trend, "first_hour_kmh": round(a, 1), "last_hour_kmh": round(b, 1), + "text": f"{trend}: {b:.1f} km/h on average in the last hour, {a:.1f} km/h 2 to 3 hours ago"} + + +# ---------- the tool ---------- +DESCRIPTION = ( + "Will it rain in the next few hours: the weather station's own read of its last 3 hours, by fixed rules, with the forecast's lines " + "for today and tomorrow. For \"will it rain?\", \"do I need an umbrella?\", \"what's it doing later?\": {}. Takes no arguments.\n" + "Not for: the days ahead (forecast); rain that fell (summary for a period's total, days for the wettest day); whether rain follows " + "pressure over weeks (relate).\n" + "The rules: pressure over the 3 hours is falling when its high came before its low; down more than 3 hPa: likely; down 1 to 3 hPa: " + "possible; under 1 hPa or rising: unlikely. A step towards rain for each of: pressure under 1005 hPa (unsettled); humidity 90% or " + "more, or the temperature within 2 °C of the dew point; wind picking up while pressure falls. A step away: pressure over 1020 hPa " + "(settled). A rain rate above 0 now, or rain in the last hour, makes it likely: showers tend to go on.\n" + "Result: `verdict` (likely, possible, unlikely) and `reason` (the one or two readings behind it, ready to quote); `pressure`, " + "`moisture`, `recent_rain` and `wind_trend`, each with its figures and text; `forecast`, Open-Meteo's lines for today and tomorrow, " + "to copy as they are. Open with the verdict and reason, say it is a read of the station's readings, then the forecast's lines; if " + "they disagree, say so.") +PARAMETERS = {"type": "object", "properties": {}} +HOW_TO_READ = ("`verdict` and `reason` are the station's read of the next few hours from its last 3 hours, by the rules in this tool's " + "description: open with them, and say it is a read of the station's readings. `forecast` holds Open-Meteo's lines for " + "today and tomorrow: give them after it, copied as they are, emoji included; if they disagree with the station's read, " + "say so plainly. For the days further ahead, call forecast.") + + +def tools(ctx) -> list[ServiceTool]: + """The `outlook` tool, when there is a weather station.""" + if ctx.eco is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + eco = ctx.eco + tz = ctx.zone + now_ts = int(ctx.clock()) + rows, live, live_ts = await readings(eco, now_ts, tz, fetch=meta["fetch"], urgent=meta["priority"] != BACKGROUND) + got = read(rows, live, now_ts, live_ts) + if got["newest"] is None: + raise Refusal("The weather station has no readings from the last 3 hours, so there is nothing to read the next few hours " + "from." + (" Ask forecast for today's forecast." if ctx.forecast is not None else "")) + newest = to_local(got.pop("newest"), tz) + extra = {} + if ctx.forecast is not None: + today = to_local(now_ts, tz).date() + days = [d for d in await held_days(ctx.forecast, today, meta["fetch"]) if (d["date"] - today).days <= 1] + extra["forecast"] = day_lines(days, today) if days else [] + if not days: + extra["forecast_note"] = "No forecast is available right now: the station's read is the whole answer." + if now_ts - newest.timestamp() > STALE_SECONDS: + extra["warning"] = (f"The station's newest reading is from {day_text(newest, year=False)} {clock_text(newest)}: this read may " + f"be out of date.") + return answer(period=None, as_of=newest, **got, **extra, how_to_read=HOW_TO_READ) + + return [ServiceTool("outlook", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +async def readings(eco, now_ts: int, tz, *, fetch: bool, urgent: bool) -> tuple[list, dict | None, int | None]: + """(the last HOURS of 5-minute readings, the reading now as {"group.field": value}, its time) from the station: the readings as + Ecowitt.recent reads them (what the file lacks asked of Ecowitt, ahead of the background requests when someone is waiting), the + reading now as the report's and the gauges' (the kept live reading while fresh, else a request for every group, kept in turn). With + `fetch` False, only what is held: the file's readings and the kept live reading.""" + groups = [g for g in GROUPS if g in eco.groups] + start = now_ts - HOURS * 3600 + if fetch: + rows = await eco.fetcher(groups, urgent=urgent).get("5min", naive_local(start, tz), naive_local(now_ts, tz)) + try: + data = await eco._live_data(LIVE_GROUPS, urgent=urgent) # (every group, as the report's: kept for the next to ask) + except Exception as e: # the readings of the last 3 hours still give a read + log.warning("Outlook: no live reading (%s: %s); reading the 5-minute history alone", type(e).__name__, e) + data = None + else: + rows = await eco.storage.read(rows_on, eco.mac, groups, "5min", start, now_ts) + data = eco._live[1] if getattr(eco, "_live", None) else None + live, live_ts = _values(data or {}) + return rows, live, live_ts + + +def _values(data: dict) -> tuple[dict, int | None]: + """A real_time response ({group: {field: {value, unit, time}}}) as {"group.field": value} and the time of its newest reading.""" + out, newest = {}, 0 + for group, fields in data.items(): + for name, obj in (fields.items() if isinstance(fields, dict) else ()): + try: + out[f"{group}.{name}"] = float(obj["value"]) + newest = max(newest, int(obj.get("time") or 0)) + except (KeyError, TypeError, ValueError): + continue + return out, newest or None + + +__all__ = ["DESCRIPTION", "PARAMETERS", "dew_point", "read", "readings", "tools"] diff --git a/lib/service/pollen.py b/lib/service/pollen.py new file mode 100644 index 00000000..cb5d0fce --- /dev/null +++ b/lib/service/pollen.py @@ -0,0 +1,78 @@ +"""The `pollen` tool (docs/mcp-service.md 3.3): Melbourne's grass pollen and the thunderstorm asthma risk, from the pollen source +(lib/pollen, melbournepollen.com.au). No arguments. + +The answer is today's pollen_asthma's, in the service's shape: the same `lines` (Pollen.lines), each level with its emoji and its +day in `grass` and `asthma`, `in_season`, `fetched_at`, `place` and `source`, and `text`, the bot's pollen section ("Pollen & asthma +(Melbourne, 6:00pm)" and a bullet per line, lib/report.py's report and lookup) written here so a client can send it as it is. Out of +season (the forecasts run October to December) it answers as pollen_asthma does, with its error. Request `_meta` `fetch: false` +answers from the page held, fetching nothing (the report's `cached`). +""" + +import logging +from calendar import month_name + +from ..pollen.parse import LEVELS +from ..pollen.source import OFF_SEASON, SEASON_MONTHS +from ..timeutil import day_text, to_local +from .common import Refusal, ServiceTool, answer, iso +from .forecast import clock_of, section + +log = logging.getLogger(__name__) + +HEADING = "Pollen & asthma" # the bot's heading for it (lib/report.py SECTIONS) +NO_LEVELS = "No pollen levels are available right now." # (pollen_asthma's own words) +SOURCE = ("melbournepollen.com.au (grass pollen from pollen-trap data; asthma risk from the Victorian Department of Health and BOM, " + "1 Oct - 31 Dec)") # (pollen_asthma's) +NO_ASTHMA = "The page had no thunderstorm asthma level for this district when it was last read." # (pollen_asthma's asthma_note) +SEASON = f"{month_name[SEASON_MONTHS[0]]} to {month_name[SEASON_MONTHS[-1]]}" + +DESCRIPTION = ( + "Melbourne's grass pollen level and the thunderstorm asthma risk for the station's district, each Low, Moderate, High or Extreme, " + "from melbournepollen.com.au. For \"pollen today\", \"is it bad for hay fever\", \"thunderstorm asthma risk\": {}. Takes no " + "arguments. The forecasts run only from October to December: out of season it says so, as an error. A report (\"report\", " + "\"status\", \"sitrep\") is current, forecast {\"period\": \"today\"} and pollen, called together.\n" + "Not for: air quality, PM2.5 and the like (the air sensor: current, summary); the weather forecast (forecast).\n" + "Result: `text`, the whole answer for the person, ready to send; `lines`, emoji included: copy them as they are; `grass` and " + "`asthma`, each level with its emoji (grass with `day`, the day its forecast is for; asthma with `updated`, when the site last " + "updated it); `place`, `fetched_at`; `asthma_note` when the page had no asthma level.") +PARAMETERS = {"type": "object", "properties": {}} + + +def tools(ctx) -> list[ServiceTool]: + """The `pollen` tool, when the pollen source is switched on.""" + if ctx.pollen is None: + return [] + + async def handle(args: dict, meta: dict) -> str: + p = ctx.pollen + if not p.in_season(): + raise Refusal(OFF_SEASON) + if p.page is None and meta["fetch"]: # (as pollen_asthma does: the page is fetched only when this season's isn't held) + try: + await p.warm(True) + except Exception as e: + log.warning("Pollen not readable: %s", e) + lines = p.lines() + if not lines: + raise Refusal(NO_LEVELS) + tz, now = clock_of(ctx, p.tz) + cur = p.current() + fetched = to_local(int(cur["fetched_at"]), tz) if cur["fetched_at"] else None + levels = {} + if g := cur["grass"]: # (its day: the day the page's grass forecast is for) + levels["grass"] = {"level": g["level"], "emoji": g["emoji"], + **({"day": g["date"].isoformat(), "day_text": day_text(g["date"])} if g["date"] else {})} + if a := cur["asthma"]: + levels["asthma"] = {"level": a["level"], "emoji": a["emoji"], **({"updated": a["updated"]} if a["updated"] else {})} + return answer(period=None, as_of=fetched, + text=section(HEADING, lines, place=p.place, fetched_at=cur["fetched_at"], tz=tz, today=now.date()), + lines=lines, grass=levels.get("grass"), asthma=levels.get("asthma"), + **({} if "asthma" in levels else {"asthma_note": NO_ASTHMA}), + scale=list(LEVELS), in_season=True, season=SEASON, + **({"place": p.place} if p.place else {}), source=SOURCE, + **({"fetched_at": iso(fetched)} if fetched else {})) + + return [ServiceTool("pollen", DESCRIPTION, PARAMETERS, handle, open_world=True)] + + +__all__ = ["DESCRIPTION", "PARAMETERS", "tools"] diff --git a/tests/test_service_forecast.py b/tests/test_service_forecast.py new file mode 100644 index 00000000..97e8c607 --- /dev/null +++ b/tests/test_service_forecast.py @@ -0,0 +1,224 @@ +"""The `forecast` tool (lib/service/forecast.py): the days ahead in words, read here; today's weather_forecast's lines, each day's +figures, the bot's forecast section word for word, what is held when the request says not to fetch, and refusals that teach.""" + +import json +from datetime import date, datetime, time as dtime, timedelta + +import httpx +import pytest + +from lib import report +from lib.forecast import Forecast +from lib.service.common import FRESH, Refusal +from lib.service.context import Context +from lib.service.forecast import DESCRIPTION, PARAMETERS, days_text, read_ahead, tools +from lib.timeutil import day_text +from tests.fakes import TZ, config + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm, as the plan's periods table is asked + + +def got(text: str) -> dict: + return json.loads(text) + + +def ahead(words, now=NOW) -> tuple[str, str]: + period = read_ahead(words, now, TZ) + return period.text, f"{period.first_day} {period.last_day}" + + +# ---------- the days ahead, in words ---------- +@pytest.mark.parametrize("words, text, days", [ + (None, "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("today", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("Tonight", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("tomorrow", "tomorrow: Wed 11 Nov 2026", "2026-11-11 2026-11-11"), + ("for tomorrow", "tomorrow: Wed 11 Nov 2026", "2026-11-11 2026-11-11"), + ("the day after tomorrow", "the day after tomorrow: Thu 12 Nov 2026", "2026-11-12 2026-11-12"), + ("next 3 days", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("in the next three days", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("3d", "the next 3 days: Tue 10 – Thu 12 Nov 2026", "2026-11-10 2026-11-12"), + ("1 day", "today: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), + ("the next 7 days", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("this week", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("the week ahead", "the next 7 days: Tue 10 – Mon 16 Nov 2026", "2026-11-10 2026-11-16"), + ("this weekend", "this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15"), + ("over the weekend", "this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15"), + ("next week", "next week: Mon 16 – Sun 22 Nov 2026", "2026-11-16 2026-11-22"), + ("Saturday", "Saturday: Sat 14 Nov 2026", "2026-11-14 2026-11-14"), + ("on Sat", "Saturday: Sat 14 Nov 2026", "2026-11-14 2026-11-14"), + ("Tuesday", "Tuesday: Tue 10 Nov 2026", "2026-11-10 2026-11-10"), # a bare weekday is today when it is one + ("next Tuesday", "Tuesday: Tue 17 Nov 2026", "2026-11-17 2026-11-17"), + ("2026-11-12", "Thu 12 Nov 2026", "2026-11-12 2026-11-12"), +]) +def test_the_days_ahead_are_read_from_the_words_and_say_how(words, text, days): + assert ahead(words) == (text, days) + + +def test_the_weekend_from_a_saturday_or_a_sunday_starts_today(): + saturday, sunday = datetime(2026, 11, 14, 9, tzinfo=TZ), datetime(2026, 11, 15, 9, tzinfo=TZ) + assert ahead("this weekend", saturday) == ("this weekend: Sat 14 – Sun 15 Nov 2026", "2026-11-14 2026-11-15") + assert ahead("this weekend", sunday) == ("this weekend: Sun 15 Nov 2026", "2026-11-15 2026-11-15") + assert ahead("the next 7 days", datetime(2026, 12, 28, 9, tzinfo=TZ))[0] == "the next 7 days: Mon 28 Dec 2026 – Sun 3 Jan 2027" + + +def test_a_period_is_whole_days_on_the_stations_clock(): + period = read_ahead("this weekend", NOW, TZ) + assert period.asked == "this weekend" and period.cut is None + assert period.start == datetime(2026, 11, 14, tzinfo=TZ) and period.end == datetime(2026, 11, 16, tzinfo=TZ) + assert read_ahead(None, NOW, TZ).asked == "the next 7 days" + assert days_text(date(2026, 11, 10), date(2026, 11, 10)) == "Tue 10 Nov 2026" + + +def test_the_past_is_refused_pointing_to_summary_and_every_form_says_what_it_means_now(): + with pytest.raises(Refusal) as e: + read_ahead("yesterday", NOW, TZ) + assert "'yesterday' reads as a period that has been measured (yesterday: Mon 9 Nov 2026)" in e.value.message + assert "use summary" in e.value.message and "It is now Tue 10 Nov 2026 2:05pm." in e.value.message + forms = e.value.teach["forms"] + assert forms["tomorrow"] == "tomorrow: Wed 11 Nov 2026" + assert forms["this weekend, the weekend (Saturday and Sunday; from today when it is one)"] == "this weekend: Sat 14 – Sun 15 Nov 2026" + assert forms["a date, YYYY-MM-DD"] == "Thu 12 Nov 2026" + with pytest.raises(Refusal) as e: + read_ahead("2026-11-01", NOW, TZ) + assert e.value.message.startswith("'2026-11-01' is in the past (Sun 1 Nov 2026)") and "use summary" in e.value.message + with pytest.raises(Refusal) as e: + read_ahead("a fortnight from now", NOW, TZ) + assert e.value.message.startswith("'a fortnight from now' isn't a period the forecast can read") and len(e.value.teach["forms"]) == 9 + with pytest.raises(Refusal): + read_ahead("in 3 days", NOW, TZ) # (one day, three days from now: not "the next 3 days") + with pytest.raises(Refusal): + read_ahead("next 0 days", NOW, TZ) + + +# ---------- the tool ---------- +def open_meteo(calls, days=7): + """Open-Meteo: `days` days from today (the station's), each a little different; its ensemble's chance for every other day.""" + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request.url.host) + today = datetime.now(TZ).date() + if request.url.host.startswith("ensemble"): + hourly = {"time": [f"{today + timedelta(days=n)}T{h:02d}:00" for n in range(days) for h in range(24)]} + members = [[(3.0 if n % 2 else 0.0) if h == 0 else 0.0 for n in range(days) for h in range(24)] for _ in range(4)] + members[0] = [0.0] * len(hourly["time"]) # one member dry every day: 75% on the wet ones + return httpx.Response(200, json={"hourly": {**hourly, "precipitation": members[0], + **{f"precipitation_member{m:02d}": s for m, s in enumerate(members[1:], 1)}}}) + return httpx.Response(200, json={"daily": { + "time": [str(today + timedelta(days=n)) for n in range(days)], "temperature_2m_min": [10.5 + n for n in range(days)], + "temperature_2m_max": [16 + n for n in range(days)], "precipitation_probability_max": [10 * n for n in range(days)], + "weather_code": [[63, 0, 95, 2, 80, 3, 61][n % 7] for n in range(days)]}}) + return httpx.MockTransport(handler) + + +def make(tmp_path, days=7, place="Melbourne"): + """(the forecast source, its requests, the context the tool is built over), all on the clock at noon today.""" + calls = [] + forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place=place), None, open_meteo(calls, days)) + noon = datetime.combine(datetime.now(TZ).date(), dtime(12, 0)) + forecast.now = lambda: noon + ctx = Context(forecast=forecast, tz=TZ, clock=lambda: noon.replace(tzinfo=TZ).timestamp()) + return forecast, calls, ctx + + +def tool(ctx): + (it,) = tools(ctx) + return it + + +async def test_the_lines_are_weather_forecasts_and_each_day_has_its_figures(tmp_path): + forecast, calls, ctx = make(tmp_path) + forecast_tool = tool(ctx) + assert forecast_tool.name == "forecast" and forecast_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await forecast_tool.call({})) + assert calls == ["api.open-meteo.com", "ensemble-api.open-meteo.com"] # nothing held: fetched, as weather_forecast does + old = got(await forecast.handle({})) + assert out["lines"] == old["lines"] and len(out["lines"]) == 7 and out["lines"][0].startswith("Today: 🌧️ Rain. 11–16°C") + today = forecast.now().date() + assert out["period"]["asked"] == "the next 7 days" and out["period"]["text"].startswith("the next 7 days: ") + assert out["period"]["start"] == datetime.combine(today, dtime(), tzinfo=TZ).isoformat() + assert out["days"][0] == {"date": today.isoformat(), "min": 10.5, "max": 16, "summary": "🌧️ Rain.", "rain_chance": 0, + "rain_1mm_pct": 0} + assert out["days"][1] == {"date": (today + timedelta(days=1)).isoformat(), "min": 11.5, "max": 17, "summary": "☀️ Clear.", + "rain_chance": 10, "rain_1mm_pct": 75} + assert out["place"] == "Melbourne" and out["source"] == "Open-Meteo" and out["fresh"] == FRESH + fetched = datetime.fromtimestamp(int(forecast.fetched_at), TZ) + assert out["fetched_at"] == fetched.isoformat() and out["as_of"]["time"] == fetched.isoformat() + assert list(out) == ["period", "as_of", "fresh", "text", "lines", "days", "place", "source", "fetched_at"] + for n in range(1, 8): # "next N days" is weather_forecast's `days: N`, line for line + assert got(await forecast_tool.call({"period": f"next {n} days"}))["lines"] == got(await forecast.handle({"days": n}))["lines"] + await forecast.close() + + +async def test_a_day_ahead_has_its_own_line_as_weather_forecast_writes_it(tmp_path): + forecast, _, ctx = make(tmp_path) + week = got(await forecast.handle({"days": 7}))["lines"] + tomorrow = got(await tool(ctx).call({"period": "tomorrow"})) + assert tomorrow["lines"] == [week[1]] and tomorrow["period"]["text"].startswith("tomorrow: ") + day = forecast.now().date() + timedelta(days=4) + named = got(await tool(ctx).call({"period": f"{day:%A}"})) + assert named["lines"] == [week[4]] and named["days"][0]["date"] == day.isoformat() + await forecast.close() + + +async def test_its_text_is_the_bots_forecast_section_word_for_word(tmp_path): + forecast, _, ctx = make(tmp_path) + today = forecast.now().date() + for words, days in (("next 3 days", 3), ("the next 7 days", 7), ("today", 1)): + out = got(await tool(ctx).call({"period": words})) + old = await forecast.handle({"days": days, "cached": True}) + assert out["text"] == report.lookup("forecast", old, [], [], today) == report.report({"weather_forecast": old}, today) + assert out["text"].startswith(f"Forecast (Melbourne, {report._stamp(json.loads(old), today)})\n• Today: ") + later = today + timedelta(days=1) # asked the next day, the time it was fetched has its day + assert got(await tool(Context(forecast=forecast, tz=TZ, clock=lambda: datetime.combine(later, dtime(9), tzinfo=TZ).timestamp())) + .call({"period": "today"}))["text"].startswith(f"Forecast (Melbourne, {report._stamp(json.loads(old), later)})\n• Today: ") + await forecast.close() + + +async def test_with_no_place_the_heading_has_only_the_time(tmp_path): + forecast, _, ctx = make(tmp_path, place="") + out = got(await tool(ctx).call({"period": "today"})) + old = await forecast.handle({"days": 1}) + assert "place" not in out and out["text"] == report.lookup("forecast", old, [], [], forecast.now().date()) + await forecast.close() + + +async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing(tmp_path): + forecast, calls, ctx = make(tmp_path) + out = got(await tool(ctx).call({}, {"fetch": False})) + assert out == {"error": "No forecast is available right now."} and calls == [] # (weather_forecast's words, with cached) + assert got(await forecast.handle({"cached": True})) == out + await forecast.warm(True) + calls.clear() + held = got(await tool(ctx).call({"period": "tomorrow"}, {"fetch": False})) + assert len(held["lines"]) == 1 and calls == [] + await forecast.close() + + +async def test_days_beyond_the_forecast_are_said_so_or_refused_with_how_far_it_reaches(tmp_path): + forecast, _, ctx = make(tmp_path, days=3) + today = forecast.now().date() + week = got(await tool(ctx).call({"period": "this week"})) + assert len(week["lines"]) == 3 and week["note"] == \ + f"The forecast reaches only {day_text(today + timedelta(days=2), year=False)}: the days after it aren't forecast yet." + far, reaches = today + timedelta(days=5), today + timedelta(days=2) + out = got(await tool(ctx).call({"period": far.isoformat()})) + assert out["error"] == f"The days asked for ({days_text(far, far)}) are beyond the forecast, which reaches {day_text(reaches)}: ask " \ + "for days up to then (the next 7 days is all of it)." + assert out["reaches"] == reaches.isoformat() + await forecast.close() + + +async def test_refusals_teach_the_call_that_works(tmp_path): + forecast, calls, ctx = make(tmp_path) + out = got(await tool(ctx).call({"period": "last week"})) + assert "reads as a period that has been measured" in out["error"] and "use summary" in out["error"] and "forms" in out + out = got(await tool(ctx).call({"start": "2026-11-12"})) + assert out["error"].startswith("The forecast takes `period` in words, not `start` and `end`") and "tomorrow" in out["forms"] + assert calls == [] # (nothing is fetched for a call that is refused) + await forecast.close() + + +def test_it_is_offered_only_with_a_forecast_and_its_description_carries_the_rules(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and "outlook" in DESCRIPTION and "summary" in DESCRIPTION and '{"period": "tomorrow"}' in DESCRIPTION + assert list(PARAMETERS["properties"]) == ["period"] and "Default: the next 7 days." in PARAMETERS["properties"]["period"]["description"] diff --git a/tests/test_service_outlook.py b/tests/test_service_outlook.py new file mode 100644 index 00000000..c93ab402 --- /dev/null +++ b/tests/test_service_outlook.py @@ -0,0 +1,320 @@ +"""The `outlook` tool (lib/service/outlook.py): will it rain in the next few hours, by the prompt's rules worked out in code from the +station's last 3 hours and its reading now: each rule alone, their combination, the result's shape, the forecast's lines beside it, +what is held when the request says not to fetch, and the refusal when there is nothing to read.""" + +import json +import time +from datetime import datetime, timedelta + +import pytest + +from lib.ecowitt.source import LIVE_GROUPS +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.outlook import DESCRIPTION, GROUPS, HOW_TO_READ, PARAMETERS, dew_point, read, tools +from tests.fakes import TZ, archived_station + +NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm +NOW_TS = int(NOW.timestamp()) +STEPS = 36 # 5-minute readings over the 3 hours: 37 of them, the last at NOW + + +def got(text: str) -> dict: + return json.loads(text) + + +def at(spec, i: int): + """A reading's value at step i of STEPS: a constant, (first, last) in a straight line, or a function of i.""" + if callable(spec): + return spec(i) + if isinstance(spec, tuple): + return round(spec[0] + (spec[1] - spec[0]) * i / STEPS, 2) + return spec + + +def station(pressure=(1012.0, 1012.0), humidity=70.0, temperature=15.0, dew=8.0, daily=0.0, rate=0.0, wind=10.0, now_ts=NOW_TS, + gauge="rainfall") -> list[tuple[int, dict]]: + """The station's last 3 hours of 5-minute readings to `now_ts`, as Ecowitt.recent gives them; a reading given as None is left out.""" + rows = [] + for i in range(STEPS + 1): + row = {"pressure.relative": at(pressure, i), "outdoor.humidity": at(humidity, i), "outdoor.temperature": at(temperature, i), + "outdoor.dew_point": at(dew, i), f"{gauge}.daily": at(daily, i), f"{gauge}.rain_rate": at(rate, i), + "wind.wind_speed": at(wind, i)} + rows.append((now_ts - (STEPS - i) * 300, {k: v for k, v in row.items() if v is not None})) + return rows + + +def outlook(rows=None, live=None, live_ts=None, **kw) -> dict: + return read(rows if rows is not None else station(**kw), live, NOW_TS, live_ts) + + +# ---------- each rule ---------- +@pytest.mark.parametrize("pressure, verdict, tendency, change", [ + ((1012.0, 1008.5), "likely", "falling", -3.5), # down more than 3 hPa + ((1012.0, 1009.0), "possible", "falling", -3.0), # 1 to 3 hPa: possible (3 is not more than 3) + ((1012.0, 1009.6), "possible", "falling", -2.4), + ((1012.0, 1011.0), "possible", "falling", -1.0), + ((1012.0, 1011.1), "unlikely", "steady", -0.9), # under 1 hPa: steady + ((1009.0, 1011.0), "unlikely", "rising", 2.0), + ((1012.0, 1012.0), "unlikely", "steady", 0.0), +]) +def test_the_pressure_tendency_over_3_hours_sets_the_verdict(pressure, verdict, tendency, change): + out = outlook(pressure=pressure) + assert (out["verdict"], out["pressure"]["tendency"], out["pressure"]["change_hpa"]) == (verdict, tendency, change) + assert out["pressure"]["level"] == "normal" and out["pressure"]["hpa"] == pressure[1] + + +def test_falling_or_rising_is_whether_the_high_or_the_low_came_first_not_where_it_ends(): + dip = lambda i: 1012.0 - 3.5 * min(i, 30) / 30 + (0.5 if i > 30 else 0) # down 3.5 hPa, then back up a little at the end + out = outlook(pressure=dip) + assert out["pressure"]["tendency"] == "falling" and out["pressure"]["change_hpa"] == -3.5 and out["verdict"] == "likely" + rise = lambda i: 1008.5 + 3.5 * min(i, 30) / 30 - (0.5 if i > 30 else 0) # up 3.5, then down a little + assert outlook(pressure=rise)["pressure"]["tendency"] == "rising" and outlook(pressure=rise)["verdict"] == "unlikely" + + +def test_the_reason_cites_one_or_two_readings_ready_to_quote(): + out = outlook(pressure=(1012.0, 1009.6), humidity=91.0) + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.4 hPa in 3 hours, humidity 91%" # the prompt's example + assert out["pressure"]["text"] == "1009.6 hPa, down 2.4 hPa in 3 hours" + assert outlook(pressure=(1012.0, 1008.5))["reason"] == "pressure down 3.5 hPa in 3 hours, humidity 70%" + assert outlook(pressure=(1009.0, 1011.0))["reason"] == "pressure up 2.0 hPa in 3 hours, humidity 70%" + steady = outlook(pressure=(1012.0, 1011.4)) + assert steady["reason"] == "pressure steady, humidity 70%" + assert steady["pressure"]["text"] == "1011.4 hPa, steady (down 0.6 hPa in 3 hours)" + + +def test_the_pressure_level_unsettled_or_settled_moves_the_verdict_a_step(): + low = outlook(pressure=(1003.4, 1003.0)) + assert low["pressure"]["level"] == "unsettled" and low["verdict"] == "possible" + assert low["reason"] == "low pressure (1003.0 hPa), pressure steady" and low["pressure"]["text"].endswith("; under 1005 hPa: unsettled") + high = outlook(pressure=(1026.0, 1024.0)) + assert high["pressure"]["level"] == "settled" and high["verdict"] == "unlikely" # falling 2 hPa, but settled + assert high["reason"] == "high pressure (1024.0 hPa), pressure down 2.0 hPa in 3 hours" + assert high["pressure"]["text"].endswith("; over 1020 hPa: settled") + assert outlook(pressure=(1005.0, 1005.0))["pressure"]["level"] == outlook(pressure=(1020.0, 1020.0))["pressure"]["level"] == "normal" + + +def test_moist_air_by_humidity_or_by_the_dew_point_moves_the_verdict_a_step(): + humid = outlook(humidity=90.0) + assert humid["moisture"] == {"humidity": 90, "dew_point_spread": 7.0, "moist": True, + "text": "humidity 90%, 7.0 °C above the dew point"} + assert humid["verdict"] == "possible" and humid["reason"] == "humidity 90%, pressure steady" + near = outlook(humidity=85.0, temperature=15.0, dew=13.5) + assert near["moisture"]["moist"] and near["moisture"]["dew_point_spread"] == 1.5 and near["verdict"] == "possible" + assert near["reason"] == "temperature within 1.5 °C of the dew point, pressure steady" + dry = outlook(humidity=89.0, dew=12.9) + assert not dry["moisture"]["moist"] and dry["moisture"]["dew_point_spread"] == 2.1 and dry["verdict"] == "unlikely" + at_dew = outlook(humidity=None, temperature=12.0, dew=12.0) + assert at_dew["moisture"] == {"humidity": None, "dew_point_spread": 0.0, "moist": True, "text": "at the dew point"} + + +def test_a_station_without_a_dew_point_has_it_worked_out(): + assert dew_point(20.0, 50.0) == pytest.approx(9.26, abs=0.05) and dew_point(15.0, 100.0) == pytest.approx(15.0, abs=0.01) + out = outlook(dew=None, temperature=15.0, humidity=88.0) + assert out["moisture"]["dew_point_spread"] == 2.0 and out["moisture"]["moist"] and "missing" not in out + + +def test_rain_now_or_in_the_last_hour_makes_it_likely_whatever_the_pressure(): + raining = outlook(pressure=(1009.0, 1011.0), rate=lambda i: 1.8 if i == STEPS else 0.0, daily=lambda i: 0.2 if i == STEPS else 0.0) + assert raining["verdict"] == "likely" and raining["recent_rain"] == {"rained": True, "raining_now": True, "rate_mm_h": 1.8, + "last_hour_mm": 0.2, + "text": "raining now (1.8 mm/h), 0.2 mm in the last hour"} + assert raining["reason"] == "raining now (1.8 mm/h), pressure up 2.0 hPa in 3 hours" + shower = outlook(daily=lambda i: 0.0 if i < 30 else 0.6) # 0.6 mm 30 minutes ago, dry since + assert shower["verdict"] == "likely" and shower["recent_rain"]["raining_now"] is False + assert shower["recent_rain"]["text"] == "0.6 mm in the last hour" and shower["reason"] == "0.6 mm in the last hour, pressure steady" + earlier = outlook(daily=lambda i: 0.0 if i < 10 else 0.6) # 2 hours ago: not recent + assert earlier["verdict"] == "unlikely" and earlier["recent_rain"]["rained"] is False + assert earlier["recent_rain"]["text"] == "no rain in the last hour" and earlier["recent_rain"]["last_hour_mm"] == 0.0 + trace = outlook(daily=lambda i: 0.0 if i < 30 else 0.02) + assert trace["recent_rain"]["text"] == "a trace of rain in the last hour" and trace["verdict"] == "likely" + + +def test_rain_across_midnight_counts_the_reset(): + late = NOW.replace(hour=0, minute=20) + rows = station(now_ts=int(late.timestamp()), daily=lambda i: 3.0 if i < 32 else 0.0 if i == 32 else 0.4) # reset at midnight + out = read(rows, None, int(late.timestamp())) + assert out["recent_rain"]["last_hour_mm"] == 0.4 and out["verdict"] == "likely" + + +def test_the_piezo_gauge_is_read_when_the_station_has_no_other(): + out = outlook(gauge="rainfall_piezo", rate=lambda i: 2.0 if i == STEPS else 0.0) + assert out["recent_rain"]["raining_now"] and out["verdict"] == "likely" + + +def test_wind_picking_up_strengthens_a_falling_pressure_only(): + picking_up = lambda i: 5.0 if i < 12 else 14.0 + out = outlook(pressure=(1012.0, 1010.0), wind=picking_up) + assert out["wind_trend"] == {"trend": "picking up", "first_hour_kmh": 5.0, "last_hour_kmh": 14.0, + "text": "picking up: 14.0 km/h on average in the last hour, 5.0 km/h 2 to 3 hours ago"} + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.0 hPa in 3 hours, wind picking up" + assert outlook(pressure=(1010.0, 1012.0), wind=picking_up)["verdict"] == "unlikely" # rising pressure: it doesn't count + assert outlook(pressure=(1012.0, 1011.6), wind=picking_up)["verdict"] == "unlikely" # nor with steady pressure + assert outlook(wind=lambda i: 15.0 if i < 12 else 9.0)["wind_trend"]["trend"] == "easing" + assert outlook(wind=lambda i: 10.0 if i < 12 else 14.0)["wind_trend"]["trend"] == "steady" + + +# ---------- the rules together ---------- +@pytest.mark.parametrize("kw, verdict", [ + (dict(pressure=(1004.0, 1001.0), humidity=95.0, wind=lambda i: 5.0 if i < 12 else 14.0), "likely"), # everything: no more than likely + (dict(pressure=(1012.0, 1010.0), humidity=93.0), "likely"), # possible, and moist + (dict(pressure=(1004.0, 1003.5), humidity=93.0), "likely"), # steady, but unsettled and moist + (dict(pressure=(1024.0, 1024.2), humidity=93.0), "unlikely"), # moist, but settled + (dict(pressure=(1025.0, 1021.0)), "possible"), # likely, but settled + (dict(pressure=(1025.0, 1021.0), rate=0.4), "likely"), # ... and it's raining + (dict(pressure=(1010.0, 1014.0), humidity=60.0), "unlikely"), +]) +def test_the_rules_together_stay_between_unlikely_and_likely(kw, verdict): + assert outlook(**kw)["verdict"] == verdict + + +def test_the_reading_now_is_used_when_it_is_newer_than_the_5_minute_readings(): + rows = station(pressure=(1012.0, 1010.0), now_ts=NOW_TS - 240) + live = {"pressure.relative": 1008.0, "rainfall.rain_rate": 0.0, "outdoor.humidity": 92.0, "outdoor.temperature": 14.0, + "outdoor.dew_point": 12.7} + out = read(rows, live, NOW_TS, NOW_TS - 30) + assert out["pressure"]["change_hpa"] == -4.0 and out["moisture"]["humidity"] == 92 and out["newest"] == NOW_TS - 30 + stale = read(rows, live, NOW_TS, NOW_TS - 600) # older than the newest 5 minutes': the rows say it all + assert stale["pressure"]["change_hpa"] == -2.0 and stale["newest"] == NOW_TS - 240 + + +def test_what_the_station_lacks_is_listed_and_the_verdict_rests_on_the_rest(): + rows = [(ts, {k: v for k, v in r.items() if not k.startswith("pressure")}) for ts, r in station(humidity=95.0)] + out = read(rows, None, NOW_TS) + assert out["pressure"] is None and out["missing"] == ["pressure"] and out["verdict"] == "possible" and out["reason"] == "humidity 95%" + assert read([], None, NOW_TS) == {"verdict": "unlikely", "reason": "too few readings in the last 3 hours to tell", "pressure": None, + "moisture": None, "recent_rain": None, "wind_trend": None, + "missing": ["pressure", "humidity and dew point", "rain", "wind"], "newest": None} + + +# ---------- the tool ---------- +class Station: + """A stand-in for lib.ecowitt.Ecowitt: what the outlook reads of it, and what it was asked.""" + + def __init__(self, rows, live=None): + self.rows, self.tz, self.mac, self.groups = rows, TZ, "M", ["outdoor", "indoor", "pressure", "wind", "rainfall", "solar_and_uvi"] + self._live = (time.time(), live) if live else None + self.asked = [] + self.storage = self # (its read() is the file's) + + def fetcher(self, groups, urgent=False): + self.asked.append(("fetcher", tuple(groups), urgent)) + return self + + async def get(self, cycle, start, end, refresh=False, load=True): + self.asked.append(("get", cycle, start, end)) + return self.rows + + async def read(self, fn, mac, groups, cycle, start, end): + self.asked.append(("held", fn.__name__, tuple(groups), cycle, start, end)) + return self.rows + + async def _live_data(self, groups, max_age=90, urgent=True): + self.asked.append(("live", tuple(groups), urgent)) + return self._live[1] if self._live else {} + + +def live_reading(ts=NOW_TS, **values) -> dict: + """A real_time response: {group: {field: {value, unit, time}}}.""" + out = {} + for name, value in values.items(): + group, field = name.split("__") + out.setdefault(group, {})[field] = {"value": str(value), "unit": "", "time": str(ts)} + return out + + +class HeldForecast: + """A stand-in for lib.forecast.Forecast with its days held.""" + + def __init__(self, days): + self.days, self.fetched_at, self.place, self.tz, self.warmed = days, NOW_TS - 600, "Melbourne", TZ, 0 + + async def warm(self, fresh=True): + self.warmed += 1 + + +def context(eco, forecast=None, now_ts=NOW_TS) -> Context: + return Context(eco=eco, forecast=forecast, tz=TZ, clock=lambda: now_ts) + + +async def test_the_result_has_the_verdict_its_reason_each_rules_figures_and_the_forecasts_lines(): + eco = Station(station(pressure=(1012.0, 1009.6), humidity=91.0, now_ts=NOW_TS - 120), + live_reading(rainfall__rain_rate=0.0, pressure__relative=1009.5)) + today = NOW.date() + days = [{"date": today - timedelta(days=1), "min_c": 9, "max_c": 15, "summary": "☁️ Overcast.", "rain_chance_pct": 20}, + {"date": today, "min_c": 11, "max_c": 17, "summary": "🌧️ Rain.", "rain_chance_pct": 80, "rain_1mm_pct": 65}, + {"date": today + timedelta(days=1), "min_c": 10, "max_c": 18, "summary": "🌦️ Showers.", "rain_chance_pct": 60}, + {"date": today + timedelta(days=2), "min_c": 12, "max_c": 22, "summary": "☀️ Clear.", "rain_chance_pct": 0}] + (outlook_tool,) = tools(context(eco, HeldForecast(days))) + assert outlook_tool.name == "outlook" and outlook_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await outlook_tool.call({})) + assert list(out) == ["as_of", "fresh", "verdict", "reason", "pressure", "moisture", "recent_rain", "wind_trend", "forecast", + "how_to_read"] + assert out["as_of"] == {"text": "Tue 10 Nov 2026 2:05pm", "time": NOW.isoformat()} and out["fresh"] == FRESH + assert out["verdict"] == "likely" and out["reason"] == "pressure down 2.5 hPa in 3 hours, humidity 91%" + assert out["pressure"] == {"hpa": 1009.5, "change_hpa": -2.5, "tendency": "falling", "level": "normal", + "text": "1009.5 hPa, down 2.5 hPa in 3 hours"} + assert out["moisture"]["humidity"] == 91 and out["recent_rain"]["text"] == "no rain in the last hour" + assert out["wind_trend"]["trend"] == "steady" + assert out["forecast"] == ["Today: 🌧️ Rain. 11–17°C, 65% chance of at least 1 mm", + "Wednesday: 🌦️ Showers. 10–18°C, 60% chance of rain"] # (yesterday's and the day after's left out) + assert out["how_to_read"] == HOW_TO_READ + groups = ("outdoor", "pressure", "rainfall", "wind") # (the station has no piezo gauge) + assert eco.asked[0][:3] == ("fetcher", groups, True) and eco.asked[1][:2] == ("get", "5min") + assert eco.asked[2] == ("live", tuple(LIVE_GROUPS), True) # (every group, as the report asks: the reading is kept for the next) + assert eco.asked[1][2:] == (datetime(2026, 11, 10, 11, 5), datetime(2026, 11, 10, 14, 5)) # the last 3 hours, on the station's clock + + +async def test_with_fetch_false_it_reads_what_is_held_and_drawn_ahead_its_fetches_wait_their_turn(): + eco = Station(station(), live_reading(pressure__relative=1012.0)) + forecast = HeldForecast([]) + out = got(await tools(context(eco, forecast))[0].call({}, {"fetch": False})) + assert [a[0] for a in eco.asked] == ["held"] and eco.asked[0][1:4] == ("rows_on", ("outdoor", "pressure", "rainfall", "wind"), "5min") + assert eco.asked[0][4:] == (NOW_TS - 3 * 3600, NOW_TS) and forecast.warmed == 0 + assert out["forecast"] == [] and out["forecast_note"] == "No forecast is available right now: the station's read is the whole answer." + eco.asked.clear() + await tools(context(eco))[0].call({}, {"priority": "background"}) + assert eco.asked[0][2] is False and eco.asked[2][2] is False # (not urgent: nobody is waiting) + + +async def test_without_the_forecast_the_stations_read_is_the_whole_answer_and_an_old_reading_is_warned_about(): + eco = Station(station(now_ts=NOW_TS - 3600)) + out = got(await tools(context(eco))[0].call({})) + assert "forecast" not in out and out["as_of"]["text"] == "Tue 10 Nov 2026 1:05pm" + assert out["warning"] == "The station's newest reading is from Tue 10 Nov 1:05pm: this read may be out of date." + + +async def test_with_no_readings_it_is_refused_pointing_to_the_forecast(): + out = got(await tools(context(Station([]), HeldForecast([])))[0].call({})) + assert out == {"error": "The weather station has no readings from the last 3 hours, so there is nothing to read the next few hours " + "from. Ask forecast for today's forecast."} + + +async def test_on_the_fake_station_it_reads_the_last_3_hours_from_the_file_and_the_reading_now(tmp_path, archived_cache): + eco, fake = await archived_station(tmp_path, archived_cache) + try: + ctx = Context(eco=eco) + nothing = got(await tools(ctx)[0].call({}, {"fetch": False})) # the archive holds no 5-minute readings of today yet + assert fake.calls == [] and nothing["error"].startswith("The weather station has no readings from the last 3 hours") + out = got(await tools(ctx)[0].call({})) + assert {(c["path"], c.get("cycle_type")) for c in fake.calls} == {("history", "5min"), ("real_time", None)} + fake.calls.clear() + held = got(await tools(ctx)[0].call({}, {"fetch": False})) # now held: nothing asked of Ecowitt + assert fake.calls == [] and held["pressure"] == out["pressure"] and held["verdict"] == out["verdict"] + rows = await eco.recent(3) + last = rows[-1][1] + assert out["pressure"]["hpa"] == round(last["pressure.relative"], 1) # (the reading now has no pressure: the newest 5 minutes') + assert out["moisture"]["dew_point_spread"] == 0.0 and out["moisture"]["moist"] # (the fake's dew point is its temperature) + assert out["verdict"] in ("possible", "likely") + assert datetime.fromisoformat(out["as_of"]["time"]) > datetime.now(TZ) - timedelta(minutes=10) + finally: + await eco.close() + + +def test_it_is_offered_only_with_a_station_and_its_description_carries_the_rules(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and PARAMETERS == {"type": "object", "properties": {}} + for rule in ("high came before its low", "more than 3 hPa", "1005 hPa", "1020 hPa", "humidity 90%", "within 2 °C of the dew point", + "wind picking up", "rain rate above 0 now", "forecast", "summary", "relate"): + assert rule in DESCRIPTION, rule + assert set(GROUPS) == {"outdoor", "pressure", "rainfall", "rainfall_piezo", "wind"} # (the prefetch's groups) diff --git a/tests/test_service_pollen.py b/tests/test_service_pollen.py new file mode 100644 index 00000000..1912044c --- /dev/null +++ b/tests/test_service_pollen.py @@ -0,0 +1,90 @@ +"""The `pollen` tool (lib/service/pollen.py): today's pollen_asthma lines, each level with its emoji and its day, the bot's pollen +section word for word, what is held when the request says not to fetch, and the off-season answer pollen_asthma gives.""" + +import json +from datetime import date, datetime, time as dtime, timedelta + +from lib import report +from lib.pollen.source import OFF_SEASON +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.pollen import DESCRIPTION, PARAMETERS, tools +from tests.fakes import TZ +from tests.test_pollen import SEASON_DAY, make, page + + +def got(text: str) -> dict: + return json.loads(text) + + +def context(pollen, day: date = SEASON_DAY, hour: int = 12) -> Context: + """The context the tool is built over, its clock at `hour` on `day` (the pollen source's own clock says the same, make()).""" + return Context(pollen=pollen, tz=TZ, clock=lambda: datetime.combine(day, dtime(hour), tzinfo=TZ).timestamp()) + + +def tool(ctx): + (it,) = tools(ctx) + return it + + +async def test_the_lines_are_pollen_asthmas_and_each_level_has_its_emoji_and_day(tmp_path): + pollen, calls = make(tmp_path, lambda: page(grass="High", asthma="Moderate")) + pollen_tool = tool(context(pollen)) + assert pollen_tool.name == "pollen" and pollen_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} + out = got(await pollen_tool.call({})) + assert len(calls) == 1 # nothing held: fetched, as pollen_asthma does + old = got(await pollen.handle({})) + assert out["lines"] == old["lines"] == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🟠 Moderate"] + assert out["grass"] == {"level": "High", "emoji": "🔴", "day": "2026-11-10", "day_text": "Tue 10 Nov 2026"} + assert out["asthma"] == {"level": "Moderate", "emoji": "🟠", "updated": "1 Oct 2026 4:00pm"} + assert out["in_season"] is True and out["season"] == "October to December" and out["scale"] == ["Low", "Moderate", "High", "Extreme"] + assert out["place"] == old["place"] and out["source"] == old["source"] and out["fresh"] == FRESH and "period" not in out + fetched = datetime.fromtimestamp(int(pollen.fetched_at), TZ) + assert out["fetched_at"] == out["as_of"]["time"] == fetched.isoformat() + assert "Central" not in json.dumps(out) # (the district is never named, as in pollen_asthma's) + await pollen.close() + + +async def test_its_text_is_the_bots_pollen_section_word_for_word(tmp_path): + pollen, _ = make(tmp_path, lambda: page(grass="Low", asthma="Low")) + out = got(await tool(context(pollen)).call({})) + old = await pollen.handle({"cached": True}) + assert out["text"] == report.lookup("pollen", old, [], [], SEASON_DAY) == report.report({"pollen_asthma": old}, SEASON_DAY) + assert out["text"].endswith("\n• Grass pollen forecast: 🟢 Low\n• Thunderstorm asthma forecast: 🟢 Low") + later = SEASON_DAY + timedelta(days=1) + assert got(await tool(context(pollen, later)).call({}))["text"] == report.lookup("pollen", old, [], [], later) + await pollen.close() + + +async def test_a_forecast_for_another_day_says_its_day_and_a_missing_asthma_level_is_said_so(tmp_path): + pollen, _ = make(tmp_path, lambda: page(grass="Moderate", day=SEASON_DAY + timedelta(days=1), season=False)) + out = got(await tool(context(pollen)).call({})) + old = got(await pollen.handle({})) + assert out["lines"] == old["lines"] == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] + assert out["grass"]["day"] == "2026-11-11" and out["asthma"] is None and out["asthma_note"] == old["asthma_note"] + await pollen.close() + + +async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing(tmp_path): + pollen, calls = make(tmp_path) + out = got(await tool(context(pollen)).call({}, {"fetch": False})) + assert out == {"error": "No pollen levels are available right now."} == got(await pollen.handle({"cached": True})) and calls == [] + await pollen.warm(True) + calls.clear() + held = got(await tool(context(pollen)).call({}, {"fetch": False})) + assert held["lines"] == pollen.lines() and calls == [] + await pollen.close() + + +async def test_out_of_season_it_gives_pollen_asthmas_answer_and_fetches_nothing(tmp_path): + pollen, calls = make(tmp_path) + pollen.now = lambda: datetime(2026, 1, 15, 12, 0) + out = await tool(context(pollen, date(2026, 1, 15))).call({}) + assert out == await pollen.handle({}) and got(out) == {"error": OFF_SEASON} and calls == [] + await pollen.close() + + +def test_it_is_offered_only_with_the_pollen_source_and_its_description_says_what_it_is_not_for(): + assert tools(Context(tz=TZ)) == [] + assert len(DESCRIPTION) < 1500 and "forecast" in DESCRIPTION and "October to December" in DESCRIPTION and "{}" in DESCRIPTION + assert PARAMETERS == {"type": "object", "properties": {}} From 39549ebbbc60fc9c45c7d34747a0d324ac2cfca4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 05:06:59 +0000 Subject: [PATCH 031/125] lib/service/readings.py, relate.py, scan.py: the readings, relate and scan tools `readings` (docs/mcp-service.md 3.3), in place of the bot's readings tool, on its engine (lib/history.py): one reading (ctx.readings(), a word for several reads the first and names the others in note_others; wind is its speed), a period in words (default the last 24 hours; start/end too, an end with a time stopping at it), an interval (1min to 1day, required, aliases as today). The rows are read_intervals' and read_days' for the same span, capped at 300 rows; more is refused with the interval that fits. It reads only the file, so fetch and priority change nothing, and it draws no chart. `relate`: rain against one reading over whole days to yesterday. pressure.relative, outdoor.humidity and wind.wind_speed go to weather_link's engine (lib/ecowitt/link.py link), air.pm2_5 and air.pm10 to Composer.air_link; their findings come back as they are (verdict, how_to_read, findings first). Default pressure over the last 90 days (60 for the air). A chart only when `chart` is true, with drawn_by {tool, arguments, periods 1M 3M 1Y}; a call with dates replays as " to ". `scan`: each air reading (or all) against the weather, Composer.air_scan's findings; at most 400 days, a longer period cut to its latest with the period and note_period saying so; a chart of the strongest pair when asked, with drawn_by. A request that may not fetch reads the air from the file (relate.HeldAir) instead of the AirGradient cloud. "On record" starts at the first day row held for the readings asked about (readings.first_day). lib/compose.py: air_scan no longer raises KeyError when there is nothing to scan (summarise gives no `strongest` then): it says "Not enough data to say", as it was meant to. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/compose.py | 2 +- lib/service/readings.py | 166 ++++++++++++++++++++++++ lib/service/relate.py | 174 +++++++++++++++++++++++++ lib/service/scan.py | 113 ++++++++++++++++ tests/test_service_readings.py | 214 +++++++++++++++++++++++++++++++ tests/test_service_relate.py | 227 +++++++++++++++++++++++++++++++++ tests/test_service_scan.py | 162 +++++++++++++++++++++++ 7 files changed, 1057 insertions(+), 1 deletion(-) create mode 100644 lib/service/readings.py create mode 100644 lib/service/relate.py create mode 100644 lib/service/scan.py create mode 100644 tests/test_service_readings.py create mode 100644 tests/test_service_relate.py create mode 100644 tests/test_service_scan.py diff --git a/lib/compose.py b/lib/compose.py index 3f8f68dc..d6bcb044 100644 --- a/lib/compose.py +++ b/lib/compose.py @@ -273,7 +273,7 @@ async def air_scan(self, args: dict, turn: Turn | None = None) -> str: origin, days = day_bounds(first, self.tz)[0], (last - first).days + 1 result = await asyncio.to_thread(scan.scan, {m: v[0] for m, v in air.items()}, weather, direction, speed, origin, days, self.tz) summary = scan.summarise(result, air_names, weather_names) - strongest = summary.pop("strongest") + strongest = summary.pop("strongest", None) # (none when there was nothing to scan) out = {"period": f"{first} to {last}", "resolution": "30-minute slots; each pair compared within the day and day to day", "how_to_read": ("Open with `verdict`, then the relationships in `findings`, strongest first. These go together; they " "do not cause each other (shared weather and season). If nothing stands out, say so and that the " diff --git a/lib/service/readings.py b/lib/service/readings.py new file mode 100644 index 00000000..4e6e98aa --- /dev/null +++ b/lib/service/readings.py @@ -0,0 +1,166 @@ +"""The `readings` tool (docs/mcp-service.md 3.3): one reading's values at an interval, a row per interval with its time, over a period in +the person's words. It replaces the bot's `readings` tool, and wraps its engine (lib/history.py): the same rows read the same way +(read_intervals, read_days: an interval's average with its lowest and highest, rain as the mm that fell, gusts as the highest, wind +direction as the reading at the interval's end, days from the day rows), the same cap of MAX_ROWS rows with the interval that fits when +there are more, over the service's periods (common.read_period) and its reading names (ctx.readings()). + +It reads only the file: nothing is fetched, so a request's `fetch` and `priority` change nothing here, and it draws no chart. + +Also here, for the tools over the file (relate, scan): the id of a reading's sensor in the file (sensor_id) and the first day held for +some readings (first_day), which "on record" starts from. +""" + +from datetime import date + +from ..history import (ALIASES, DAY_VALUE_IS, INTERVALS, MAX_ROWS, VALUE_IS, finest_fit, interval_starts, read_days, read_intervals, + row_count) +from ..storage.read import Reader +from ..timeutil import local_date +from .common import Refusal, ServiceTool, answer, period_properties, read_period +from .context import Context +from .names import AIR_DEVICE, Catalogue, Reading + +DEFAULT_PERIOD = "last 24 hours" +NOTHING_STORED = "Nothing is stored for this sensor yet." +NO_ROWS = "No readings are stored for this period at this interval: say so; never fill the gap." + +DESCRIPTION = ( + "The stored values of ONE reading at a fixed interval, a row per interval with its time: for values at set times or per interval, " + "or a table of values. Examples: \"humidity each hour for the last 5 hours\" {reading: \"outdoor.humidity\", period: \"last 5 " + "hours\", interval: \"1hour\"}; \"PM2.5 every 30 minutes this morning\" {reading: \"pm2.5\", period: \"this morning\", interval: " + "\"30min\"}; \"rain each hour today\" {reading: \"rain\", period: \"today\", interval: \"1hour\"}; \"the temperature at 3pm " + "yesterday\" {reading: \"outdoor.temperature\", period: \"yesterday afternoon\", interval: \"5min\"}, then its 3:00pm row. One " + "reading a call: outdoor and indoor are two calls, made together. " + f"At most {MAX_ROWS} rows: 5min for up to a day, 30min up to 6 days, 1hour up to 12 days, 4hour up to 7 weeks, 1day up to 300 " + "days; more is refused with the interval that fits (`fits`). " + "Not for: a period's highs and lows with when, averages, totals or a chart (summary); days ranked, counted or totalled, a figure " + "per month or year (days); how it is now (current). " + "Result: `columns` names each row's values and `value_is` what `value` is: an interval's average with its lowest and highest; rain " + "the mm that fell in it; gusts the highest; wind direction the reading at its end; at 1day the day's figures and when its lowest " + "and highest happened. Only what is stored is read, nothing is fetched: an empty row is `missing` (say so, never fill it), and " + "`note_coarser` with `fits` names the interval those times are held at.") + + +def parameters(catalogue: Catalogue) -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": f"ONE reading. {catalogue.description()} A word that stands for several " + "(temperature: outdoor and indoor) reads the first, and the result names the " + "others to ask for."}, + **period_properties(DEFAULT_PERIOD), + "interval": {"type": "string", "enum": list(INTERVALS), + "description": "One row per interval, a block of local time (1hour runs from :00 to :00, 1day from midnight; " + "4hour follows the station's own 4-hour records, whose times say where they start). 1min goes " + "back 10 days, and only where the sensor was read every minute."}, + }, + "required": ["reading", "interval"], + } + + +# ---------- the file ---------- +def sensor_id(ctx: Context, reading: Reading) -> int | None: + """The id of the reading's sensor in the file: the station's Ecowitt group, or the air sensor; None when it isn't there.""" + if reading.device == AIR_DEVICE: + store = getattr(ctx.air, "store", None) + sensor = getattr(store, "sensor", None) + sensor = sensor() if callable(sensor) else sensor # (AirReadings.sensor is a property; a test's stand-in may be a function) + else: + sensor = ctx.storage.sensors.find(ctx.eco.mac, reading.sensor) if ctx.eco else None + return sensor.id if sensor else None + + +def _first_days(r: Reader, wanted: list[tuple[str, int]]) -> list[date | None]: + out = [] + for kind, sensor in wanted: + (day,) = r.db.execute(f"SELECT MIN(day) FROM {kind}_day WHERE sensor = ?", (sensor,)).fetchone() + out.append(date.fromisoformat(day) if day else None) + return out + + +async def first_day(ctx: Context, readings: list[Reading]) -> date | None: + """The first day these readings are all held (each sensor's first day row, the latest of them): where "on record" starts. None + when one of them has nothing held.""" + wanted = [(r.kind, sensor_id(ctx, r)) for r in readings] + if not wanted or ctx.storage is None or any(sensor is None for _, sensor in wanted): + return None + days = await ctx.storage.read(_first_days, wanted) + return None if None in days else max(days) + + +# ---------- the arguments ---------- +def one_reading(catalogue: Catalogue, words) -> tuple[Reading, list[Reading]]: + """(the reading these words name, the others they name too). A sensor's wind is its speed: its direction goes with it only on a + chart (the compass rose). Raises UnknownReading, or Refusal when nothing is named.""" + if not [w for w in (words if isinstance(words, (list, tuple)) else [words]) if str(w or "").strip()]: + raise Refusal("Send `reading`: one name from `names`, or a word from `words` (each with the names it stands for).", + names=catalogue.names, words=catalogue.words()) + found = catalogue.resolve(words, default=None) + found = [r for r in found if r.drawn != "rose"] or found + return found[0], found[1:] + + +def interval_of(value) -> str: + """The interval sent, as INTERVALS names it ("hourly" is 1hour). Raises Refusal for one it can't read.""" + text = str(value or "").strip().lower() + interval = ALIASES.get(text, text) + if interval not in INTERVALS: + said = f"`interval` {value!r} isn't one this tool reads" if text else "Send `interval`" + raise Refusal(f"{said}: one of {', '.join(INTERVALS)} (a row each; at most {MAX_ROWS} rows).", intervals=list(INTERVALS)) + return interval + + +def others_note(reading: Reading, others: list[Reading]) -> str: + names = ", ".join(r.name for r in others) + return f"Read {reading.name} only: this tool reads one reading a call. For {names}, call it again, once for each, in the same round." + + +# ---------- the tool ---------- +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + catalogue = ctx.readings() + reading, others = one_reading(catalogue, args.get("reading")) + interval = interval_of(args.get("interval")) + tz, now = ctx.zone, ctx.now() + sensor = sensor_id(ctx, reading) if ctx.storage is not None else None + period = read_period(args, tz=tz, now=now, default=DEFAULT_PERIOD, + first_held=await first_day(ctx, [reading]) if sensor is not None else None) + m, now_ts = reading.metric, int(now.timestamp()) + start, end = int(period.start.timestamp()), int(period.end.timestamp()) - 1 # (the end not included) + by_day = interval == "1day" and m.how != "last" # (a compass point has no day figures: the last reading of each day) + n = row_count(start, end, interval, tz) + too_many = n > (MAX_ROWS if by_day else MAX_ROWS + 1) # (an interval's count is exact only once listed: the first starts before `start`) + marks = [] if too_many or by_day else interval_starts(start, end, INTERVALS[interval], tz) + if too_many or len(marks) > MAX_ROWS: + fits = finest_fit(start, end, tz) + rows = max(n, len(marks)) + raise Refusal(f"Too many rows: {period.text} at {interval} is {rows} rows, and this tool gives at most {MAX_ROWS}. " + + (f"Ask again with interval {fits}." if fits else + "Too long even for days: split the period, or for its highs, lows and averages use summary, for a figure " + "per day, month or year days."), + rows=rows, max_rows=MAX_ROWS, fits=fits) + out = {"reading": reading.name, "label": reading.label, "unit": reading.unit, "interval": interval, + "value_is": (DAY_VALUE_IS if by_day else VALUE_IS)[m.how]} + if sensor is None: + return answer(period=period, as_of=now, **out, rows=[], note=NOTHING_STORED, + **({"note_others": others_note(reading, others)} if others else {})) + if by_day: + first, last = local_date(start, tz), local_date(end, tz) + out |= await ctx.storage.read(read_days, m, sensor, first, last, tz) + partial = last == local_date(now_ts, tz) + else: + out |= await ctx.storage.read(read_intervals, m, sensor, interval, marks, end, now_ts, tz) + partial = marks[-1] + INTERVALS[interval] > now_ts + if partial: + out["note_last"] = "The last row is still filling: it runs up to now." + if not any(row[1] is not None for row in out["rows"]): + out["note"] = (f"No readings at this interval for this period: ask again with interval {out['fits']}." if out.get("fits") else + NO_ROWS) + if others: + out["note_others"] = others_note(reading, others) + return answer(period=period, as_of=now, **out) + + return [ServiceTool("readings", DESCRIPTION, parameters(ctx.readings()), handle)] + + +__all__ = ["DEFAULT_PERIOD", "DESCRIPTION", "first_day", "interval_of", "one_reading", "parameters", "sensor_id", "tools"] diff --git a/lib/service/relate.py b/lib/service/relate.py new file mode 100644 index 00000000..a718adc0 --- /dev/null +++ b/lib/service/relate.py @@ -0,0 +1,174 @@ +"""The `relate` tool (docs/mcp-service.md 3.3): rain against one reading, the two read together at 30-minute resolution over whole days +to yesterday. For pressure, humidity or wind: does rain follow a change in it (lib/ecowitt/link.py, today's weather_link); for PM2.5 or +PM10: is the air cleaner after rain (lib/compose.py Composer.air_link, today's air_link). Their findings come back as they are, in the +service's shape; a chart, when asked, is the reading with rain as bars behind it, carrying the call that drew it (drawn_by, 3.7). + +The station's side reads only the file. The air's asks the AirGradient cloud for the finished days the file lacks (up to 30, as today), +unless the request's metadata says `fetch` false; its `priority` changes nothing, as those requests have no queue to wait in. + +Also here, for scan, which reads the air through the same Composer: the charts with their drawn_by (drawn_charts), the period a whole-day +call is replayed with (whole_day_words), the Composer of a request (composer_for: from what is held, when its metadata says `fetch` +false: HeldAir). +""" + +import asyncio +import copy +import json +from datetime import date, datetime, timedelta + +from ..airgradient.metrics import without_spikes +from ..compose import Composer +from ..ecowitt.link import link +from ..periods_text import Period +from ..specs import ECOWITT_SOURCE, Chart +from ..timeutil import local_date, local_epoch +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, period_properties, read_period, with_charts +from .context import Context +from .names import Catalogue, Reading +from .readings import first_day + +STATION = {"pressure.relative": "pressure", "outdoor.humidity": "humidity", "wind.wind_speed": "wind"} # -> weather_link's driver +AIR = {"air.pm2_5": "pm2_5", "air.pm10": "pm10"} # -> air_link's metric +DEFAULT_READING = "pressure.relative" +DEFAULT_PERIOD, AIR_PERIOD = "last 90 days", "last 60 days" +# The periods a chart of rain against a reading is worth redrawing over (3.7) +PERIODS = ({"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) +RAIN_NAME = ("rainfall (rainfall.daily)", "rain (rainfall.rain)") # weather_link's name for the rain in its notes -> the service's + +DESCRIPTION = ( + "Rain against one reading, the two read together at 30-minute resolution over whole days (never averaged to days). For pressure, " + "humidity or wind: does rain follow a change in it (how much of the rain fell after the reading had been falling, steady or " + "rising over the 3 hours before, its level in rain and when dry, the biggest rain spells with the change before each). For PM2.5 or " + "PM10: is the air cleaner after rain (the 6 hours after each rain against the 6 before, wet days against dry). Any \"X against " + "rain\" is this tool. Examples: \"does rain follow a pressure drop?\", \"is there a correlation between pressure and rainfall?\" " + "{reading: \"pressure\"}; \"does humidity go with rain over the past year?\" {reading: \"humidity\", period: \"past year\"}; " + "\"does rain clear the air?\" {reading: \"pm2.5\"}; \"plot pressure against rainfall\" {reading: \"pressure\", chart: true}. " + "Not for: each air reading against every weather reading (scan); a chart of readings over time with no question of rain " + "(summary); rain totals, wet days or rain per month (days). " + "Result: open with `verdict` (yes, no or weak) in your own words, then the evidence in `findings`, as `how_to_read` says; " + "say the two go together or not, never that one causes the other. `note` when there was nothing to compare: say exactly that.") + + +def parameters() -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": "The reading set against rain, a name or the word for it: pressure " + "(pressure.relative, the default), humidity (outdoor.humidity), wind (its " + "speed, wind.wind_speed), pm2.5 (air.pm2_5) or pm10 (air.pm10)."}, + **period_properties("the last 90 days; for pm2.5 and pm10, the last 60 days", whole_days=True), + "chart": {"type": "boolean", "description": "true for a chart: the reading as a line, rain as bars behind it. Default " + "false."}, + }, + } + + +# ---------- shared with scan ---------- +def drawn_charts(charts: list[Chart], ctx: Context, meta: dict, tool: str, arguments: dict, periods=PERIODS) -> dict: + """The fields an answer with charts ends with (common.with_charts), each chart carrying the call that drew it: `drawn_by: {tool, + arguments, periods}`, `arguments` the call as the tool read it (the readings' full names, every default filled in), `periods` those + it is worth redrawing over, each replayed with only `period` changed.""" + fields = with_charts(charts, ctx.zone, meta) + for chart in fields.get("charts", []): + chart["drawn_by"] = {"tool": tool, "arguments": copy.deepcopy(arguments), "periods": [dict(p) for p in periods]} + return fields + + +def whole_day_words(args: dict, period: Period) -> str: + """The period of a whole-day call as words a replay reads the same: the words asked (or the default), or, for one made with + `start` and `end`, " to ".""" + if str(args.get("start") or "").strip(): + return f"{period.first_day.isoformat()} to {period.last_day.isoformat()}" + return period.asked + + +def flag(value) -> bool: + """A boolean argument as sent (true, "true").""" + return value is True or str(value).strip().lower() == "true" + + +class HeldAir: + """The air sensor as Composer reads it (`rows`), answering from what the file holds and fetching nothing: for a request whose + metadata says `fetch` false. The readings are AirGradient.rows' (each stored reading, the particles' glitches taken out); a day + not held is left out and counted, as one beyond the inline fetch is.""" + + def __init__(self, air): + self.air, self.tz = air, air.tz + + async def rows(self, t0: datetime, t1: datetime) -> tuple[list[dict], int, list[date]]: + store = self.air.store + days = [t0.date() + timedelta(days=k) for k in range((t1.date() - t0.date()).days + 1)] + lo, hi = local_epoch(t0, self.tz), local_epoch(t1, self.tz) + held = await store.held(days) + rows = [r for r in without_spikes(await store.load(lo, hi + 1)) if lo <= r["ts"] <= hi] + have = {local_date(r["ts"], self.tz) for r in rows} + hourly = sum(1 for h in held.values() if h.n and h.hourly) + return rows, hourly, [d for d in days if held[d].n is None and d not in have] + + +def composer_for(ctx: Context, meta: dict, what: str) -> Composer: + """The Composer that reads the air for this request: the context's, or, when the request's metadata says `fetch` false, one over + what the file holds (HeldAir). Refusal when there is none: `what` needs both devices.""" + if ctx.composer is None: + raise Refusal(f"{what} needs both the weather station and the air sensor, and this service has " + f"{'only the weather station' if ctx.eco else 'only the air sensor' if ctx.air else 'neither'}.") + return ctx.composer if meta["fetch"] else Composer(ctx.composer.eco, HeldAir(ctx.composer.air)) + + +# ---------- the reading ---------- +def relate_reading(catalogue: Catalogue, words) -> tuple[Reading, list[Reading]]: + """(the reading set against rain, the others the words name that could be). Raises UnknownReading, or Refusal when the words name + none that can be.""" + found = catalogue.resolve(words, default=DEFAULT_READING) + usable = [r for r in found if r.name in STATION or r.name in AIR] + if not usable: + can = [n for n in (*STATION, *AIR) if n in catalogue] + raise Refusal(f"{words!r} ({', '.join(r.name for r in found)}) can't be set against rain: this tool relates rain to one of " + f"{', '.join(can)}. For rain itself (totals, wet days) use days; for a chart of readings over time, summary.", + readings=can) + return usable[0], usable[1:] + + +# ---------- the tool ---------- +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + reading, others = relate_reading(ctx.readings(), args.get("reading")) + air = reading.name in AIR + if not air and ctx.eco is None: + raise Refusal(f"{reading.name} is the weather station's, and this service has no weather station.") + composer = composer_for(ctx, meta, "Setting PM2.5 or PM10 against rain") if air else None + rain = ctx.readings().get("rainfall.rain") + now = ctx.now() + period = read_period(args, tz=ctx.zone, now=now, default=AIR_PERIOD if air else DEFAULT_PERIOD, whole_days=True, + first_held=await first_day(ctx, [reading, *([rain] if rain else [])])) + chart = flag(args.get("chart")) + dates = {"start_date": period.first_day.isoformat(), "end_date": period.last_day.isoformat()} + if air: + turn = Turn() + out = json.loads(await composer.air_link({"metric": AIR[reading.name], **dates, "chart": chart}, turn)) + charts = turn.charts + else: + out, spec, _, _ = await asyncio.to_thread(link, ctx.storage.read_now, ctx.eco.mac, ctx.zone, + {"driver": STATION[reading.name], **dates}, now) + charts = [spec] if spec else [] + for c in charts: + c.source = ECOWITT_SOURCE + if "error" in out: # (not expected: the reading and the period were checked here) + raise Refusal(out["error"]) + if "note" in out: + out["note"] = out["note"].replace(*RAIN_NAME) + fields = {"reading": reading.name, "label": reading.label, "unit": reading.unit, + **{k: out[k] for k in ("verdict", "how_to_read", "findings") if k in out}, + **{k: v for k, v in out.items() if k not in ("period", "driver", "metric", "chart", "verdict", "how_to_read", "findings")}} + if others: + fields["note_others"] = (f"Set {reading.name} against rain only: one reading a call. For " + f"{', '.join(r.name for r in others)}, call again, once for each, in the same round.") + drawn = {"reading": reading.name, "period": whole_day_words(args, period), "chart": True} + return answer(period=period, as_of=now, **fields, **(drawn_charts(charts, ctx, meta, "relate", drawn) if chart else {})) + + return [ServiceTool("relate", DESCRIPTION, parameters(), handle, open_world=ctx.composer is not None)] + + +__all__ = ["AIR", "DESCRIPTION", "HeldAir", "PERIODS", "STATION", "composer_for", "drawn_charts", "flag", "parameters", "relate_reading", + "tools", "whole_day_words"] diff --git a/lib/service/scan.py b/lib/service/scan.py new file mode 100644 index 00000000..90692bab --- /dev/null +++ b/lib/service/scan.py @@ -0,0 +1,113 @@ +"""The `scan` tool (docs/mcp-service.md 3.3): each air reading against every weather reading, read together at 30-minute resolution +over whole days to yesterday, for the relationships that stand out (lib/compose.py Composer.air_scan, today's air_scan, over +lib/analysis/scan.py). Its verdict and findings come back as they are, in the service's shape; a chart, when asked, is the strongest pair +over time, carrying the call that drew it (drawn_by, 3.7). + +At most SCAN_MAX_DAYS days are scanned, as today: a longer period is cut to its latest days, and the result's `period` and +`note_period` say so. The air sensor's missing finished days are fetched (up to 30) unless the request's metadata says `fetch` false +(relate.composer_for); its `priority` changes nothing. +""" + +import json +from dataclasses import replace +from datetime import timedelta + +from ..compose import SCAN_AIR, SCAN_MAX_DAYS +from ..periods_text import Period +from ..specs import period_text +from ..timeutil import day_bounds, to_local +from ..tools import Turn +from .common import Refusal, ServiceTool, answer, period_properties, read_period +from .context import Context +from .names import Catalogue +from .readings import first_day +from .relate import composer_for, drawn_charts, flag, whole_day_words + +SCANNED = {f"air.{m}": m for m in SCAN_AIR} # the air readings scanned -> air_scan's metric +ALL = "all" +DEFAULT_PERIOD = "last 90 days" + +DESCRIPTION = ( + "Which weather goes with air quality: each air reading (PM2.5, PM10, CO2, VOC, NOx) against every weather reading (temperature, " + "humidity, dew point, pressure and its 3-hour change, wind speed, gusts, wind direction, rain), read together at 30-minute " + "resolution over whole days, allowing for the daily cycle and for chance. It reports only the relationships that stand out, " + "strongest first, with a plain verdict. Examples: \"what affects air quality?\" {}; \"is there a correlation between CO2 and the " + "other readings?\" {reading: \"co2\"}; \"what goes with PM2.5 over the past year? show me\" {reading: \"pm2.5\", period: \"past " + "year\", chart: true}. " + f"At most {SCAN_MAX_DAYS} days: a longer period is cut to its latest {SCAN_MAX_DAYS}, and the result says so. " + "Not for: whether rain clears the air, or rain against any one reading (relate); a chart of readings over time (summary); the air " + "now (current). " + "Result: open with `verdict`, then the relationships in `findings`, strongest first, as `how_to_read` says: they go together, " + "they don't cause each other. With `chart`, the strongest pair over time (none when nothing stands out).") + + +def parameters() -> dict: + return { + "type": "object", + "properties": { + "reading": {"type": "string", "description": "The air reading scanned against the weather, a name or the word for it: " + "pm2.5 (air.pm2_5), pm10 (air.pm10), co2 (air.co2), voc (air.voc_index), nox " + "(air.nox_index); or all of them, the default."}, + **period_properties(f"the last 90 days; at most {SCAN_MAX_DAYS} days", whole_days=True), + "chart": {"type": "boolean", "description": "true for a chart of the strongest relationship found, the two readings over " + "time. Default false."}, + }, + } + + +def scan_reading(catalogue: Catalogue, words) -> str: + """"all", or the full name of the one air reading the words name. Raises UnknownReading, or Refusal for words that name no air + reading scanned, or several.""" + if isinstance(words, (list, tuple)) and len(words) == 1: + words = words[0] + if words is None or str(words).strip().lower() in ("", ALL, "every", "everything", "all of them"): + return ALL + names = [r.name for r in catalogue.resolve(words, default=ALL)] + scanned = [n for n in names if n in SCANNED] + if scanned and set(SCANNED) <= set(names): # the air sensor named ("air", "airgradient"): all its readings + return ALL + if len(scanned) == 1: + return scanned[0] + readings = [ALL, *(n for n in SCANNED if n in catalogue)] + if not scanned: + raise Refusal(f"{words!r} ({', '.join(names)}) isn't an air reading this tool scans: send one of {', '.join(readings)}. For rain " + "against a weather reading use relate.", readings=readings) + raise Refusal(f"{words!r} names {len(scanned)} air readings: send one, or all.", readings=readings) + + +def latest_days(period: Period, tz) -> tuple[Period, str | None]: + """The period cut to its latest SCAN_MAX_DAYS days, and the note that says so (None when it wasn't longer).""" + first, last = period.first_day, period.last_day + if (last - first).days < SCAN_MAX_DAYS: + return period, None + first = last - timedelta(days=SCAN_MAX_DAYS - 1) + span = period_text(first, last) + cut = replace(period, start=to_local(day_bounds(first, tz)[0], tz), text=f"its last {SCAN_MAX_DAYS} days: {span}") + return cut, (f"Only the last {SCAN_MAX_DAYS} days can be scanned in one call: this covers {span}, not all of {period.text}.") + + +def tools(ctx: Context) -> list[ServiceTool]: + async def handle(args: dict, meta: dict) -> str: + reading = scan_reading(ctx.readings(), args.get("reading")) + composer = composer_for(ctx, meta, "Scanning the air against the weather") + air = ctx.readings().get(reading) or ctx.readings().get("air.pm2_5") + now = ctx.now() + period = read_period(args, tz=ctx.zone, now=now, default=DEFAULT_PERIOD, whole_days=True, + first_held=await first_day(ctx, [air]) if air else None) + period, note_period = latest_days(period, ctx.zone) + chart = flag(args.get("chart")) + turn = Turn() + out = json.loads(await composer.air_scan({"metric": SCANNED.get(reading, ALL), "start_date": period.first_day.isoformat(), + "end_date": period.last_day.isoformat(), "chart": chart}, turn)) + if "error" in out: # (not expected: the reading and the period were checked here) + raise Refusal(out["error"]) + fields = {"reading": reading, **{k: out[k] for k in ("verdict", "how_to_read", "findings") if k in out}, + **{k: v for k, v in out.items() if k not in ("period", "chart", "verdict", "how_to_read", "findings")}, + **({"note_period": note_period} if note_period else {})} + drawn = {"reading": reading, "period": whole_day_words(args, period), "chart": True} + return answer(period=period, as_of=now, **fields, **(drawn_charts(turn.charts, ctx, meta, "scan", drawn) if chart else {})) + + return [ServiceTool("scan", DESCRIPTION, parameters(), handle, open_world=True)] + + +__all__ = ["DESCRIPTION", "SCANNED", "latest_days", "parameters", "scan_reading", "tools"] diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py new file mode 100644 index 00000000..d8128e47 --- /dev/null +++ b/tests/test_service_readings.py @@ -0,0 +1,214 @@ +"""The service's `readings` tool (lib/service/readings.py): one reading's values at an interval, over a period in words, with the rows +the bot's readings tool (lib/history.py) gives for the same span.""" + +import json +from datetime import datetime +from types import SimpleNamespace + +import pytest + +from lib.history import INTERVALS, MAX_ROWS, History +from lib.service import readings +from lib.service.common import FRESH +from lib.service.context import Context +from lib.service.names import Catalogue +from lib.storage import Storage +from lib.storage.catalogue import CLOUD +from lib.timeutil import local_epoch +from lib.tools import Tools, Turn +from tests.fakes import TZ + +MAC, LOC = "M", "42" +NOW = local_epoch(datetime(2026, 11, 9, 1, 47), TZ) # Mon 9 Nov 2026 1:47am, as lib/history.py's tests ask +SENT = {"outdoor": {"temperature": "℃", "temperature_low": "℃", "humidity": "%"}, "indoor": {"temperature": "℃", "humidity": "%"}, + "wind": {"wind_speed": "km/h", "wind_gust": "km/h", "wind_direction": "º"}, "rainfall": {"daily": "mm", "rain_rate": "mm/hr"}} + + +def at(day: int, hour: int, minute: int = 0) -> int: + return local_epoch(datetime(2026, 11, day, hour, minute), TZ) + + +@pytest.fixture +def storage(tmp_path): + s = Storage(tmp_path / "ecobot.sqlite", TZ) + yield s + s.close() + + +def put(storage, sensor: str, res: str, rows: list[dict]): + """Readings written as a source writes them: an Ecowitt group's, or the air sensor's ("air").""" + def write(w): + s = w.air_sensor(LOC) if sensor == "air" else w.ecowitt_sensor(MAC, sensor) + w.put(s, res, rows, CLOUD) + storage.writer.run(write, ()) + + +class AirStore: + """The air sensor's readings in the file, as AirGradient keeps them (lib/airgradient/readings.py): its sensor is a property.""" + + def __init__(self, storage): + self.storage = storage + + @property + def sensor(self): + return self.storage.air_sensor(LOC) + + +def sources(storage): + """(the station, the air sensor) as the tools read them: the file, the station's MAC, the air sensor's place in the file.""" + return SimpleNamespace(storage=storage, mac=MAC, tz=TZ), SimpleNamespace(store=AirStore(storage), tz=TZ) + + +def tool(storage): + station, air = sources(storage) + (made,) = readings.tools(Context(eco=station, air=air, catalogue=Catalogue.of(SENT), tz=TZ, clock=lambda: NOW)) + return made + + +async def ask(storage, meta: dict | None = None, **args) -> dict: + return json.loads(await tool(storage).call(args, meta)) + + +async def old(storage, **args) -> dict: + """The bot's readings tool (lib/history.py) over the same file, at the same time (it calls the air sensor's `sensor`).""" + station = SimpleNamespace(storage=storage, mac=MAC, tz=TZ) + air = SimpleNamespace(store=SimpleNamespace(storage=storage, sensor=lambda: storage.air_sensor(LOC)), tz=TZ) + return json.loads(await History(station, air, SENT, now=lambda: NOW).handle(args, Turn())) + + +ROWS = ("columns", "rows", "from", "missing", "note_coarser", "fits", "note_minutes", "note_daily", "note_last", "note") + + +def same_rows(new: dict, before: dict) -> bool: + return {k: new.get(k) for k in ROWS} == {k: before.get(k) for k in ROWS} and new["value_is"] == before["value_is"] + + +# ---------- what it takes ---------- +def test_it_takes_one_reading_a_period_in_words_and_an_interval(storage): + made = tool(storage) + props = made.parameters["properties"] + assert made.name == "readings" and made.parameters["required"] == ["reading", "interval"] + assert set(props) == {"reading", "period", "start", "end", "interval"} and props["interval"]["enum"] == list(INTERVALS) + assert "Default: last 24 hours" in props["period"]["description"] and "this week" in props["period"]["description"] + assert "outdoor.humidity" in props["reading"]["description"] and "ONE reading" in props["reading"]["description"] + assert len(made.description) < 1500 and all(f"({tool})" in made.description for tool in ("summary", "days", "current")) + assert made.description.count("{reading:") >= 3 and "`value_is`" in made.description and "`fits`" in made.description + assert made.annotations == {"readOnlyHint": True, "openWorldHint": False} # it reads the file only + + +# ---------- the rows ---------- +async def test_the_rows_are_the_bots_readings_over_the_period_the_words_name(storage): + put(storage, "outdoor", "30min", [{"ts": at(8, 20) + 1800 * i, "humidity": 60 + 10 * (i // 2)} for i in range(4)]) # 8pm to 9:30pm + put(storage, "outdoor", "5min", [{"ts": at(8, 22) + 300 * i, "humidity": 70 + (i // 12)} for i in range(12 * 4 - 2)]) # 10pm on + out = await ask(storage, reading="outdoor.humidity", period="last 5 hours", interval="1hour") # "humidity each hour for the last 5 hours" + assert list(out)[:3] == ["period", "as_of", "fresh"] and out["fresh"] == FRESH + assert out["period"]["asked"] == "last 5 hours" and out["period"]["text"] == "the last 5 hours: Sun 8 Nov 8:47pm – Mon 9 Nov 2026 1:47am" + assert out["as_of"] == {"text": "Mon 9 Nov 2026 1:47am", "time": "2026-11-09T01:47:00+11:00"} + assert list(out)[3:8] == ["reading", "label", "unit", "interval", "value_is"] + assert (out["reading"], out["label"], out["unit"], out["interval"]) == ("outdoor.humidity", "Outdoor humidity", "%", "1hour") + assert [r[1] for r in out["rows"]] == [60, 70, 70, 71, 72, 73] and out["from"] == ["5min", "30min"] and "note_last" in out + assert same_rows(out, await old(storage, metric="outdoor.humidity", start="2026-11-08 20:47", interval="1hour")) + + +async def test_with_no_period_it_reads_the_last_24_hours(storage): + put(storage, "outdoor", "5min", [{"ts": at(8, 1) + 300 * i, "temperature": 10.0 + i % 12} for i in range(24 * 12 + 9)]) + out = await ask(storage, reading="temperature", interval="1hour") + assert out["period"]["asked"] == "last 24 hours" and out["period"]["start"] == "2026-11-08T01:47:00+11:00" + assert len(out["rows"]) == 25 and out["rows"][0][0] == "Sun 8 Nov 2026 1:00am" and out["rows"][-1][0] == "Mon 9 Nov 2026 1:00am" + assert same_rows(out, await old(storage, metric="outdoor.temperature", start="2026-11-08 01:47", interval="1hour")) + + +async def test_rain_gusts_and_days_are_read_as_the_bot_reads_them(storage): + put(storage, "rainfall", "5min", [{"ts": at(8, 22, 30), "daily": 0.0}, {"ts": at(8, 23), "daily": 0.0}, {"ts": at(8, 23, 30), "daily": 1.0}, + {"ts": at(8, 23, 55), "daily": 2.0}, {"ts": at(9, 0), "daily": 0.0}, {"ts": at(9, 0, 30), "daily": 0.5}]) + out = await ask(storage, reading="rain", start="2026-11-08 23:00", end="2026-11-09 00:59", interval="hourly") + assert out["reading"] == "rainfall.rain" and out["interval"] == "1hour" and [r[1] for r in out["rows"]] == [2.0, 0.5] # the midnight reset + assert out["value_is"] == "the mm of rain that fell in the interval" and out["columns"] == ["time", "value"] + assert same_rows(out, await old(storage, metric="rainfall.rain", start="2026-11-08 23:00", end="2026-11-09 00:59", interval="1hour")) + put(storage, "wind", "5min", [{"ts": at(8, 22) + 300 * i, "wind_speed": 5.0, "wind_gust": 10.0 + i} for i in range(24)]) + out = await ask(storage, reading="gust", start="2026-11-08 22:00", end="2026-11-08 23:59", interval="1hour") + assert out["reading"] == "wind.wind_gust" and [r[1] for r in out["rows"]] == [21.0, 33.0] + put(storage, "outdoor", "5min", [{"ts": at(6, 0) + 300 * i, "temperature": 10.0 + (i % 288 == 180) * 10} for i in range(288 * 2)]) + out = await ask(storage, reading="outdoor.temperature", start="2026-11-06", end="2026-11-07", interval="1day") # dates: whole days + assert out["columns"] == ["day", "value", "low", "low_time", "high", "high_time"] and out["rows"][0][:5] == ["Fri 6 Nov 2026", 10.0, 10.0, "12:00am", 20.0] + assert same_rows(out, await old(storage, metric="outdoor.temperature", start="2026-11-06 00:00", end="2026-11-07 23:59", interval="1day")) + + +async def test_the_air_sensors_readings_and_its_own_temperature(storage): + rows = [{"ts": at(8, 22) + 300 * i, "pm2_5": 5.0, "pm10": 8.0, "pm1": 3.0, "air_temperature": 18.0 + i} for i in range(6)] + rows[3] |= {"pm2_5": 50.0, "pm10": 60.0, "pm1": 40.0} # a glitch of the sensor, taken out as air_quality takes it out + put(storage, "air", "5min", rows) + out = await ask(storage, reading="pm2.5", start="2026-11-08 22:00", end="2026-11-08 22:29", interval="30min") + assert out["reading"] == "air.pm2_5" and out["unit"] == "µg/m³" and out["rows"] == [["Sun 8 Nov 2026 10:00pm", 5.0, 5.0, 5.0]] + out = await ask(storage, reading="airgradient temperature", start="2026-11-08 22:00", end="2026-11-08 22:29", interval="30min") + assert (out["reading"], out["label"], out["unit"]) == ("air.temperature", "AirGradient temperature", "°C") and out["rows"][0][1:] == [20.5, 18.0, 23.0] + + +async def test_a_word_for_several_readings_reads_the_first_and_names_the_others(storage): + put(storage, "outdoor", "5min", [{"ts": at(9, 1), "humidity": 80}]) + out = await ask(storage, reading="humidity", period="last 30 minutes", interval="5min") + assert out["reading"] == "outdoor.humidity" and "indoor.humidity" in out["note_others"] and "call it again" in out["note_others"] + out = await ask(storage, reading="wind", period="last 30 minutes", interval="5min") + assert out["reading"] == "wind.wind_speed" and "note_others" not in out # wind is its speed: its direction goes with it only on a chart + put(storage, "wind", "5min", [{"ts": at(9, 1, 5 * i), "wind_speed": 5.0, "wind_direction": 90 + i} for i in range(9)]) + out = await ask(storage, reading="wind direction", period="last 30 minutes", interval="5min") + assert out["reading"] == "wind.wind_direction" and out["columns"] == ["time", "value"] and out["rows"][-2:] == [["Mon 9 Nov 2026 1:40am", 98], ["Mon 9 Nov 2026 1:45am", None]] + + +# ---------- refusals that teach ---------- +async def test_a_reading_or_an_interval_it_cant_read_lists_those_it_can(storage): + out = await ask(storage, reading="soil moisture", interval="1hour") + assert "isn't a reading" in out["error"] and "outdoor.humidity" in out["names"] and out["words"]["pressure"] == ["pressure.relative"] + out = await ask(storage, interval="1hour") + assert out["error"].startswith("Send `reading`") and "rainfall.rain" in out["names"] + out = await ask(storage, reading="humidity") + assert out["error"].startswith("Send `interval`") and out["intervals"] == list(INTERVALS) + out = await ask(storage, reading="humidity", interval="fortnightly") + assert "'fortnightly' isn't one" in out["error"] and out["intervals"] == list(INTERVALS) + + +async def test_a_period_it_cant_read_says_what_it_can(storage): + out = await ask(storage, reading="humidity", period="the other day", interval="1hour") + assert "isn't a period" in out["error"] and any(form.startswith("last N hours") for form in out["forms"]) + assert "It is now Mon 9 Nov 2026 1:47am." in out["error"] + assert "use forecast" in (await ask(storage, reading="humidity", period="tomorrow", interval="1hour"))["error"] + assert "not both" in (await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour"))["error"] + out = await ask(storage, reading="humidity", period="on record", interval="1day") + assert "Nothing is held yet" in out["error"] + + +async def test_too_many_rows_are_refused_with_the_interval_that_fits_and_that_one_is_accepted(storage): + out = await ask(storage, reading="outdoor.temperature", period="last 3 days", interval="5min") + assert out["error"].startswith("Too many rows: the last 3 days") and out["rows"] > MAX_ROWS and out["max_rows"] == MAX_ROWS + assert out["fits"] == "30min" and "Ask again with interval 30min." in out["error"] + assert "error" not in await ask(storage, reading="outdoor.temperature", period="last 3 days", interval=out["fits"]) + out = await ask(storage, reading="outdoor.temperature", period="last 2 years", interval="1day") + assert out["fits"] is None and "summary" in out["error"] and "days" in out["error"] + + +async def test_on_record_starts_at_the_first_day_held(storage): + put(storage, "outdoor", "5min", [{"ts": at(6, 12) + 300 * i, "temperature": 12.0} for i in range(12)]) + out = await ask(storage, reading="outdoor.temperature", period="on record", interval="1day") + assert out["period"]["start"] == "2026-11-06T00:00:00+11:00" and [r[0] for r in out["rows"]] == \ + ["Fri 6 Nov 2026", "Sat 7 Nov 2026", "Sun 8 Nov 2026", "Mon 9 Nov 2026"] and out["missing"] == 3 + + +async def test_what_isnt_held_is_said_never_filled(storage): + out = await ask(storage, reading="outdoor.humidity", period="last 2 hours", interval="1hour") + assert out["rows"] == [] and out["note"] == "Nothing is stored for this sensor yet." + put(storage, "outdoor", "5min", [{"ts": at(7, 12), "temperature": 12.0}]) # the sensor has readings, none of them here + out = await ask(storage, reading="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + assert out["missing"] == 10 and "note_minutes" in out and "never fill the gap" in out["note"] # (an end with a time stops at it) + put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "temperature": 12.0} for i in range(3)]) + out = await ask(storage, reading="outdoor.temperature", start="2026-11-09 01:00", end="2026-11-09 01:10", interval="1min") + assert out["fits"] == "5min" and "note_coarser" in out + + +# ---------- only its arguments reach it ---------- +async def test_only_the_arguments_reach_it_and_its_metadata_changes_nothing(storage): + put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "humidity": 80 + i} for i in range(9)]) + args = {"reading": "outdoor.humidity", "period": "last hour", "interval": "5min"} + direct = await tool(storage).call(args) + via_bot = await Tools([tool(storage).tool()]).call("readings", json.dumps(args), Turn(text="humidity every 30 minutes", per_day=True)) + assert via_bot == direct and json.loads(direct)["interval"] == "5min" + assert await tool(storage).call(args, {"fetch": False, "priority": "background"}) == direct # nothing is fetched here anyway diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py new file mode 100644 index 00000000..4fdd1a25 --- /dev/null +++ b/tests/test_service_relate.py @@ -0,0 +1,227 @@ +"""The service's `relate` tool (lib/service/relate.py): rain against one reading over whole days, with the findings of the bot's +weather_link (pressure, humidity, wind) and air_link (PM2.5, PM10), and a chart that says how to draw it again.""" + +import json +import time +from datetime import date, timedelta +from types import SimpleNamespace + +from lib.airgradient.readings import NOT_HELD, Held +from lib.compose import Composer +from lib.ecowitt.link import link +from lib.service import relate +from lib.service.common import CHART_NOTE +from lib.service.context import Context +from lib.timeutil import local_date +from lib.tools import Tools, Turn +from tests.fakes import TZ, archived_station +from tests.test_chart_json import errors +from tests.test_compose import StubAir + + +class HeldStubAir(StubAir): + """The air sensor as the composer reads it (StubAir), its readings also held in its file (`store`), as AirGradient's are: what a + request that may not fetch reads. `fetched` counts the reads that may fetch.""" + + def __init__(self, days=40): + super().__init__(days) + self.fetched = 0 + self.store = SimpleNamespace(held=self._held, load=self._load) + + async def rows(self, t0, t1): + self.fetched += 1 + return await super().rows(t0, t1) + + async def _held(self, days): + have = {local_date(r["ts"], TZ) for r in self.readings} + return {d: Held(288, False) if d in have else NOT_HELD for d in days} + + async def _load(self, lo, hi): + return [r for r in self.readings if lo <= r["ts"] < hi] + + +async def world(tmp_path, archived_cache): + """(the context over the archived station and a stand-in air sensor, at one moment; the station).""" + eco, _ = await archived_station(tmp_path, archived_cache) + sensor, now = HeldStubAir(), int(time.time()) + ctx = Context(eco=eco, air=sensor, composer=Composer(eco, sensor), tz=TZ, clock=lambda: now) + return ctx, eco + + +async def ask(ctx, meta: dict | None = None, **args) -> dict: + (made,) = relate.tools(ctx) + return json.loads(await made.call(args, meta)) + + +def days_of(out: dict) -> tuple[date, date]: + """The first and last day a result's period covers.""" + start, end = (date.fromisoformat(out["period"][k][:10]) for k in ("start", "end")) + return start, end - timedelta(days=1) + + +def without_drawn_by(chart: dict) -> dict: + return {k: v for k, v in chart.items() if k != "drawn_by"} + + +async def replays(ctx, chart: dict, **swap) -> dict: + """The call a chart says drew it, made again (with `swap` in its arguments).""" + drawn = chart["drawn_by"] + return await ask(ctx, **{**drawn["arguments"], **swap}) + + +# ---------- what it takes ---------- +async def test_it_takes_a_reading_whole_days_and_a_chart_and_says_what_it_is_not_for(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + (made,) = relate.tools(ctx) + props = made.parameters["properties"] + assert made.name == "relate" and set(props) == {"reading", "period", "start", "end", "chart"} and "required" not in made.parameters + assert "Whole days only, up to yesterday" in props["period"]["description"] and "the last 90 days" in props["period"]["description"] + assert all(name in props["reading"]["description"] for name in ("pressure.relative", "outdoor.humidity", "wind.wind_speed", "air.pm2_5", "air.pm10")) + assert len(made.description) < 1500 and "\"X against rain\" is this tool" in made.description + assert all(f"({tool})" in made.description for tool in ("scan", "summary", "days")) and made.description.count("{reading:") >= 3 + assert made.annotations == {"readOnlyHint": True, "openWorldHint": True} # the air sensor's missing days are fetched + (station_only,) = relate.tools(Context(eco=eco, tz=TZ)) + assert station_only.annotations["openWorldHint"] is False + await eco.close() + + +# ---------- the findings ---------- +async def test_with_nothing_named_it_is_pressure_against_rain_over_the_last_90_days_as_weather_link_finds(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx) + assert list(out)[:9] == ["period", "as_of", "fresh", "reading", "label", "unit", "verdict", "how_to_read", "findings"] + assert (out["reading"], out["label"], out["unit"]) == ("pressure.relative", "Pressure", "hPa") + assert out["period"]["asked"] == "last 90 days" and out["period"]["cut"].endswith("today isn't over") + first, last = days_of(out) + assert last == ctx.now().date() - timedelta(days=1) and (last - first).days == 89 + before, _, _, _ = link(eco.storage.read_now, eco.mac, TZ, {"start_date": str(first), "end_date": str(last)}, ctx.now()) + assert {k: v for k, v in out.items() if k in before and k != "period"} == \ + {k: v for k, v in before.items() if k not in ("period", "driver")} + assert "charts" not in out and "chart_note" not in out and "driver" not in out # a chart only when asked + await eco.close() + + +async def test_the_words_people_use_name_the_reading(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + for words, name in (("humidity", "outdoor.humidity"), ("wind", "wind.wind_speed"), ("barometer", "pressure.relative"), + ("outdoor humidity", "outdoor.humidity"), ("PM2.5", "air.pm2_5"), ("pm10", "air.pm10")): + out = await ask(ctx, reading=words, period="last 30 days") + assert out["reading"] == name and out["verdict"] and "note_others" not in out, words + out = await ask(ctx, reading="pm2.5") + assert out["period"]["asked"] == "last 60 days" and out["label"] == "PM2.5" # the air's own default + out = await ask(ctx, reading="air", period="last 30 days") # the air sensor: its first that rain relates to + assert out["reading"] == "air.pm2_5" and "air.pm10" in out["note_others"] + out = await ask(ctx, reading="pressure and humidity", period="last 30 days") + assert out["reading"] == "pressure.relative" and "outdoor.humidity" in out["note_others"] and "call again" in out["note_others"] + await eco.close() + + +async def test_air_against_rain_is_air_links_findings(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="air.pm10", period="last 3 weeks") + first, last = days_of(out) + before = json.loads(await ctx.composer.air_link({"metric": "pm10", "start_date": str(first), "end_date": str(last)}, Turn())) + assert {k: v for k, v in out.items() if k in before and k != "period"} == \ + {k: v for k, v in before.items() if k not in ("period", "metric", "chart")} + assert out["how_to_read"].startswith("Open with `verdict`") and (out["reading"], out["unit"]) == ("air.pm10", "µg/m³") + await eco.close() + + +async def test_a_request_that_may_not_fetch_reads_the_air_from_the_file(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + fetched = await ask(ctx, reading="pm2.5", chart=True) + assert ctx.air.fetched == 1 + held = await ask(ctx, {"fetch": False}, reading="pm2.5", chart=True) + assert ctx.air.fetched == 1 and held["notes"] == {"missing": "20 older day(s) aren't in the bot's cache yet and were left out"} + assert {k: v for k, v in held.items() if k != "notes"} == fetched # (the 40 days it holds: those the stand-in has) + await eco.close() + + +# ---------- refusals that teach ---------- +async def test_what_it_cant_relate_is_refused_with_what_it_can(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="temperature") + assert "can't be set against rain" in out["error"] and out["readings"] == ["pressure.relative", "outdoor.humidity", "wind.wind_speed", + "air.pm2_5", "air.pm10"] + out = await ask(ctx, reading="rain") + assert "rainfall.rain" in out["error"] and "use days" in out["error"] + out = await ask(ctx, reading="soil moisture") + assert "isn't a reading" in out["error"] and "pressure.relative" in out["names"] + assert "needs both the weather station and the air sensor" in (await ask(Context(eco=eco, tz=TZ), reading="air.pm2_5"))["error"] + await eco.close() + + +async def test_a_period_that_isnt_whole_days_points_to_the_tools_that_read_one(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + for period in ("today", "last 5 hours", "this morning"): + out = await ask(ctx, period=period) + assert "use summary or readings" in out["error"], period + assert "has a time" in (await ask(ctx, start="2026-09-01 10:00"))["error"] + assert "use forecast" in (await ask(ctx, period="next week"))["error"] + out = await ask(ctx, period="whenever") + assert "isn't a period" in out["error"] and "on record, all time, ever (from the first reading held)" in out["forms"] + await eco.close() + + +async def test_on_record_starts_where_both_the_reading_and_the_rain_are_held(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, period="on record") + first, last = days_of(out) + assert out["verdict"] and (last - first).days > 500 and out["period"]["text"].startswith("on record: ") + await eco.close() + + +# ---------- the chart ---------- +async def test_a_chart_when_asked_carries_the_call_that_draws_it_again(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="pressure", chart=True) + (chart,) = out["charts"] + assert out["chart_note"] == CHART_NOTE and chart["title"] == "Pressure, Rain" and chart["source"] == "Ecowitt weather station" + assert errors(without_drawn_by(chart)) == [] + assert chart["drawn_by"] == {"tool": "relate", "arguments": {"reading": "pressure.relative", "period": "last 90 days", "chart": True}, + "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} + assert await replays(ctx, chart) == out # the same call again: the same answer + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and again["period"]["asked"] == each["period"], each + (redrawn,) = again["charts"] + assert redrawn["title"] == chart["title"] and redrawn["period"] == [str(d) for d in days_of(again)] + assert redrawn["drawn_by"] == {**chart["drawn_by"], "arguments": {**chart["drawn_by"]["arguments"], "period": each["period"]}} + await eco.close() + + +async def test_a_chart_of_dates_is_drawn_again_from_those_dates(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + yesterday = ctx.now().date() - timedelta(days=1) + first, last = yesterday - timedelta(days=40), yesterday - timedelta(days=10) + out = await ask(ctx, reading="humidity", start=str(first), end=str(last), chart=True) + (chart,) = out["charts"] + assert chart["drawn_by"]["arguments"] == {"reading": "outdoor.humidity", "period": f"{first} to {last}", "chart": True} + again = await replays(ctx, chart) + assert again["charts"] == out["charts"] and again["findings"] == out["findings"] and again["period"]["text"] == out["period"]["text"] + await eco.close() + + +async def test_the_air_against_rain_is_drawn_with_its_zones_and_drawn_again_over_each_period(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, reading="pm2.5", chart=True) + (chart,) = out["charts"] + assert chart["title"] == "PM2.5, Rain" and chart["source"] == "Ecowitt weather station and AirGradient sensor" + assert chart["panels"][0]["zones"] == [9.0, 55.4] and errors(without_drawn_by(chart)) == [] + assert chart["drawn_by"]["arguments"] == {"reading": "air.pm2_5", "period": "last 60 days", "chart": True} + assert await replays(ctx, chart) == out + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and [c["title"] for c in again["charts"]] == ["PM2.5, Rain"], each + await eco.close() + + +async def test_a_chart_is_sent_in_the_points_the_request_asks_for_and_only_when_the_arguments_ask(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + small = await ask(ctx, {"chart_points": 20}, reading="humidity", chart=True) + lines = [s for p in small["charts"][0]["panels"] for s in p["series"] if s["kind"] in ("line", "band")] + assert lines and all(len(s["points"]) <= 20 for s in lines) + (made,) = relate.tools(ctx) + asked = json.loads(await Tools([made.tool()]).call("relate", "{}", Turn(text="plot pressure against rain", chart_asked=True))) + assert "charts" not in asked # the words of the question never reach it: only `chart` draws + await eco.close() diff --git a/tests/test_service_scan.py b/tests/test_service_scan.py new file mode 100644 index 00000000..c6be4e91 --- /dev/null +++ b/tests/test_service_scan.py @@ -0,0 +1,162 @@ +"""The service's `scan` tool (lib/service/scan.py): each air reading against every weather reading over whole days, with the findings of +the bot's air_scan, at most 400 days, and a chart of the strongest pair that says how to draw it again.""" + +import json +import time +from datetime import date, datetime, timedelta + +from lib.compose import Composer +from lib.service import scan +from lib.service.common import CHART_NOTE, read_period +from lib.service.context import Context +from lib.tools import Turn +from tests.fakes import TZ, archived_station, pressure +from tests.test_chart_json import errors +from tests.test_service_relate import HeldStubAir, days_of, without_drawn_by + + +class PressureAir(HeldStubAir): + """An air sensor whose PM2.5 follows the station's pressure (and whose PM10 changes by the day): a relationship that stands out, + so the scan has a strongest pair to draw.""" + + def __init__(self, days=60): + super().__init__(days=0) + now = datetime.now(TZ).replace(minute=0, second=0, microsecond=0) + for i in range(days * 288, 0, -1): + when = now - timedelta(minutes=5 * i) + ts = int(when.timestamp()) + self.readings.append({"ts": ts, "pm2_5": 2 * (pressure(ts) - 1000), "pm10": 10.0 + when.day % 3}) + + +async def world(tmp_path, archived_cache, air=None): + eco, _ = await archived_station(tmp_path, archived_cache) + sensor, now = air or PressureAir(), int(time.time()) + return Context(eco=eco, air=sensor, composer=Composer(eco, sensor), tz=TZ, clock=lambda: now), eco + + +async def ask(ctx, meta: dict | None = None, **args) -> dict: + (made,) = scan.tools(ctx) + return json.loads(await made.call(args, meta)) + + +async def replays(ctx, chart: dict, **swap) -> dict: + return await ask(ctx, **{**chart["drawn_by"]["arguments"], **swap}) + + +# ---------- what it takes ---------- +async def test_it_takes_an_air_reading_or_all_whole_days_and_a_chart(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + (made,) = scan.tools(ctx) + props = made.parameters["properties"] + assert made.name == "scan" and set(props) == {"reading", "period", "start", "end", "chart"} and "required" not in made.parameters + assert "Whole days only, up to yesterday" in props["period"]["description"] and "at most 400 days" in props["period"]["description"] + assert all(name in props["reading"]["description"] for name in ("air.pm2_5", "air.co2", "air.voc_index", "all of them")) + assert len(made.description) < 1500 and all(f"({tool})" in made.description for tool in ("relate", "summary", "current")) + assert "{reading: \"co2\"}" in made.description and "At most 400 days" in made.description + assert made.annotations == {"readOnlyHint": True, "openWorldHint": True} + await eco.close() + + +# ---------- the findings ---------- +async def test_with_nothing_named_it_scans_every_air_reading_over_the_last_90_days_as_air_scan_does(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx) + assert list(out)[:7] == ["period", "as_of", "fresh", "reading", "verdict", "how_to_read", "findings"] + assert out["reading"] == "all" and out["period"]["asked"] == "last 90 days" and out["period"]["cut"].endswith("today isn't over") + assert out["verdict"] == "Yes - 1 relationship stands out" and "pressure" in out["findings"][0] + first, last = days_of(out) + assert last == ctx.now().date() - timedelta(days=1) and (last - first).days == 89 + before = json.loads(await ctx.composer.air_scan({"start_date": str(first), "end_date": str(last)}, Turn())) + assert {k: v for k, v in out.items() if k in before and k != "period"} == {k: v for k, v in before.items() if k not in ("period", "chart")} + assert "charts" not in out and "chart" not in out # a chart only when asked + await eco.close() + + +async def test_the_words_people_use_name_the_air_reading(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + for words, name in (("pm2.5", "air.pm2_5"), ("CO2", "air.co2"), ("voc", "air.voc_index"), ("air.nox_index", "air.nox_index"), + ("air", "all"), ("airgradient", "all"), ("everything", "all"), (["all"], "all"), ("", "all")): + out = await ask(ctx, reading=words, period="last 2 weeks") + assert out["reading"] == name and out["verdict"], words + await eco.close() + + +async def test_a_reading_with_nothing_to_scan_says_so(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) # (the stand-in measures no CO2) + out = await ask(ctx, reading="co2", chart=True) + assert out["verdict"] == "Not enough data to say" and out["findings"] and "charts" not in out + await eco.close() + + +async def test_what_it_cant_scan_is_refused_with_what_it_can(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + readings = ["all", "air.pm2_5", "air.pm10", "air.co2", "air.voc_index", "air.nox_index"] + out = await ask(ctx, reading="pm1") + assert "isn't an air reading this tool scans" in out["error"] and out["readings"] == readings + out = await ask(ctx, reading="temperature") + assert "use relate" in out["error"] and out["readings"] == readings + out = await ask(ctx, reading="pm2.5 and pm10") + assert "names 2 air readings: send one, or all" in out["error"] + assert "use summary or readings" in (await ask(ctx, period="today"))["error"] + assert "needs both the weather station and the air sensor" in (await ask(Context(eco=eco, tz=TZ)))["error"] + await eco.close() + + +def test_a_period_longer_than_400_days_is_cut_to_its_latest_and_says_so(): + now = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) + two = read_period({"period": "2y"}, tz=TZ, now=now, default="last 90 days", whole_days=True) + cut, note = scan.latest_days(two, TZ) + assert (cut.first_day, cut.last_day) == (date(2025, 10, 6), date(2026, 11, 9)) and cut.asked == "2y" and cut.cut == two.cut + assert cut.start == datetime(2025, 10, 6, tzinfo=TZ) and cut.text == "its last 400 days: Mon 6 Oct 2025 – Mon 9 Nov 2026" + assert note == ("Only the last 400 days can be scanned in one call: this covers Mon 6 Oct 2025 – Mon 9 Nov 2026, not all of the last " + "2 years: Sun 10 Nov 2024 – Mon 9 Nov 2026.") + one = read_period({"period": "1y"}, tz=TZ, now=now, default="last 90 days", whole_days=True) + assert scan.latest_days(one, TZ) == (one, None) + + +async def test_a_long_period_is_scanned_over_its_latest_400_days_and_drawn_again_over_them(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + yesterday = ctx.now().date() - timedelta(days=1) + long = await ask(ctx, start=str(yesterday - timedelta(days=500)), chart=True) + assert days_of(long) == (yesterday - timedelta(days=399), yesterday) and long["period"]["text"].startswith("its last 400 days: ") + assert long["note_period"].startswith("Only the last 400 days can be scanned in one call") + (chart,) = long["charts"] + assert chart["drawn_by"]["arguments"]["period"] == f"{yesterday - timedelta(days=399)} to {yesterday}" # the days it scanned + again = await replays(ctx, chart) + assert again["charts"] == long["charts"] and again["findings"] == long["findings"] and "note_period" not in again + await eco.close() + + +async def test_a_request_that_may_not_fetch_reads_the_air_from_the_file(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + fetched = await ask(ctx, reading="pm2.5", period="last 30 days") + held = await ask(ctx, {"fetch": False}, reading="pm2.5", period="last 30 days") + assert ctx.air.fetched == 1 and held == fetched + await eco.close() + + +# ---------- the chart ---------- +async def test_a_chart_of_the_strongest_pair_carries_the_call_that_draws_it_again(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache) + out = await ask(ctx, chart=True) + (chart,) = out["charts"] + assert out["chart_note"] == CHART_NOTE and chart["title"] == "PM2.5, Pressure" and errors(without_drawn_by(chart)) == [] + assert chart["source"] == "Ecowitt weather station and AirGradient sensor" + assert chart["drawn_by"] == {"tool": "scan", "arguments": {"reading": "all", "period": "last 90 days", "chart": True}, + "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} + assert await replays(ctx, chart) == out + for each in chart["drawn_by"]["periods"]: + again = await replays(ctx, chart, period=each["period"]) + assert "error" not in again and again["period"]["asked"] == each["period"], each + (redrawn,) = again["charts"] + assert redrawn["title"] == chart["title"] and redrawn["period"] == [str(d) for d in days_of(again)] + small = await ask(ctx, {"chart_points": 30}, chart=True) + assert all(len(s["points"]) <= 30 for p in small["charts"][0]["panels"] for s in p["series"] if s["kind"] in ("line", "band")) + await eco.close() + + +async def test_no_chart_when_nothing_stands_out(tmp_path, archived_cache): + ctx, eco = await world(tmp_path, archived_cache, air=HeldStubAir()) # PM2.5 by the day, nothing to do with the weather + out = await ask(ctx, reading="pm2.5", chart=True) + assert out["verdict"].startswith("Nothing stands out") and "charts" not in out and "chart_note" not in out + await eco.close() From 09acbc82567eeb95e22a43544a97e3552df1af75 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 05:10:44 +0000 Subject: [PATCH 032/125] drawn_by in schemas/chart.json; History reads the air sensor as the property it is - schemas/chart.json gains drawn_by {tool, arguments, periods: [{period, label}]}, so a service tool's chart validates whole; the tool tests stop stripping it. - lib/history.py: AirReadings.sensor is a property, so the readings tool failed on every air.* reading ('Sensor' object is not callable). The test's stand-in is now a property too, so it would have caught it. - tests/test_service_current.py: the PM2.5 AQI is read back rather than pinned (it moves with the clock). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/history.py | 2 +- schemas/chart.json | 9 +++++++++ tests/test_history.py | 13 ++++++++++++- tests/test_service_current.py | 4 ++-- tests/test_service_days.py | 2 +- tests/test_service_relate.py | 8 ++------ tests/test_service_scan.py | 4 ++-- tests/test_service_summary.py | 2 +- 8 files changed, 30 insertions(+), 14 deletions(-) diff --git a/lib/history.py b/lib/history.py index 746a1600..6695bdca 100644 --- a/lib/history.py +++ b/lib/history.py @@ -378,7 +378,7 @@ def find(self, name: str) -> Metric | None: def _sensor(self, m: Metric) -> int | None: if m.air: - s = self.air.store.sensor() if self.air else None + s = self.air.store.sensor if self.air else None else: s = self.storage.sensors.find(self.eco.mac, m.sensor) if self.eco else None return s.id if s else None diff --git a/schemas/chart.json b/schemas/chart.json index 0875103e..e15e8289 100644 --- a/schemas/chart.json +++ b/schemas/chart.json @@ -18,6 +18,15 @@ "minItems": 2 }, "source": {"type": "string", "description": "Where the data came from (\"Ecowitt weather station\"), written small in the corner; \"\" for none."}, + "drawn_by": {"type": "object", "description": "The call that drew this chart, to draw it again: the same tool with these arguments, `period` swapped for one of `periods` to draw it over another stretch. Absent on a chart no tool call drew.", + "required": ["tool", "arguments", "periods"], "additionalProperties": false, + "properties": { + "tool": {"type": "string", "description": "The tool's name (\"summary\")."}, + "arguments": {"type": "object", "description": "Every argument the call was given, filled in: readings fully named, the period in words."}, + "periods": {"type": "array", "description": "The periods it can be redrawn over, in order; [] when it can't be (a chart over set times).", + "items": {"type": "object", "required": ["period", "label"], "additionalProperties": false, + "properties": {"period": {"type": "string", "description": "The `period` argument to send (\"7d\")."}, + "label": {"type": "string", "description": "What to call it on a button (\"7 days\")."}}}}}}, "newest": {"$ref": "#/$defs/time", "description": "The time of the newest reading drawn: a line's last point or the start of the last bar."}, "panels": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/panel"}} }, diff --git a/tests/test_history.py b/tests/test_history.py index 275a9ba6..317c996e 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -30,6 +30,17 @@ def storage(tmp_path): s.close() +class AirStore: + """The air sensor's store as History reads it: its file, and its sensor a property (AirReadings.sensor).""" + + def __init__(self, storage): + self.storage = storage + + @property + def sensor(self): + return self.storage.air_sensor(LOC) + + def put(storage, sensor: str, res: str, rows: list[dict]): """Readings written as a source writes them: an Ecowitt group's, or the air sensor's ("air").""" def write(w): @@ -40,7 +51,7 @@ def write(w): def tool(storage, eco: bool = True, air: bool = True, sent: dict | None = SENT) -> History: station = SimpleNamespace(storage=storage, mac=MAC, tz=TZ) if eco else None - sensor = SimpleNamespace(store=SimpleNamespace(storage=storage, sensor=lambda: storage.air_sensor(LOC)), tz=TZ) if air else None + sensor = SimpleNamespace(store=AirStore(storage), tz=TZ) if air else None return History(station, sensor, sent if eco else None, now=lambda: NOW) diff --git a/tests/test_service_current.py b/tests/test_service_current.py index 8891d502..d395ae54 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -138,7 +138,7 @@ async def test_every_reading_now_with_its_value_unit_words_and_emoji(tmp_path, a assert s["pressure"]["absolute"]["text"] == "1009.5 hPa" assert "rainfall_piezo" not in s # every reading the sensors have now: this station has no piezo gauge pm = s["air"]["pm2_5"] - assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and pm["aqi_us"] == 56 and pm["band"] == "moderate" + assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and 51 <= pm["aqi_us"] <= 100 and pm["band"] == "moderate" assert pm["rating"].endswith(("good", "poor")) assert s["air"]["co2"]["text"] == "450 ppm" and s["air"]["nox_index"]["text"] == "1.0" and s["air"]["voc_index"]["text"] == "100" assert s["air"]["temperature"]["unit"] == "°C" and "rating" not in s["air"]["temperature"] # the sensor's own: no rating @@ -154,7 +154,7 @@ async def test_named_readings_alone_each_once_in_the_order_named(tmp_path, archi assert [(g, list(r)) for g, r in got["sensors"].items()] == [("rainfall", ["rain"]), ("outdoor", ["temperature"]), ("indoor", ["temperature"]), ("wind", ["wind_gust"]), ("air", ["pm2_5"])] assert set(got["lines"]) == {STATION, AIR_DEVICE} and got["lines"][AIR_DEVICE] == ["• PM2.5: " + got["sensors"]["air"]["pm2_5"]["text"] - + f" {got['sensors']['air']['pm2_5']['rating']} (AQI 56)"] + + f" {got['sensors']['air']['pm2_5']['rating']} (AQI {got['sensors']['air']['pm2_5']['aqi_us']})"] assert (await call(tool, readings="indoor temperature, outdoor humidity"))["sensors"] == { "indoor": {"temperature": {"value": 18.3, "unit": "°C", "text": "18.3 °C", "emoji": "🧥"}}, "outdoor": {"humidity": {"value": 94, "unit": "%", "text": "94 %", "emoji": "💦"}}} # (a string of names will do) diff --git a/tests/test_service_days.py b/tests/test_service_days.py index cdee7a2d..c57aec37 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -357,7 +357,7 @@ async def test_a_figure_per_month_is_drawn_and_its_drawn_by_redraws_it_over_each chart = chart_of(out) assert out["chart_note"] == CHART_NOTE and "chart" not in out and out["by_month"] assert chart["title"] == "Total rain" and chart["source"] == "Ecowitt weather station" - assert schema_errors({k: v for k, v in chart.items() if k != "drawn_by"}) == [] + assert schema_errors(chart) == [] drawn = chart["drawn_by"] assert drawn == {"tool": "days", "arguments": {"where": [], "sort_by": "rain", "order": "desc", "count_only": False, "group_by": "month", "stat": "sum", "of": "rain", "limit": 5, "period": "last 6 months", "chart_answers_it": True}, diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py index 4fdd1a25..1528f17a 100644 --- a/tests/test_service_relate.py +++ b/tests/test_service_relate.py @@ -59,10 +59,6 @@ def days_of(out: dict) -> tuple[date, date]: return start, end - timedelta(days=1) -def without_drawn_by(chart: dict) -> dict: - return {k: v for k, v in chart.items() if k != "drawn_by"} - - async def replays(ctx, chart: dict, **swap) -> dict: """The call a chart says drew it, made again (with `swap` in its arguments).""" drawn = chart["drawn_by"] @@ -177,7 +173,7 @@ async def test_a_chart_when_asked_carries_the_call_that_draws_it_again(tmp_path, out = await ask(ctx, reading="pressure", chart=True) (chart,) = out["charts"] assert out["chart_note"] == CHART_NOTE and chart["title"] == "Pressure, Rain" and chart["source"] == "Ecowitt weather station" - assert errors(without_drawn_by(chart)) == [] + assert errors(chart) == [] assert chart["drawn_by"] == {"tool": "relate", "arguments": {"reading": "pressure.relative", "period": "last 90 days", "chart": True}, "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} assert await replays(ctx, chart) == out # the same call again: the same answer @@ -207,7 +203,7 @@ async def test_the_air_against_rain_is_drawn_with_its_zones_and_drawn_again_over out = await ask(ctx, reading="pm2.5", chart=True) (chart,) = out["charts"] assert chart["title"] == "PM2.5, Rain" and chart["source"] == "Ecowitt weather station and AirGradient sensor" - assert chart["panels"][0]["zones"] == [9.0, 55.4] and errors(without_drawn_by(chart)) == [] + assert chart["panels"][0]["zones"] == [9.0, 55.4] and errors(chart) == [] assert chart["drawn_by"]["arguments"] == {"reading": "air.pm2_5", "period": "last 60 days", "chart": True} assert await replays(ctx, chart) == out for each in chart["drawn_by"]["periods"]: diff --git a/tests/test_service_scan.py b/tests/test_service_scan.py index c6be4e91..b9e22691 100644 --- a/tests/test_service_scan.py +++ b/tests/test_service_scan.py @@ -12,7 +12,7 @@ from lib.tools import Turn from tests.fakes import TZ, archived_station, pressure from tests.test_chart_json import errors -from tests.test_service_relate import HeldStubAir, days_of, without_drawn_by +from tests.test_service_relate import HeldStubAir, days_of class PressureAir(HeldStubAir): @@ -140,7 +140,7 @@ async def test_a_chart_of_the_strongest_pair_carries_the_call_that_draws_it_agai ctx, eco = await world(tmp_path, archived_cache) out = await ask(ctx, chart=True) (chart,) = out["charts"] - assert out["chart_note"] == CHART_NOTE and chart["title"] == "PM2.5, Pressure" and errors(without_drawn_by(chart)) == [] + assert out["chart_note"] == CHART_NOTE and chart["title"] == "PM2.5, Pressure" and errors(chart) == [] assert chart["source"] == "Ecowitt weather station and AirGradient sensor" assert chart["drawn_by"] == {"tool": "scan", "arguments": {"reading": "all", "period": "last 90 days", "chart": True}, "periods": [{"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}]} diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index aec73733..9b51038d 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -221,7 +221,7 @@ async def replays(tool: ServiceTool, out: dict) -> dict: (chart,) = out["charts"] by = chart["drawn_by"] assert by["tool"] == "summary" and set(by) == {"tool", "arguments", "periods"} - assert schema_errors(without_drawn_by(chart)) == [] # the chart is schemas/chart.json's, with drawn_by beside it + assert schema_errors(chart) == [] # drawn_by and all again = await ask(tool, **by["arguments"]) assert [without_drawn_by(c) for c in again["charts"]] == [without_drawn_by(chart)] and again["charts"][0]["drawn_by"] == by for period in by["periods"]: From 65af2ebe016081da7953ae7b30c1fbd87df1dc55 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 05:20:11 +0000 Subject: [PATCH 033/125] Pin the bot's own answers before they move to the service's tools tests/test_service_switch.py: every answer the bot gives without the model (the keyboard's charts, the shortcuts and plain lookups, the report, the dashboard, a period button's redraw, an alert's chart), recorded on the archived fake station at a fixed time: the messages sent, the text kept in the history, each chart's JSON and the gauges' sheet (tests/service_switch.json). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- tests/service_switch.json | 3738 ++++++++++++++++++++++++++++++++++ tests/test_service_switch.py | 325 +++ 2 files changed, 4063 insertions(+) create mode 100644 tests/service_switch.json create mode 100644 tests/test_service_switch.py diff --git a/tests/service_switch.json b/tests/service_switch.json new file mode 100644 index 00000000..ad78ad2a --- /dev/null +++ b/tests/service_switch.json @@ -0,0 +1,3738 @@ +{ + "Air quality all metrics 1d": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + }, + { + "label": "CO₂", + "series": [ + [ + "CO₂", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 450.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 450.0 + ] + ] + ] + ], + "unit": "ppm" + }, + { + "label": "VOC index", + "series": [ + [ + "VOC index", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 100.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 100.0 + ] + ] + ] + ], + "unit": "" + }, + { + "label": "NOx index", + "series": [ + [ + "NOx index", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 1.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1.0 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "eb74a3c6b7c7f982", + "source": "AirGradient sensor", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Mon 9 Nov 10:00pm) · 🟡 poor · average 10.6\n• PM10: peak 8.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 8.0\n• PM1: peak 3.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 3.0\n• CO₂: peak 450.0 ppm (Mon 9 Nov 3:00pm) · 🟢 good · average 450.0\n• VOC index: peak 100.0 relative index (100 = this sensor's recent average) (Mon 9 Nov 3:00pm) · 🟢 good · average 100.0\n• NOx index: peak 1.0 relative index (1 = baseline) (Mon 9 Nov 3:00pm) · 🟢 good · average 1.0", + "sent": [ + [ + "photo", + "Air quality\nMon 9 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Humidity chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Humidity", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 55.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 55.0 + ] + ] + ] + ], + "unit": "%" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "0c4b899e234ed02a", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Humidity" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am", + "sent": [ + [ + "photo", + "Humidity, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Particulates chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "218963e99fe3d441", + "source": "AirGradient sensor", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Mon 9 Nov 10:00pm) · 🟡 poor · average 10.6\n• PM10: peak 8.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 8.0\n• PM1: peak 3.0 µg/m³ (Mon 9 Nov 3:00pm) · 🟢 good · average 3.0", + "sent": [ + [ + "photo", + "Air quality, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Rain chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 25, + [ + [ + "2026-11-09T14:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "84f5e24e4493ff27", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour", + "title": "Rain" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all", + "sent": [ + [ + "photo", + "Rain, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Report": { + "charts": [], + "gauges": [ + "aa7350dd52231dc7" + ], + "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "sent": [ + [ + "photo", + "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + [ + [ + [ + "🔄", + "rp:refresh" + ] + ] + ] + ] + ] + }, + "Temperature chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "d935397aaf78f0d5", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Weather chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Humidity", + "series": [ + [ + "Humidity", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 55.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 55.0 + ] + ] + ], + [ + "Rain", + "bars", + 25, + [ + [ + "2026-11-09T14:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "%" + }, + { + "label": "Solar radiation", + "series": [ + [ + "Solar radiation", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 848.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 848.0 + ] + ] + ] + ], + "unit": "W/m²" + }, + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 1012.1 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 1007.8 + ] + ] + ] + ], + "unit": "hPa" + }, + { + "label": "Dew point", + "series": [ + [ + "Dew point", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "a5e62602517de50d", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour · range shaded", + "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am\nSolar radiation: low 0.0 °C, Mon 9 Nov at 7pm · high 880.0 °C, Tue 10 Nov at 12:40pm\nPressure: low 1007.0 °C, Tue 10 Nov at 7:45am · high 1012.1 °C, Mon 9 Nov at 2:05pm\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all\nDew point: low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 9 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "Wind chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "0fd7a0b036ac1b81", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings, shaded up to the gusts", + "title": "Wind" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Wind, since Mon 9 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "air quality chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "PM2.5", + "series": [ + [ + "PM2.5", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 6.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "8f50228347701651", + "source": "AirGradient sensor", + "subtitle": "Wed 4 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "PM2.5" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Wed 4 Nov 10:00am) · 🟡 poor · average 10.4", + "sent": [ + [ + "photo", + "PM2.5, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "air quality now": { + "charts": [], + "gauges": [], + "history": "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", + "sent": [ + [ + "text", + "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", + null + ] + ] + }, + "alert gusts": { + "charts": [ + { + "panels": [ + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "785a7105037691ba", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings, shaded up to the gusts", + "title": "Wind" + } + ], + "newest": 1794279900, + "title": "Wind, since Mon 9 Nov 2026" + }, + "alert particulates": { + "charts": [ + { + "panels": [ + { + "label": "PM1, PM2.5, PM10", + "series": [ + [ + "PM1", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], + [ + "PM2.5", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 9.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ], + [ + "PM10", + "line", + 24, + [ + [ + "2026-11-09T15:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "ea4787312db7f13c", + "source": "", + "subtitle": "Mon 9 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "Air quality" + } + ], + "newest": 1794279600, + "title": "Air quality, since Mon 9 Nov 2026" + }, + "alert temps": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "42aab5676fd09bf3", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "Temperature" + } + ], + "newest": 1794279900, + "title": "Temperature, since Mon 9 Nov 2026" + }, + "alert uv": { + "charts": [ + { + "panels": [ + { + "label": "UV index", + "series": [ + [ + "UV index", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.6 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.6 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "548b7ec71a831b23", + "source": "", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · 5-minute readings · records marked", + "title": "UV index" + } + ], + "newest": 1794279900, + "title": "UV index, since Mon 9 Nov 2026" + }, + "average pressure yesterday": { + "charts": [], + "gauges": [], + "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Pressure: average 1012.1 °C (low 1009.1, high 1015.9)", + "sent": [ + [ + "text", + "Mon 9 Nov – Mon 9 Nov 2026\n• Pressure: average 1012.1 °C (low 1009.1, high 1015.9)", + null + ] + ] + }, + "average temperature 7d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 6, + [ + [ + "2026-11-04T12:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ], + [ + [ + "2026-11-09T12:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 6, + [ + [ + "2026-11-04T12:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ], + [ + [ + "2026-11-09T12:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "0762f22a458eb82c", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): average 14.1 °C (low 8.1, high 20.4)\nTemperature (indoor): average 14.1 °C (low 8.1, high 20.4)", + "sent": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "average temperature per month this year": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Temperature", + "bars", + 11, + [ + [ + "2026-01-01T00:00:00+11:00", + 14.3 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 14.3 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-01-01", + "2026-11-09" + ], + "sha": "ea97546802ab0054", + "source": "Ecowitt weather station", + "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 days counted · per month", + "title": "Average temperature" + } + ], + "gauges": [], + "history": "Average temperature: 14.3 °C over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + "sent": [ + [ + "photo", + "Average temperature, Thu 1 Jan – Mon 9 Nov 2026\n\nAverage temperature: 14.3 °C over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "chart weather": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ], + [ + "Outdoor", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Humidity", + "series": [ + [ + "Humidity", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 55.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 55.0 + ] + ] + ], + [ + "Rain", + "bars", + 25, + [ + [ + "2026-11-09T14:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "%" + }, + { + "label": "Solar radiation", + "series": [ + [ + "Solar radiation", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 848.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 848.0 + ] + ] + ] + ], + "unit": "W/m²" + }, + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 1012.1 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 1007.8 + ] + ] + ] + ], + "unit": "hPa" + }, + { + "label": "Dew point", + "series": [ + [ + "Dew point", + "line", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 19.95 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 20.0 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 289, + [ + [ + "2026-11-09T14:05:00+11:00", + 10.0, + 10.0, + 26.0 + ] + ], + [ + [ + "2026-11-10T14:05:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-09", + "2026-11-10" + ], + "sha": "a5e62602517de50d", + "source": "Ecowitt weather station", + "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour · range shaded", + "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + } + ], + "gauges": [], + "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am\nSolar radiation: low 0.0 °C, Mon 9 Nov at 7pm · high 880.0 °C, Tue 10 Nov at 12:40pm\nPressure: low 1007.0 °C, Tue 10 Nov at 7:45am · high 1012.1 °C, Mon 9 Nov at 2:05pm\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all\nDew point: low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 9 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "co2": { + "charts": [], + "gauges": [], + "history": "• CO₂: 450 ppm 🟢 good", + "sent": [ + [ + "text", + "• CO₂: 450 ppm 🟢 good", + null + ] + ] + }, + "dashboard": { + "charts": [], + "gauges": [ + "1bc0e0d78b0b8287" + ], + "history": "Weather station dashboard, Tue 10 Nov 2026 2:05pm", + "sent": [ + [ + "photo", + "Weather station dashboard, Tue 10 Nov 2026 2:05pm", + [ + [ + [ + "🔄", + "rp:dashboard" + ] + ] + ] + ] + ] + }, + "days with uv over 9 per month this year": { + "charts": [ + { + "panels": [ + { + "label": "Days", + "series": [ + [ + "Days", + "bars", + 11, + [ + [ + "2026-01-01T00:00:00+11:00", + 31.0 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 9.0 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-01-01", + "2026-11-09" + ], + "sha": "16cbdac19c3806a9", + "source": "Ecowitt weather station", + "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 of 313 days · per month", + "title": "Days with UV index ≥ 9" + } + ], + "gauges": [], + "history": "313 of 313 days with UV index ≥ 9 (Thu 1 Jan – Mon 9 Nov 2026). Older days use averages, so a count near the limit may fall slightly short.", + "sent": [ + [ + "photo", + "Days with UV index ≥ 9, Thu 1 Jan – Mon 9 Nov 2026\n\n313 of 313 days with UV index ≥ 9 (Thu 1 Jan – Mon 9 Nov 2026). Older days use averages, so a count near the limit may fall slightly short.", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "forecast": { + "charts": [], + "gauges": [], + "history": "Forecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm\n• Friday: ⛅ Partly cloudy. 14–19°C, 75% chance of at least 1 mm\n• Saturday: 🌦️ Showers. 15–20°C, 0% chance of at least 1 mm\n• Sunday: ☁️ Overcast. 16–21°C, 75% chance of at least 1 mm\n• Monday: 🌧️ Light rain. 17–22°C, 0% chance of at least 1 mm", + "sent": [ + [ + "text", + "Forecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm\n• Friday: ⛅ Partly cloudy. 14–19°C, 75% chance of at least 1 mm\n• Saturday: 🌦️ Showers. 15–20°C, 0% chance of at least 1 mm\n• Sunday: ☁️ Overcast. 16–21°C, 75% chance of at least 1 mm\n• Monday: 🌧️ Light rain. 17–22°C, 0% chance of at least 1 mm", + null + ] + ] + }, + "high and low today": { + "charts": [], + "gauges": [], + "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", + "sent": [ + [ + "text", + "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", + null + ] + ] + }, + "highest humidity this week": { + "charts": [ + { + "panels": [ + { + "label": "Humidity", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 80.0, + 80.0, + 82.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 55.0, + 55.0, + 55.0 + ] + ] + ] + ], + "unit": "%" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "790cb258a590921b", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Humidity" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", + "sent": [ + [ + "photo", + "Humidity, since Wed 4 Nov 2026\n\nWed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "highest temperature yesterday": { + "charts": [], + "gauges": [], + "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n• Temperature (indoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", + "sent": [ + [ + "text", + "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n• Temperature (indoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", + null + ] + ] + }, + "how hot is it": { + "charts": [], + "gauges": [], + "history": "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C\n• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + "sent": [ + [ + "text", + "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C\n• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + null + ] + ] + }, + "how many days was humidity under 60 last month": { + "charts": [], + "gauges": [], + "history": "31 of 31 days with lowest humidity < 60 % (Thu 1 Oct – Sat 31 Oct 2026).", + "sent": [ + [ + "text", + "31 of 31 days with lowest humidity < 60 % (Thu 1 Oct – Sat 31 Oct 2026).", + null + ] + ] + }, + "how many days was pm2.5 over 15 this week": { + "charts": [], + "gauges": [], + "history": "0 of 0 days with PM2.5 > 15 µg/m³ (Wed 4 Nov – Mon 9 Nov 2026).", + "sent": [ + [ + "text", + "0 of 0 days with PM2.5 > 15 µg/m³ (Wed 4 Nov – Mon 9 Nov 2026).", + null + ] + ] + }, + "how many days was the temperature over 18 this year": { + "charts": [], + "gauges": [], + "history": "313 of 313 days with temperature > 18 °C (Thu 1 Jan – Mon 9 Nov 2026).", + "sent": [ + [ + "text", + "313 of 313 days with temperature > 18 °C (Thu 1 Jan – Mon 9 Nov 2026).", + null + ] + ] + }, + "how's the air": { + "charts": [], + "gauges": [], + "history": "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", + "sent": [ + [ + "text", + "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", + null + ] + ] + }, + "humidity": { + "charts": [], + "gauges": [], + "history": "• Outdoor: 💦 94 %\n• Indoor: 63 %", + "sent": [ + [ + "text", + "• Outdoor: 💦 94 %\n• Indoor: 63 %", + null + ] + ] + }, + "humidity 7d": { + "charts": [ + { + "panels": [ + { + "label": "Humidity", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 80.0, + 80.0, + 82.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 55.0, + 55.0, + 55.0 + ] + ] + ] + ], + "unit": "%" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "790cb258a590921b", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Humidity" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", + "sent": [ + [ + "photo", + "Humidity, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "indoor temperature": { + "charts": [], + "gauges": [], + "history": "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + "sent": [ + [ + "text", + "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", + null + ] + ] + }, + "indoor temperature chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "7fc9b62280a4051f", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature: low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "is it raining": { + "charts": [], + "gauges": [], + "history": "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)", + "sent": [ + [ + "text", + "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)", + null + ] + ] + }, + "lowest humidity yesterday": { + "charts": [], + "gauges": [], + "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am", + "sent": [ + [ + "text", + "Mon 9 Nov – Mon 9 Nov 2026\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am", + null + ] + ] + }, + "lowest temperature on record": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 1458, + [ + [ + "2022-11-13T11:00:00+11:00", + 17.4, + 8.5, + 20.4 + ] + ], + [ + [ + "2026-11-09T10:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 1458, + [ + [ + "2022-11-13T11:00:00+11:00", + 17.4, + 8.5, + 20.4 + ] + ], + [ + [ + "2026-11-09T10:00:00+11:00", + 14.103125, + 8.1, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2022-11-13", + "2026-11-10" + ], + "sha": "8757c1081d06b47b", + "source": "Ecowitt weather station", + "subtitle": "Sun 13 Nov 2022 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Sun 13 Nov 2022 – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov\nTemperature (indoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov", + "sent": [ + [ + "photo", + "Temperature, since Sun 13 Nov 2022\n\nSun 13 Nov 2022 – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov\nTemperature (indoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "plot uv and solar on two axes 7d": { + "charts": [ + { + "panels": [ + { + "label": "UV index and Solar radiation", + "series": [ + [ + "UV index", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0, + 0.0, + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 10.7, + 10.4, + 10.7 + ] + ] + ], + [ + "Solar radiation (W/m²)", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0, + 0.0, + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 856.0, + 832.0, + 856.0 + ] + ] + ] + ], + "unit": "" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "399d97ba4eef630b", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · range shaded", + "title": "UV index and Solar radiation" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nUV index: low 0 °C, Wed 4 Nov at 12am · high 11 °C, Wed 4 Nov at 12:40pm\nSolar radiation: low 0.0 °C, Wed 4 Nov at 12am · high 880.0 °C, Wed 4 Nov at 12:40pm", + "sent": [ + [ + "photo", + "UV index and Solar radiation, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "pm2.5 chart 3d": { + "charts": [ + { + "panels": [ + { + "label": "PM2.5", + "series": [ + [ + "PM2.5", + "line", + 63, + [ + [ + "2026-11-08T00:00:00+11:00", + 6.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] + ] + ], + "unit": "µg/m³" + } + ], + "period": [ + "2026-11-08", + "2026-11-10" + ], + "sha": "30a44e700edbe879", + "source": "AirGradient sensor", + "subtitle": "Sun 8 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "PM2.5" + } + ], + "gauges": [], + "history": "Sun 8 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Sun 8 Nov 10:00am) · 🟡 poor · average 10.3", + "sent": [ + [ + "photo", + "PM2.5, since Sun 8 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "pollen": { + "charts": [], + "gauges": [], + "history": "Pollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low", + "sent": [ + [ + "text", + "Pollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low", + null + ] + ] + }, + "press 30 under Rain chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 119, + [ + [ + "2026-10-12T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-10-12", + "2026-11-10" + ], + "sha": "faca6ea0ee20ddf7", + "source": "Ecowitt weather station", + "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours", + "title": "Rain" + } + ], + "edits": [ + [ + "photo", + "Rain, since Mon 12 Oct 2026" + ] + ] + }, + "press 365 under rain by month this year": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 13, + [ + [ + "2025-11-01T00:00:00+11:00", + 11.5 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 5.5 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2025-11-11", + "2026-11-09" + ], + "sha": "5712fdfd9c1551e6", + "source": "Ecowitt weather station", + "subtitle": "Tue 11 Nov 2025 – Mon 9 Nov 2026 · 364 days counted · per month", + "title": "Total rain" + } + ], + "edits": [ + [ + "photo", + "Total rain, Tue 11 Nov 2025 – Mon 9 Nov 2026\n\nTotal rain: 248 mm over 364 days (Tue 11 Nov 2025 – Mon 9 Nov 2026)." + ] + ] + }, + "press 7 under Temperature chart 1d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "4b8bc87c49be3cd2", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "edits": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026" + ] + ] + }, + "pressure": { + "charts": [], + "gauges": [], + "history": "• Pressure: 🗜️ 1025.0 hPa", + "sent": [ + [ + "text", + "• Pressure: 🗜️ 1025.0 hPa", + null + ] + ] + }, + "pressure chart this month": { + "charts": [ + { + "panels": [ + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "band", + 461, + [ + [ + "2026-11-01T00:00:00+11:00", + 1022.3, + 1022.3, + 1022.4 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1007.9, + 1007.8, + 1007.9 + ] + ] + ] + ], + "unit": "hPa" + } + ], + "period": [ + "2026-11-01", + "2026-11-10" + ], + "sha": "6e7a1c488d0f5081", + "source": "Ecowitt weather station", + "subtitle": "Sun 1 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Pressure" + } + ], + "gauges": [], + "history": "Sun 1 Nov – Tue 10 Nov 2026\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.5 °C, Sat 7 Nov at 1:45am", + "sent": [ + [ + "photo", + "Pressure, since Sun 1 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "rain by month this year": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 11, + [ + [ + "2026-01-01T00:00:00+11:00", + 17.0 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 5.5 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-01-01", + "2026-11-09" + ], + "sha": "78e9e3e016d11dc1", + "source": "Ecowitt weather station", + "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 days counted · per month", + "title": "Total rain" + } + ], + "gauges": [], + "history": "Total rain: 214.5 mm over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + "sent": [ + [ + "photo", + "Total rain, Thu 1 Jan – Mon 9 Nov 2026\n\nTotal rain: 214.5 mm over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "rain chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "Rain", + "series": [ + [ + "Rain", + "bars", + 27, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "mm" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "f692fad2845dea7b", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours", + "title": "Rain" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", + "sent": [ + [ + "photo", + "Rain, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "status": { + "charts": [], + "gauges": [ + "aa7350dd52231dc7" + ], + "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "sent": [ + [ + "photo", + "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + [ + [ + [ + "🔄", + "rp:refresh" + ] + ] + ] + ] + ] + }, + "strongest gust today": { + "charts": [], + "gauges": [], + "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Wind: low 0.0 °C, Tue 10 Nov at 12am · high 10.0 °C, Tue 10 Nov at 6am\n• Wind gust: low 29.0 °C, Tue 10 Nov at 12am · high 29.0 °C, Tue 10 Nov at 12am", + "sent": [ + [ + "text", + "Tue 10 Nov – Tue 10 Nov 2026\n• Wind: low 0.0 °C, Tue 10 Nov at 12am · high 10.0 °C, Tue 10 Nov at 6am\n• Wind gust: low 29.0 °C, Tue 10 Nov at 12am · high 29.0 °C, Tue 10 Nov at 12am", + null + ] + ] + }, + "temperature and rain chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Rain", + "bars", + 27, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "c71494e2da2cb207", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours · range shaded", + "title": "Temperature, Rain" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", + "sent": [ + [ + "photo", + "Temperature, Rain, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "temperature chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "4b8bc87c49be3cd2", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "temperature chart last month": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 372, + [ + [ + "2026-10-01T01:00:00+10:00", + 9.225, + 8.4, + 9.9 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 10.899999999999999, + 10.1, + 11.2 + ] + ] + ], + [ + "Indoor", + "band", + 372, + [ + [ + "2026-10-01T01:00:00+10:00", + 9.225, + 8.4, + 9.9 + ] + ], + [ + [ + "2026-11-01T00:00:00+11:00", + 10.899999999999999, + 10.1, + 11.2 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-10-01", + "2026-10-31" + ], + "sha": "bb098dff493e9c96", + "source": "Ecowitt weather station", + "subtitle": "Thu 1 – Sat 31 Oct 2026 · 2-hour averages, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Thu 1 Oct – Sat 31 Oct 2026\nTemperature (outdoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, Thu 1 – Sat 31 Oct 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "temps this week": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "4b8bc87c49be3cd2", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "temps today": { + "charts": [], + "gauges": [], + "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", + "sent": [ + [ + "text", + "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", + null + ] + ] + }, + "uv": { + "charts": [], + "gauges": [], + "history": "• UV index: 😎 6", + "sent": [ + [ + "text", + "• UV index: 😎 6", + null + ] + ] + }, + "weather 30d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 19.733333333333334, + 19.4, + 20.1 + ] + ] + ], + [ + "Outdoor", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 19.733333333333334, + 19.4, + 20.1 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Humidity", + "series": [ + [ + "Humidity", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 80.5, + 80.0, + 82.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 55.666666666666664, + 55.0, + 56.0 + ] + ] + ], + [ + "Rain", + "bars", + 119, + [ + [ + "2026-10-12T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "%" + }, + { + "label": "Solar radiation", + "series": [ + [ + "Solar radiation", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 0.0, + 0.0, + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 869.3333333333334, + 832.0, + 880.0 + ] + ] + ] + ], + "unit": "W/m²" + }, + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 1018.4, + 1018.3, + 1018.4 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1007.8666666666667, + 1007.8, + 1007.9 + ] + ] + ] + ], + "unit": "hPa" + }, + { + "label": "Dew point", + "series": [ + [ + "Dew point", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 19.733333333333334, + 19.4, + 20.1 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 356, + [ + [ + "2026-10-12T00:00:00+11:00", + 0.0, + 0.0, + 35.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-10-12", + "2026-11-10" + ], + "sha": "b93089b10c508d01", + "source": "Ecowitt weather station", + "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours · range shaded", + "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + } + ], + "gauges": [], + "history": "Mon 12 Oct – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nHumidity: low 54 %, Mon 12 Oct at 2:20pm · high 85 %, Thu 15 Oct at 2:15am\nSolar radiation: low 0.0 °C, Mon 12 Oct at 12am · high 880.0 °C, Mon 12 Oct at 12:40pm\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.7 °C, Sat 17 Oct at 1:25pm\n☔ Rain per 6 hours: least 0 mm (Mon 12 Oct 12am) · most 5 mm (Thu 15 Oct 12pm) · 21.5 mm in all\nDew point: low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\n🌬️ Wind: strongest gust 48.0 °C, Tue 13 Oct at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 12 Oct – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "weather all week": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ + [ + "Indoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ], + [ + "Outdoor", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Humidity", + "series": [ + [ + "Humidity", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 80.0, + 80.0, + 82.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 55.0, + 55.0, + 55.0 + ] + ] + ], + [ + "Rain", + "bars", + 27, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] + ] + ], + "unit": "%" + }, + { + "label": "Solar radiation", + "series": [ + [ + "Solar radiation", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0, + 0.0, + 0.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 856.0, + 832.0, + 856.0 + ] + ] + ] + ], + "unit": "W/m²" + }, + { + "label": "Pressure", + "series": [ + [ + "Pressure", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 1007.4, + 1007.4, + 1007.5 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1007.9, + 1007.8, + 1007.9 + ] + ] + ] + ], + "unit": "hPa" + }, + { + "label": "Dew point", + "series": [ + [ + "Dew point", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, + 20.1 + ] + ] + ] + ], + "unit": "°C" + }, + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 317, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0, + 0.0, + 32.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 10.0, + 10.0, + 29.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "89defd08995bd00d", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours · range shaded", + "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am\nSolar radiation: low 0.0 °C, Wed 4 Nov at 12am · high 880.0 °C, Wed 4 Nov at 12:40pm\nPressure: low 1006.9 °C, Wed 4 Nov at 6:50am · high 1023.5 °C, Sat 7 Nov at 1:45am\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all\nDew point: low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\n🌬️ Wind: strongest gust 48.0 °C, Fri 6 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nWed 4 – Tue 10 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "weather now": { + "charts": [], + "gauges": [], + "history": "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + "sent": [ + [ + "text", + "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + null + ] + ] + }, + "what can you do": { + "charts": [], + "gauges": [], + "history": "• Temperature, humidity (indoor, outdoor)\n• Dew point, vapour pressure deficit, pressure, wind speed\n• Rain, solar radiation, UV index\n• PM1, PM2.5, PM10, CO₂, VOC, NOx\n• Pollen and thunderstorm asthma risk (October to December)\n• Forecast\n• History charts", + "sent": [ + [ + "text", + "• Temperature, humidity (indoor, outdoor)\n• Dew point, vapour pressure deficit, pressure, wind speed\n• Rain, solar radiation, UV index\n• PM1, PM2.5, PM10, CO₂, VOC, NOx\n• Pollen and thunderstorm asthma risk (October to December)\n• Forecast\n• History charts", + null + ] + ] + }, + "wind": { + "charts": [], + "gauges": [], + "history": "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + "sent": [ + [ + "text", + "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + null + ] + ] + }, + "wind direction plot 3m": { + "charts": [ + { + "panels": [ + { + "label": "Wind", + "series": [ + [ + "Wind", + "band", + 90, + [ + [ + "2026-08-12T12:00:00+10:00", + 11.25, + 0.0, + 45.0 + ] + ], + [ + [ + "2026-11-09T12:00:00+11:00", + 11.25, + 0.0, + 36.0 + ] + ] + ] + ], + "unit": "km/h" + } + ], + "period": [ + "2026-08-12", + "2026-11-10" + ], + "sha": "ef71e4a1cb0f9892", + "source": "Ecowitt weather station", + "subtitle": "Wed 12 Aug – Tue 10 Nov 2026 · daily averages, shaded up to the gusts", + "title": "Wind" + } + ], + "gauges": [], + "history": "Wed 12 Aug – Tue 10 Nov 2026\n🌬️ Wind: strongest gust 48.0 °C, Thu 13 Aug around 3pm\n🧭 Mostly from the N (100%), steady", + "sent": [ + [ + "photo", + "Wind, since Wed 12 Aug 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + } +} diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py new file mode 100644 index 00000000..6d048f14 --- /dev/null +++ b/tests/test_service_switch.py @@ -0,0 +1,325 @@ +"""The bot's own answers (everything it answers without the model) pinned word for word, chart for chart, on the archived fake station +at a fixed time (Tue 10 Nov 2026 2:05pm, Melbourne), so moving them onto the service's tools (docs/mcp-service.md 6, step 2) changes +nothing the person sees but what is meant to change. + +What is pinned, for each question the bot answers in code (its keyboard's charts, the shortcuts and plain lookups intent.read answers, +the report, the dashboard, an alert's chart, a period button's redraw): every message sent (its text or caption, and its buttons), the +text the answer leaves in the chat's history, and each chart as JSON (specs.to_json, less `drawn_by`, which only the service's charts +carry) and the gauges' sheet. They are recorded in tests/service_switch.json: `ECOBOT_RECORD_SWITCH=1 pytest tests/test_service_switch.py` +writes it afresh (only ever on purpose). + +The clock: every `datetime.now()`, `date.today()` and `time.time()` in lib/ and tests/ reads the fixed time, and the station's archive is +built under it (once per module), so every figure, time and point is the same on every run.""" + +import asyncio +import hashlib +import json +import os +import shutil +import sys +import time as _time +from datetime import date as _date, datetime as _datetime +from pathlib import Path +from types import SimpleNamespace as NS +from unittest import mock +from zoneinfo import ZoneInfo + +import pytest + +GOLDEN = Path(__file__).with_name("service_switch.json") +RECORD = os.environ.get("ECOBOT_RECORD_SWITCH") == "1" +FROZEN = _datetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")).timestamp() + + +# ---------- the clock, fixed ---------- +class _DatetimeType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _datetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _datetime) + + +class FrozenDatetime(_datetime, metaclass=_DatetimeType): + """datetime whose now() and today() are the fixed time (anything else, and its instances, are the real datetime's).""" + + @classmethod + def now(cls, tz=None): + return _datetime.fromtimestamp(FROZEN, tz) + + @classmethod + def today(cls): + return _datetime.fromtimestamp(FROZEN) + + +class _DateType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _date) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _date) + + +class FrozenDate(_date, metaclass=_DateType): + @classmethod + def today(cls): + return _datetime.fromtimestamp(FROZEN).date() + + +def freeze(patch): + """Fix the clock in every module of lib/ and tests/ (and ecobot.py) loaded so far, with `patch` (a MonkeyPatch).""" + import lib.alerts.pictures, lib.bot, lib.compose, lib.ecowitt.archive, lib.forecast, lib.history, lib.pollen, lib.service.about # noqa: F401 + import lib.service.current, lib.service.days, lib.service.forecast, lib.service.pollen, lib.service.summary # noqa: F401 + import tests.fakes, tests.test_service_forecast, tests.test_pollen # noqa: F401 + patch.setattr(_time, "time", lambda: FROZEN) + for name, module in list(sys.modules.items()): + if module is None or not (name == "lib" or name.startswith(("lib.", "tests.")) or name == "ecobot"): + continue + for attr, value in list(vars(module).items()): + if value is _datetime: + patch.setattr(module, attr, FrozenDatetime) + elif value is _date: + patch.setattr(module, attr, FrozenDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: FROZEN) + + +async def _inline(func, /, *args, **kwargs): + return func(*args, **kwargs) + + +@pytest.fixture(scope="module") +def frozen_archive(tmp_path_factory): + """The fake station's whole archive, built at the fixed time (about 8 s, once for the module).""" + from lib.ecowitt import Archive, Ecowitt, api, archive + from tests.fakes import config, ecowitt_transport + + async def build(path): + transport, _ = ecowitt_transport() + eco = Ecowitt(config(path), transport=transport) + await eco.start() + await Archive(eco).run_once() + await eco.close() + return config(path).storage_path + path = tmp_path_factory.mktemp("frozen") + with pytest.MonkeyPatch.context() as patch: + freeze(patch) + with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ + mock.patch.object(asyncio, "to_thread", _inline): + return asyncio.run(build(path)) + + +# ---------- the bot over every source ---------- +def summary_of(chart: dict) -> dict: + """What a chart's JSON is pinned as: its hash (less drawn_by), and enough of it to see where two differ.""" + chart = {k: v for k, v in chart.items() if k != "drawn_by"} + panels = [{"label": p["label"], "unit": p["unit"], + "series": [[s["name"], s["kind"], len(s["points"]), s["points"][:1], s["points"][-1:]] for s in p["series"]]} + for p in chart["panels"]] + digest = hashlib.sha256(json.dumps(chart, sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:16] + return {"title": chart["title"], "subtitle": chart["subtitle"], "period": chart["period"], "source": chart["source"], + "panels": panels, "sha": digest} + + +def buttons(markup) -> list | None: + rows = getattr(markup, "inline_keyboard", None) + return [[[b.text, b.callback_data] for b in row] for row in rows] if rows else None + + +class World: + """The archived station (its live reading the wet night of tests/test_service_current), the fake AirGradient on the same file, the + forecast and the pollen, all at the fixed time; and what the bot drew and sent.""" + + def __init__(self): + self.charts: list[dict] = [] + self.sheets: list[str] = [] + self.sent: list[list] = [] + self.edits: list[list] = [] + self.toasts: list = [] + + async def open(self, tmp_path, archive): + from lib.airgradient import AirGradient + from lib.compose import Composer + from lib.ecowitt import Ecowitt + from lib.forecast import Forecast + from lib.history import History + from lib.tools import Tools + from tests.fakes import TZ, config, ecowitt_transport + from tests.test_pollen import make as make_pollen, page + from tests.test_service_current import Station, live + from tests.test_service_forecast import open_meteo + cfg = config(tmp_path) + shutil.copy(archive, cfg.storage_path) + transport, _ = ecowitt_transport() + eco = Ecowitt(cfg, transport=transport) + await eco.start() + Station(eco, live(FROZEN, **{"solar_and_uvi.solar": "412.5", "solar_and_uvi.uvi": "6", "wind.wind_speed": "14.0", + "wind.wind_gust": "31.0"})) + air_transport_, _ = __import__("tests.fakes", fromlist=["air_transport"]).air_transport() + air = AirGradient(cfg, transport=air_transport_, storage=eco.storage, owned=False) + await air.start() + forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, + open_meteo([], 7)) + await forecast.warm(True) + pollen, _ = make_pollen(tmp_path, lambda: page(grass="Moderate", asthma="Low")) + pollen.now = lambda: _datetime.fromtimestamp(FROZEN, TZ).replace(tzinfo=None) + await pollen.warm(True) + self.sources = [eco, air, pollen, forecast] + self.eco, self.air, self.pollen, self.forecast = eco, air, pollen, forecast + self.composer = Composer(eco, air) + history = await History.open(eco, air) + self.tools = Tools([t for s in self.sources for t in s.tools] + self.composer.tools + history.tools) + self.tz, self.cfg = TZ, cfg + return self + + async def close(self): + for source in (self.air, self.eco, self.forecast, self.pollen): + close = getattr(source, "close", None) + if close: + await close() + + def bot(self, alert_state, monkeypatch): + from lib import bot as botmod + from lib.llm import Agent + + def render(data, tz, times=None, dark=None): + self.charts.append(summary_of(data)) + return b"png" + + def gauges(sheet): + self.sheets.append(hashlib.sha256(repr(sheet).encode()).hexdigest()[:16]) + return b"gauges" + monkeypatch.setattr(botmod, "render_data", render) + monkeypatch.setattr(botmod.gauges, "render", gauges) + return botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), self.sources, alert_state) + + def message(self, message_id=50): + world = self + + async def reply_text(body, **kw): + world.sent.append(["text", body, buttons(kw.get("reply_markup"))]) + return NS(message_id=100 + len(world.sent)) + + async def reply_photo(photo, caption=None, **kw): + world.sent.append(["photo", caption, buttons(kw.get("reply_markup"))]) + return NS(message_id=100 + len(world.sent), photo=[NS(file_id=f"file{len(world.sent)}")]) + + async def reply_media_group(media, **kw): + world.sent.append(["photos", [m.caption for m in media], None]) + + async def edit_media(media, reply_markup=None): + world.edits.append(["photo", media.caption, buttons(reply_markup)]) + return NS(photo=[NS(file_id="edited")]) + return NS(chat_id=-5, message_id=message_id, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + reply_photo=reply_photo, reply_media_group=reply_media_group, edit_media=edit_media, + chat=NS(type="supergroup", title="Weather", id=-5), from_user=NS(full_name="Rob"), reply_to_message=None, photo=None) + + +async def nothing(*a, **k): + pass + + +CONTEXT = NS(bot=NS(send_chat_action=nothing, send_message_draft=nothing, id=99, username="ecobot")) + + +@pytest.fixture +async def world(tmp_path, frozen_archive, monkeypatch): + freeze(monkeypatch) + w = await World().open(tmp_path, frozen_archive) + yield w + await w.close() + + +# ---------- what is pinned ---------- +def golden() -> dict: + return json.loads(GOLDEN.read_text()) if GOLDEN.exists() else {} + + +def pinned(name: str, got: dict): + """Compare what the bot did with the recording (or record it).""" + if RECORD: + data = golden() + data[name] = got + GOLDEN.write_text(json.dumps(data, indent=1, ensure_ascii=False, sort_keys=True) + "\n") + return + want = golden().get(name) + assert want is not None, f"{name} isn't recorded: run with ECOBOT_RECORD_SWITCH=1" + assert json.loads(json.dumps(got, ensure_ascii=False)) == want + + +async def asked(world, alert_state, monkeypatch, text) -> dict: + """Ask the bot `text`, as a group's message to it, and return what it did.""" + bot = world.bot(alert_state, monkeypatch) + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await bot.respond(update, CONTEXT, text) + history = bot.chats[(msg.chat_id, None)].history + said = history[-1]["content"] if history and history[-1]["role"] == "assistant" else None + return {"sent": world.sent, "charts": world.charts, "gauges": world.sheets, "history": said} + + +# Every question the bot answers in code: the keyboard's charts (templates.chart_sentences, the same with irrigation: only Wind goes), +# then each of intent's shortcuts and plain lookups (bot._answer: a chart made in code, the dashboard, a lookup, the report and +# "weather now") +from lib import templates # noqa: E402 + +KEYBOARD = templates.chart_sentences(False) +SHORTCUTS = [ + # the report and "weather now" (written in code from weather_now, air_quality, pollen_asthma, weather_forecast) + "Report", "weather now", "status", + # a reading now (lookup "reading") + "how hot is it", "is it raining", "humidity", "wind", "indoor temperature", "uv", "pressure", + # the air now (fast path air_quality {}, lookup "air") + "air quality now", "co2", "how's the air", + # pollen, forecast, what the bot can do, the gauges + "pollen", "forecast", "what can you do", "dashboard", + # a days count and a figure per month or year (weather_days, lookup "days"; the per-month ones draw bars) + "how many days was the temperature over 18 this year", "how many days was humidity under 60 last month", + "how many days was pm2.5 over 15 this week", "days with uv over 9 per month this year", + "rain by month this year", "average temperature per month this year", + # extremes of a short period (weather_history without a chart, lookup "extremes") + "highest temperature yesterday", "high and low today", "lowest humidity yesterday", "average pressure yesterday", + "strongest gust today", "temps today", + # a chart made in code (weather_history or air_quality with a chart, captioned in code) + "temperature chart 7d", "humidity 7d", "rain chart 7d", "pressure chart this month", "temperature and rain chart 7d", + "weather 30d", "weather all week", "average temperature 7d", "plot uv and solar on two axes 7d", "indoor temperature chart 7d", + "wind direction plot 3m", "temperature chart last month", "lowest temperature on record", "highest humidity this week", + "temps this week", "air quality chart 7d", "pm2.5 chart 3d", "chart weather", +] + + +@pytest.mark.parametrize("text", KEYBOARD + SHORTCUTS) +async def test_the_bots_own_answers_are_unchanged(world, alert_state, monkeypatch, text): + pinned(text, await asked(world, alert_state, monkeypatch, text)) + + +@pytest.mark.parametrize("question, press", [("Temperature chart 1d", "7"), ("Rain chart 1d", "30"), ("rain by month this year", "365")]) +async def test_a_period_button_redraws_the_same_chart_as_before(world, alert_state, monkeypatch, question, press): + """A press on a period button under a chart: the chart over that period, put into the same message.""" + bot = world.bot(alert_state, monkeypatch) + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await bot.respond(update, CONTEXT, question) + sent_id = 100 + len(world.sent) + row = next((s[2] for s in world.sent if s[0] == "photo" and s[2]), None) + assert row, "a single chart with its period buttons" + data = next(d for r in row for t, d in r if d.removeprefix("pd:").rstrip("dmy") == press or d == f"pd:{press}") + under = world.message(sent_id) + under.reply_markup = NS(inline_keyboard=[[NS(text=t, callback_data=d) for t, d in r] for r in row]) + world.charts.clear() + + async def answer(text=None, **k): + world.toasts.append(text) + query = NS(data=data, message=under, answer=answer) + await bot.on_period_button(NS(callback_query=query, effective_message=under, effective_chat=under.chat, + effective_user=NS(username="rob", full_name="Rob", id=7)), CONTEXT) + pinned(f"press {press} under {question}", {"charts": world.charts, "edits": [e[:2] for e in world.edits]}) + + +@pytest.mark.parametrize("kind", ["gusts", "uv", "temps", "particulates"]) +async def test_an_alerts_chart_is_the_same_as_before(world, monkeypatch, kind): + from lib.alerts import pictures + captured = [] + monkeypatch.setattr(pictures, "render_data", lambda data, tz, *a, **k: captured.append(summary_of(data)) or b"png") + source = world.air if kind == "particulates" else world.eco + picture = await pictures.chart(source, pictures.CHARTS[kind], world.tz) + pinned(f"alert {kind}", {"title": picture.title, "newest": picture.newest, "charts": captured}) From cc16fd1248338828e867ea5f886b3b6c0db3fb42 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 05:23:18 +0000 Subject: [PATCH 034/125] Service evals: the saved questions against the ten tools alone tests/evals/service_cases.json gives every case in cases.json its expectation in service terms (which of the ten tools, which arguments, readings by what the service resolves them to, periods by what they mean at the evals' NOW), with a note for each. tests/test_service_evals.py checks them offline: every case has one, every tool and argument exists, every expected call answers over the fake station, air sensor, forecast and pollen, and the descriptions and schemas are short JSON Schema. The plumbing of `scripts/eval_prompts.py --live --service` (the ten tools alone, a neutral system line with the date, time and zone) is tested with a scripted model; without a key it stops with the same message as --live. The default run is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- scripts/eval_prompts.py | 11 + tests/evalkit.py | 235 +++- tests/evals/service_cases.json | 2099 ++++++++++++++++++++++++++++++++ tests/test_service_evals.py | 244 ++++ 4 files changed, 2584 insertions(+), 5 deletions(-) create mode 100644 tests/evals/service_cases.json create mode 100644 tests/test_service_evals.py diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 393a0a4a..484bf29d 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -8,6 +8,13 @@ python scripts/eval_prompts.py --live # and the model python scripts/eval_prompts.py --live --effort low # force a reasoning level to see what it fixes python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? + +With --service: the same questions against the service's ten tools alone (lib/service; docs/mcp-service.md, step 2), scored against +tests/evals/service_cases.json: the model is offered only their names, descriptions and parameters, with a neutral system line and the +date, time and zone, and none of the bot's prompt, hints or fast path. Without --live it checks the expectations themselves. + + python scripts/eval_prompts.py --service # every case has a service expectation, each one the tools take + python scripts/eval_prompts.py --live --service # and the model, with the ten tools alone """ import asyncio @@ -25,6 +32,7 @@ async def main() -> int: ap.add_argument("--ids", help="comma-separated case ids") ap.add_argument("--repeat", type=int, default=1, help="ask the model this many times per case") ap.add_argument("--effort", choices=["none", "low", "medium"], help="force this reasoning effort for every case") + ap.add_argument("--service", action="store_true", help="the service's ten tools alone, scored against tests/evals/service_cases.json") args = ap.parse_args() cases = evalkit.load_cases() if args.ids: @@ -37,6 +45,9 @@ async def main() -> int: sys.exit("--live needs OPENROUTER_API_KEY (and OPENROUTER_BASE_URL, OPENROUTER_MODEL) in the environment") client = AsyncOpenAI(api_key=os.environ["OPENROUTER_API_KEY"], base_url=os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")) model = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") + if args.service: + failed = await evalkit.run_service(cases, evalkit.load_service_cases(), client, model, repeat=args.repeat, effort=args.effort) + return 1 if failed else 0 failed = 0 for case in cases: problems = evalkit.deterministic(case) diff --git a/tests/evalkit.py b/tests/evalkit.py index be39cde3..36903a45 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -4,12 +4,14 @@ - decisions made in code (fast path, period hints, reasoning effort, which readings a chart combines): run by pytest; - what the model does with them (which tool, which arguments): `python scripts/eval_prompts.py --live`, against the real model with recording stand-in tools (nothing is fetched). +tests/evals/service_cases.json holds, for the same case ids, what a model offered only the service's ten tools (lib/service) should +call: checked offline by tests/test_service_evals.py, and asked of the model by `python scripts/eval_prompts.py --live --service`. """ import json import re from dataclasses import dataclass, field -from datetime import datetime +from datetime import date, datetime from pathlib import Path from lib import compose, history, intent, prompt @@ -99,8 +101,17 @@ def content(case: Case) -> str: def _matches(actual, want) -> str | None: - """None if `actual` satisfies `want`, else why not. want: a value, {"regex"}, {"absent"}, {"has"}, {"any_of"}.""" + """None if `actual` satisfies `want`, else why not. want: a value, {"regex"}, {"absent"}, {"has"}, {"any_of"} (or "one_of"), or + the service's {"reads"} / {"reads_any"} (_reads). Any of them with "optional": true also takes no value at all.""" if isinstance(want, dict): + if want.get("optional") and actual in (None, "", [], {}): + return None + if "reads" in want or "reads_any" in want: + return _reads(actual, want) + if "means" in want: + return _means(actual, want["means"]) + if "one_of" in want: + return None if actual in want["one_of"] else f"{actual!r} not one of {want['one_of']}" if "absent" in want: return None if actual in (None, "", [], {}) else f"expected no value, got {actual!r}" if "regex" in want: @@ -117,7 +128,8 @@ def check_args(args: dict, want: dict) -> list[str]: def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: - """Failures of what the model called against the case's expectations.""" + """Failures of what the model called against the case's expectations. A tool's expected arguments may be a list of alternatives + (the service's cases: `period` in words, or `start` and `end`): a call matching any one of them passes.""" fails = [] names = [n for n, _ in calls] for tool in expect.get("tools", []): @@ -132,8 +144,9 @@ def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: fails.append(f"first tool was {names[:1]}, expected {expect['first_tool']}") for tool, want in expect.get("args", {}).items(): made = [a for n, a in calls if n == tool] - if made and not any(not check_args(a, want) for a in made): - fails.append(f"{tool} arguments: " + "; ".join(check_args(made[0], want))) + alternatives = want if isinstance(want, list) else [want] + if made and not any(not check_args(a, w) for a in made for w in alternatives): + fails.append(f"{tool} arguments: " + " | or: ".join("; ".join(check_args(made[0], w)) for w in alternatives)) return fails @@ -186,3 +199,215 @@ async def run_live(case: Case, client, model: str, effort: str | None = None) -> if fast or r.extra: calls[0:0] = [*([(fast[0], fast[1]), *r.more] if fast else []), *r.extra] # the bot ran them itself, before the model return calls, reply + + +# ---------- the service's ten tools, offered alone (docs/mcp-service.md 6, step 2; 7) ---------- +# The same questions asked of a model given only the service's tool list: no prompt of ours (a neutral line, the date, time and zone), +# no hints, no fast path, nothing filled in from the words. tests/evals/service_cases.json says, for every case id in cases.json, which +# of the ten tools answers it and with which arguments, as a client that has never seen this repository would call them. +SERVICE_CASES = CASES.parent / "service_cases.json" +SERVICE_SYSTEM = "You answer questions about a home weather station and air sensor using the tools." +SERVICE_EFFORT = "low" # one reasoning level for every case: there is no intent.read to choose one +NOW_TZ = "Australia/Melbourne" +EXPECT_KEYS = {"tools", "any_tools", "not_tools", "first_tool", "args", "note"} + + +def service_modules(): + from lib.service import about, current, days, forecast, outlook, pollen, readings, relate, scan, summary + return (current, summary, readings, days, relate, scan, outlook, forecast, pollen, about) + + +def service_tool_names() -> list[str]: + return ["current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen", "about"] + + +def service_tools(ctx=None) -> list: + """The ten ServiceTools, each module's tools(ctx). With no ctx: over stand-ins for every source (nothing behind them: the tools are + built, never run), the catalogue of every reading the service knows, the station's zone and NOW.""" + if ctx is None: + from zoneinfo import ZoneInfo + + from lib.service.context import Context + tz = ZoneInfo(NOW_TZ) + ctx = Context(eco=object(), air=object(), composer=object(), forecast=object(), pollen=object(), tz=tz, + clock=lambda: NOW.replace(tzinfo=tz).timestamp()) + return [t for module in service_modules() for t in module.tools(ctx)] + + +def make_service_tools(calls: list) -> Tools: + """The ten tools as a model is offered them (name, description, parameters from lib/service), with handlers that record the call.""" + def recorder(name): + async def handler(args, turn=None): + calls.append((name, args)) + return CANNED + return handler + return Tools([Tool(t.name, t.description, t.parameters, recorder(t.name)) for t in service_tools()]) + + +def service_system(now: datetime = NOW) -> str: + """The whole system prompt of a service run: the neutral line, and the date, time and zone now.""" + return f"{SERVICE_SYSTEM}\nNow: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M} ({NOW_TZ} time)." + + +def load_service_cases(path: Path = SERVICE_CASES) -> dict[str, dict]: + """{case id: its expectation in service terms ({"tools", "any_tools", "not_tools", "first_tool", "args", "note"})}.""" + return json.loads(path.read_text()) + + +def _resolved(names) -> list[str] | str: + """The service names these readings stand for (lib/service/names.py; ":rating" set aside), or why they can't be read.""" + from lib.service.names import CATALOGUE, UnknownReading + words = [names] if isinstance(names, str) else names + if not isinstance(words, list): + return f"{names!r} is not a reading or a list of them" + try: + return [r.name for r in CATALOGUE.resolve([str(w).split(":", 1)[0] for w in words], default=None)] + except UnknownReading as e: + return f"{names!r}: {e.message}" + + +def _reads(actual, want: dict) -> str | None: + """{"reads": [names]}: the readings sent stand for every one of these; {"reads_any": [names]}: for at least one; "not": [names]: for + none of these. What was sent is read as the service reads it (names or words).""" + if actual in (None, "", []): + return "no readings sent" + got = _resolved(actual) + if isinstance(got, str): + return got + if need := [n for n in want.get("reads", []) if n not in got]: + return f"{actual!r} ({', '.join(got)}) lacks {', '.join(need)}" + if "reads_any" in want and not set(want["reads_any"]) & set(got): + return f"{actual!r} ({', '.join(got)}) has none of {', '.join(want['reads_any'])}" + if extra := [n for n in want.get("not", []) if n in got]: + return f"{actual!r} ({', '.join(got)}) should not have {', '.join(extra)}" + return None + + +FIRST_HELD = date(2022, 10, 1) # where "on record" starts when a case's period is read (the station's record, as the cases have it) + + +def _period_span(words) -> tuple | str: + """(start, end) of a `period` as the service reads it at NOW in the station's zone (lib/periods_text.py), or why it can't.""" + from zoneinfo import ZoneInfo + + from lib.periods_text import PeriodError, read_period + if not isinstance(words, str) or not words.strip(): + return f"{words!r} is not a period in words" + try: + p = read_period(words, None, None, now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), tz=ZoneInfo(NOW_TZ), default="today", + first_held=FIRST_HELD) + except PeriodError as e: + return f"{words!r} can't be read: {e.message.split('. ')[0]}" + return p.start, p.end + + +def _means(actual, refs) -> str | None: + """{"means": words or [words]}: the `period` sent reads, at NOW, as the same span as (one of) these words: "past week", "this week" + and "7d" are the same period, "last week" is another.""" + got = _period_span(actual) + if isinstance(got, str): + return got + refs = refs if isinstance(refs, list) else [refs] + if any(_period_span(r) == got for r in refs): + return None + return f"{actual!r} ({got[0]:%a %d %b %Y %H:%M} to {got[1]:%a %d %b %Y %H:%M}) is not the period of {' or '.join(map(repr, refs))}" + + +ABSENT = object() # (example_value: the argument is best left out) + + +def example_value(want): + """A concrete value that satisfies `want` (_matches), to call the tool with: a matcher's own "e.g.", else the first of any_of / + one_of, the names of reads / has; ABSENT where the argument is best left out.""" + if not isinstance(want, dict): + return want + if "e.g." in want: + return want["e.g."] + if "absent" in want: + return ABSENT + for key in ("one_of", "any_of"): + if key in want: + return ABSENT if want[key][0] is None else want[key][0] + if "reads" in want or "reads_any" in want: + return list(want.get("reads") or want["reads_any"][:1]) + if "means" in want: + return want["means"][0] if isinstance(want["means"], list) else want["means"] + if "has" in want: + return list(want["has"]) + raise ValueError(f"no example for {want!r}: give it an \"e.g.\"") + + +def expected_tools(expect: dict) -> list[str]: + """The tools an expectation would have called (tools, any_tools, first_tool, and those it gives arguments for), each once.""" + return list(dict.fromkeys([*expect.get("tools", []), *expect.get("any_tools", []), + *([expect["first_tool"]] if "first_tool" in expect else []), *expect.get("args", {})])) + + +def example_calls(expect: dict) -> list[tuple[str, dict]]: + """Every call a service expectation describes, made concrete: (tool, arguments) for each tool and each alternative of its arguments + (example_value); a tool expected with no arguments named is called with {}.""" + out = [] + for tool in expected_tools(expect): + want = expect.get("args", {}).get(tool, {}) + for alternative in (want if isinstance(want, list) else [want]): + out.append((tool, {k: v for k, w in alternative.items() if (v := example_value(w)) is not ABSENT})) + return out + + +def service_problems(expect: dict | None) -> list[str]: + """What is wrong with a case's service expectation itself (no model): missing, an unknown key or tool, an argument the tool doesn't + take, an example that doesn't satisfy its own matcher.""" + if expect is None: + return ["no service expectation (tests/evals/service_cases.json)"] + fails = [f"unknown keys {sorted(extra)}"] if (extra := set(expect) - EXPECT_KEYS) else [] + tools = {t.name: t for t in service_tools()} + fails += [f"unknown tool {n!r}" for n in dict.fromkeys([*expected_tools(expect), *expect.get("not_tools", [])]) if n not in tools] + for tool, want in expect.get("args", {}).items(): + known = tools[tool].parameters.get("properties", {}) if tool in tools else {} + for alternative in (want if isinstance(want, list) else [want]): + fails += [f"{tool} takes no argument {k!r}" for k in alternative if tool in tools and k not in known] + for k, w in alternative.items(): + try: + v = example_value(w) + except ValueError as e: + fails.append(f"{tool}.{k}: {e}") + continue + if v is not ABSENT and (why := _matches(v, w)): + fails.append(f"{tool}.{k}: its example doesn't satisfy it ({why})") + return fails + + +async def run_live_service(case: Case, client, model: str, effort: str | None = None) -> tuple[list[tuple[str, dict]], str]: + """Ask the model with the ten tools alone and the neutral system line; returns the tool calls it made and its final reply. It may + answer with no tool at all (tool_choice auto): a plain client forces nothing.""" + calls: list[tuple[str, dict]] = [] + messages = [*case.history, {"role": "user", "content": content(case)}] + reply = await Agent(client, model, make_service_tools(calls)).run(messages, service_system(), effort or SERVICE_EFFORT, + tool_choice="auto") + return calls, reply + + +async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, + effort: str | None = None, out=print) -> int: + """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times with + the ten tools alone and its calls scored against it (check_calls), as `--live` scores cases.json. Prints a line per case (`out`); + returns how many cases fail.""" + failed = 0 + for case in cases: + expect = expectations.get(case.id) + problems = service_problems(expect) + line = "ok" if not problems else "FAIL" + if client and not problems: + passes = 0 + for _ in range(repeat): + calls, _reply = await run_live_service(case, client, model, effort) + why = check_calls(calls, expect) + passes += not why + problems += [f" run: {w}" for w in why[:3]] if why else [] + line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + out(f"{line:>10} {case.id} ({case.ask})") + for p in problems: + out(f" {p}") + failed += bool(problems) + out(f"\n{len(cases) - failed} of {len(cases)} cases pass (the service's ten tools alone)") + return failed diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json new file mode 100644 index 00000000..baa07934 --- /dev/null +++ b/tests/evals/service_cases.json @@ -0,0 +1,2099 @@ +{ + "3m-average": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "period": { + "means": "3m" + }, + "average": true + } + }, + "note": "an average over a period is summary's `average`; 3m is the last 3 months, passed as said" + }, + "3m-wind-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "3m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a chart over time is summary's; wind direction draws the compass rose" + }, + "temperature-and-rain": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "rainfall.rain" + ] + }, + "chart": true + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "rainfall.rain" + ] + }, + "chart": true + } + ] + }, + "note": "both readings drawn, a panel each (the bot once drew only temperature); no period: a chart's default, the last 24 hours" + }, + "humidity-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ], + "not": [ + "outdoor.temperature" + ] + } + } + }, + "note": "the lowest and highest of a period are summary's; only humidity (the bot once charted temperature)" + }, + "pressure-rain-correlation": { + "tools": [ + "relate" + ], + "not_tools": [ + "days" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "\"X against rain\" is relate (pressure is its default), not monthly extremes" + }, + "pressure-vs-rain-graph": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "pressure.relative" + ], + "optional": true + }, + "chart": true + } + }, + "note": "a chart of a reading against rain is relate's, with chart" + }, + "public-holidays": { + "tools": [ + "days" + ], + "args": { + "days": { + "only": "public_holiday", + "sort_by": { + "one_of": [ + "temp_max", + null + ] + } + } + }, + "note": "days filtered to public holidays and ranked; no period: every day on record" + }, + "hottest-day-that-rained": { + "tools": [ + "days" + ], + "args": { + "days": { + "sort_by": "temp_max", + "order": { + "one_of": [ + "desc", + null + ] + }, + "where": { + "regex": "'field': 'rain', 'op': '>=?'", + "e.g.": [ + { + "field": "rain", + "op": ">=", + "value": 1 + } + ] + } + } + }, + "note": "a condition on one figure and a ranking on another is days (a rainy day is rain >= 1)" + }, + "wind-direction-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "this week" + } + } + }, + "note": "the most common direction of a period is summary's wind direction" + }, + "will-it-rain": { + "tools": [ + "outlook" + ], + "note": "will it rain in the next few hours is outlook" + }, + "air-now": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "the air now is current; with no readings named it gives everything, the air included" + }, + "weather-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a bare reading and a period is a chart over the period; \"weather\" is every station reading" + }, + "hello": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen", + "about" + ], + "note": "thanks: no tool" + }, + "chart-pm10-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm10" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "an air chart is summary's like any other" + }, + "weather-4-months": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "4m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "4 months, passed as said (the bot once read it as 7 days)" + }, + "chart-indoors": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "indoor.temperature" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "indoor.temperature" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "indoor is the indoor set (temperature and humidity)" + }, + "pressure-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a bare reading and a period: summary, which charts a week by default" + }, + "wind-3m": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_speed" + ] + }, + "period": { + "means": "3m" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "3m is 3 months (the bot once read it as 3 days)" + }, + "hottest-weekends": { + "tools": [ + "days" + ], + "args": { + "days": { + "only": "weekend", + "sort_by": { + "one_of": [ + "temp_max", + null + ] + } + } + }, + "note": "days filtered to weekends and ranked" + }, + "windiest-day-on-record": { + "tools": [ + "days" + ], + "args": { + "days": { + "sort_by": "wind_gust", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the windiest day is days ranked by the highest gust; no period is every day on record" + }, + "rainy-days-in-september": { + "tools": [ + "days" + ], + "args": { + "days": [ + { + "where": { + "regex": "'field': 'rain', 'op': '>=?'", + "e.g.": [ + { + "field": "rain", + "op": ">=", + "value": 1 + } + ] + }, + "period": { + "means": "September" + } + }, + { + "where": { + "regex": "'field': 'rain', 'op': '>=?'", + "e.g.": [ + { + "field": "rain", + "op": ">=", + "value": 1 + } + ] + }, + "start": "2026-09-01" + } + ] + }, + "note": "days found by a condition, over September (this month: to yesterday)" + }, + "a-day-in-2023": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "start": { + "regex": "^2023-11-10 11:00", + "e.g.": "2023-11-10 11:00" + }, + "end": { + "regex": "^2023-11-11 11:00", + "e.g.": "2023-11-11 11:00" + } + } + }, + "note": "a window with times is start and end, never a period" + }, + "weather-on-june-11": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": [ + { + "period": { + "means": "11 June" + } + }, + { + "start": { + "regex": "^2026-06-11", + "e.g.": "2026-06-11" + } + } + ], + "days": [ + { + "period": { + "means": "11 June" + } + }, + { + "start": { + "regex": "^2026-06-11", + "e.g.": "2026-06-11" + } + } + ] + }, + "note": "one known day: its figures and its look (summary), or its day row (days {period: \"5 Sep\"})" + }, + "what-it-would-have-been-like": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": [ + { + "period": { + "means": "10 Aug" + } + }, + { + "start": { + "regex": "^2026-08-10", + "e.g.": "2026-08-10" + } + } + ], + "days": [ + { + "period": { + "means": "10 Aug" + } + }, + { + "start": { + "regex": "^2026-08-10", + "e.g.": "2026-08-10" + } + } + ] + }, + "note": "a hypothetical about one day: that day's figures" + }, + "add-an-alert": { + "tools": [ + "about" + ], + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "alerts can't be added by asking: about lists those there are, with their thresholds" + }, + "metrics-bare": { + "tools": [ + "about" + ], + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "what is measured is about's (the bot answered it from its prompt)" + }, + "most-rain-days-jja": { + "tools": [ + "days" + ], + "args": { + "days": [ + { + "sort_by": "rain", + "period": { + "means": "June to August 2026" + } + }, + { + "sort_by": "rain", + "start": "2026-06-01", + "end": "2026-08-31" + } + ] + }, + "note": "days ranked by rain over three months: \"June to August 2026\", or start and end" + }, + "fastest-gust": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_gust" + ] + }, + "period": { + "means": "on record" + } + }, + "days": { + "sort_by": "wind_gust", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a record with when it happened is summary (on record); the windiest day ranked is days" + }, + "chart-all-airgradient-week": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "airgradient is the air sensor's usual set" + }, + "rain-on-a-named-day": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": [ + { + "period": { + "means": "5 Sep" + } + }, + { + "start": "2026-09-05" + } + ], + "summary": [ + { + "period": { + "means": "5 Sep" + } + }, + { + "start": { + "regex": "^2026-09-05", + "e.g.": "2026-09-05" + } + } + ] + }, + "note": "one known day: its figures, not a search of the month" + }, + "pushback-cooler-this-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a challenge: call again (the result's `fresh` says so), don't defend or agree from memory" + }, + "all-time-follow-up": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a follow-up that keeps the subject with a new period: on record" + }, + "typo-win-direction": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "wind.wind_direction" + ] + }, + "period": { + "means": "3m" + } + } + }, + "note": "a typo for wind direction" + }, + "hottest-coldest-this-month": { + "any_tools": [ + "summary", + "days" + ], + "args": { + "summary": { + "period": { + "means": "this month" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + }, + "days": { + "period": { + "means": "this month" + } + } + }, + "note": "the highest and lowest with when are summary's; the hottest and coldest days ranked are days'" + }, + "high-low-all-time": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + } + } + }, + "note": "the record high and low: summary over on record" + }, + "use-five-minute-data": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "on record" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "the resolution is the service's (records are refined to 5 minutes where held): call again, there is no argument for it" + }, + "report": { + "tools": [ + "current", + "forecast", + "pollen" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^today$", + "e.g.": "today", + "optional": true + } + } + }, + "note": "a report is current, forecast (today) and pollen, called together" + }, + "dashboard": { + "tools": [ + "current" + ], + "args": { + "current": { + "context": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's gauges (drawn in code) are the bot's; a plain client shows current, with context the gauges' highs and lows" + }, + "weather-report-for-a-day": { + "any_tools": [ + "summary", + "days", + "forecast" + ], + "not_tools": [ + "pollen" + ], + "args": { + "summary": { + "period": { + "means": [ + "Tuesday", + "today" + ] + } + }, + "days": { + "period": { + "means": "Tuesday" + } + }, + "forecast": { + "period": { + "regex": "(?i)tuesday|today", + "e.g.": "Tuesday" + } + } + }, + "note": "asked on a Tuesday: last Tuesday's figures, or today's forecast; not the full report" + }, + "air-quality-vs-rain": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads_any": [ + "air.pm2_5", + "air.pm10" + ] + } + } + }, + "note": "is the air cleaner after rain: relate with PM2.5 or PM10, both devices together" + }, + "rating-against-rainfall": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "chart_readings": { + "regex": "(?s)(?=.*:rating)(?=.*rain)", + "e.g.": [ + "air.pm2_5:rating", + "rainfall.rain" + ] + }, + "period": { + "means": "last 30 days" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the rating drawn over time is summary's chart (\":rating\"), with rain in a panel below; relate would draw PM2.5, not its rating" + }, + "air-quality-vs-everything": { + "tools": [ + "scan" + ], + "not_tools": [ + "relate" + ], + "note": "every air reading against every weather reading: scan" + }, + "ecowitt-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + }, + "readings": { + "reads": [ + "outdoor.temperature", + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "ecowitt names the weather station: every reading" + }, + "ag-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm2_5" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "ag names the air sensor" + }, + "air-gradient-now": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "air gradient names the air sensor; bare, it is the sensor now" + }, + "ecowitt-all-week": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "\"all\" is every station reading in the station's order (the service's, not the model's)" + }, + "sitrep": { + "tools": [ + "current", + "forecast", + "pollen" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^today$", + "e.g.": "today", + "optional": true + } + } + }, + "note": "sitrep is a report: current, forecast (today) and pollen" + }, + "think-hottest-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "this week" + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "the hottest of a period with when it was is summary (a record), not days" + }, + "button-rain-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's Rain chart button, asked in words" + }, + "button-humidity-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ] + }, + "period": { + "means": "7d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's Humidity chart button, asked in words" + }, + "button-aq-all-week": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "air.pm2_5" + ] + }, + "period": { + "means": "this week" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "the bot's AQ all week button: the air sensor's set over the week" + }, + "weather-now-everything": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature", + "pressure.relative" + ], + "optional": true + } + } + }, + "note": "everything now: current with no readings (or all of them)" + }, + "pollen-now": { + "tools": [ + "pollen" + ], + "note": "pollen and thunderstorm asthma" + }, + "hay-fever-today": { + "tools": [ + "pollen" + ], + "note": "a pollen question" + }, + "forecast-tomorrow": { + "tools": [ + "forecast" + ], + "not_tools": [ + "outlook" + ], + "args": { + "forecast": { + "period": { + "regex": "(?i)^tomorrow$", + "e.g.": "tomorrow" + } + } + }, + "note": "the forecast, not the station's own read of the next few hours" + }, + "philosophical-weather": { + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "an opinion, not a lookup: no search of the readings (a tool for now is fine)" + }, + "only-that-its-cold": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "a chat reply, not a request (the bot once answered it with the temperatures)" + }, + "how-cold-is-it": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "a plain question about now" + }, + "now-what": { + "not_tools": [ + "current", + "summary", + "readings", + "days", + "relate", + "scan", + "outlook", + "forecast", + "pollen" + ], + "note": "'now' alone is not a weather question" + }, + "chart-with-forecast": { + "tools": [ + "summary", + "forecast" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "this week" + }, + "chart_answers_it": { + "one_of": [ + null, + false + ] + } + }, + "forecast": { + "period": { + "regex": "(?i)^tomorrow$", + "e.g.": "tomorrow" + } + } + }, + "note": "two questions, two tools together: the chart of the week's rain and tomorrow's forecast" + }, + "chart-correlation": { + "tools": [ + "relate" + ], + "args": { + "relate": { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "chart": true + } + }, + "note": "a reading against rain, drawn: relate with chart" + }, + "chart-pressure-30d": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "30d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "a plain chart of one reading" + }, + "lookup-how-hot": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "how hot is it: current, temperature" + }, + "lookup-raining": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads_any": [ + "rainfall.rain", + "rainfall.rain_rate" + ], + "optional": true + } + } + }, + "note": "is it raining: current, rain (or rain rate)" + }, + "lookup-air": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads": [ + "air.pm2_5" + ], + "optional": true + } + } + }, + "note": "the air now" + }, + "lookup-forecast": { + "tools": [ + "forecast" + ], + "note": "forecast: the next 7 days by default" + }, + "lookup-about": { + "tools": [ + "about" + ], + "not_tools": [ + "summary", + "readings", + "days", + "relate", + "scan" + ], + "note": "what the service can do" + }, + "lookup-judgement": { + "tools": [ + "current" + ], + "args": { + "current": { + "readings": { + "reads_any": [ + "outdoor.temperature", + "outdoor.feels_like" + ], + "optional": true + } + } + }, + "note": "a judgement on the conditions now: current, then the model's words" + }, + "lookup-hottest-today": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "period": { + "means": "today", + "optional": true + }, + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "the high of a short period: summary (today is its default)" + }, + "lookup-hottest-vs": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ], + "optional": true + } + } + }, + "note": "two periods compared: summary for today and yesterday (two calls, or one over both with every_day)" + }, + "average-temp-yesterday": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.temperature" + ] + }, + "period": { + "means": "yesterday" + }, + "average": true + } + }, + "note": "an average of a period: summary's average" + }, + "highest-humidity-yesterday": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "outdoor.humidity" + ] + }, + "period": { + "means": "yesterday" + } + } + }, + "note": "the high of a period with when it was: summary" + }, + "pollen-tomorrow": { + "tools": [ + "pollen" + ], + "not_tools": [ + "forecast" + ], + "note": "pollen gives the grass forecast and the day it is for; the weather forecast has no pollen" + }, + "average-rain": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": { + "stat": "avg", + "of": "rain", + "period": { + "means": "last week" + } + }, + "summary": { + "readings": { + "reads": [ + "rainfall.rain" + ] + }, + "period": { + "means": "last week" + } + } + }, + "note": "the average daily rain is days' avg of rain; summary gives the week's total (rain has no average there)" + }, + "uv-days-two-years": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "'field': 'uv_max', 'op': '>=', 'value': '?9(\\.0)?'?\\}", + "e.g.": [ + { + "field": "uv_max", + "op": ">=", + "value": 9 + } + ] + }, + "period": { + "means": "past two years" + }, + "count_only": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "how many days a figure reached a limit: days counted" + }, + "uv-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "'field': 'uv_max', 'op': '>=?', 'value': '?10(\\.0)?'?\\}", + "e.g.": [ + { + "field": "uv_max", + "op": ">", + "value": 10 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a count per year, drawn as bars: group_by year over the whole record" + }, + "rain-per-month": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "sum", + "of": "rain", + "group_by": "month", + "period": { + "means": "this year" + } + } + }, + "note": "a total per month: days' sum of rain by month, drawn as bars" + }, + "hottest-day-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "max", + "of": "temp_max", + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the highest daily maximum per year, as bars" + }, + "air-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "'field': 'pm2_5_(max|avg)', 'op': '>=?', 'value': '?25(\\.0)?'?\\}", + "e.g.": [ + { + "field": "pm2_5_max", + "op": ">", + "value": 25 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "the air sensor's days through the same days tool: a count per year" + }, + "count-pm25-days-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "'field': 'pm2_5_(max|avg)', 'op': '>=?', 'value': '?90(\\.0)?'?\\}", + "e.g.": [ + { + "field": "pm2_5_max", + "op": ">", + "value": 90 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "a count per year of the air sensor's days" + }, + "days-over-limit-by-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "'field': 'uv_max', 'op': '>=?', 'value': '?10(\\.0)?'?\\}", + "e.g.": [ + { + "field": "uv_max", + "op": ">", + "value": 10 + } + ] + }, + "group_by": "year", + "period": { + "means": "on record", + "optional": true + } + } + }, + "note": "per year over the whole record, not one overall count" + }, + "days-two-readings-go-to-the-model": { + "tools": [ + "days" + ], + "args": { + "days": { + "where": { + "regex": "(?s)(?=.*'field': 'temp_max', 'op': '>=?', 'value': '?35)(?=.*'field': 'rain', 'op': '>=?')", + "e.g.": [ + { + "field": "temp_max", + "op": ">", + "value": 35 + }, + { + "field": "rain", + "op": ">=", + "value": 1 + } + ] + } + } + }, + "note": "two conditions on the same day: days' where holds both" + }, + "rain-by-month-two-years": { + "tools": [ + "days" + ], + "args": { + "days": [ + { + "stat": "sum", + "of": "rain", + "group_by": "month", + "period": { + "means": "2 years" + } + }, + { + "stat": "sum", + "of": "rain", + "group_by": "month", + "start": { + "regex": "^2024-(09|10)-", + "e.g.": "2024-10-01" + } + } + ] + }, + "note": "monthly bars, one per month, over the last 2 years" + }, + "avg-temp-per-year": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "avg", + "of": "temp_avg", + "group_by": "year" + } + }, + "note": "an average per year is days' avg of each day's mean" + }, + "highest-pm25-by-month": { + "tools": [ + "days" + ], + "args": { + "days": { + "stat": "max", + "of": "pm2_5_max", + "group_by": "month" + } + }, + "note": "the highest per month, from the air sensor's days" + }, + "two-readings-by-month-go-to-the-model": { + "any_tools": [ + "days", + "summary" + ], + "args": { + "days": { + "group_by": "month", + "of": { + "regex": "^(pm2_5|co2)_", + "e.g.": "pm2_5_avg" + } + }, + "summary": { + "readings": { + "reads": [ + "air.pm2_5", + "air.co2" + ] + } + } + }, + "note": "two readings by month: a days call for each (a figure per month), or summary of both (its breakdown is by month for a long period); the period is the model's choice" + }, + "chart-weather-90d": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "a chart naming no reading is every reading, a panel each" + }, + "chart-all-90d": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "outdoor.temperature", + "outdoor.humidity", + "solar_and_uvi.solar", + "pressure.relative", + "rainfall.rain", + "outdoor.dew_point", + "wind.wind_speed" + ] + }, + "period": { + "means": "90d" + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "all is every station reading, a panel each" + }, + "two-axes-chart": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "solar_and_uvi.uvi", + "solar_and_uvi.solar" + ] + }, + "layout": "two_axes", + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "solar_and_uvi.uvi", + "solar_and_uvi.solar" + ] + }, + "layout": "two_axes", + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "two readings on one panel with a scale each: layout two_axes" + }, + "airgradient-humidity-over-ecowitt": { + "tools": [ + "summary" + ], + "args": { + "summary": [ + { + "readings": { + "reads": [ + "air.humidity", + "outdoor.humidity" + ] + }, + "chart": { + "one_of": [ + true, + null + ] + } + }, + { + "chart_readings": { + "reads": [ + "air.humidity", + "outdoor.humidity" + ] + }, + "chart": { + "one_of": [ + true, + null + ] + } + } + ] + }, + "note": "the AirGradient's own humidity is air.humidity; both sensors on one chart" + }, + "humidity-each-hour": { + "tools": [ + "readings" + ], + "not_tools": [ + "summary" + ], + "args": { + "readings": [ + { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "interval": "1hour", + "period": { + "means": "last 5 hours" + } + }, + { + "reading": { + "reads": [ + "outdoor.humidity" + ] + }, + "interval": "1hour", + "start": { + "regex": "^2026-09-29 (08|09)", + "e.g.": "2026-09-29 09:00" + }, + "end": { + "regex": "^2026-09-29", + "e.g.": "2026-09-29 14:05", + "optional": true + } + } + ] + }, + "note": "a value per hour is readings (the bot once said it only had extremes)" + }, + "temperature-every-30-minutes": { + "tools": [ + "readings" + ], + "args": { + "readings": [ + { + "reading": { + "reads": [ + "outdoor.temperature" + ] + }, + "interval": "30min", + "period": { + "means": "today" + } + }, + { + "reading": { + "reads": [ + "outdoor.temperature" + ] + }, + "interval": "30min", + "start": { + "regex": "^2026-09-29( 00:00)?$", + "e.g.": "2026-09-29" + }, + "end": { + "regex": "^2026-09-29", + "e.g.": "2026-09-29 14:05", + "optional": true + } + } + ] + }, + "note": "values every 30 minutes, not a highs-and-lows summary" + }, + "chart-only-answers-itself": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "since Sunday" + }, + "chart_answers_it": true, + "chart": { + "one_of": [ + true, + null + ] + } + } + }, + "note": "only the chart is asked for: chart_answers_it, and the result carries the reply" + }, + "chart-and-a-question": { + "tools": [ + "summary" + ], + "args": { + "summary": { + "readings": { + "reads": [ + "pressure.relative" + ] + }, + "period": { + "means": "since Sunday" + }, + "chart_answers_it": { + "one_of": [ + null, + false + ] + } + } + }, + "note": "the chart and something else to answer (outlook may be called too): chart_answers_it stays unset" + } +} diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py new file mode 100644 index 00000000..104366b8 --- /dev/null +++ b/tests/test_service_evals.py @@ -0,0 +1,244 @@ +"""The saved questions in service terms (tests/evals/service_cases.json): what a model given only the service's ten tools should call for +every case in cases.json, checked without a model. Every case has an expectation; every tool in it is one of the ten; every call it +describes, made concrete, is one the real tool answers rather than refuses; the tool list itself is one any model can read. (What a +real model does with the ten is `scripts/eval_prompts.py --live --service`; its plumbing is tested here with a scripted model.) + +The expectations are written for evalkit.NOW (Tue 29 Sep 2026 14:05), and a period is matched by what it means then ({"means"}). The +real tools are called on the real clock over the fake station (its history runs to now), so that check is of the arguments being taken +(names, words, forms, start and end), not of the figures.""" + +import json +import os +import subprocess +import sys +from datetime import datetime, time as dtime +from pathlib import Path +from types import SimpleNamespace as NS + +import pytest + +from lib.airgradient import AirGradient +from lib.compose import Composer +from lib.forecast import Forecast +from lib.service.context import Context +from tests import evalkit +from tests.fakes import TZ, air_transport, archived_station, config + +CASES = evalkit.load_cases() +EXPECT = evalkit.load_service_cases() +ROOT = Path(__file__).resolve().parent.parent + + +# ---------- the expectations ---------- +def test_every_case_has_a_service_expectation_and_no_other_id_does(): + ids = [c.id for c in CASES] + assert [i for i in ids if i not in EXPECT] == [] and [i for i in EXPECT if i not in ids] == [] + assert list(EXPECT) == ids # (kept in cases.json's order, so the two files read side by side) + + +@pytest.mark.parametrize("case", CASES, ids=[c.id for c in CASES]) +def test_each_expectation_names_only_the_ten_tools_and_their_own_arguments(case): + expect = EXPECT[case.id] + assert evalkit.service_problems(expect) == [] + assert expect.get("note"), "say why: the expectation is a reading of the question and of 3.3's routing rules" + for name, args in evalkit.example_calls(expect): # each concrete call passes the checker it was made from + assert evalkit.check_calls([(name, args)], {"args": {name: expect.get("args", {}).get(name, {})}}) == [], (name, args) + + +def test_the_checker_reads_names_words_and_periods_as_the_service_does(): + check = evalkit.check_args + assert check({"readings": ["temperature"]}, {"readings": {"reads": ["outdoor.temperature"]}}) == [] + assert check({"readings": "outdoor humidity"}, {"readings": {"reads": ["outdoor.humidity"], "not": ["outdoor.temperature"]}}) == [] + assert check({"readings": ["humidity", "temp"]}, {"readings": {"reads": ["outdoor.humidity"], "not": ["outdoor.temperature"]}}) + assert check({"readings": ["airgradient humidity"]}, {"readings": {"reads": ["air.humidity"]}}) == [] + assert check({"chart_readings": ["air.pm2_5:rating"]}, {"chart_readings": {"reads": ["air.pm2_5"]}}) == [] + assert "lacks" in check({"readings": ["pressure"]}, {"readings": {"reads": ["rainfall.rain"]}})[0] + assert check({"readings": ["lightning"]}, {"readings": {"reads": ["rainfall.rain"]}}) # (not a reading: refused, so a failure) + assert check({}, {"readings": {"reads": ["outdoor.temperature"], "optional": True}}) == [] + assert check({}, {"readings": {"reads": ["outdoor.temperature"]}}) == ["readings: no readings sent"] + assert check({"readings": ["rain rate"]}, {"readings": {"reads_any": ["rainfall.rain", "rainfall.rain_rate"]}}) == [] + # periods: the same span at NOW (Tue 29 Sep 2026 14:05), whatever the words + for same in ("this week", "past week", "7d", "last 7 days", "the last week", "1w"): + assert check({"period": same}, {"period": {"means": "this week"}}) == [], same + assert check({"period": "last week"}, {"period": {"means": "this week"}}) # (the previous Monday to Sunday) + assert check({"period": "3 months"}, {"period": {"means": "3m"}}) == [] and check({"period": "3d"}, {"period": {"means": "3m"}}) + assert check({"period": "all time"}, {"period": {"means": "on record"}}) == [] + assert check({"period": "Tuesday"}, {"period": {"means": ["Tuesday", "today"]}}) == [] + assert "can't be read" in check({"period": "sometime"}, {"period": {"means": "today"}})[0] + assert check({"x": 1}, {"x": {"one_of": [1, 2]}}) == [] and check({"x": 3}, {"x": {"one_of": [1, 2]}}) + + +def test_alternatives_pass_when_any_one_does(): + expect = {"args": {"days": [{"period": {"means": "September"}}, {"start": "2026-09-01"}]}} + assert evalkit.check_calls([("days", {"period": "this month"})], expect) == [] + assert evalkit.check_calls([("days", {"start": "2026-09-01"})], expect) == [] + fails = evalkit.check_calls([("days", {"period": "August"})], expect) + assert len(fails) == 1 and "| or:" in fails[0] + + +# ---------- the tool list a model is offered ---------- +def test_the_tool_list_is_the_ten_service_tools_with_their_own_descriptions_and_schemas(): + built = evalkit.service_tools() + assert [t.name for t in built] == evalkit.service_tool_names() + offered = evalkit.make_service_tools([]) + assert set(offered.by_name) == set(evalkit.service_tool_names()) + # (the two lists are never offered together; the one name they share is the service's own `readings`, not the bot's) + assert set(offered.by_name) & set(evalkit.tool_names()) == {"readings"} + assert offered.by_name["readings"].parameters != evalkit.make_tools([]).by_name["readings"].parameters + for tool, schema in zip(built, offered.schemas): + assert schema == {"type": "function", "function": {"name": tool.name, "description": tool.description, + "parameters": tool.parameters}} + + +JSON_TYPES = {"object", "array", "string", "number", "integer", "boolean", "null"} + + +def schema_problems(schema, where: str) -> list[str]: + """What isn't JSON Schema as function-calling APIs read it: a type each, a description on each property, enums of the type's values, + `required` naming properties, items for an array.""" + out = [] + kind = schema.get("type") + if kind not in JSON_TYPES: + out.append(f"{where}: type {kind!r}") + if kind == "object": + props = schema.get("properties") + if not isinstance(props, dict): + out.append(f"{where}: an object needs properties") + props = {} + out += [f"{where}: required {r!r} is no property" for r in schema.get("required", []) if r not in props] + for name, prop in props.items(): + out += schema_problems(prop, f"{where}.{name}") + if kind == "array": + out += schema_problems(schema["items"], f"{where}[]") if isinstance(schema.get("items"), dict) else [f"{where}: no items"] + if "enum" in schema: + py = {"string": str, "integer": int, "number": (int, float)}.get(kind, object) + if not schema["enum"] or not all(isinstance(v, py) for v in schema["enum"]) or len(set(schema["enum"])) != len(schema["enum"]): + out.append(f"{where}: enum {schema['enum']!r}") + if extra := set(schema) - {"type", "properties", "required", "items", "enum", "description", "additionalProperties"}: + out.append(f"{where}: unknown keys {sorted(extra)}") + return out + + +@pytest.mark.parametrize("name", evalkit.service_tool_names()) +def test_each_description_is_short_and_each_schema_is_json_schema(name): + (tool,) = [t for t in evalkit.service_tools() if t.name == name] + assert 0 < len(tool.description) < 1500 + assert tool.parameters.get("type") == "object" and schema_problems(tool.parameters, name) == [] + json.dumps(tool.parameters) # (serialisable as it is) + for prop_name, prop in tool.parameters.get("properties", {}).items(): + if "properties" not in prop: # (a condition's own fields are described by the array that holds them) + assert prop.get("description"), f"{name}.{prop_name} has no description" + + +# ---------- every expected call is one the real tool answers ---------- +def calls_for(tool: str) -> list[tuple[str, dict]]: + return [(cid, args) for cid, expect in EXPECT.items() for name, args in evalkit.example_calls(expect) if name == tool] + + +async def real_context(tmp_path, archived_cache) -> Context: + """The ten tools' sources, faked: the archived station, an AirGradient on the same file, both together, Open-Meteo, the pollen page + in season.""" + from tests.test_pollen import make as pollen_source + from tests.test_service_forecast import open_meteo + eco, _ = await archived_station(tmp_path, archived_cache) + air = AirGradient(config(tmp_path), transport=air_transport(rows_per_day=24)[0], storage=eco.storage) + await air.start() + forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, open_meteo([])) + noon = datetime.combine(datetime.now(TZ).date(), dtime(12, 0)) + forecast.now = lambda: noon + pollen, _ = pollen_source(tmp_path) + ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen) + (summary,) = [t for t in evalkit.service_tools(ctx) if t.name == "summary"] + held = json.loads(await summary.call({"readings": ["air"], "period": "last 30 days", "chart": False})) # (the air's month, held) + assert "error" not in held + return ctx + + +@pytest.mark.parametrize("tool", evalkit.service_tool_names()) +async def test_every_expected_call_is_answered_not_refused(tool, tmp_path, archived_cache): + calls = calls_for(tool) + if not calls: + pytest.skip(f"no case expects {tool}") + ctx = await real_context(tmp_path, archived_cache) + try: + (service_tool,) = [t for t in evalkit.service_tools(ctx) if t.name == tool] + refused = {} + for case_id, args in calls: + out = json.loads(await service_tool.call(args)) + if "error" in out: + refused[case_id] = (args, out["error"]) + assert refused == {}, json.dumps(refused, indent=1, ensure_ascii=False) + finally: + await ctx.pollen.close() + await ctx.air.close() + await ctx.eco.close() + + +# ---------- the live run, with a scripted model ---------- +class ScriptedModel: + """An OpenAI-style client whose answers are scripted per question: {question: [(tool, args), ...] or a text}. Each question gets its + calls, then a one-line reply. Every request is kept.""" + + def __init__(self, script: dict): + self.script, self.requests = script, [] + self.chat = NS(completions=NS(create=self.create)) + + async def create(self, **kw): + self.requests.append(kw) + asked = next(m["content"] for m in reversed(kw["messages"]) if m["role"] == "user") + answered = kw["messages"][-1]["role"] == "tool" + step = "Done." if answered else self.script.get(asked, "Nothing to look up.") + calls = None if isinstance(step, str) else [NS(id=f"c{i}", function=NS(name=n, arguments=json.dumps(a))) + for i, (n, a) in enumerate(step)] + msg = NS(content=step if isinstance(step, str) else "", tool_calls=calls) + return NS(choices=[NS(message=msg)], usage=None) + + +def case(case_id: str): + return next(c for c in CASES if c.id == case_id) + + +async def test_a_live_service_run_offers_the_ten_tools_alone_with_no_prompt_of_ours_and_scores_the_calls(): + picked = [case("3m-average"), case("will-it-rain"), case("hello"), case("pushback-cooler-this-week")] + model = ScriptedModel({"average temp 3m": [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})], + "will it rain later?": [("forecast", {})], # wrong: outlook + "Wrong. It was cooler this week": [("summary", {"period": "past week"})]}) + lines = [] + failed = await evalkit.run_service(picked, EXPECT, model, "m", out=lines.append) + assert failed == 1 + text = "\n".join(lines) + assert "1/1 3m-average" in text and "0/1 FAIL will-it-rain" in text and "did not call outlook (called: forecast)" in text + assert "1/1 hello" in text and "1/1 pushback-cooler-this-week" in text + assert text.endswith("3 of 4 cases pass (the service's ten tools alone)") + first = model.requests[0] + assert [t["function"]["name"] for t in first["tools"]] == evalkit.service_tool_names() + assert first["tool_choice"] == "auto" and first["extra_body"] == {"reasoning": {"effort": evalkit.SERVICE_EFFORT}} + system = first["messages"][0] + assert system == {"role": "system", "content": evalkit.service_system()} + assert system["content"] == ("You answer questions about a home weather station and air sensor using the tools.\n" + "Now: Tuesday 29 September 2026, 14:05 (Australia/Melbourne time).") + assert first["messages"][1:] == [{"role": "user", "content": "average temp 3m"}] + follow_up = next(r for r in model.requests if r["messages"][-1].get("content") == "Wrong. It was cooler this week") + assert [m["role"] for m in follow_up["messages"]] == ["system", "user", "assistant", "user"] # (the case's history, as it was) + + +async def test_without_a_model_the_service_run_checks_only_the_expectations(): + lines = [] + assert await evalkit.run_service(CASES, EXPECT, out=lines.append) == 0 + assert lines[-1] == f"\n{len(CASES)} of {len(CASES)} cases pass (the service's ten tools alone)" + assert await evalkit.run_service([case("hello")], {}, out=lines.append) == 1 and "no service expectation" in lines[-2] + + +def script(*args: str, key: str | None = None) -> subprocess.CompletedProcess: + env = {k: v for k, v in os.environ.items() if not k.startswith("OPENROUTER_")} + if key: + env["OPENROUTER_API_KEY"] = key + return subprocess.run([sys.executable, str(ROOT / "scripts" / "eval_prompts.py"), *args], capture_output=True, text=True, env=env, + cwd=ROOT, timeout=120) + + +def test_the_script_runs_the_service_evals_offline_and_needs_a_key_to_ask_a_model(): + run = script("--service", "--ids", "3m-average,hello") + assert run.returncode == 0 and "2 of 2 cases pass (the service's ten tools alone)" in run.stdout + run = script("--live", "--service") + assert run.returncode != 0 and "--live needs OPENROUTER_API_KEY" in run.stderr From 8a166bfaa13fa7639751d8f2a4974c73a987e1c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 05:49:00 +0000 Subject: [PATCH 035/125] Step 2: the bot's own code paths call the service's ten tools - lib/service/__init__.py: build(ctx), the ten in 3.3's order, and Service (by name). ecobot.py builds them over Context.open once the sources have started and hands them to the bot (not to the model); about's RAIN_QUIET_HOURS and ALERT_COOLDOWN_MINUTES are set from the config. - lib/service/legacy.py: the old tool call and the Turn's code-decided inputs read as the service's call, in one place (step 3 deletes it whole). - lib/bot.py: charts made in code, lookups, the report and "weather now", Help, alert charts, period buttons, the preload and the charts drawn ahead all call the service and quote its words; charts are drawn from their JSON. The picture cache is keyed by the call. Period buttons come from drawn_by.periods and replay drawn_by with the period pressed; a refused replay shows its refusal on the button. Charts the model draws through the old tools get a drawn_by by translation, else keep the question replay. - lib/service/common.py: chart_points "drawn" (unbucketed) for a client that draws for itself (the bot). - lib/service/summary.py: a period that runs to now is read by the engines to now, as before. - lib/report.py keeps only what the model path needs; the old words stay as the tests' oracle. - tests/test_service_switch.py: unchanged answers, and an assertion for each deliberate change; the recording was redone on the code before the switch (65af2eb) once the fake world was made consistent (no indoor humidity in the live reading, no background refresh racing the answer). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 7 +- ecobot.py | 12 +- lib/alerts/pictures.py | 92 +++++--- lib/bot.py | 410 ++++++++++++++++++++++++--------- lib/periods.py | 147 ++++++++---- lib/report.py | 206 ++--------------- lib/service/__init__.py | 51 +++- lib/service/common.py | 16 +- lib/service/context.py | 2 +- lib/service/legacy.py | 192 +++++++++++++++ lib/service/summary.py | 13 +- lib/tools.py | 7 +- tests/fakes.py | 39 +++- tests/report_words.py | 324 ++++++++++++++++++++++++++ tests/service_switch.json | 24 +- tests/test_alert_menu.py | 37 +-- tests/test_bot.py | 147 ++++-------- tests/test_dashboard.py | 28 +-- tests/test_periods.py | 331 ++++++++++++++++---------- tests/test_pollen.py | 2 +- tests/test_report.py | 160 +------------ tests/test_service_current.py | 2 +- tests/test_service_days.py | 2 +- tests/test_service_forecast.py | 2 +- tests/test_service_legacy.py | 83 +++++++ tests/test_service_pollen.py | 2 +- tests/test_service_summary.py | 2 +- tests/test_service_switch.py | 93 +++++++- 28 files changed, 1602 insertions(+), 831 deletions(-) create mode 100644 lib/service/legacy.py create mode 100644 tests/report_words.py create mode 100644 tests/test_service_legacy.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 22f12c3a..9a44ed5f 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -471,7 +471,12 @@ Each step ships on its own, with the tests and evals green and the bot working t service labels them, and none when it lists none (today every single chart gets all five, so a count per month offers a 1D that draws nothing); a replay the service still refuses shows its error on the button. Begun: what the tools share, in `lib/service/` (`common.py`: a tool and its request metadata, answers, refusals, periods, chart - data; `names.py`: the reading names and the words for them; `daylook.py`: a day's look by its rule). + data; `names.py`: the reading names and the words for them; `daylook.py`: a day's look by its rule). Done: the ten, registered + (`lib/service/__init__.py` `build`, `Service`), built in `ecobot.py` and handed to the bot; the bot's own code paths call them, + through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in + step 3), and quote their words; its answers pinned before and after (`tests/test_service_switch.py`). The bot asks for its charts + as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. Left + for later: the dashboard's gauges still read `Ecowitt.dashboard()` (its sheet is the client's layout, which `current` doesn't give). 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. diff --git a/ecobot.py b/ecobot.py index a71d5365..b1b84837 100644 --- a/ecobot.py +++ b/ecobot.py @@ -37,7 +37,10 @@ from lib.llm import Agent from lib.logs import BUGS, LogFormat, on_journal, stream_handlers from lib.pollen import Pollen +from lib.service import Service +from lib.service import about as service_about from lib.service import names as service_names +from lib.service.context import Context from lib.compose import Composer from lib.history import History from lib.sources import Source @@ -228,6 +231,8 @@ async def main(): air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive service_names.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like # "all" (and "weather all week") draws these too service_names.VPD_IN_ALL = cfg.chart_all_vpd + service_about.RAIN_QUIET_HOURS = cfg.rain_quiet_hours # what `about` says of the rain alert's quiet hours ... + service_about.ALERT_COOLDOWN_MINUTES = cfg.alert_cooldown_minutes # ... and of the alerts' cooldown # Whatever starts is closed on the way out, the last started first, however the bot stops (a failure part-way included) async with contextlib.AsyncExitStack() as stack: app = (Application.builder().token(cfg.telegram_token).concurrent_updates(True) @@ -264,7 +269,12 @@ async def main(): if irrigation: stack.push_async_callback(safely, irrigation.close) tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, tools), sources, state, irrigation, tasks) + # The service's ten tools over the sources that started (lib/service): the bot's own code paths call them (its shortcuts, lookups, + # report, alert charts and period buttons); the model is still offered the old tools above, until step 3 + service = Service.of(await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), + pollen=by_name.get("Pollen"), tz=cfg.tz)) + log.info("Service tools: %s", ", ".join(t.name for t in service)) + bot = Bot(cfg, Agent(client, cfg.openrouter_model, tools), sources, state, irrigation, tasks, service=service) bot.register(app) stop = asyncio.Event() diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index 2bc4f6f9..f70963b4 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -1,16 +1,19 @@ """The chart that goes with an alert: the same picture a typed request for it would give ("Wind chart 1d" is what the Wind button sends), so what an -alert shows is defined once, by the button sentences and lib/intent. AlertCharts keeps those charts with the bot's other charts (the ImageCache), -so one is drawn once and uploaded once however many times it is sent.""" +alert shows is defined once, by the button sentences, which the bot reads as a service call (lib/intent, lib/service/legacy.py: "Wind chart 1d" is +summary over the wind for the last 24 hours) and the service draws. AlertCharts keeps those charts with the bot's other charts (the ImageCache, +by call), so one is drawn once and uploaded once however many times it is sent.""" import asyncio +import json import logging import time -from datetime import datetime, timezone +from datetime import datetime, timezone, tzinfo from typing import Callable, NamedTuple from .. import intent from ..charts import render_data -from ..specs import to_json +from ..periods import call_key +from ..specs import from_json from ..timeutil import now_local from ..tools import Turn @@ -18,6 +21,7 @@ # The alert types that carry a chart, and the request it answers: what the alert is sent with, and what its Refresh draws again CHARTS = {"gusts": "Wind chart 1d", "uv": "UV chart 1d", "temps": "Temperature chart 1d", "particulates": "Particulates chart 1d"} +CHART_POINTS = "drawn" # every point, as drawn (lib/service/common.py AS_DRAWN): the bot draws the chart itself class Picture(NamedTuple): @@ -25,28 +29,50 @@ class Picture(NamedTuple): png: bytes title: str newest: int | None # the time of the newest reading it draws (epoch), when the chart tells it + drawn_by: dict | None = None # the call that draws it again -async def chart(source, text: str, tz) -> Picture | None: - """The chart for the request `text`, made from `source`'s tool the way the bot would answer it; None when it cannot be made (the alert then - goes out as text). `source` is the station or the air sensor: the tool is found in its `tools` by the name the request resolves to.""" +def call_of(text: str, now: datetime, tz: tzinfo) -> tuple[str, dict] | None: + """The service call a chart's request is read as (`now`: the station's local time), or None.""" + from ..service import legacy + if now.tzinfo is not None: + now = now.astimezone(tz).replace(tzinfo=None) + read = intent.read(text, now) + if not read.fast: + return None + return legacy.translate(read.fast[0], read.fast[1], Turn.of(read, text), now=now, tz=tz) + + +def _service_of(source, tz): + """The service's tools over one source (the station or the air sensor), for a monitor that has only its source.""" + from ..service import Service + from ..service.context import Context + name = getattr(source, "name", "") + return Service.of(Context(eco=source if name == "Ecowitt" else None, air=source if name == "AirGradient" else None, tz=tz)) + + +async def chart(source, text: str, tz, service=None) -> Picture | None: + """The chart for the request `text`, drawn by the service the way the bot would answer it; None when it cannot be made (the alert then + goes out as text). `source` is the station or the air sensor; `service` the service's tools (the bot's), else built over `source`.""" try: - now = now_local(tz) - read = intent.read(text, now) - tool, args = read.fast[0], read.fast[1] - turn = Turn.of(read, text) - handler = next(t for t in source.tools if t.name == tool).handler - await handler(args, turn) - spec = turn.charts[0] - return Picture(await asyncio.to_thread(render_data, to_json(spec, tz), tz), spec.caption(now.date()), spec.newest) + tool, args = call_of(text, now_local(tz), tz) + service = service or _service_of(source, tz) + if isinstance(args.get("readings"), list): # (those the service holds: a side the station has nothing of is left out) + args = {**args, "readings": service.held(args["readings"]) or args["readings"]} + out = json.loads(await service[tool].call(args, {"chart_points": CHART_POINTS})) + if "error" in out: + raise ValueError(out["error"]) + data = out["charts"][0] + spec = from_json(data) + return Picture(await asyncio.to_thread(render_data, data, tz), spec.caption(now_local(tz).date()), spec.newest, data.get("drawn_by")) except Exception as e: log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) return None class AlertCharts: - """The charts alerts carry (CHARTS), kept in the bot's ImageCache under their request's key (the keyboard's "Wind chart 1d" is the same - chart), so each is drawn once and uploaded once: + """The charts alerts carry (CHARTS), kept in the bot's ImageCache under the call their request is read as (the keyboard's "Wind chart + 1d" is the same chart), so each is drawn once and uploaded once: - an alert sends the chart the bot holds when it has the alert's data (drawn with the newest reading the alert is about, `since`, or a later one): Telegram's copy once it has been sent, to this chat or another, or by a button; else its chart is drawn and kept, and Telegram's copy remembered from the first chat it goes to; @@ -56,21 +82,27 @@ class AlertCharts: WARM_SECONDS = 6 * 3600 - def __init__(self, images, now: Callable[[], datetime], clock: Callable[[], float] = time.monotonic): - """images: the bot's ImageCache. now: the local time (for the requests' keys). clock: the seconds the warm time is counted in.""" - self.images, self.now, self.clock = images, now, clock - self.alerted: dict[str, float] = {} # request -> the clock when an alert carrying its chart last went out + def __init__(self, images, now: Callable[[], datetime], clock: Callable[[], float] = time.monotonic, tz: tzinfo | None = None): + """images: the bot's ImageCache. now: the local time (for the requests' calls). clock: the seconds the warm time is counted in. + tz: the station's zone (default: now()'s own).""" + self.images, self.now, self.clock, self.tz = images, now, clock, tz + self.alerted: dict[str, float] = {} # alert type -> the clock when an alert carrying its chart last went out + + def call(self, kind: str) -> tuple[str, dict] | None: + """The service call an alert type's chart is drawn by; None for a type without one.""" + text, now = CHARTS.get(kind), self.now() + return call_of(text, now, self.tz or now.tzinfo) if text else None def key(self, kind: str) -> str | None: - """The image key of an alert type's chart; None for a type without one.""" - text = CHARTS.get(kind) - return self.images.canonical(text, self.now()) if text else None + """The image key of an alert type's chart (its call); None for a type without one.""" + call = self.call(kind) + return call_key(*call) if call else None - def warm(self) -> list[str]: - """The requests whose charts are kept drawn ahead: those of the alert types sent in the last WARM_SECONDS.""" + def warm(self) -> list[tuple[str, dict]]: + """The calls whose charts are kept drawn ahead: those of the alert types sent in the last WARM_SECONDS.""" now = self.clock() - self.alerted = {text: at for text, at in self.alerted.items() if now - at <= self.WARM_SECONDS} - return list(self.alerted) + self.alerted = {kind: at for kind, at in self.alerted.items() if now - at <= self.WARM_SECONDS} + return [call for kind in self.alerted if (call := self.call(kind))] def held(self, kind: str, since: int | None) -> bytes | str | None: """The chart the bot holds for an alert of `kind` when it draws the alert's data (its newest reading is `since` or later): Telegram's @@ -81,14 +113,14 @@ def held(self, kind: str, since: int | None) -> bytes | str | None: def keep(self, kind: str, picture: Picture, since: int | None = None): """A chart just drawn for an alert of `kind` (about the reading `since`: it draws that reading, whatever its own time says).""" newest = max((t for t in (picture.newest, since) if t is not None), default=None) - self.images.put(self.key(kind), picture.png, picture.title, newest=newest) + self.images.put(self.key(kind), picture.png, picture.title, newest=newest, drawn_by=picture.drawn_by) def sent(self, kind: str, message, alerted: bool = True): """The chart of `kind` went out in `message` (as Telegram returned it): later sends use Telegram's copy. An alert (not a Refresh) starts the WARM_SECONDS its chart is drawn ahead for.""" self.images.sent(self.key(kind), message) if alerted: - self.alerted[CHARTS[kind]] = self.clock() + self.alerted[kind] = self.clock() def newer_than(self, kind: str, message) -> bytes | str | None: """What the Refresh under `message` can send without drawing: the held chart of `kind` when it was drawn since the message was last diff --git a/lib/bot.py b/lib/bot.py index 11fbea7a..489af250 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -30,7 +30,11 @@ from .irrigation import menu as irrigation_menu from . import gauges from .charts import render_data -from .specs import to_json +from .service import Service +from .service import legacy +from .service.common import AS_DRAWN, BACKGROUND +from .service.context import Context +from .specs import from_json, to_json from .ecowitt.dashboard import STATUS from .ecowitt.query import chart_field, stack_names from .tools import Turn @@ -62,6 +66,7 @@ NOT_ADMIN_TOAST = "Only group admins can use this bot" STALE_BUTTON = "That button is out of date, please ask again" MAX_CALLBACK_BYTES = 64 # Telegram's own limit on a button's data +TOAST_LIMIT = 200 # ... and on the text a button's answer shows HELP = ("Hi! Message me directly, or in groups @mention me or reply to me.\n" "/reset clears this chat's memory, /alerts opens the alert settings (buttons to subscribe or unsubscribe), /usage shows what I can do.\n" @@ -90,6 +95,16 @@ class Answer: ready: periods.Drawn | None = None # a chart drawn moments ago, sent as it is made: float | None = None # seconds the tool took to make the chart in code, for the timing line ok: bool = True # False: the reply says something went wrong + charts: list[dict] = field(default_factory=list) # the charts a service tool drew, as data (each with its drawn_by), still to draw + drawn_by: list = field(default_factory=list) # each photo's drawn_by (the call that draws it again), None for one with none + key: str | None = None # the call a chart made in code was read as (periods.call_key): the picture cache's key + + +@dataclass +class Made: + """What a service tool gave for a question answered in code: its words (a caption, an answer, lines) and its charts as data.""" + text: str | None + charts: list[dict] = field(default_factory=list) async def answer_query(query, *args, **kwargs) -> bool: @@ -390,11 +405,15 @@ async def close(self): class Bot: - def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None): + def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None, + service: Service | None = None): """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); - its own when none is given.""" + its own when none is given. service: the service's tools (lib/service), which the bot's own code paths call (its shortcuts, + lookups, report, alert charts and period buttons); built over `sources` when none is given. The model is offered the old + tools (agent.tools), not these, until step 3.""" self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation + self._service = service self.tasks = tasks or Tasks() self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends self.keyboard_version = templates.version(irrigation is not None) @@ -404,11 +423,94 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler self.chats: dict[tuple, ChatState] = defaultdict(ChatState) self.by_name = {s.name: s for s in sources} self.images = periods.ImageCache() # charts drawn lately, so toggling the period buttons is instant - self.alert_charts = pictures.AlertCharts(self.images, lambda: now_local(self.cfg.tz)) # the alerts' charts, kept with them - self.preloading: set[str] = set() # questions whose other periods are being uploaded (TELEGRAM_PRELOAD_CHAT) + self.alert_charts = pictures.AlertCharts(self.images, lambda: now_local(self.cfg.tz), + tz=getattr(cfg, "tz", None)) # the alerts' charts, kept with them + self.preloading: set[str] = set() # the calls whose other periods are being uploaded (TELEGRAM_PRELOAD_CHAT) self.last_used = 0.0 # when a message or a press last came in (monotonic; 0: never) self.preload_off = False # Telegram refused an upload to that chat (not a flood limit or a timeout): no more are tried until restart - self.charted = periods.Charted(state.charts, state.save) # the question behind each chart sent (kept across restarts) + self.charted = periods.Charted(state.charts, state.save) # the call behind each chart sent (kept across restarts) + + @property + def service(self) -> Service: + """The service's tools over the bot's sources (built on first use when none was given).""" + if self._service is None: + get = self.by_name.get + self._service = Service.of(Context(eco=get("Ecowitt"), air=get("AirGradient"), forecast=get("Forecast"), pollen=get("Pollen"), + tz=getattr(self.cfg, "tz", None))) + return self._service + + # ---------- the service's tools, as the bot calls them ---------- + async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dict: + """A service tool's answer as data: its charts as drawn (AS_DRAWN, so its pictures are as they were), + a chart drawn ahead (nobody waiting) as a background request. {"error": ...} when it refuses or fails.""" + found = self.service.get(tool) + if found is None: + return {"error": f"There is no {tool} here."} + meta = {"chart_points": AS_DRAWN, **({"priority": BACKGROUND} if ahead else {})} + log.debug("Service call %s %s", tool, json.dumps(args, ensure_ascii=False), extra=QUOTES) + try: + out = json.loads(await found.call(args, meta)) + except Exception as e: + log.error("Service tool %s failed: %s: %s", tool, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + return {"error": f"{type(e).__name__}: {e}"} + return out if isinstance(out, dict) else {"error": "not an answer"} + + def _call_of(self, read, turn: Turn, now: datetime) -> tuple[str, dict] | None: + """The service's call for the fast path's old tool call (lib/service/legacy.py), or None.""" + if not read.fast: + return None + try: + return self._held_call(legacy.translate(read.fast[0], read.fast[1], turn, now=now, tz=self.cfg.tz)) + except Exception as e: + log.error("Couldn't read %s as a service call (%s: %s)", read.fast[0], type(e).__name__, e, exc_info=isinstance(e, BUGS)) + return None + + def _held_call(self, call: tuple[str, dict] | None) -> tuple[str, dict] | None: + """The call with its readings (full names) cut to those the service holds: the old tools read whichever groups the station has, + so "temperature" was outdoor and indoor, and a side with nothing held was left out quietly.""" + if call is None or call[0] != "summary" or not isinstance(call[1].get("readings"), list): + return call + held = self.service.held(call[1]["readings"]) + return (call[0], {**call[1], "readings": held}) if held else call + + def _model_drawn_by(self, turn: Turn, i: int, now: datetime) -> dict | None: + """A drawn_by for the i-th chart the model drew through the old tools (it has none of its own until step 3): its call read as the + service's, with the periods that tool would list; None when the call has no service equivalent (its question is asked again).""" + if i >= len(turn.chart_calls): + return None + name, args = turn.chart_calls[i] + try: + call = self._held_call(legacy.translate(name, args if isinstance(args, dict) else {}, turn, now=now, tz=self.cfg.tz)) + except Exception as e: + log.debug("The model's %s chart has no service call (%s: %s)", name, type(e).__name__, e) + return None + if call is None or call[0] not in ("summary", "days"): + return None + tool, arguments = call[0], {k: v for k, v in call[1].items() if k != "chart_answers_it"} + if tool == "summary": + arguments["chart"] = True + return {"tool": tool, "arguments": arguments, "periods": legacy.periods_of(tool, arguments)} + + def _sentence_call(self, text: str, now: datetime) -> tuple[str, dict] | None: + """The call a question is read as when it is a chart made in code ("Wind chart 1d"); None for any other.""" + read = intent.read(text, now, self.by_name) + return self._call_of(read, Turn.of(read, text), now) if read.chart_in_code else None + + def _draw(self, chart: dict, times: dict | None = None) -> tuple[bytes, str, int]: + """(PNG, title, the time of its newest reading) of a chart given as data.""" + spec = from_json(chart) + return render_data(chart, self.cfg.tz, times), spec.caption(now_local(self.cfg.tz).date()), spec.newest + + async def _draw_call(self, tool: str, args: dict, ahead: bool = True) -> tuple[bytes, str, str | None, int, dict | None, dict] | None: + """(PNG, title, its words, newest reading, drawn_by, the answer) of the chart a call draws; None when it draws none (the refusal + logged).""" + out = await self._service_call(tool, args, ahead=ahead) + charts = out.get("charts") or [] + if "error" in out or len(charts) != 1: + log.debug("No chart from %s %s: %s", tool, args, out.get("error")) + return None + png, title, newest = await asyncio.to_thread(self._draw, charts[0]) + return png, title, out.get("caption") or out.get("answer"), newest, charts[0].get("drawn_by"), out def register(self, app): app.add_handler(CommandHandler(["start", "help"], self.on_start)) @@ -563,7 +665,8 @@ async def on_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): async def _help_and_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """What the bot can do, then the alert settings: the Help & Alerts button and /usage.""" - await update.effective_message.reply_text(templates.capabilities_text(self.by_name)) + about = await self._service_call("about", {}) + await update.effective_message.reply_text("\n".join(about.get("lines") or []) or templates.capabilities_text(self.by_name)) await self.on_alerts(update, context) async def on_usage(self, update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -653,7 +756,7 @@ async def _redraw_alert(self, query, kind: str): photo, drawn = self.alert_charts.newer_than(kind, message), False if photo is None: try: - picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz), TURN_SECONDS) + picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz, self.service), TURN_SECONDS) except TimeoutError: picture = None if picture is None: # (pictures.chart has said why) the message stays as it was @@ -833,12 +936,18 @@ async def _recaption(query, text: str, photo: bytes | None): await _edit_quietly(query.edit_message_caption(caption=body, caption_entities=ents or None, reply_markup=report_menu.keyboard())) async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): - """A press on 1D / 7D / 1M / 3M / 1Y under a chart: ask the chart's question again for that period and put the new chart - in the same message.""" + """A press on a period button under a chart: the chart's call (its drawn_by) replayed with that period, by the service, and the + new chart put in the same message (from the picture cache when it was drawn lately). A replay the service refuses shows its + refusal on the button. A chart the service can't replay (one the model drew with a call it has no equivalent of) asks its + question again for that period instead.""" query = update.callback_query - days = periods.days_in(query.data) message = query.message - question = self.charted.get(message.chat_id, message.message_id) if days and message else None + record = self.charted.get(message.chat_id, message.message_id) if message else None + if isinstance(record, dict) and record.get("drawn_by"): + await self._replay(query, message, record, context.bot) + return + days = periods.days_in(query.data) + question = record if isinstance(record, str) and days else None if not question: await answer_query(query, "That chart is out of date, please ask again") return @@ -849,23 +958,60 @@ async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_T await answer_query(query, f"Drawing {periods.NAMES[days]}...") asked = intent.with_period(question, days, now) log.debug("Period button %s: %s", periods.NAMES[days], question, extra=QUOTES) - key = self.images.key(asked, days, now) - if cached := self.images.get(key): # drawn lately: no new question - photo, title = cached + await self.respond(update, context, asked, redraw=message) + + async def _replay(self, query, message: Message, record: dict, bot): + """A period button under a chart the service drew: its drawn_by replayed with the period pressed, into the same message.""" + drawn_by, words = record["drawn_by"], bool(record.get("words")) + period = periods.period_in(query.data) + listed = {p["period"]: p["label"] for p in drawn_by.get("periods") or ()} + if period not in listed: + await answer_query(query, "That chart is out of date, please ask again") + return + now = now_local(self.cfg.tz) + if periods.own_period(drawn_by, now, self.cfg.tz) == period: # the chart already shows this period + await answer_query(query) + return + tool, args = drawn_by["tool"], periods.with_period(drawn_by, period) + key = periods.call_key(tool, args) + log.debug("Period button %s: %s", listed[period], key, extra=QUOTES) + if (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: nothing is asked again + await answer_query(query, f"Drawing {listed[period]}...") began = time.monotonic() - if await self._redraw(message, "", photo, title, periods.keyboard(days), asked, key, TelegramError, "drawing it again"): - self.preload_soon(context.bot, asked) + row = periods.periods_keyboard(held.drawn_by, period) + if await self._redraw(message, (held.caption or "") if words else "", held.photo, held.title, row, + {"drawn_by": held.drawn_by, "words": words}, key, TelegramError, "drawing it again"): + self.preload_soon(bot, held.drawn_by) log.debug("Period button: cached chart sent in %.0f ms%s", (time.monotonic() - began) * 1000, - " (Telegram's copy)" if isinstance(photo, str) else "") + " (Telegram's copy)" if isinstance(held.photo, str) else "") return - await self.respond(update, context, asked, redraw=message) - - async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: str, row, question: str, key: str | None = None, + try: + out = await asyncio.wait_for(self._service_call(tool, args), TURN_SECONDS) + except TimeoutError: + out = {"error": "That took too long, please try again"} + charts = out.get("charts") or [] + if "error" in out or not charts: + await toast_quietly(query, fit(str(out.get("error") or "No chart came of it for that period"), TOAST_LIMIT)) + return + await answer_query(query, f"Drawing {listed[period]}...") + png, title, newest = await asyncio.to_thread(self._draw, charts[0]) + drawn = charts[0].get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} + text = out.get("caption") or out.get("answer") or "" + self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn) + row = periods.periods_keyboard(drawn, period) + if not await self._redraw(message, text if words else "", png, title, row, {"drawn_by": drawn, "words": words}, key): + sent = await deliver(message, text if words else "", [png], titles=[title], period_row=row) + if sent.photo: + self.charted.remember(message.chat_id, sent.photo.message_id, {"drawn_by": drawn, "words": words}) + self.images.sent(key, sent.photo) + self.preload_soon(bot, drawn) + + async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: str, row, record: str | dict, key: str | None = None, refused=BadRequest, then: str = "sending a new one") -> bool: """Put a new chart into the message a period button was pressed under (its answer text, if any, follows as a message of its own, unless it fits the caption: then the chart's caption is its title and the answer, as deliver sends them). False when Telegram refuses (an error of the `refused` kind, logged with what is done `then`): the chart is then sent as a new message, - or drawn again. key: where the image cache keeps it.""" + or drawn again. key: where the image cache keeps it. record: what drew it (periods.Charted), remembered for its buttons.""" text = strip_chart_talk(reply.strip()) fitted = caption_of(text, title) if text else None in_caption = fitted is not None @@ -877,7 +1023,7 @@ async def _redraw(self, message: Message, reply: str, photo: bytes | str, title: except refused as e: log.warning("Couldn't edit the chart in place (%s); %s", e, then) return False - self.charted.remember(message.chat_id, message.message_id, question) + self.charted.remember(message.chat_id, message.message_id, record) if text and not in_caption: await deliver(message, reply, []) return True @@ -1004,13 +1150,28 @@ def _content(self, msg: Message, text: str, bot_id: int) -> str: return f"{sender} ({reply}): {text}" if reply else f"{sender}: {text}" async def _written_in_code(self, read, turn: Turn) -> str: - """The report ("weather now") from the fast path's tool calls, made together; lib/report.py lays it out.""" - calls = [read.fast[:2], *read.more] - results = await self.agent.tools.call_all(calls, turn) - by_tool = {name: result for (name, _), result in zip(calls, results)} - if read.report: - return report.report(by_tool, now_local(self.cfg.tz).date()) - return report.weather_now(by_tool["weather_now"]) or "The weather station isn't answering right now." + """The report, or "weather now", in the service's words: the readings now (current: each device's heading and lines), then the + pollen's and the forecast's own text, the calls made together.""" + calls = legacy.report(self.by_name) if read.report else [("current", {})] + results = await asyncio.gather(*(self._service_call(name, args, ahead=turn.ahead) for name, args in calls)) + by_tool = {name: out for (name, _), out in zip(calls, results)} + now = by_tool.get("current") or {"error": "none"} + if not read.report: + if "error" in now or "station" in (now.get("unavailable") or {}) or not (now.get("lines") or {}).get("station"): + return "The weather station isn't answering right now." + return "\n".join(now["lines"]["station"]) + sections = [] if "error" in now else [ + "\n".join([now["headings"][device], *now["lines"][device]]) for device in ("station", "air") if device in now.get("lines", {})] + sections += [out["text"] for name in ("pollen", "forecast") if (out := by_tool.get(name)) and out.get("text")] + self._shown_forecast(by_tool.get("forecast"), turn) + return "\n\n".join(sections) or "No readings are available right now." + + def _shown_forecast(self, out: dict | None, turn: Turn): + """The forecast days an answer shows, remembered for the chat once it is sent (a later revision of them is worth telling it).""" + source = self.by_name.get("Forecast") + if source is not None and out and "error" not in out and out.get("days"): + shown = {day["date"] for day in out["days"]} + turn.forecast_shown.extend(d for d in source.days or [] if d["date"].isoformat() in shown) async def _report(self, read, turn: Turn, gauges: bool) -> tuple[str, bytes | None]: """The report (or "weather now") written in code and, with `gauges`, its picture drawn alongside (None without one), in TURN_SECONDS.""" @@ -1039,16 +1200,14 @@ async def _warn(self, msg: Message, tokens: int): with contextlib.suppress(TelegramError): await msg.reply_text(text) - async def _chart_in_code(self, read, turn: Turn) -> str | None: - """A chart asked for plainly: the tool draws it and the caption is written here. None (the model then takes the - question) when there is nothing to caption.""" - calls = [read.fast[:2], *read.more] - results = await self.agent.tools.call_all(calls, turn) - caption = report.chart_caption(read.fast[0], read.fast[1], results[0], turn, self.cfg.tz) - if caption is None: - turn.charts.clear() - turn.forecast_shown.clear() - return caption + async def _chart_in_code(self, call: tuple[str, dict] | None, turn: Turn) -> Made | None: + """A chart asked for plainly: the service tool the fast path's call means (summary, days ...) draws it and its caption (days: + its answer) goes with it. None (the model then takes the question) when it drew nothing or has nothing to say.""" + if call is None: + return None + out = await self._service_call(*call, ahead=turn.ahead) + text, charts = out.get("caption") or out.get("answer"), out.get("charts") or [] + return Made(text, charts) if "error" not in out and charts and text else None async def _dashboard(self, ecowitt) -> Answer: """The station's gauges as one picture, sent with just its title (no period buttons: it is the state now).""" @@ -1059,14 +1218,26 @@ async def _dashboard(self, ecowitt) -> Answer: title = f"Weather station dashboard, {day_text(now)} {clock_text(now)}" return Answer(title, [await asyncio.to_thread(gauges.render, sheet)], [title], silent=True) - async def _lookup_in_code(self, read, turn: Turn) -> str | None: - """A plain lookup (a reading, the air, the pollen, the forecast, what the bot can do) answered from its one tool result; None - (the model then takes the question) when it can't be.""" - if read.lookup == "about": - return templates.capabilities_text(self.by_name) - name, args = read.fast[:2] - result = await self.agent.tools.call(name, json.dumps(args), turn) - return report.lookup(read.lookup, result, read.lookup_arg, read.sides, now_local(self.cfg.tz).date()) + async def _lookup_in_code(self, read, turn: Turn, now: datetime) -> Made | None: + """A plain lookup (a reading, the air, a day's figures or a count, a short period's highs and lows, the pollen, the forecast, + what the bot can do) answered in its service tool's own words: current's lines, days' answer (with its chart, if it drew one), + summary's text, pollen's and forecast's text, about's lines. None (the model then takes the question) when it can't be.""" + call = legacy.lookup(read) or self._call_of(read, turn, now) + if call is None: + return None + out = await self._service_call(*call, ahead=turn.ahead) + if "error" in out: + return None + tool, kind = call[0], read.lookup + if tool == "current": + device = "air" if kind == "air" else "station" + lines = (out.get("lines") or {}).get(device) + return Made("\n".join(lines)) if lines and device not in (out.get("unavailable") or {}) else None + if tool == "about": + return Made("\n".join(out.get("lines") or []) or None) + if tool == "forecast": + self._shown_forecast(out, turn) + return Made(out.get("answer") or out.get("text") or None, out.get("charts") or []) def _chart_answer(self, turn: Turn): """The model loop's finish: when each call the model made in a step set chart_answers_it, drew its chart and can be captioned @@ -1116,64 +1287,52 @@ async def _ask_model(self, working: list[dict], system: str, read, turn: Turn, d working[:] = before # the unfinished attempt's turns are dropped effort, budget, retried = lower, RETRY_SECONDS, True - async def _draw_ahead(self, text: str, now) -> tuple[str, bytes, str, str, int] | None: - """(image key, PNG, title, write-up, the time of the newest reading drawn) of the chart `text` asks for when it is one made in code - with its own words as its key; None otherwise. Raises when it can't be drawn. Nobody is waiting: its requests are not urgent and its - logs are quiet.""" - read = intent.read(text, now, self.by_name) - key = self.images.canonical(text, now) - if not (read.chart_in_code and key): # not a chart made in code ("Report"), or a source that isn't there - return None - turn = Turn.of(read, text, ahead=True) - caption = await asyncio.wait_for(self._chart_in_code(read, turn), TURN_SECONDS) - if caption is None or len(turn.charts) != 1: - raise ValueError("no chart came of it") - png = await asyncio.to_thread(render_data, to_json(turn.charts[0], self.cfg.tz), self.cfg.tz) - return key, png, turn.charts[0].caption(now.date()), caption, turn.charts[0].newest - - def preload_soon(self, bot, question: str): - """With TELEGRAM_PRELOAD_CHAT set, upload the other periods of this chart's question in the background.""" + def preload_soon(self, bot, drawn_by: dict | None): + """With TELEGRAM_PRELOAD_CHAT set, upload the chart of each other period its drawn_by lists, in the background.""" chat = getattr(self.cfg, "telegram_preload_chat", None) - if chat is None or self.preload_off or question in self.preloading: + key = periods.drawn_key(drawn_by) + if chat is None or self.preload_off or not drawn_by or not drawn_by.get("periods") or key in self.preloading: return - self.preloading.add(question) - self.tasks.start(self.preload(bot, chat, question)) + self.preloading.add(key) + self.tasks.start(self.preload(bot, chat, drawn_by)) - async def preload(self, bot, chat: int, question: str): - """Upload (silently, to `chat`) the chart for each other period of `question`, so a press of a period button edits the message by - Telegram's copy and uploads nothing. Nothing holds it back: each period is drawn and uploaded on its own, the moment it can be, - whatever else is being answered.""" + async def preload(self, bot, chat: int, drawn_by: dict): + """Upload (silently, to `chat`) the chart for each other period of a chart's drawn_by, each its call replayed with that period + (in the background: nobody is waiting), so a press of a period button edits the message by Telegram's copy and uploads nothing. + Nothing holds it back: each period is drawn and uploaded on its own, the moment it can be, whatever else is being answered.""" started, done, skipped = time.monotonic(), set(), [] + tool = drawn_by["tool"] try: - now = now_local(self.cfg.tz) - own = intent.period_days(question, now) - asked = {days: intent.with_period(question, days, now) for days in periods.PERIODS if days != own} - asked = {days: text for days, text in asked.items() if not self.images.has_copy(self.images.key(text, days, now))} + own = periods.own_period(drawn_by, now_local(self.cfg.tz), self.cfg.tz) + asked = {p["period"]: periods.with_period(drawn_by, p["period"]) for p in drawn_by.get("periods") or () if p["period"] != own} + asked = {p: args for p, args in asked.items() if not self.images.has_copy(periods.call_key(tool, args))} - async def upload(days, text): + async def upload(period, args): + key = periods.call_key(tool, args) try: - drawn = await self._draw_ahead(text, now) + drawn = await asyncio.wait_for(self._draw_call(tool, args), TURN_SECONDS) except Exception as e: - log.debug("Couldn't draw %r to preload: %s: %s", text, type(e).__name__, e) + log.debug("Couldn't draw %s to preload: %s: %s", key, type(e).__name__, e) return if drawn is None: return - key, png, title, caption, newest = drawn - self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest) + png, title, caption, newest, by, _ = drawn + self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest, drawn_by=by) if self.preload_off: # an upload was refused meanwhile return if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: skipped.append(why) elif not self.preload_off: - done.add(days) + done.add(period) - await asyncio.gather(*(upload(days, text) for days, text in asked.items())) + await asyncio.gather(*(upload(period, args) for period, args in asked.items())) if skipped: log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) if done: - log.info("[Telegram] Preloaded %r to %s in %.1fs", intent.without_period(question, now), chat, time.monotonic() - started, extra=QUOTES) + log.info("[Telegram] Preloaded %s %s to %s in %.1fs", tool, json.dumps(periods.with_period(drawn_by, "…"), ensure_ascii=False), + chat, time.monotonic() - started, extra=QUOTES) finally: - self.preloading.discard(question) + self.preloading.discard(periods.drawn_key(drawn_by)) async def _upload_ahead(self, bot, chat: int, key: str, png: bytes, title: str) -> Exception | None: """Upload a chart drawn ahead to the preload chat, silently, and keep Telegram's copy under its key. Returns the flood limit or @@ -1190,28 +1349,29 @@ async def _upload_ahead(self, bot, chat: int, key: str, png: bytes, title: str) return None async def draw_buttons_ahead(self, bot): - """The chart of each keyboard button, and of each alert type sent in the last hours (alert_charts.warm), drawn afresh (every - AHEAD_SECONDS, from ecobot.warm_up), so a press, or the Refresh under the alert, is answered with a chart already drawn - (images.ready, AlertCharts.newer_than) instead of drawing one then; with TELEGRAM_PRELOAD_CHAT set and the bot used in the last - 15 minutes, uploaded too, so the press sends Telegram's copy and uploads nothing. A chart drawn for a question in the last minute is left. - Nobody is waiting: the requests are not urgent, and the logs are quiet.""" + """The chart of each keyboard button (each a fixed service call: the call its sentence is read as), and of each alert type sent in + the last hours (alert_charts.warm, by their calls), drawn afresh (every AHEAD_SECONDS, from ecobot.warm_up), so a press, or the + Refresh under the alert, is answered with a chart already drawn (images.ready, AlertCharts.newer_than) instead of drawing one + then; with TELEGRAM_PRELOAD_CHAT set and the bot used in the last 15 minutes, uploaded too, so the press sends Telegram's copy and + uploads nothing. A chart drawn for a question in the last minute is left. Nobody is waiting: the requests are background ones, + and the logs are quiet.""" started, now = time.monotonic(), now_local(self.cfg.tz) chat = getattr(self.cfg, "telegram_preload_chat", None) if self.used_lately else None drawn, uploaded, skipped = 0, 0, [] - texts = templates.chart_sentences(self.irrigation is not None) - for text in texts + [text for text in self.alert_charts.warm() if text not in texts]: - key = self.images.canonical(text, now) - if key is None or (age := self.images.age_of(key)) is not None and age < AHEAD_KEEP_SECONDS: + calls = [call for text in templates.chart_sentences(self.irrigation is not None) if (call := self._sentence_call(text, now))] + calls = list({periods.call_key(*call): call for call in [*calls, *self.alert_charts.warm()]}.items()) + for key, (tool, args) in calls: + if (age := self.images.age_of(key)) is not None and age < AHEAD_KEEP_SECONDS: continue try: - made = await self._draw_ahead(text, now) + made = await asyncio.wait_for(self._draw_call(tool, args), TURN_SECONDS) except Exception as e: - log.debug("Couldn't draw %r ahead: %s: %s", text, type(e).__name__, e) + log.debug("Couldn't draw %s ahead: %s: %s", key, type(e).__name__, e) continue - if made is None: # not a chart made in code, or its source is not there + if made is None: # it drew no chart (its source is not there) continue - key, png, title, caption, newest = made - self.images.put(key, png, title, caption, newest=newest) + png, title, caption, newest, drawn_by, _ = made + self.images.put(key, png, title, caption, newest=newest, drawn_by=drawn_by) drawn += 1 if chat is not None and not self.preload_off: if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: @@ -1265,10 +1425,19 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text | {intent.TOOL_TOPICS[t] for t in tools_used if t in intent.TOOL_TOPICS} | ({"air_extra"} if turn.air_extra_used else set())) chat.history = shorten_old(trim_history(strip_tool_turns(working))) - for spec in turn.charts[:MAX_CHARTS]: # drawn (from its JSON, as a tool will hand it over) while "typing..." is still showing + for chart in answer.charts[:MAX_CHARTS]: # a service tool's charts, drawn from their data while "typing..." is still showing + try: + png, title, _ = await asyncio.to_thread(self._draw, chart, turn.times) + answer.photos.append(png) + answer.titles.append(title) + answer.drawn_by.append(chart.get("drawn_by")) + except Exception as e: + log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + for i, spec in enumerate(turn.charts[:MAX_CHARTS - len(answer.photos)]): # the model's (old tools): drawn from their JSON too try: answer.photos.append(await asyncio.to_thread(render_data, to_json(spec, self.cfg.tz), self.cfg.tz, turn.times)) answer.titles.append(spec.caption(now.date())) + answer.drawn_by.append(self._model_drawn_by(turn, i, now)) except Exception as e: log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) except TimeoutError: @@ -1287,16 +1456,20 @@ async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], dra """The answer, from the first way that gives one: a chart drawn moments ago, a chart made in code, a lookup, the report written in code, else the model. `working` is the conversation, the question last; the answer joins it.""" shown = bool(intent.HILO.search(turn.text)) # "when was CO2 highest": the answer is a chart's figures, so they go with it - if read.chart_in_code and redraw is None and (ready := self.images.ready(turn.text, now)): - answer = Answer(ready.caption, [ready.photo], [ready.title], silent=not shown or not ready.caption, ready=ready) # drawn ahead, or for someone's same question - elif read.chart_in_code: # drawn by the tool; the chart goes out with just its title (the text is kept for the history) + call = self._call_of(read, turn, now) if read.chart_in_code else None # the service's call the chart is (its cache key) + key = periods.call_key(*call) if call else None + if read.chart_in_code and redraw is None and (ready := self.images.ready(key)): # drawn ahead, or for someone's same call + answer = Answer(ready.caption, [ready.photo], [ready.title], silent=not shown or not ready.caption, ready=ready, + drawn_by=[ready.drawn_by], key=key) + elif read.chart_in_code: # drawn by the service; the chart goes out with just its title (the text is kept for the history) began = time.monotonic() - reply = await asyncio.wait_for(self._chart_in_code(read, turn), TURN_SECONDS) - answer = Answer(reply, silent=reply is not None and not shown, made=time.monotonic() - began if reply is not None else None) + made = await asyncio.wait_for(self._chart_in_code(call, turn), TURN_SECONDS) + answer = Answer(made.text, silent=not shown, made=time.monotonic() - began, charts=made.charts, key=key) if made else Answer() elif read.dashboard and "Ecowitt" in self.by_name: answer = await asyncio.wait_for(self._dashboard(self.by_name["Ecowitt"]), TURN_SECONDS) elif read.lookup: - answer = Answer(await asyncio.wait_for(self._lookup_in_code(read, turn), TURN_SECONDS)) + made = await asyncio.wait_for(self._lookup_in_code(read, turn, now), TURN_SECONDS) + answer = Answer(made.text, charts=made.charts) if made and made.text else Answer() if answer.reply is None: turn.forecast_shown.clear() elif read.fast and (read.report or read.weather_now): # written in code from the tools' results, no model (the report: with its gauges) @@ -1338,14 +1511,23 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added air = self.by_name.get("AirGradient") markup = templates.keyboard(self.irrigation is not None) if self._keyboard_stale(msg) else None refresh = answer.ok and read.report and 0 < len(reply) <= TG_LIMIT and not markup # the report, to be refreshed in place - row = periods.keyboard(intent.period_days(text, now)) if len(photos) == 1 and not (read.dashboard or read.report) else None # period buttons under a single chart + single = len(photos) == 1 and not (read.dashboard or read.report) # a single chart: its period buttons go under it + drawn_by = answer.drawn_by[0] if single and answer.drawn_by else None + if drawn_by: # the periods its call lists, the chart's own shaded; none when it lists none + row = periods.periods_keyboard(drawn_by, periods.own_period(drawn_by, now, self.cfg.tz)) + record = {"drawn_by": drawn_by, "words": bool(reply.strip())} + else: # a chart the service can't replay (the model's, through a call it has no equivalent of): its question asked again + row = periods.keyboard(intent.period_days(text, now)) if single else None + record = text drawn = list(photos) - kept = self.images.key(text, intent.period_days(text, now), now) if row and answer.ok and not reply.strip() else None - if kept and not answer.ready: # a chart and nothing else: keep it for the period buttons (and, its words being its key, for the next to ask them) - self.images.put(kept, photos[0], titles[0], caption if kept == self.images.canonical(text, now) else None) + kept = (answer.key or periods.drawn_key(drawn_by)) if single and answer.ok and (drawn_by or not reply.strip()) else None + if kept and not answer.ready: # kept for the period buttons, and (made in code) for the next to ask for the same call + self.images.put(kept, photos[0], titles[0], (caption or reply or None) if answer.key else None, drawn_by=drawn_by) + if kept and drawn_by and (own := periods.own_period(drawn_by, now, self.cfg.tz)): # ... and as its own button replays it + self.images.alias(kept, periods.call_key(drawn_by["tool"], periods.with_period(drawn_by, own))) try: began = time.monotonic() - if redraw is not None and row and await self._redraw(redraw, reply, photos[0], titles[0], row, text, kept): + if redraw is not None and row and await self._redraw(redraw, reply, photos[0], titles[0], row, record, kept): reply, photos, row = "", [], None sent = await deliver(msg, reply, photos, link=air.link if air and used_air else None, markup=markup or (report_menu.keyboard() if refresh else report_menu.dashboard_keyboard() @@ -1358,10 +1540,10 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added elif drawn: log.debug("Chart ms: %s", chart_times(turn.times, answer.made, drawn, time.monotonic() - began)) if sent.photo and row is not None: - self.charted.remember(msg.chat_id, sent.photo.message_id, text) + self.charted.remember(msg.chat_id, sent.photo.message_id, record) self.images.sent(kept, sent.photo) - if kept and read.chart_in_code: # a chart with period buttons, made in code: its other periods are uploaded ahead - self.preload_soon(bot, text) + if kept and row is not None and drawn_by and read.chart_in_code: # made in code: its other periods are uploaded ahead + self.preload_soon(bot, drawn_by) if answer.ok and turn.forecast_shown: # it was sent: a later revision of these days is worth telling this chat self.state.record_forecast(msg.chat_id, turn.forecast_shown, now_local(self.cfg.tz).date()) if carried_keyboard: diff --git a/lib/periods.py b/lib/periods.py index 8411a391..8711501b 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -1,40 +1,102 @@ -"""The period buttons under a chart: 1D, 7D, 1M, 3M and 1Y (1, 7, 30, 90 and 365 days), always all five, the chart's own shaded (the blue of an alert toggle that is on). Pressing one redraws the chart -for that period (Bot.on_period_button); the question behind each chart is remembered for that.""" +"""The period buttons under a chart, and the charts drawn lately. +A chart the service drew carries `drawn_by` (docs/mcp-service.md 3.7): the call that drew it and the periods it is worth drawing over, +each with its label ("7d", "7D"). Its buttons are those periods, the chart's own shaded (the blue of an alert toggle that is on), and +none when it lists none; a button's data is the period ("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one +replays the call with that period (Bot.on_period_button); what drew each chart is remembered for that (Charted). + +A chart the model drew through the old tools whose call has no service equivalent keeps the old buttons, 1D / 7D / 1M / 3M / 1Y (1, +7, 30, 90 and 365 days, "pd:7"), which ask its question again with that period.""" + +import json import time from collections import OrderedDict from dataclasses import dataclass +from datetime import datetime, tzinfo from telegram import InlineKeyboardMarkup - -from . import charts, intent from telegram.constants import KeyboardButtonStyle +from . import charts from .buttons import button -NAMES = {1: "1D", 7: "7D", 30: "1M", 90: "3M", 365: "1Y"} # each period, in days, and what its button says +NAMES = {1: "1D", 7: "7D", 30: "1M", 90: "3M", 365: "1Y"} # each period, in days, and what its button says (a question asked again) PERIODS = tuple(NAMES) PREFIX = "pd:" -REMEMBERED = 300 # charts whose question is kept, newest first to stay +REMEMBERED = 300 # charts whose call is kept, newest first to stay +WHOLE_DAY_TOOLS = ("days", "relate", "scan") # the tools that read a period as whole days, up to yesterday def keyboard(current: int | None = None) -> InlineKeyboardMarkup: - """The one row of period buttons; the one for the chart's own period (`current`, in days) is shaded.""" + """The old row of period buttons, for a question asked again; the one for the chart's own period (`current`, in days) is shaded.""" return InlineKeyboardMarkup([[button(NAMES[days], f"{PREFIX}{days}", KeyboardButtonStyle.PRIMARY if days == current else None) for days in PERIODS]]) def days_in(data: str | None) -> int | None: - """The period a button's callback data asks for, if it is one of ours.""" + """The period an old button's callback data asks for ("pd:7"), if it is one of ours.""" if not data or not data.startswith(PREFIX): return None days = data.removeprefix(PREFIX) return int(days) if days.isdigit() and int(days) in PERIODS else None +def period_in(data: str | None) -> str | None: + """The period a button under a service's chart asks for ("pd:7d" -> "7d").""" + return data.removeprefix(PREFIX) if data and data.startswith(PREFIX) and data != PREFIX else None + + +def call_key(tool: str, arguments: dict) -> str: + """A call as the picture cache keys it: the tool and its arguments as canonical JSON (sorted keys).""" + return f"{tool} {json.dumps(arguments, sort_keys=True, ensure_ascii=False, separators=(',', ':'))}" + + +def drawn_key(drawn_by: dict | None) -> str | None: + """The key of the call a chart's drawn_by states.""" + return call_key(drawn_by["tool"], drawn_by["arguments"]) if drawn_by else None + + +def with_period(drawn_by: dict, period: str) -> dict: + """The arguments of a chart's call with its period swapped for `period` (any start and end taken out).""" + return {**{k: v for k, v in drawn_by["arguments"].items() if k not in ("period", "start", "end")}, "period": period} + + +def own_period(drawn_by: dict, now: datetime, tz: tzinfo) -> str | None: + """Which of the chart's periods it was drawn over (its button is shaded): the one the service reads as the same span as its call's + period; None when none is.""" + from .periods_text import read_period + asked = (drawn_by.get("arguments") or {}).get("period") + if not asked: + return None + whole = drawn_by.get("tool") in WHOLE_DAY_TOOLS + + def span(words: str): + try: + read = read_period(words, None, None, now=now, tz=tz, default=words, whole_days=whole, first_held=now.date()) + except Exception: # (PeriodError, or words only a tool with the file can read) + return None + return read.start, read.end + own = span(asked) + for p in drawn_by.get("periods") or (): + if p["period"] == asked or own is not None and span(p["period"]) == own: + return p["period"] + return None + + +def periods_keyboard(drawn_by: dict, current: str | None = None) -> InlineKeyboardMarkup | None: + """One button for each period the chart's drawn_by lists, labelled as the service labels it, the chart's own (`current`) shaded; + None when it lists none.""" + listed = drawn_by.get("periods") or [] + if not listed: + return None + return InlineKeyboardMarkup([[button(p["label"], f"{PREFIX}{p['period']}", KeyboardButtonStyle.PRIMARY if p["period"] == current else None) + for p in listed]]) + + class Charted: - """{chat_id:message_id -> the question that drew that chart}, the newest REMEMBERED. With a `store` (a dict the alert state saves - to its file) the questions outlive a restart, so a chart's buttons keep working.""" + """{chat_id:message_id -> what drew that chart}, the newest REMEMBERED: {"drawn_by": the service's call, "words": whether its + caption carries the answer's text}, or the question (a string) for a chart whose call the service can't replay. With a `store` (a + dict the alert state saves to its file) they outlive a restart, so a chart's buttons keep working.""" def __init__(self, store: dict | None = None, save=None): self.store = store if store is not None else {} @@ -44,13 +106,13 @@ def __init__(self, store: dict | None = None, save=None): def _key(chat_id: int, message_id: int) -> str: return f"{chat_id}:{message_id}" - def get(self, chat_id: int, message_id: int) -> str | None: + def get(self, chat_id: int, message_id: int) -> str | dict | None: return self.store.get(self._key(chat_id, message_id)) - def remember(self, chat_id: int, message_id: int, question: str): + def remember(self, chat_id: int, message_id: int, record: str | dict): key = self._key(chat_id, message_id) self.store.pop(key, None) # re-added at the end: the newest - self.store[key] = question + self.store[key] = record while len(self.store) > REMEMBERED: del self.store[next(iter(self.store))] if self.save: @@ -64,10 +126,11 @@ class Drawn: png: bytes title: str file_id: str | None = None # Telegram's copy, once the chart has been sent: it is sent again by this, not uploaded - caption: str | None = None # the answer's text (kept in the chat's history), when it was made in code for exactly the key's words + caption: str | None = None # the answer's text (kept in the chat's history), when it was made in code ttl: float = 10 * 60 # how long it is kept (ImageCache.CHART_TTL; PRELOAD_TTL for one uploaded ahead) newest: int | None = None # the time of the newest reading it draws (epoch), when known: an alert about that reading can send it dark: bool = False # drawn in the dark theme: kept only while the charts are (a DARKMODE time range turns at its ends) + drawn_by: dict | None = None # the call that drew it, as the service states it @property def photo(self) -> bytes | str: @@ -75,37 +138,26 @@ def photo(self) -> bytes | str: class ImageCache: - """The charts drawn lately, by question: toggling between the period buttons brings a chart back at once instead of drawing it + """The charts drawn lately, by the call that drew them (call_key: the tool and its arguments), so two wordings of one chart, or two + chats asking for it, share one picture: toggling between the period buttons brings a chart back at once instead of drawing it again, and once it has been sent, as Telegram's copy instead of an upload. A chart is kept CHART_TTL seconds (the readings move - slowly) and the newest CHART_IMAGES stay. A chart drawn in the last FRESH - seconds is the answer to its question (ready).""" + slowly) and the newest CHART_IMAGES stay. A chart made in code in the last FRESH seconds is the answer to its call (ready). One + chart may be kept under several keys (alias): the call a question was read as, and the call the service says drew it.""" CHART_TTL = 10 * 60 CHART_IMAGES = 60 PRELOAD_TTL = 30 * 60 # a chart uploaded ahead (TELEGRAM_PRELOAD_CHAT) is used for this long, then drawn afresh - FRESH = 330 # a chart made in code this lately answers the same words again as it is (the readings move slowly) + FRESH = 330 # a chart made in code this lately answers the same call again as it is (the readings move slowly) def __init__(self, clock=None): self.clock = clock or time.monotonic self.items: OrderedDict = OrderedDict() - @staticmethod - def key(question: str, days: int, now) -> str: - """The question with its period made explicit, so "Temperature chart 30d" and a button's "…30d" are the one chart.""" - return intent.with_period(question, days, now).lower() - - @classmethod - def canonical(cls, question: str, now) -> str | None: - """The key of a question that is its own key, word for word ("Temperature chart 7d", a button's): its chart is the same - whoever asks it. None for any other ("temperature chart today" is kept under the 1d key, but it is another chart).""" - key = cls.key(question, intent.period_days(question, now), now) - return key if key == " ".join(question.split()).lower() else None - def _kept(self, entry: Drawn | None) -> bool: """Is there a chart, still within its time to live, in the theme charts are drawn in now?""" return entry is not None and self.age(entry) <= entry.ttl and entry.dark == charts.dark_now() - def get(self, key: str) -> tuple[bytes | str, str] | None: + def get(self, key: str | None) -> tuple[bytes | str, str] | None: """(the picture: Telegram's file id once it has been sent, else the PNG; its title), or None.""" entry = self.items.get(key) if not self._kept(entry): @@ -114,7 +166,7 @@ def get(self, key: str) -> tuple[bytes | str, str] | None: self.items.move_to_end(key) return entry.photo, entry.title - def age_of(self, key: str) -> float | None: + def age_of(self, key: str | None) -> float | None: """How long ago this chart was drawn, if it is held.""" entry = self.items.get(key) return self.age(entry) if self._kept(entry) else None @@ -124,15 +176,14 @@ def held(self, key: str | None) -> Drawn | None: entry = self.items.get(key) return entry if self._kept(entry) else None - def has_copy(self, key: str) -> bool: + def has_copy(self, key: str | None) -> bool: """Does Telegram hold this chart (drawn lately and already sent, so it has a file id)?""" entry = self.items.get(key) return self._kept(entry) and entry.file_id is not None - def ready(self, question: str, now) -> Drawn | None: - """The chart made in code for exactly these words in the last FRESH seconds (for someone's question, or uploaded ahead to + def ready(self, key: str | None) -> Drawn | None: + """The chart made in code for this call in the last FRESH seconds (for someone's question, or uploaded ahead to TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" - key = self.canonical(question, now) entry = self.items.get(key) if key else None if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != charts.dark_now(): return None @@ -142,11 +193,27 @@ def ready(self, question: str, now) -> Drawn | None: def age(self, entry: Drawn) -> float: return self.clock() - entry.at - def put(self, key: str, png: bytes, title: str, caption: str | None = None, ttl: float | None = None, newest: int | None = None): - """caption: the answer's text, only for a chart made in code for its canonical question (then it can be ready). - newest: the time of the newest reading drawn, when known.""" - self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, dark=charts.dark_now()) + def put(self, key: str | None, png: bytes, title: str, caption: str | None = None, ttl: float | None = None, newest: int | None = None, + drawn_by: dict | None = None): + """caption: the answer's text, only for a chart made in code (then it can be ready). newest: the time of the newest reading + drawn, when known. drawn_by: the call that drew it (it is kept under that call's key too).""" + if key is None: + return + self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, dark=charts.dark_now(), + drawn_by=drawn_by) self.items.move_to_end(key) + self._trim() + self.alias(key, drawn_key(drawn_by)) + + def alias(self, key: str | None, other: str | None): + """Keep the chart held under `key` under `other` too (one picture, one Telegram copy).""" + if key is None or other is None or key == other or (entry := self.items.get(key)) is None: + return + self.items[other] = entry + self.items.move_to_end(other) + self._trim() + + def _trim(self): while len(self.items) > self.CHART_IMAGES: self.items.popitem(last=False) diff --git a/lib/report.py b/lib/report.py index effeb37b..60bbb098 100644 --- a/lib/report.py +++ b/lib/report.py @@ -1,16 +1,17 @@ -"""The report (and "weather now") written in code from the tools' own results, with no model: the layout, units and emoji are all -decided here, so it is instant and always the same. Each tool result is JSON; one that failed or is missing is left out.""" +"""What the model path still needs written in code from the old tools' results, until the model gets the service's tools (docs/ +mcp-service.md 6, step 3): the caption of a chart that answers the question by itself (the bot's chart_answers_it finish on +weather_history, air_quality and the day tools), and the bold names of the report's headings. Everything the bot answers without the +model is the service's own words now (lib/service: current's lines, summary's caption and text, days' answer, the forecast's and the +pollen's text). Each tool result is JSON; one that failed or is missing gives nothing.""" import json import re -from datetime import date, datetime from telegram import MessageEntity from .ecowitt.api import unit_text -from .ecowitt.glance import solar_band from .entities import utf16_len -from .series import AIR, INDOOR_READINGS, WEATHER, find +from .series import AIR, find from .timeutil import clock_text, day_text, to_local @@ -23,136 +24,9 @@ def _load(result: str | None) -> dict | None: return data if isinstance(data, dict) and "error" not in data else None -def _zero(text: str | None) -> bool: - """Is this reading missing or zero ("0.0 W/m²", "0")?""" - try: - return not text or float(text.split()[0]) == 0 - except ValueError: - return False - - -def _band(solar: str | None) -> str: - """" (medium)" for a solar reading like "40.2 W/m²"; nothing when it can't be read.""" - try: - return f" ({solar_band(float(solar.split()[0]))})" - except (AttributeError, IndexError, ValueError): - return "" - - -def _join(parts: list[str | None], sep: str = ", ") -> str: - return sep.join(p for p in parts if p) - - -def _stamp(result: dict, today: date) -> str | None: - """The time of the data, "11:45pm", with its day when that isn't today ("Sat 10 Oct 11:45pm"), from the result's "time" (as - timeutil.when writes it, "Sun 11 Oct 2026 11:45pm"); None when it is missing or unreadable.""" - try: - at = datetime.strptime(result.get("time") or "", "%a %d %b %Y %I:%M%p") - except ValueError: - return None - return clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" - - -def _heading(name: str, result: dict, today: date) -> str: - """"Forecast (Melbourne, 6:00pm)": the place the result names and the time of its data, whichever it has.""" - note = ", ".join(x for x in (result.get("place"), _stamp(result, today)) if x) - return f"{name} ({note})" if note else name - - -def _getters(now: dict): - """(get, tag) for a weather_now result: a reading's text, and the same with its emoji (if it has one) before it.""" - emoji = now.get("emoji") or {} - - def get(group: str, field: str) -> str | None: - return unit_text((now.get(group) or {}).get(field)) - - def tag(group: str, field: str, text: str | None = None) -> str | None: - text = text or get(group, field) - return f"{emoji[f'{group}.{field}']} {text}" if text and f"{group}.{field}" in emoji else text - return get, tag - - -def _rain(now: dict) -> str: - """Today's rain, the month's and, while it rains, the rate: "☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)".""" - get, tag = _getters(now) - rate, month = get("rainfall", "rain_rate"), get("rainfall", "monthly") - return _join([_join([tag("rainfall", "daily"), f"(month total {month})" if month else None], " "), - None if _zero(rate) else tag("rainfall", "rain_rate", f"raining ({rate})")], "; ") - - -def _wind(now: dict) -> str | None: - """The wind, where it comes from and its gusts: "14.0 km/h from 131°, gust 31.0 km/h"; None when it is calm.""" - get, tag = _getters(now) - if _zero(get("wind", "wind_speed")) and _zero(get("wind", "wind_gust")): - return None - direction, gust = get("wind", "wind_direction"), tag("wind", "wind_gust") - return _join([_join([tag("wind", "wind_speed"), f"from {direction}" if direction else None], " "), f"gust {gust}" if gust else None]) - - -def weather_lines(now: dict) -> list[str]: - """The weather station's bullets from a weather_now result: an emoji sits right before the reading it is keyed to.""" - get, tag = _getters(now) - solar, uvi = get("solar_and_uvi", "solar"), get("solar_and_uvi", "uvi") - sun = _join([None if _zero(solar) else tag("solar_and_uvi", "solar", f"solar radiation {solar}{_band(solar)}"), # night: no sun line - None if _zero(uvi) else tag("solar_and_uvi", "uvi", f"UV index {uvi}")]) - bullets = [("Outdoor", _join([tag("outdoor", "temperature"), tag("outdoor", "humidity")])), # (dew point and VPD are there to ask for) - ("Indoor", _join([tag("indoor", "temperature"), tag("indoor", "humidity")])), - ("Pressure", tag("pressure", "relative")), - ("Rain today", _rain(now)), - ("Sun", sun), - ("Wind", _wind(now))] # calm: no line - return [f"• {name}: {text}" for name, text in bullets if text] - - -def air_lines(air: dict, only: list[str] | None = None) -> list[str]: - out = [] - for key, label in ((name, m.label) for name, m in AIR.items()): - entry = air.get(key) if only is None or key in only else None - if not isinstance(entry, dict) or entry.get("value") is None: - continue - unit = entry.get("unit", "") - shown = (f"{entry['value']:.1f} {unit}" if unit.startswith("µg") else f"{entry['value']:.0f} {unit}" if unit == "ppm" - else f"{entry['value']:.1f}" if key == "nox_index" else f"{entry['value']:.0f}") - aqi = f" (AQI {entry['aqi_us']})" if key == "pm2_5" and "aqi_us" in entry else "" - out.append(f"• {label}: {_join([shown, entry.get('rating')], ' ')}{aqi}") - return out - - -def reading_lines(now: dict, names: list[str], sides: list[str]) -> list[str]: - """Just the readings asked about from a weather_now result ("how hot is it": the temperature, indoors and out).""" - get, tag = _getters(now) - lines = [] - for name in names: - reading = WEATHER[name] - if name in ("temperature", "humidity"): # a line for each side asked about; the temperature with what it feels like - for side in sides: - feels = get(side, "feels_like") if name == "temperature" else None - if text := _join([tag(side, reading.field), f"feels like {feels}" if feels else None]): - lines.append(f"• {side.capitalize()}: {text}") - elif name == "wind": - lines.append(f"• Wind: {_wind(now) or 'calm'}") - elif name == "rain": - lines.append(f"• Rain today: {_rain(now) or 'none'}") - else: - group = sides[0] if name in INDOOR_READINGS and len(sides) == 1 else reading.group # "indoor dew point": that sensor's - if text := tag(group, reading.field): - lines.append(f"• {reading.label}{' (indoor)' if group == 'indoor' else ''}: {text}") - return lines - - -def _own_lines(result: dict) -> list[str]: - """The bullets of a result that brings its own lines (pollen and asthma, the forecast).""" - return [f"• {line}" for line in result.get("lines", [])] - - -# The report's sections in order: the tool, the section's heading, its bullets from the tool's result, and whether it is still -# shown when that result failed ("• not available right now") rather than left out -SECTIONS = (("weather_now", "Weather station", weather_lines, True), - ("air_quality", "Air quality", air_lines, True), - ("pollen_asthma", "Pollen & asthma", _own_lines, False), - ("weather_forecast", "Forecast", _own_lines, False)) -HEADINGS = {tool: heading for tool, heading, _, _ in SECTIONS} # the pollen and forecast lookups start with theirs too -HEADING_LINE = re.compile(rf"^({'|'.join(map(re.escape, HEADINGS.values()))})(?= \(|$)", re.M) +# ---------- the report's headings (the service's current, pollen and forecast write them) ---------- +HEADINGS = ("Weather station", "Air quality", "Pollen & asthma", "Forecast") +HEADING_LINE = re.compile(rf"^({'|'.join(map(re.escape, HEADINGS))})(?= \(|$)", re.M) def heading_entities(text: str) -> list[MessageEntity]: @@ -160,29 +34,7 @@ def heading_entities(text: str) -> list[MessageEntity]: return [MessageEntity(MessageEntity.BOLD, utf16_len(text[:m.start()]), utf16_len(m.group(1))) for m in HEADING_LINE.finditer(text)] -def report(results: dict[str, str], today: date) -> str: - """The full report from the tool results by tool name (weather_now, air_quality, pollen_asthma, weather_forecast), on `today` (local).""" - sections = [] - for tool, heading, bullets, always in SECTIONS: - data = _load(results.get(tool)) - if data or (always and tool in results): - sections.append("\n".join([_heading(heading, data or {}, today), *(bullets(data) if data else ["• not available right now"])])) - return "\n\n".join(sections) or "No readings are available right now." - - -def weather_now(result: str | None) -> str | None: - """"Weather now": the weather station's bullets alone (None if the reading isn't available).""" - now = _load(result) - return "\n".join(weather_lines(now)) if now else None - - -# ---------- plain lookups ---------- -def _alone(tool: str, result: dict, today: date) -> str | None: - """A pollen or forecast result on its own: its section of the report, or None when it has no lines.""" - lines = _own_lines(result) - return "\n".join([_heading(HEADINGS[tool], result, today), *lines]) if lines else None - - +# ---------- a days lookup ---------- def _days(data: dict) -> str | None: """"137 of 1,454 days with UV index ≥ 10 (period)", or a total, average, highest or lowest over the period: the chart (if any) carries the breakdown.""" @@ -196,40 +48,11 @@ def _days(data: dict) -> str | None: return f"{data['matching_days']:,} of {data['days_checked']:,} days{what} ({_period(data)}).{note}" -def _series_label(field: str) -> str: - """A series' name: its reading's label ("Temperature"), the gusts their own ("Wind gust").""" - if field == "wind_gust": - return "Wind gust" - return reading.label if (reading := find(field)) else field.replace("_", " ").capitalize() - - -def _extremes(data: dict, names: list[str]) -> str | None: - """The period, then the low and high (or the average) of each reading named, each with its day and time: wind, its speed and - its gusts; nothing named, the temperature. A reading on both sides (indoor, outdoor) has a line for each.""" - series = data.get("series") or {} - wanted = [f for r in filter(None, map(find, names)) for f in (r.field, r.band_field) if f] or ["temperature"] - keys = [k for k in series if k.split(".", 1)[1] in wanted and "low" in series[k]] - fields = [k.split(".", 1)[1] for k in keys] - lines = [] - for key in keys: - group, field = key.split(".", 1) - label = _series_label(field) + (f" ({group})" if fields.count(field) > 1 else "") - lines.append(f"• {_range(label, series[key], 'average' in series[key])}") - return "\n".join([_period(data), *lines]) if lines else None - - -def lookup(kind: str, result: str | None, names: list[str], sides: list[str], today: date) -> str | None: - """A plain lookup written from its one tool result: `kind` is "reading", "air", "days", "extremes", "pollen" or "forecast", - `names` the readings asked about and `sides` where (indoor, outdoor), on `today` (local). None when the result can't be used - (the model then takes the question).""" +def lookup(kind: str, result: str | None, names: list[str] = (), sides: list[str] = (), today=None) -> str | None: + """A day tool's result in words (`kind` "days"): the count, or the figure over the period. None when the result can't be used (the + model then answers). (`names`, `sides` and `today` are the old lookups', kept so its callers read as before.)""" data = _load(result) - answers = {"reading": lambda: "\n".join(reading_lines(data, names, sides)), - "air": lambda: "\n".join(air_lines(data, names or None)), - "days": lambda: _days(data), - "extremes": lambda: _extremes(data, names), - "pollen": lambda: _alone("pollen_asthma", data, today), - "forecast": lambda: _alone("weather_forecast", data, today)} - return (answers[kind]() or None) if data and kind in answers else None + return (_days(data) or None) if data and kind == "days" else None # ---------- chart captions ---------- @@ -265,6 +88,7 @@ def _rain_line(turn, tz) -> list[str]: bars = next((p.bars for c in turn.charts for p in c.panels if p.bars and p.bars.x), None) if not bars: return [] + def day(i: int) -> str: start = to_local(bars.x[i], tz) return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") diff --git a/lib/service/__init__.py b/lib/service/__init__.py index 54d5c867..4ad63d81 100644 --- a/lib/service/__init__.py +++ b/lib/service/__init__.py @@ -4,7 +4,54 @@ - common.py: how a tool is made, what it is sent (its arguments and the request's metadata, nothing else), and the shape of what it answers: the period it read, the time of its figures, its charts, and its refusals; - names.py: the readings the service has, one name each (`outdoor.temperature`, `air.pm2_5`), and the words people use for them; - - daylook.py: a day's look ("wet", 🌧️) from its figures. + - daylook.py: a day's look ("wet", 🌧️) from its figures; + - legacy.py: the bot's old tool calls read as the service's (its own code paths' only way in; deleted whole in step 3). -Nothing here is offered to a model yet, and nothing here knows of Telegram, of the bot's buttons or of who draws a chart. +`build(ctx)` makes the ten, in 3.3's order, each module's `tools(ctx)` (a tool whose source isn't there is left out), and `Service` +holds them by name. Nothing here is offered to a model yet (the bot's own code paths call them: step 2), and nothing here knows of +Telegram, of the bot's buttons or of who draws a chart. """ + +from .common import ServiceTool + +ORDER = ("current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen", "about") # 3.3's + + +def build(ctx) -> list["ServiceTool"]: + """The service's tools over this Context, in 3.3's order: each module's tools(ctx).""" + from importlib import import_module + return [t for name in ORDER for t in import_module(f"{__name__}.{name}").tools(ctx)] + + +class Service: + """The service's tools by name: `service["summary"]`, `service.get(name)`, `name in service`; iterated in 3.3's order.""" + + def __init__(self, tools: list["ServiceTool"] = (), ctx=None): + self.tools, self.ctx = list(tools), ctx # ctx: the Context they were built over, when known + self.by_name = {t.name: t for t in self.tools} + + @classmethod + def of(cls, ctx) -> "Service": + return cls(build(ctx), ctx) + + def held(self, names: list[str]) -> list[str]: + """These readings' names, less those the service's catalogue doesn't hold (all of them when it isn't known).""" + if self.ctx is None: + return list(names) + known = set(self.ctx.readings().names) + return [n for n in names if n in known] + + def get(self, name: str) -> "ServiceTool | None": + return self.by_name.get(name) + + def __getitem__(self, name: str) -> "ServiceTool": + return self.by_name[name] + + def __contains__(self, name: str) -> bool: + return name in self.by_name + + def __iter__(self): + return iter(self.tools) + + +__all__ = ["ORDER", "Service", "build"] diff --git a/lib/service/common.py b/lib/service/common.py index abe1ac13..3106a6d8 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -39,7 +39,9 @@ # ---------- the request's metadata ---------- CHART_POINTS = 150 # the most points a line of a chart is sent in, unless the request asks for more (3.7): enough for a model to redraw -MAX_CHART_POINTS = 500 # the most a request may ask for: today's drawing budget (lines.POINT_BUDGET), what the bot asks for +MAX_CHART_POINTS = 500 # the most a request may ask for: today's drawing budget (lines.POINT_BUDGET) +AS_DRAWN = "drawn" # chart_points asking for every point as the chart was drawn, unbucketed: what the bot asks for, so its pictures + # are as they were (a chart of each day's average over years has more points than the budget) NORMAL, BACKGROUND = "normal", "background" # priority: someone is waiting, or the work is ahead of need (a chart drawn ahead) META = {"chart_points": CHART_POINTS, "fetch": True, "priority": NORMAL} # each key a handler reads, with its default @@ -47,13 +49,15 @@ def request_meta(raw: dict | None = None) -> dict: """The request's metadata as a handler reads it: every key in META, each checked, defaulted where missing or not understood; any other key passed on as it came. - - chart_points: the most points a chart's line is sent in, a whole number from 2 to MAX_CHART_POINTS (default CHART_POINTS); + - chart_points: the most points a chart's line is sent in, a whole number from 2 to MAX_CHART_POINTS (default CHART_POINTS), or + AS_DRAWN ("drawn"): every point, as the chart was drawn (a client that draws for itself, as the bot does); - fetch: False answers from what is held, fetching nothing that is missing (default True); - priority: "background" for work nobody is waiting on (a chart drawn ahead), whose requests wait their turn; else "normal".""" raw = dict(raw) if isinstance(raw, dict) else {} points = raw.get("chart_points") try: - points = CHART_POINTS if points is None or isinstance(points, bool) else min(max(int(points), 2), MAX_CHART_POINTS) + points = AS_DRAWN if points == AS_DRAWN else CHART_POINTS if points is None or isinstance(points, bool) else \ + min(max(int(points), 2), MAX_CHART_POINTS) except (TypeError, ValueError): points = CHART_POINTS fetch = raw.get("fetch", True) @@ -236,9 +240,9 @@ def answer(*, period: Period | None, as_of: datetime | None, **fields) -> str: def charts_field(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> list[dict]: """The charts as data (specs.to_json, schemas/chart.json), each line bucketed to the request's `chart_points` (default CHART_POINTS, - at most MAX_CHART_POINTS), times local to `tz`.""" + at most MAX_CHART_POINTS; AS_DRAWN: as drawn), times local to `tz`.""" points = request_meta(meta)["chart_points"] - return [specs.to_json(chart, tz, max_points=points) for chart in charts] + return [specs.to_json(chart, tz, max_points=None if points == AS_DRAWN else points) for chart in charts] def with_charts(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) -> dict: @@ -254,6 +258,6 @@ def complete(reply: str) -> dict: return {"reply": reply, "complete": True} -__all__ = ["BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", +__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_field", "complete", "iso", "period_field", "period_properties", "read_period", "refuse", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/service/context.py b/lib/service/context.py index 6b80297b..5ae656f0 100644 --- a/lib/service/context.py +++ b/lib/service/context.py @@ -19,7 +19,7 @@ class Context: pollen: object | None = None # lib.pollen.Pollen, when switched on catalogue: Catalogue | None = None # the readings the file holds (names.Catalogue.open); None: every reading the service knows tz: tzinfo | None = None # the station's zone (the station's own, once it has named it) - clock: Callable[[], float] = field(default=time.time) # the time now, as an epoch (a test's own) + clock: Callable[[], float] = field(default=lambda: time.time()) # the time now, as an epoch (a test's own) @property def storage(self): diff --git a/lib/service/legacy.py b/lib/service/legacy.py new file mode 100644 index 00000000..9d0431a0 --- /dev/null +++ b/lib/service/legacy.py @@ -0,0 +1,192 @@ +"""The bot's old tool calls read as the service's (docs/mcp-service.md 6, step 2): one of the twelve tools' calls, with what the bot's +words decided beside it (the Turn: the reading charted, the readings stacked, an average, every day, two axes), as the service tool +that answers it and that tool's arguments. The bot's own code paths (its shortcuts, lookups and keyboard charts, intent.read's +decisions) and the charts the model draws through the twelve go through here, and nowhere else, so step 3, when the model gets the +service's tools and the Turn goes, deletes this module whole. + + - translate(name, args, turn, now, tz): (tool, arguments) of a call, or None when it has no service equivalent here; + - lookup(read): the call behind a plain lookup intent.read answers in code ("how hot is it", "co2", "pollen" ...); + - report(sources): the calls the report is written from; + - periods_of(tool, arguments): the periods a chart of that call is worth drawing over, as its drawn_by would list them. +""" + +from datetime import datetime, timedelta, tzinfo + +from ..ecowitt.query import chart_field, stack_names +from ..periods_text import PeriodError, read_period +from ..series import INDOOR_READINGS, WEATHER +from .days import MONTH_PERIODS +from .names import BARE +from .summary import DAILY_MEANS, OVER_TIME + +FMT = "%Y-%m-%d %H:%M:%S" +FIELD_NAMES = {r.field: name for name, r in WEATHER.items()} # a field a chart plots -> its reading's name ("relative" -> "pressure") +SIDES = ("outdoor", "indoor") +RELATED = ({"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) + + +def station_readings(names: list[str], sides: list[str]) -> list[str]: + """The service's names of lib/series.py's readings, each on the sides asked (temperature and humidity: outdoor and indoor unless + one is named; dew point and feels like indoor's only when indoor alone is).""" + out: list[str] = [] + for name in names: + if name in ("temperature", "humidity"): + out += [f"{side}.{name}" for side in sides] + elif name in INDOOR_READINGS and sides == ["indoor"]: + out.append(f"indoor.{name}") + elif name in BARE: + out += BARE[name] + return list(dict.fromkeys(out)) + + +def _sides(groups) -> list[str]: + groups = [g.strip() for g in (groups.split(",") if isinstance(groups, str) else groups or [])] + return [s for s in SIDES if s in groups] or list(SIDES) + + +def _when(text: str, fmt: str = FMT) -> datetime | None: + try: + return datetime.strptime(str(text).strip(), fmt) + except ValueError: + try: + return datetime.fromisoformat(str(text).strip()) + except ValueError: + return None + + +def period(start: str | None, end: str | None, words: list[str], now: datetime, tz: tzinfo, whole_days: bool = False) -> dict: + """The period of an old call (its start_date and end_date, the station's clock) as the service takes it: the first of `words` (the + period's name as the question gave it) that the service reads as the same span, else whole days as words ("2026-11-04 to 2026-11-10"), else the times.""" + first, last = _when(start) if start else None, _when(end) if end else None + if first is None: + return {} + if whole_days: + return {"period": f"{first:%Y-%m-%d} to {last:%Y-%m-%d}" if last else f"{first:%Y-%m-%d} to now"} + now = now.replace(tzinfo=None, microsecond=0) + until = min(last, now) if last else now + for said in words: + try: + read = read_period(said, None, None, now=now, tz=tz, default=said) + except PeriodError: + continue + if read.start.replace(tzinfo=None) == first and until <= read.end.replace(tzinfo=None) <= until + timedelta(seconds=1): + return {"period": said} + whole_end = last is None or last >= now or last.strftime("%H:%M:%S") == "23:59:59" + if first.time() == datetime.min.time() and whole_end: # whole days, as words the service can swap for another period + return {"period": f"{first:%Y-%m-%d} to {last:%Y-%m-%d}" if last else f"{first:%Y-%m-%d} to now"} + out = {"start": first.strftime("%Y-%m-%d") if first.time() == datetime.min.time() else first.strftime("%Y-%m-%d %H:%M")} + if last is not None and last < now: + out["end"] = last.strftime("%Y-%m-%d") if last.strftime("%H:%M:%S") == "23:59:59" else \ + (last + timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M") + return out + + +def _words(text: str, now: datetime) -> list[str]: + """The names intent gives the periods the question names (and a chart's default), as candidates for period().""" + from .. import intent # (the bot's own reading of the words: lazy, as the service doesn't need it) + names = [name for name, _, _ in intent.spans_in(text, now)] if text else [] + return [*names, *[n.replace("past ", "the last ") for n in names if n.startswith("past ")], "last 24 hours"] + + +def translate(name: str, args: dict, turn=None, *, now: datetime, tz: tzinfo) -> tuple[str, dict] | None: + """(service tool, arguments) for one of the old tools' calls with its Turn (what the words decided; None: nothing), or None.""" + args = dict(args or {}) + text = getattr(turn, "text", "") or "" + if name == "weather_history": + return "summary", _history(args, turn, now, tz) + if name == "air_quality": + metrics = [m for m in (args.get("metrics") or getattr(turn, "air_named", None) or ["pm2_5"])] + if not (args.get("start_date") or args.get("end_date")): + return "current", {"readings": [f"air.{m}" for m in metrics] if args.get("metrics") else ["air"]} + out = {"readings": [f"air.{m}" for m in metrics], + **period(args.get("start_date"), args.get("end_date"), _words(text, now), now, tz)} + if args.get("chart") is not None: + out["chart"] = bool(args.get("chart")) + return "summary", _flags(out, args) + if name in ("weather_days", "air_days"): + keep = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "chart_answers_it") + out = {k: args[k] for k in keep if args.get(k) not in (None, "", [])} + out.update(period(args.get("start_date"), args.get("end_date") or now.strftime("%Y-%m-%d"), [], now, tz, whole_days=True)) + return "days", out + if name == "weather_now": + return "current", {} + if name == "pollen_asthma": + return "pollen", {} + if name == "weather_forecast": + days = int(args.get("days") or 7) + return "forecast", {"period": "the next 7 days" if days >= 7 else "today" if days == 1 else f"next {days} days"} + return None + + +def _flags(out: dict, args: dict) -> dict: + if args.get("chart_answers_it") is True: + out["chart_answers_it"] = True + return out + + +def _history(args: dict, turn, now: datetime, tz: tzinfo) -> dict: + """weather_history as summary: the readings the chart draws (the words' reading, else the model's; several stacked; else the + temperature), on the sides its groups ask for, over its period, with its chart, average, every day and two axes.""" + turn = turn or _NoTurn() + sides = _sides(args.get("groups")) + stacked = stack_names(args, turn) + field = chart_field(args, turn) + names = stacked or ([FIELD_NAMES.get(field, field)] if field else None) or \ + [n for n in (getattr(turn, "readings", None) or []) if n in WEATHER][:1] or ["temperature"] + out = {"readings": station_readings(names, sides), + **period(args.get("start_date"), args.get("end_date"), _words(turn.text or "", now), now, tz)} + if args.get("chart") is not None or turn.chart_asked: + out["chart"] = bool(args.get("chart")) or bool(turn.chart_asked) + if args.get("average") or turn.average_asked: + out["average"] = True + if turn.per_day: + out["every_day"] = True + if turn.two_axes and len(names) == 2: + out["layout"] = "two_axes" + return _flags(out, args) + + +class _NoTurn: + text, chart_asked, average_asked, per_day, two_axes, readings, chart_field, chart_fields, air_named = "", False, False, False, False, [], None, [], [] + + +def lookup(read) -> tuple[str, dict] | None: + """The call behind a plain lookup intent.read answers in code (read.lookup: "reading", "air", "days", "extremes", "pollen", + "forecast", "about"), from what the words decided.""" + kind = read.lookup + if kind == "about": + return "about", {} + if kind == "reading": + sides = read.sides or list(SIDES) + words = [f"{sides[0]} {n.replace('_', ' ')}" if n in INDOOR_READINGS and len(sides) == 1 else n.replace("_", " ") + for n in read.lookup_arg] + return "current", {"readings": words} + if kind == "air": + return "current", {"readings": [f"air.{m}" for m in read.lookup_arg] or ["air"]} + return None + + +def report(sources) -> list[tuple[str, dict]]: + """The calls the report is written from, for these sources (by name): the readings now (both devices), the forecast's next 3 days + (what the report has always shown) and the pollen.""" + calls = [("current", {})] if {"Ecowitt", "AirGradient"} & set(sources) else [] + calls += [("pollen", {})] if "Pollen" in sources else [] + calls += [("forecast", {"period": "next 3 days"})] if "Forecast" in sources else [] + return calls + + +def periods_of(tool: str, arguments: dict) -> list[dict]: + """The periods a chart drawn by this call is worth drawing over, as the tool's own drawn_by lists them (summary, days, relate, + scan): for a chart the model drew through the old tools, which has none of its own.""" + if tool == "summary": + if "period" not in arguments: + return [] + return [dict(p) for p in (DAILY_MEANS if arguments.get("average") else OVER_TIME)] + if tool == "days": + return [{"period": p, "label": label} for p, label in MONTH_PERIODS] if arguments.get("group_by") == "month" else [] + if tool in ("relate", "scan"): + return [dict(p) for p in RELATED] + return [] + + +__all__ = ["lookup", "period", "periods_of", "report", "station_readings", "translate"] diff --git a/lib/service/summary.py b/lib/service/summary.py index a993a420..989a486f 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -561,6 +561,15 @@ async def handle(self, args: dict, meta: dict) -> str: fields.update(complete(caption)) return answer(period=call.period, as_of=ctx.now(), **fields) + def _span(self, call: Call) -> tuple[str, str]: + """The period as the engines take it ('YYYY-MM-DD HH:MM:SS', both ends included): to its last second, or, for a period that runs + to now, to now itself (the reading of this very minute is in it, as it always was).""" + start, end = call.period.as_naive_strings() + now = self.ctx.now().replace(microsecond=0) + if call.period.end >= now: + end = f"{now.astimezone(self.ctx.zone):%Y-%m-%d %H:%M:%S}" + return start, end + async def _station(self, call: Call, station: list[Reading], drawn: list[Reading], here: bool, background: bool, fetch: bool, charts: list[Chart], found: dict) -> tuple[_Query | None, dict | None]: """HistoryQuery over the station's readings summarised and drawn, drawing its chart when `here`.""" @@ -572,7 +581,7 @@ async def _station(self, call: Call, station: list[Reading], drawn: list[Reading turn = Turn(chart_asked=here, chart_field=named[0] if len(named) == 1 else None, chart_fields=named if len(named) > 1 else [], two_axes=here and call.layout == "two_axes", average_asked=call.average, per_day=call.every_day, readings=series_names, text="", ahead=background) - start, end = call.period.as_naive_strings() + start, end = self._span(call) args = {"start_date": start, "end_date": end, "average": call.average, "include_derived": sorted({r.column for r in every if r.column in DERIVED})} make = Fetcher if fetch else _HeldOnly @@ -607,7 +616,7 @@ async def _air(self, call: Call, figures: list[Reading], drawn: list[Reading], c """AirGradient.history over the air readings whose figures are wanted (and drawn, when the chart is the air sensor's alone). Its `metrics` are what it draws, and bring in its own temperature and humidity: a reading summarised but not drawn that is one of those takes a call of its own.""" - start, end = call.period.as_naive_strings() + start, end = self._span(call) metrics = [r.column for r in drawn] wanted = [r.column for r in figures] out: dict = {} diff --git a/lib/tools.py b/lib/tools.py index 6df22636..3ba2f68e 100644 --- a/lib/tools.py +++ b/lib/tools.py @@ -26,6 +26,7 @@ def json_result(out) -> str: class Turn: """What one question carries between the bot and the tools it calls (nothing is shared between questions).""" charts: list = field(default_factory=list) # chart specs the tools add; the bot renders them after the answer + chart_calls: list = field(default_factory=list) # (tool, arguments) of the call that drew each chart, in the same order chart_asked: bool = False # the person's words asked for a chart ("plot"), whatever the model sets chart_field: str | None = None # the one reading the question is about ("humidity"); None: temperature chart_fields: list[str] = field(default_factory=list) # readings asked to be seen together ("temperature and rain") @@ -93,13 +94,17 @@ async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: return f"Error: tool arguments were not valid JSON ({e})" log.debug("Tool call %s %s", name, raw_args, extra=QUOTES) sourced = CHART_SOURCE.set(source_text(args.get("source") if isinstance(args, dict) else None) or tool.source or "") # the charts this call draws + turn = turn or Turn() + before = len(turn.charts) try: # no time limit of its own: the question's (bot.TURN_SECONDS) runs from before the call - out = await tool.handler(args, turn or Turn()) + out = await tool.handler(args, turn) except Exception as e: log.error("Tool %s failed: %s: %s", name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) return f"Error calling tool: {e}" finally: CHART_SOURCE.reset(sourced) + calls = (turn.chart_calls + [(None, {})] * before)[:before] # (charts added another way have no call) + turn.chart_calls[:] = calls + [(name, args)] * max(0, len(turn.charts) - before) out = out or "(no output)" if len(out) > MAX_OUTPUT_CHARS: log.warning("Tool %s output truncated: %d chars", name, len(out)) diff --git a/tests/fakes.py b/tests/fakes.py index 4bae764b..1654ce3e 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -8,7 +8,6 @@ import httpx from lib.config import Config -from lib.tools import Tools TZ = ZoneInfo("Australia/Melbourne") MAC = "AA:BB:CC:DD:EE:FF" @@ -17,9 +16,41 @@ STEP = {"5min": 300, "30min": 1800, "4hour": 14400, "1day": 86400} -class StandInTools: - """A test's stand-in for lib.tools.Tools: it answers call(name, raw, turn) itself, and call_all is the real one over it.""" - call_all = Tools.call_all +class StandInService: + """A test's stand-in for the service's tools (lib.service.Service), as the bot calls them: `answers` is {tool: its answer}, each a + dict (sent as JSON) or a function (args, meta) -> dict; every call is kept in `calls` as (tool, args).""" + + def __init__(self, **answers): + self.answers, self.calls = answers, [] + + def get(self, name): + if name not in self.answers: + return None + service = self + + class Tool: + async def call(self, args=None, meta=None): + import json + service.calls.append((name, dict(args or {}))) + answer = service.answers[name] + return json.dumps(answer(dict(args or {}), meta) if callable(answer) else answer, ensure_ascii=False) + return Tool() + + def __getitem__(self, name): + return self.get(name) + + def __contains__(self, name): + return name in self.answers + + def held(self, names): + return list(names) + + +def chart_data(title: str = "Temperature", drawn_by: dict | None = None) -> dict: + """A chart as a service tool gives it (specs.to_json), with its drawn_by.""" + from lib.specs import Chart, Line, Panel, to_json + data = to_json(Chart(title, "", [Panel(title, "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])]), TZ) + return {**data, "drawn_by": drawn_by or {"tool": "summary", "arguments": {"period": "7d"}, "periods": []}} def config(tmp_path, **over) -> Config: diff --git a/tests/report_words.py b/tests/report_words.py new file mode 100644 index 00000000..0948079a --- /dev/null +++ b/tests/report_words.py @@ -0,0 +1,324 @@ +"""The bot's words before step 2 (docs/mcp-service.md 6): lib/report.py as it was, the report, "weather now" and the plain lookups +written in code from the old tools' results. The bot now quotes the service's words instead; these stay as the oracle the service's +words are checked against (tests/test_service_current.py, _forecast, _pollen, _summary), word for word.""" + +import json +import re +from datetime import date, datetime + +from telegram import MessageEntity + +from lib.ecowitt.api import unit_text +from lib.ecowitt.glance import solar_band +from lib.entities import utf16_len +from lib.series import AIR, INDOOR_READINGS, WEATHER, find +from lib.timeutil import clock_text, day_text, to_local + + +def _load(result: str | None) -> dict | None: + """The tool's JSON, or None when it is missing, an error message or says it has nothing.""" + try: + data = json.loads(result or "") + except ValueError: + return None + return data if isinstance(data, dict) and "error" not in data else None + + +def _zero(text: str | None) -> bool: + """Is this reading missing or zero ("0.0 W/m²", "0")?""" + try: + return not text or float(text.split()[0]) == 0 + except ValueError: + return False + + +def _band(solar: str | None) -> str: + """" (medium)" for a solar reading like "40.2 W/m²"; nothing when it can't be read.""" + try: + return f" ({solar_band(float(solar.split()[0]))})" + except (AttributeError, IndexError, ValueError): + return "" + + +def _join(parts: list[str | None], sep: str = ", ") -> str: + return sep.join(p for p in parts if p) + + +def _stamp(result: dict, today: date) -> str | None: + """The time of the data, "11:45pm", with its day when that isn't today ("Sat 10 Oct 11:45pm"), from the result's "time" (as + timeutil.when writes it, "Sun 11 Oct 2026 11:45pm"); None when it is missing or unreadable.""" + try: + at = datetime.strptime(result.get("time") or "", "%a %d %b %Y %I:%M%p") + except ValueError: + return None + return clock_text(at) if at.date() == today else f"{day_text(at, year=False)} {clock_text(at)}" + + +def _heading(name: str, result: dict, today: date) -> str: + """"Forecast (Melbourne, 6:00pm)": the place the result names and the time of its data, whichever it has.""" + note = ", ".join(x for x in (result.get("place"), _stamp(result, today)) if x) + return f"{name} ({note})" if note else name + + +def _getters(now: dict): + """(get, tag) for a weather_now result: a reading's text, and the same with its emoji (if it has one) before it.""" + emoji = now.get("emoji") or {} + + def get(group: str, field: str) -> str | None: + return unit_text((now.get(group) or {}).get(field)) + + def tag(group: str, field: str, text: str | None = None) -> str | None: + text = text or get(group, field) + return f"{emoji[f'{group}.{field}']} {text}" if text and f"{group}.{field}" in emoji else text + return get, tag + + +def _rain(now: dict) -> str: + """Today's rain, the month's and, while it rains, the rate: "☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)".""" + get, tag = _getters(now) + rate, month = get("rainfall", "rain_rate"), get("rainfall", "monthly") + return _join([_join([tag("rainfall", "daily"), f"(month total {month})" if month else None], " "), + None if _zero(rate) else tag("rainfall", "rain_rate", f"raining ({rate})")], "; ") + + +def _wind(now: dict) -> str | None: + """The wind, where it comes from and its gusts: "14.0 km/h from 131°, gust 31.0 km/h"; None when it is calm.""" + get, tag = _getters(now) + if _zero(get("wind", "wind_speed")) and _zero(get("wind", "wind_gust")): + return None + direction, gust = get("wind", "wind_direction"), tag("wind", "wind_gust") + return _join([_join([tag("wind", "wind_speed"), f"from {direction}" if direction else None], " "), f"gust {gust}" if gust else None]) + + +def weather_lines(now: dict) -> list[str]: + """The weather station's bullets from a weather_now result: an emoji sits right before the reading it is keyed to.""" + get, tag = _getters(now) + solar, uvi = get("solar_and_uvi", "solar"), get("solar_and_uvi", "uvi") + sun = _join([None if _zero(solar) else tag("solar_and_uvi", "solar", f"solar radiation {solar}{_band(solar)}"), # night: no sun line + None if _zero(uvi) else tag("solar_and_uvi", "uvi", f"UV index {uvi}")]) + bullets = [("Outdoor", _join([tag("outdoor", "temperature"), tag("outdoor", "humidity")])), # (dew point and VPD are there to ask for) + ("Indoor", _join([tag("indoor", "temperature"), tag("indoor", "humidity")])), + ("Pressure", tag("pressure", "relative")), + ("Rain today", _rain(now)), + ("Sun", sun), + ("Wind", _wind(now))] # calm: no line + return [f"• {name}: {text}" for name, text in bullets if text] + + +def air_lines(air: dict, only: list[str] | None = None) -> list[str]: + out = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = air.get(key) if only is None or key in only else None + if not isinstance(entry, dict) or entry.get("value") is None: + continue + unit = entry.get("unit", "") + shown = (f"{entry['value']:.1f} {unit}" if unit.startswith("µg") else f"{entry['value']:.0f} {unit}" if unit == "ppm" + else f"{entry['value']:.1f}" if key == "nox_index" else f"{entry['value']:.0f}") + aqi = f" (AQI {entry['aqi_us']})" if key == "pm2_5" and "aqi_us" in entry else "" + out.append(f"• {label}: {_join([shown, entry.get('rating')], ' ')}{aqi}") + return out + + +def reading_lines(now: dict, names: list[str], sides: list[str]) -> list[str]: + """Just the readings asked about from a weather_now result ("how hot is it": the temperature, indoors and out).""" + get, tag = _getters(now) + lines = [] + for name in names: + reading = WEATHER[name] + if name in ("temperature", "humidity"): # a line for each side asked about; the temperature with what it feels like + for side in sides: + feels = get(side, "feels_like") if name == "temperature" else None + if text := _join([tag(side, reading.field), f"feels like {feels}" if feels else None]): + lines.append(f"• {side.capitalize()}: {text}") + elif name == "wind": + lines.append(f"• Wind: {_wind(now) or 'calm'}") + elif name == "rain": + lines.append(f"• Rain today: {_rain(now) or 'none'}") + else: + group = sides[0] if name in INDOOR_READINGS and len(sides) == 1 else reading.group # "indoor dew point": that sensor's + if text := tag(group, reading.field): + lines.append(f"• {reading.label}{' (indoor)' if group == 'indoor' else ''}: {text}") + return lines + + +def _own_lines(result: dict) -> list[str]: + """The bullets of a result that brings its own lines (pollen and asthma, the forecast).""" + return [f"• {line}" for line in result.get("lines", [])] + + +# The report's sections in order: the tool, the section's heading, its bullets from the tool's result, and whether it is still +# shown when that result failed ("• not available right now") rather than left out +SECTIONS = (("weather_now", "Weather station", weather_lines, True), + ("air_quality", "Air quality", air_lines, True), + ("pollen_asthma", "Pollen & asthma", _own_lines, False), + ("weather_forecast", "Forecast", _own_lines, False)) +HEADINGS = {tool: heading for tool, heading, _, _ in SECTIONS} # the pollen and forecast lookups start with theirs too +HEADING_LINE = re.compile(rf"^({'|'.join(map(re.escape, HEADINGS.values()))})(?= \(|$)", re.M) + + +def heading_entities(text: str) -> list[MessageEntity]: + """Bold entities over the name of each heading line in `text` (not over its brackets).""" + return [MessageEntity(MessageEntity.BOLD, utf16_len(text[:m.start()]), utf16_len(m.group(1))) for m in HEADING_LINE.finditer(text)] + + +def report(results: dict[str, str], today: date) -> str: + """The full report from the tool results by tool name (weather_now, air_quality, pollen_asthma, weather_forecast), on `today` (local).""" + sections = [] + for tool, heading, bullets, always in SECTIONS: + data = _load(results.get(tool)) + if data or (always and tool in results): + sections.append("\n".join([_heading(heading, data or {}, today), *(bullets(data) if data else ["• not available right now"])])) + return "\n\n".join(sections) or "No readings are available right now." + + +def weather_now(result: str | None) -> str | None: + """"Weather now": the weather station's bullets alone (None if the reading isn't available).""" + now = _load(result) + return "\n".join(weather_lines(now)) if now else None + + +# ---------- plain lookups ---------- +def _alone(tool: str, result: dict, today: date) -> str | None: + """A pollen or forecast result on its own: its section of the report, or None when it has no lines.""" + lines = _own_lines(result) + return "\n".join([_heading(HEADINGS[tool], result, today), *lines]) if lines else None + + +def _days(data: dict) -> str | None: + """"137 of 1,454 days with UV index ≥ 10 (period)", or a total, average, highest or lowest over the period: the chart (if any) + carries the breakdown.""" + if "matching_days" not in data: + return None + if data.get("stat") and data.get("value") is not None: + unit = unit_text(data["stat"].get("unit")) or "" + return f"{data['stat']['what']}: {data['value']:g} {unit}".rstrip() + f" over {data['days_checked']:,} days ({_period(data)})." + what = f" with {data['condition']}" if data.get("condition") else "" + note = " Older days use averages, so a count near the limit may fall slightly short." if data.get("note_averaged") else "" + return f"{data['matching_days']:,} of {data['days_checked']:,} days{what} ({_period(data)}).{note}" + + +def _series_label(field: str) -> str: + """A series' name: its reading's label ("Temperature"), the gusts their own ("Wind gust").""" + if field == "wind_gust": + return "Wind gust" + return reading.label if (reading := find(field)) else field.replace("_", " ").capitalize() + + +def _extremes(data: dict, names: list[str]) -> str | None: + """The period, then the low and high (or the average) of each reading named, each with its day and time: wind, its speed and + its gusts; nothing named, the temperature. A reading on both sides (indoor, outdoor) has a line for each.""" + series = data.get("series") or {} + wanted = [f for r in filter(None, map(find, names)) for f in (r.field, r.band_field) if f] or ["temperature"] + keys = [k for k in series if k.split(".", 1)[1] in wanted and "low" in series[k]] + fields = [k.split(".", 1)[1] for k in keys] + lines = [] + for key in keys: + group, field = key.split(".", 1) + label = _series_label(field) + (f" ({group})" if fields.count(field) > 1 else "") + lines.append(f"• {_range(label, series[key], 'average' in series[key])}") + return "\n".join([_period(data), *lines]) if lines else None + + +def lookup(kind: str, result: str | None, names: list[str], sides: list[str], today: date) -> str | None: + """A plain lookup written from its one tool result: `kind` is "reading", "air", "days", "extremes", "pollen" or "forecast", + `names` the readings asked about and `sides` where (indoor, outdoor), on `today` (local). None when the result can't be used + (the model then takes the question).""" + data = _load(result) + answers = {"reading": lambda: "\n".join(reading_lines(data, names, sides)), + "air": lambda: "\n".join(air_lines(data, names or None)), + "days": lambda: _days(data), + "extremes": lambda: _extremes(data, names), + "pollen": lambda: _alone("pollen_asthma", data, today), + "forecast": lambda: _alone("weather_forecast", data, today)} + return (answers[kind]() or None) if data and kind in answers else None + + +# ---------- chart captions ---------- +def _year(text: str | None) -> str: + """"Tue 29 Sep 2026" -> "Tue 29 Sep".""" + return re.sub(r" 20\d\d\b", "", text or "") + + +def _period(data: dict) -> str: + """"Tue 29 Sep 2026 - Tue 06 Oct 2026" -> "Tue 29 Sep – Tue 06 Oct 2026" (the first year is dropped only when it is the same year).""" + text = data.get("period", "") + years = re.findall(r" (20\d\d)\b", text) + if len(years) == 2 and years[0] == years[1]: + text = re.sub(r" 20\d\d\b(?= - )", "", text) + return text.replace(" - ", " – ") + + +def _at(entry: dict, which: str) -> str: + """"high 24.3 °C, Tue 29 Sep around 3pm" for one record of a series.""" + when = _year(f"{entry.get(f'{which}_date', '')} {entry.get(f'{which}_when', '')}".strip()) + return f"{entry[which]} {unit_text(entry.get('unit')) or ''}".strip() + (f", {when}" if when else "") + + +def _range(label: str, entry: dict, average: bool) -> str: + unit = unit_text(entry.get("unit")) or "" + if average and entry.get("average"): + return f"{label}: average {entry['average']} {unit} (low {entry['low']}, high {entry['high']})".replace(" )", ")") + return f"{label}: low {_at(entry, 'low')} · high {_at(entry, 'high')}" + + +def _rain_line(turn, tz) -> list[str]: + """Least and most rain in a period (the chart's own bars).""" + bars = next((p.bars for c in turn.charts for p in c.panels if p.bars and p.bars.x), None) + if not bars: + return [] + def day(i: int) -> str: + start = to_local(bars.x[i], tz) + return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") + lo, hi = min(range(len(bars.y)), key=bars.y.__getitem__), max(range(len(bars.y)), key=bars.y.__getitem__) + per = f" per {bars.per}" if bars.per else "" + return [f"☔ Rain{per}: least {bars.y[lo]:g} mm ({day(lo)}) · most {bars.y[hi]:g} mm ({day(hi)}) · {sum(bars.y):.1f} mm in all"] + + +def _weather_caption(result: dict, turn, tz) -> list[str]: + series = result.get("series") or {} + names = [n for n in dict.fromkeys(turn.chart_fields or [turn.chart_field or "temperature"]) if find(n)] + lines: list[str] = [] + for name in names: + reading = find(name) + keys = [k for k in series if k.split(".", 1)[1] == reading.field] + if reading.field == "daily": # rain: the amounts the chart draws + lines += _rain_line(turn, tz) + continue + for key in keys: + group = key.split(".", 1)[0] + label = reading.label + (f" ({group})" if len(keys) > 1 and group in ("outdoor", "indoor") else "") + if reading.field == "wind_speed": + gust = series.get(f"{group}.wind_gust") or series.get("wind.wind_gust") + lines.append(f"🌬️ Wind: strongest gust {_at(gust, 'high')}" if gust else _range(label, series[key], bool(turn.average_asked))) + else: + lines.append(_range(label, series[key], bool(turn.average_asked))) + if reading.field == "wind_speed" and (d := series.get("wind.wind_direction")): + lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) + return lines + + +def _air_caption(result: dict, args: dict) -> list[str]: + lines = [] + for key, label in ((name, m.label) for name, m in AIR.items()): + entry = result.get(key) + if key not in (args.get("metrics") or ["pm2_5"]) or not isinstance(entry, dict): + continue + unit = unit_text(entry.get("unit")) or "" + rating = entry.get("high_rating") + lines.append(f"• {label}: peak {entry['high']} {unit} ({_year(entry.get('high_time'))})".replace(" )", ")") + + (f" · {rating}" if rating else "") + f" · average {entry['average']}") + return lines + + +def chart_caption(tool: str, args: dict, result: str | None, turn, tz) -> str | None: + """The caption for a chart, from the tool's result: the period, then a line per reading. None when there is nothing to say (the + model then takes the question).""" + data = _load(result) + if not data or not turn.charts: + return None + lines = _air_caption(data, args) if tool == "air_quality" else _weather_caption(data, turn, tz) + if not lines: + return None + notes = (["(Older days are still downloading, so they are left out.)"] if data.get("note_missing") else + ["(Some data couldn't be fetched, so this may be incomplete.)"] if data.get("warning") else []) + return "\n".join([_period(data), *lines, *notes]).strip() diff --git a/tests/service_switch.json b/tests/service_switch.json index ad78ad2a..d17634eb 100644 --- a/tests/service_switch.json +++ b/tests/service_switch.json @@ -425,11 +425,11 @@ "gauges": [ "aa7350dd52231dc7" ], - "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", "sent": [ [ "photo", - "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", [ [ [ @@ -1548,7 +1548,7 @@ "dashboard": { "charts": [], "gauges": [ - "1bc0e0d78b0b8287" + "2035f1d261cdf408" ], "history": "Weather station dashboard, Tue 10 Nov 2026 2:05pm", "sent": [ @@ -1811,11 +1811,11 @@ "humidity": { "charts": [], "gauges": [], - "history": "• Outdoor: 💦 94 %\n• Indoor: 63 %", + "history": "• Outdoor: 💦 94 %", "sent": [ [ "text", - "• Outdoor: 💦 94 %\n• Indoor: 63 %", + "• Outdoor: 💦 94 %", null ] ] @@ -2281,7 +2281,7 @@ ] ] }, - "press 30 under Rain chart 1d": { + "press 1M under Rain chart 1d": { "charts": [ { "panels": [ @@ -2326,7 +2326,7 @@ ] ] }, - "press 365 under rain by month this year": { + "press 1Y under rain by month this year": { "charts": [ { "panels": [ @@ -2371,7 +2371,7 @@ ] ] }, - "press 7 under Temperature chart 1d": { + "press 7D under Temperature chart 1d": { "charts": [ { "panels": [ @@ -2675,11 +2675,11 @@ "gauges": [ "aa7350dd52231dc7" ], - "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", "sent": [ [ "photo", - "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", [ [ [ @@ -3627,11 +3627,11 @@ "weather now": { "charts": [], "gauges": [], - "history": "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + "history": "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", "sent": [ [ "text", - "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C, 63 %\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", + "• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", null ] ] diff --git a/tests/test_alert_menu.py b/tests/test_alert_menu.py index 4b69423c..4f7b460f 100644 --- a/tests/test_alert_menu.py +++ b/tests/test_alert_menu.py @@ -506,7 +506,7 @@ def drawing(monkeypatch, photo=b"new png"): from lib.alerts import pictures drawn = [] - async def chart(source, text, tz): + async def chart(source, text, tz, service=None): drawn.append((source.name, text)) return Picture(photo, "Wind, today", None) if photo else None monkeypatch.setattr(pictures, "chart", chart) @@ -565,11 +565,17 @@ def alert_charts(clock): return AlertCharts(images, lambda: datetime(2026, 10, 2, 12, 0, tzinfo=TZ), clock=lambda: clock[0]), images -def test_every_alert_chart_has_the_key_of_the_same_typed_request(): +def test_every_alert_chart_has_the_key_of_the_call_its_typed_request_is_read_as(): from lib.alerts.pictures import CHARTS + from lib.periods import call_key charts, images = alert_charts([0.0]) - assert {kind: charts.key(kind) for kind in CHARTS} == {"gusts": "wind chart 1d", "uv": "uv chart 1d", "temps": "temperature chart 1d", - "particulates": "particulates chart 1d"} + day = {"period": "last 24 hours", "chart": True} + assert {kind: charts.call(kind) for kind in CHARTS} == { + "gusts": ("summary", {"readings": ["wind.wind_speed", "wind.wind_direction"], **day}), # "Wind chart 1d", the Wind button's + "uv": ("summary", {"readings": ["solar_and_uvi.uvi"], **day}), + "temps": ("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], **day}), + "particulates": ("summary", {"readings": ["air.pm2_5", "air.pm10", "air.pm1"], **day})} + assert charts.key("gusts") == call_key(*charts.call("gusts")) assert charts.key("rain") is None # an alert without a chart @@ -578,7 +584,7 @@ def test_an_alert_sends_the_held_chart_only_when_it_draws_the_alerts_reading_and charts, images = alert_charts(clock) assert charts.held("gusts", 1000) is None # nothing held charts.keep("gusts", Picture(b"png", "Wind, today", 900), since=1000) # drawn for the alert about the reading at 1000 - assert images.held("wind chart 1d").newest == 1000 and charts.held("gusts", 1000) == b"png" # (it draws that reading, whatever its last point says) + assert images.held(charts.key("gusts")).newest == 1000 and charts.held("gusts", 1000) == b"png" # (it draws that reading, whatever its last point says) assert charts.held("gusts", 1300) is None and charts.held("gusts", None) is None # a newer reading, or one not known: drawn again charts.sent("gusts", NS(photo=(NS(file_id="small"), NS(file_id="large")))) assert charts.held("gusts", 1000) == "large" and charts.held("gusts", 700) == "large" # the same data again: Telegram's copy @@ -595,12 +601,12 @@ def test_an_alerts_chart_is_kept_warm_for_six_hours_from_the_alert_not_from_a_re assert charts.warm() == [] charts.sent("uv", NS(photo=(NS(file_id="large"),))) charts.sent("temps", None) # an alert whose picture Telegram refused still counts - assert charts.warm() == ["UV chart 1d", "Temperature chart 1d"] + assert charts.warm() == [charts.call("uv"), charts.call("temps")] # their calls clock[0] += AlertCharts.WARM_SECONDS - 1 - assert charts.warm() == ["UV chart 1d", "Temperature chart 1d"] + assert charts.warm() == [charts.call("uv"), charts.call("temps")] charts.sent("uv", NS(photo=(NS(file_id="large"),))) # alerted again: six more hours clock[0] += 2 - assert charts.warm() == ["UV chart 1d"] + assert charts.warm() == [charts.call("uv")] def test_refresh_sends_the_chart_drawn_ahead_since_the_message_was_last_changed_when_it_is_fresh(): @@ -609,10 +615,10 @@ def test_refresh_sends_the_chart_drawn_ahead_since_the_message_was_last_changed_ charts, images = alert_charts(clock) shown = NS(date=datetime.now(timezone.utc) - timedelta(seconds=120), edit_date=None) assert charts.newer_than("gusts", shown) is None # nothing held - images.put("wind chart 1d", b"ahead", "Wind, today") + images.put(charts.key("gusts"), b"ahead", "Wind, today") clock[0] += 60 # drawn a minute ago: since the message was sent assert charts.newer_than("gusts", shown) == b"ahead" - images.sent("wind chart 1d", NS(photo=(NS(file_id="large"),))) + images.sent(charts.key("gusts"), NS(photo=(NS(file_id="large"),))) assert charts.newer_than("gusts", shown) == "large" # uploaded ahead: Telegram's copy edited = NS(date=shown.date, edit_date=datetime.now(timezone.utc) - timedelta(seconds=10)) assert charts.newer_than("gusts", edited) is None # the message changed after it was drawn @@ -639,9 +645,9 @@ async def chart(): await notifier("Strong gusts", kind="gusts", chart=chart, since=1000) await notifier("Strong gusts", kind="gusts", chart=chart, since=1000) # the same reading: the chart kept, Telegram's copy assert drawn == [1] and [p for _, p, _ in bot.photos] == [b"png", "copy 1"] - assert images.held("wind chart 1d").file_id == "copy 2" and charts.warm() == ["Wind chart 1d"] # (the copy last sent) + assert images.held(charts.key("gusts")).file_id == "copy 2" and charts.warm() == [charts.call("gusts")] # (the copy last sent) await notifier("Strong gusts", kind="gusts", chart=chart, since=1300) # a newer reading: drawn again - assert drawn == [1, 1] and bot.photos[-1][1] == b"png" and images.held("wind chart 1d").newest == 1300 + assert drawn == [1, 1] and bot.photos[-1][1] == b"png" and images.held(charts.key("gusts")).newest == 1300 await notifier("Strong gusts", kind="gusts", chart=chart) # the reading not said: drawn assert drawn == [1, 1, 1] @@ -654,8 +660,9 @@ async def test_refresh_sends_the_chart_drawn_ahead_and_otherwise_keeps_the_one_i drawn = drawing(monkeypatch) q = ChartQuery("al:refresh:gusts") q.message.date, q.message.edit_date = datetime.now(timezone.utc) - timedelta(seconds=90), None - bot.images.put("wind chart 1d", b"ahead", "Wind, today") # drawn ahead since the alert went out - bot.images.sent("wind chart 1d", NS(photo=(NS(file_id="ahead copy"),))) + key = bot.alert_charts.key("gusts") + bot.images.put(key, b"ahead", "Wind, today") # drawn ahead since the alert went out + bot.images.sent(key, NS(photo=(NS(file_id="ahead copy"),))) await press(bot, q) (media, _), = q.media assert drawn == [] and media.media == "ahead copy" and q.toast is None # Telegram's copy, nothing drawn @@ -668,4 +675,4 @@ async def edit_message_media(media, reply_markup=None): q.edit_message_media = edit_message_media await press(bot, q) assert drawn == [("Ecowitt", "Wind chart 1d")] and q.media[0][0].media.input_file_content == b"new png" - assert bot.images.held("wind chart 1d").file_id == "new copy" and bot.alert_charts.warm() == [] # (a Refresh starts no warm period) + assert bot.images.held(key).file_id == "new copy" and bot.alert_charts.warm() == [] # (a Refresh starts no warm period) diff --git a/tests/test_bot.py b/tests/test_bot.py index d9c77b6f..456f3c55 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -7,7 +7,7 @@ from lib import intent from lib.bot import Bot from lib.tools import Turn -from tests.fakes import TZ, StandInTools +from tests.fakes import TZ class RaisingAgent: @@ -218,25 +218,16 @@ async def reply_media_group(media, **kw): async def test_a_report_is_written_in_code_from_the_fast_path_calls_and_the_model_is_not_asked(alert_state): - import json - - class Tools(StandInTools): - def __init__(self): - self.called = [] - - async def call(self, name, raw, turn=None): - self.called.append(name) - return {"weather_now": json.dumps({"outdoor": {"temperature": "12.3 ℃", "humidity": "94 %"}, "emoji": {"outdoor.humidity": "💦"}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] + from tests.fakes import StandInService class Agent: - tools = Tools() - async def run(self, *a, **k): raise AssertionError("the model must not be asked for a report") async def dashboard(titles=None): return None # the station has no gauges to draw: the report goes as text sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n, dashboard=dashboard) for n in ("Ecowitt", "AirGradient")] + service = StandInService(current={"lines": {"station": ["• Outdoor: 12.3 °C, 💦 94 %"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + "headings": {"station": "Weather station", "air": "Air quality"}}) agent, replies = Agent(), [] async def reply_text(body, **kw): @@ -247,10 +238,10 @@ async def reply_text(body, **kw): async def send_chat_action(*a, **k): pass - bot = Bot(NS(tz=TZ), agent, sources, alert_state) + bot = Bot(NS(tz=TZ), agent, sources, alert_state, service=service) await bot.respond(update, NS(bot=telegram(send_chat_action)), "report") await bot.respond(update, NS(bot=telegram(send_chat_action)), "weather now") - assert agent.tools.called == ["weather_now", "air_quality", "weather_now"] + assert service.calls == [("current", {}), ("current", {})] assert replies[0] == "Weather station\n• Outdoor: 12.3 °C, 💦 94 %\n\nAir quality\n• PM10: 3.0 µg/m³ 🟢 good" assert replies[1] == "• Outdoor: 12.3 °C, 💦 94 %" history = bot.chats[(1, None)].history @@ -298,23 +289,9 @@ async def run(self, messages, system, effort, **k): async def test_a_plain_chart_request_is_drawn_and_captioned_in_code_and_the_model_is_not_asked(alert_state, monkeypatch): - import json from lib import bot as botmod - from lib.specs import Chart, Line, Panel - - class Tools(StandInTools): - calls = [] - - async def call(self, name, raw, turn=None): - self.calls.append((name, json.loads(raw))) - turn.charts.append(Chart("Humidity", "", [Panel("Humidity", "%", [Line("Outdoor", [1, 2], [50.0, 60.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.humidity": {"unit": "%", "low": "50", "high": "60", "low_when": "at 5am", "low_date": "Fri 25 Sep 2026", - "high_when": "at 3pm", "high_date": "Sat 26 Sep 2026"}}}) class Agent: - tools = Tools() - async def run(self, *a, **k): raise AssertionError("the model must not be asked for a plain chart") sent = [] @@ -329,31 +306,22 @@ async def reply_photo(photo, caption=None, **kw): async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "Humidity chart 7d") - name, args = Agent.tools.calls[0] - assert name == "weather_history" and args["chart"] and args["groups"] == "outdoor,indoor" + service = chart_service() + await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service).respond(update, NS(bot=telegram(send_chat_action)), "Humidity chart 7d") + assert service.calls == [("summary", {"readings": ["outdoor.humidity", "indoor.humidity"], "period": "last 7 days", "chart": True})] assert sent == ["Humidity"] # the chart's title is its whole caption sent.clear() - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "when was humidity highest this week") + await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service).respond(update, NS(bot=telegram(send_chat_action)), + "when was humidity highest this week") assert "high 60 %, Sat 26 Sep" in sent[0] # a record asked for: its figures, with when, go with the chart async def test_a_chart_made_in_code_starts_no_refresh_and_other_questions_do(alert_state, monkeypatch): """The chart's own reads go first in line; a refresh started beside them would only queue requests ahead of the next ones.""" - import json from lib import bot as botmod - from lib.specs import Chart, Line, Panel pokes = [] - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - turn.charts.append(Chart("t", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) - class Agent: - tools = Tools() - async def run(self, *a, **k): return "It is 12 degrees." @@ -367,7 +335,7 @@ async def reply(*a, **k): async def send_chat_action(*a, **k): pass - bot, context = Bot(NS(tz=TZ), Agent(), sources, alert_state), NS(bot=telegram(send_chat_action)) + bot, context = Bot(NS(tz=TZ), Agent(), sources, alert_state, service=chart_service()), NS(bot=telegram(send_chat_action)) await bot.respond(update, context, "Temperature chart 7d") assert pokes == [] await bot.respond(update, context, "what do you think about the weather today?") @@ -375,18 +343,17 @@ async def send_chat_action(*a, **k): async def test_a_chart_reply_logs_how_long_each_step_took(alert_state, tmp_path, monkeypatch, caplog): - """One line per chart reply: reading the data, the calculation, drawing, the PNG (and its size) and sending it.""" + """One line per chart reply: the calculation (the service's call), drawing, the PNG (and its size) and sending it.""" import re from lib.ecowitt import Ecowitt, api - from lib.tools import Tools + from lib.service import Service + from lib.service.context import Context from tests.fakes import config, ecowitt_transport monkeypatch.setattr(api, "MIN_GAP_SECONDS", 0) eco = Ecowitt(config(tmp_path), transport=ecowitt_transport()[0]) await eco.start() class Agent: - tools = Tools(eco.tools) - async def run(self, *a, **k): raise AssertionError("no model for a plain chart") sent = [] @@ -402,26 +369,21 @@ async def reply_photo(photo, caption=None, **kw): async def send_chat_action(*a, **k): pass with caplog.at_level("DEBUG"): - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), - "Temperature chart 1d") + await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=Service.of(Context(eco=eco, tz=TZ))).respond( + update, NS(bot=telegram(send_chat_action)), "Temperature chart 1d") await eco.close() lines = [r.getMessage() for r in caplog.records if r.getMessage().startswith("Chart ms:")] assert len(sent) == 1 and len(lines) == 1, lines kb = round(len(sent[0]) / 1024) - assert re.fullmatch(rf"Chart ms: data \d+, calc \d+, draw \d+, PNG \d+ \({kb} KB\), send \d+", lines[0]) + assert re.fullmatch(rf"Chart ms: calc \d+, draw \d+, PNG \d+ \({kb} KB\), send \d+", lines[0]) -async def _ask_with(alert_state, tool_result, text, monkeypatch=None): - """Ask `text` of a bot whose one tool returns `tool_result`; returns (replies, whether the model was asked).""" +async def _ask_with(alert_state, answer, text, monkeypatch=None): + """Ask `text` of a bot whose service tools all give `answer`; returns (replies, whether the model was asked).""" + from tests.fakes import StandInService asked = [] - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - return tool_result - class Agent: - tools = Tools() - async def run(self, messages, *a, **k): asked.append(True) return "from the model" @@ -436,25 +398,27 @@ async def reply_text(body, **kw): async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) + service = StandInService(**{name: answer for name in ("current", "summary", "days", "about", "pollen", "forecast")}) + await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service).respond(update, NS(bot=telegram(send_chat_action)), text) return replies, bool(asked) async def test_a_plain_reading_question_is_answered_in_code_without_the_model(alert_state): - import json - result = json.dumps({"outdoor": {"temperature": "12.3 ℃", "feels_like": "11.0 ℃"}, "indoor": {"temperature": "18.3 ℃"}}) - replies, asked = await _ask_with(alert_state, result, "how hot is it") + answer = {"lines": {"station": ["• Outdoor: 12.3 °C, feels like 11.0 °C", "• Indoor: 18.3 °C"]}} + replies, asked = await _ask_with(alert_state, answer, "how hot is it") assert not asked and replies == ["• Outdoor: 12.3 °C, feels like 11.0 °C\n• Indoor: 18.3 °C"] async def test_a_lookup_that_cannot_be_written_falls_back_to_the_model(alert_state): - import json - replies, asked = await _ask_with(alert_state, json.dumps({"error": "station not answering"}), "how hot is it") + replies, asked = await _ask_with(alert_state, {"error": "station not answering"}, "how hot is it") + assert asked and replies == ["from the model"] + replies, asked = await _ask_with(alert_state, {"lines": {"station": ["• not available right now"]}, + "unavailable": {"station": "The weather station isn't answering right now."}}, "how hot is it") assert asked and replies == ["from the model"] async def test_about_the_bot_is_answered_in_code_without_the_model(alert_state): - replies, asked = await _ask_with(alert_state, "{}", "what can you do") + replies, asked = await _ask_with(alert_state, {"lines": ["• Temperature, humidity (indoor, outdoor)", "• History charts"]}, "what can you do") assert not asked and replies[0].startswith("• Temperature, humidity") @@ -556,17 +520,14 @@ async def send_chat_action(*a, **k): async def test_a_days_over_a_limit_question_is_counted_in_code_with_no_model(alert_state): - import json - result = json.dumps({"period": "Wed 5 Oct 2022 - Sat 3 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"}) - replies, asked = await _ask_with(alert_state, result, "days over UVI 10 by year") + answer = {"answer": "137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026).", "days_checked": 1454, "matching_days": 137} + replies, asked = await _ask_with(alert_state, answer, "days over UVI 10 by year") assert not asked and replies == ["137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)."] async def test_rain_by_month_is_worked_out_in_code_with_no_model(alert_state): - import json - result = json.dumps({"period": "Fri 4 Oct 2024 - Sat 3 Oct 2026", "days_checked": 731, "matching_days": 731, - "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": 1234.5}) - replies, asked = await _ask_with(alert_state, result, "rain by month for 2 years") + answer = {"answer": "Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026).", "value": 1234.5} + replies, asked = await _ask_with(alert_state, answer, "rain by month for 2 years") assert not asked and replies == ["Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026)."] @@ -594,19 +555,9 @@ async def send_chat_action(*a, **k): async def test_weather_all_week_and_a_plain_chart_are_sent_with_just_their_title(alert_state, monkeypatch): - import json from lib import bot as botmod - from lib.specs import Chart, Line, Panel - - class Tools(StandInTools): - async def call(self, name, raw, turn=None): - turn.charts.append(Chart("t", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) class Agent: - tools = Tools() - async def run(self, *a, **k): raise AssertionError("no model for a chart") sent = [] @@ -615,7 +566,7 @@ async def reply_photo(photo, caption=None, **kw): sent.append(caption) monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - for text, caption_wanted in (("ecowitt all week", True), ("temperature chart 7d", True)): + for text in ("ecowitt all week", "temperature chart 7d"): sent.clear() msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) @@ -623,23 +574,20 @@ async def reply_photo(photo, caption=None, **kw): async def send_chat_action(*a, **k): pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) + await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=chart_service(title="t")).respond(update, NS(bot=telegram(send_chat_action)), text) assert sent == ["t"], text async def test_the_report_carries_a_refresh_button_that_redraws_it_in_place(alert_state): - import json from lib import report_menu - - class Tools(StandInTools): - reading = "12.3 ℃" - - async def call(self, name, raw, turn=None): - return {"weather_now": json.dumps({"outdoor": {"temperature": self.reading}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] + from tests.fakes import StandInService + reading = ["12.3 °C"] + service = StandInService(current=lambda args, meta: { + "lines": {"station": [f"• Outdoor: {reading[0]}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + "headings": {"station": "Weather station", "air": "Air quality"}}) class Agent: - tools = Tools() + pass class Query: data, edits, toast = report_menu.REFRESH, [], None @@ -662,14 +610,14 @@ async def reply_text(body, **kw): async def send_chat_action(*a, **k): pass context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Agent(), sources, alert_state) + bot = Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service) alert_state.add_chat(1, "Rob") alert_state.set_keyboard(1, bot.keyboard_version) # its buttons are current, so a reply carries only its own await bot.respond(update, context, "report") await bot.respond(update, context, "weather now") assert [b.callback_data for b in sent[0][1].inline_keyboard[0]] == [report_menu.REFRESH] and sent[1][1] is None assert [e.type for e in sent[0][2]] == ["bold", "bold"] and sent[1][2] is None # the report's headings are bold; "weather now" has none - Tools.reading = "13.0 ℃" + reading[0] = "13.0 °C" query = Query() await bot.on_report_button(NS(callback_query=query), context) assert query.toast is None and "13.0 °C" in query.edits[0][0] and query.edits[0][1].inline_keyboard[0][0].callback_data == report_menu.REFRESH @@ -831,3 +779,10 @@ async def test_an_answer_that_comes_with_a_chart_is_not_streamed_into_the_draft( bot = DraftBot() await ask_private(alert_state, StreamingAgent(), bot, text="how hot is it") assert [t for _, t in bot.drafts][-1] == "It is 12 degrees." # a plain answer still streams + + +def chart_service(caption="Fri 25 Sep – Thu 1 Oct 2026\nHumidity: low 50 %, Fri 25 Sep at 5am · high 60 %, Sat 26 Sep at 3pm", + title="Humidity"): + """A stand-in service whose summary draws a chart titled `title` and captions it.""" + from tests.fakes import StandInService, chart_data + return StandInService(summary=lambda args, meta: {"caption": caption, "charts": [chart_data(title)]}) diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index d5bee7f4..9a28bdf0 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -180,30 +180,26 @@ async def read(self, fn, *args): def report_bot(alert_state, sheet): - """A bot whose station gives the report's tool results and, through dashboard(), its gauges (`sheet()`: a Dashboard, or raises).""" - import json - - from tests.fakes import StandInTools - - class Tools(StandInTools): - reading = "12.3 ℃" - - async def call(self, name, raw, turn=None): - return {"weather_now": json.dumps({"outdoor": {"temperature": self.reading}}), - "air_quality": json.dumps({"pm10": {"value": 3.0, "unit": "µg/m³", "rating": "🟢 good"}})}[name] + """A bot whose service gives the report's readings now (its `reading`, the outdoor temperature, which a test may change) and whose + station gives, through dashboard(), its gauges (`sheet()`: a Dashboard, or raises).""" + from tests.fakes import StandInService + now = NS(reading="12.3 °C") + service = StandInService(current=lambda args, meta: { + "lines": {"station": [f"• Outdoor: {now.reading}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + "headings": {"station": "Weather station", "air": "Air quality"}}) class Agent: - tools = Tools() + pass async def dashboard(titles=None): assert titles in (dash.STATUS, None) # the report's three gauges, or the whole dashboard return sheet() sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=dashboard), NS(name="AirGradient", wants=lambda t: True, poke=lambda: None, describe=lambda: "AirGradient")] - bot = Bot(NS(tz=TZ), Agent(), sources, alert_state) + bot = Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service) alert_state.add_chat(1, "Rob") alert_state.set_keyboard(1, bot.keyboard_version) - return bot, Agent.tools + return bot, now def three_tiles(): @@ -256,7 +252,7 @@ async def edit_message_media(self, media, reply_markup=None): async def edit_message_caption(self, caption=None, caption_entities=None, reply_markup=None): edits.append(("caption", caption, caption_entities, reply_markup)) - tools.reading = "13.0 ℃" + tools.reading = "13.0 °C" await bot.on_report_button(NS(callback_query=Query()), CONTEXT) what, caption, entities, markup = edits[-1] assert what == "media" and "13.0 °C" in caption and [e.type for e in entities] == ["bold", "bold"] @@ -265,7 +261,7 @@ async def edit_message_caption(self, caption=None, caption_entities=None, reply_ async def failing(titles=None): raise RuntimeError("cache gone") bot.by_name["Ecowitt"].dashboard = failing - tools.reading = "14.0 ℃" + tools.reading = "14.0 °C" await bot.on_report_button(NS(callback_query=Query()), CONTEXT) assert edits[-1][0] == "caption" and "14.0 °C" in edits[-1][1] # no new picture: the caption alone diff --git a/tests/test_periods.py b/tests/test_periods.py index 4338a7ce..3fd1fdbb 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -1,3 +1,4 @@ +import asyncio import json from datetime import datetime from types import SimpleNamespace as NS @@ -5,10 +6,13 @@ from lib import bot as botmod from lib import intent, periods from lib.bot import Bot -from lib.specs import Chart, Line, Panel -from tests.fakes import TZ, StandInTools +from lib.service import Service +from lib.service.summary import OVER_TIME +from lib.specs import Chart, Line, Panel, to_json +from tests.fakes import TZ NOW = datetime(2026, 10, 2, 12, 0) +ROW = [("1D", "pd:1d"), ("7D", "pd:7d"), ("1M", "pd:1m"), ("3M", "pd:3m"), ("1Y", "pd:1y")] # summary's periods, as its drawn_by lists them def labels(markup): @@ -20,7 +24,8 @@ def shaded(markup): return [b.text for row in markup.inline_keyboard for b in row if b.style == "primary"] -def test_the_row_is_always_week_month_quarter_and_year(): +def test_the_old_row_is_always_week_month_quarter_and_year(): + """(The buttons of a chart the service can't replay, which ask its question again.)""" assert labels(periods.keyboard()) == [[("1D", "pd:1"), ("7D", "pd:7"), ("1M", "pd:30"), ("3M", "pd:90"), ("1Y", "pd:365")]] assert [t for t, _ in labels(periods.keyboard(30))[0]] == ["1D", "7D", "1M", "3M", "1Y"] and shaded(periods.keyboard(30)) == ["1M"] # the chart's own period is shaded assert shaded(periods.keyboard(61)) == [] and shaded(periods.keyboard()) == [] @@ -28,6 +33,19 @@ def test_the_row_is_always_week_month_quarter_and_year(): assert periods.days_in("pd:1") == 1 and periods.days_in("pd:90") == 90 and periods.days_in("pd:365") == 365 and periods.days_in("pd:30000") is None and periods.days_in("al:on:x") is None +def test_a_charts_buttons_are_its_drawn_bys_periods_labelled_as_the_service_labels_them_its_own_shaded(): + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}, + "periods": list(OVER_TIME)} + own = periods.own_period(drawn_by, NOW, TZ) + assert own == "1m" and labels(periods.periods_keyboard(drawn_by, own)) == [ROW] and shaded(periods.periods_keyboard(drawn_by, own)) == ["1M"] + assert periods.periods_keyboard({**drawn_by, "periods": []}) is None # none listed: no buttons + months = {"tool": "days", "arguments": {"group_by": "month", "period": "2026-01-01 to 2026-10-01"}, + "periods": [{"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}, {"period": "on record", "label": "All"}]} + assert labels(periods.periods_keyboard(months)) == [[("3M", "pd:3m"), ("1Y", "pd:1y"), ("All", "pd:on record")]] # no 1D for a count per month + assert periods.period_in("pd:on record") == "on record" and periods.with_period(months, "1y") == {"group_by": "month", "period": "1y"} + assert periods.call_key("summary", {"b": 1, "a": [2]}) == periods.call_key("summary", {"a": [2], "b": 1}) == 'summary {"a":[2],"b":1}' + + def test_a_question_keeps_its_words_and_swaps_its_period(): for ask, expected in (("Temperature chart 30d", "Temperature chart 90d"), ("chart air quality last month", "chart air quality 90d"), ("rain chart for the last week", "rain chart 90d"), ("weather chart", "weather chart 90d"), @@ -37,44 +55,58 @@ def test_a_question_keeps_its_words_and_swaps_its_period(): assert intent.period_days("chart 24h", NOW) == 1 and intent.period_days("chart 365d", NOW) == 365 -def test_only_the_newest_questions_are_remembered(): +def test_only_the_newest_charts_are_remembered(): charted = periods.Charted() for i in range(periods.REMEMBERED + 5): charted.remember(1, i, f"q{i}") assert len(charted.store) == periods.REMEMBERED and charted.get(1, 0) is None and charted.get(1, periods.REMEMBERED + 4) -def test_the_questions_behind_charts_survive_a_restart(tmp_path): +def test_the_calls_behind_charts_survive_a_restart(tmp_path): from lib.alerts.notify import AlertState state = AlertState(tmp_path / "s.json") - Bot(NS(tz=TZ), None, [], state).charted.remember(1, 101, "Temperature chart 7d") + record = {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": list(OVER_TIME)}, "words": False} + Bot(NS(tz=TZ), None, [], state).charted.remember(1, 101, record) again = Bot(NS(tz=TZ), None, [], AlertState(tmp_path / "s.json")) - assert again.charted.get(1, 101) == "Temperature chart 7d" + assert again.charted.get(1, 101) == record + +class Summary: + """The service's summary as the stand-in draws it: a temperature chart of the period asked (its picture is the period's words, so a + test can tell which period it is), with its drawn_by; `refuse` the periods it refuses, `slow` those it waits on.""" + name = "summary" -class Tools(StandInTools): def __init__(self): - self.calls = [] + self.calls, self.refuse, self.slow = [], set(), {} - async def call(self, name, raw, turn=None): - self.calls.append((name, json.loads(raw))) - turn.charts.append(Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 01 Oct 2026", "series": {"outdoor.temperature": {"unit": "℃", "low": "1", "high": "2"}}}) + async def call(self, args, meta=None): + self.calls.append(dict(args)) + period = args.get("period") or "last 24 hours" + if period in self.slow: + await self.slow[period].wait() + if period in self.refuse: + return json.dumps({"error": f"Nothing is held for {period}."}) + chart = Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])]) + arguments = {**{k: v for k, v in args.items() if k not in ("start", "end")}, "period": period} + data = {**to_json(chart, TZ), "drawn_by": {"tool": "summary", "arguments": arguments, "periods": [dict(p) for p in OVER_TIME]}} + return json.dumps({"caption": "Fri 25 Sep – Thu 1 Oct 2026\nTemperature: low 1 °C · high 2 °C", "charts": [data]}) def make_bot(alert_state, monkeypatch): class Agent: - tools = Tools() - async def run(self, *a, **k): raise AssertionError("no model for a plain chart") - monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: data["drawn_by"]["arguments"]["period"].encode()) sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - return Bot(NS(tz=TZ), Agent(), sources, alert_state) + return Bot(NS(tz=TZ), Agent(), sources, alert_state, service=Service([Summary()])) + + +def calls(bot) -> list[dict]: + """The calls the bot made of the service's summary.""" + return bot.service["summary"].calls async def test_closing_the_bot_cancels_its_uploads_still_running(alert_state, monkeypatch): - import asyncio bot = make_bot(alert_state, monkeypatch) upload = asyncio.create_task(asyncio.Event().wait()) bot.tasks.running.add(upload) @@ -100,32 +132,53 @@ async def send_chat_action(*a, **k): CONTEXT = NS(bot=NS(send_chat_action=send_chat_action, send_message_draft=send_chat_action, id=99)) -async def test_a_chart_is_sent_with_the_other_periods_under_it_and_its_question_is_remembered(alert_state, monkeypatch): +def press(msg, data, answer): + return NS(callback_query=NS(data=data, message=msg, answer=answer), effective_message=msg, effective_chat=msg.chat, + effective_user=NS(username="rob", full_name="Rob")) + + +async def test_a_chart_is_sent_with_its_periods_under_it_and_its_call_is_remembered(alert_state, monkeypatch): bot, sent = make_bot(alert_state, monkeypatch), [] msg = chat_message(sent) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) await bot.respond(update, CONTEXT, "Temperature chart 30d") caption, markup = sent[0] - assert caption == "Temperature" and labels(markup) == [[("1D", "pd:1"), ("7D", "pd:7"), ("1M", "pd:30"), ("3M", "pd:90"), ("1Y", "pd:365")]] - assert bot.charted.get(1, 101) == "Temperature chart 30d" + assert caption == "Temperature" and labels(markup) == [ROW] and shaded(markup) == ["1M"] + assert calls(bot) == [{"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 30 days", "chart": True}] + record = bot.charted.get(1, 101) + assert record["drawn_by"]["arguments"]["period"] == "last 30 days" and record["words"] is False -async def test_pressing_a_period_redraws_the_chart_in_place_with_that_period_left_out(alert_state, monkeypatch): +async def test_pressing_a_period_replays_the_charts_call_with_that_period_in_place(alert_state, monkeypatch): bot, edits = make_bot(alert_state, monkeypatch), [] msg = chat_message([], edits) - bot.charted.remember(1, 50, "Temperature chart 30d") + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": drawn_by, "words": False}) answers = [] - async def answer(text=None): + async def answer(text=None, **k): answers.append(text) - query = NS(data="pd:90", message=msg, answer=answer) - update = NS(callback_query=query, effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.on_period_button(update, CONTEXT) - name, args = bot.agent.tools.calls[0] - assert name == "weather_history" and args["start_date"].startswith("2026-") and answers == ["Drawing 3M..."] + await bot.on_period_button(press(msg, "pd:3m", answer), CONTEXT) + assert calls(bot) == [{"readings": ["outdoor.temperature"], "period": "3m", "chart": True}] and answers == ["Drawing 3M..."] caption, markup = edits[0] - assert caption == "Temperature" and [t for t, _ in labels(markup)[0]] == ["1D", "7D", "1M", "3M", "1Y"] and shaded(markup) == ["3M"] - assert bot.charted.get(1, 50) == "Temperature chart 90d" + assert caption == "Temperature" and labels(markup) == [ROW] and shaded(markup) == ["3M"] + assert bot.charted.get(1, 50)["drawn_by"]["arguments"]["period"] == "3m" + + +async def test_a_replay_the_service_refuses_shows_its_refusal_on_the_button(alert_state, monkeypatch): + bot, edits = make_bot(alert_state, monkeypatch), [] + bot.service["summary"].refuse.add("1y") + msg = chat_message([], edits) + bot.charted.remember(1, 50, {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}}) + answers = [] + + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) + assert answers == ["Nothing is held for 1y."] and edits == [] + await bot.on_period_button(press(msg, "pd:2y", answer), CONTEXT) # a period the chart doesn't list + assert answers[-1] == "That chart is out of date, please ask again" async def test_a_button_on_a_chart_from_before_a_restart_says_so(alert_state, monkeypatch): @@ -135,8 +188,8 @@ async def test_a_button_on_a_chart_from_before_a_restart_says_so(alert_state, mo async def answer(text=None): answers.append(text) msg = chat_message([]) - await bot.on_period_button(NS(callback_query=NS(data="pd:7", message=msg, answer=answer)), CONTEXT) - assert answers == ["That chart is out of date, please ask again"] and not bot.agent.tools.calls + await bot.on_period_button(press(msg, "pd:7d", answer), CONTEXT) + assert answers == ["That chart is out of date, please ask again"] and not calls(bot) async def test_a_reply_with_period_buttons_leaves_the_persistent_keyboard_for_the_next_reply(): @@ -154,10 +207,10 @@ async def reply_photo(self, photo, **kw): def test_a_chart_drawn_lately_comes_back_from_the_cache_until_it_is_too_old_or_pushed_out(): clock = [0.0] cache = periods.ImageCache(lambda: clock[0]) - key = cache.key("Temperature chart 30d", 30, NOW) - assert key == cache.key("temperature chart for the last month", 30, NOW) and cache.get(key) is None - cache.put(key, b"png", "Temperature") - assert cache.get(key) == (b"png", "Temperature") + key = periods.call_key("summary", {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}) + assert cache.get(key) is None + cache.put(key, b"png", "Temperature", drawn_by={"tool": "summary", "arguments": {"period": "1m"}, "periods": []}) + assert cache.get(key) == (b"png", "Temperature") == cache.get('summary {"period":"1m"}') # under the call drawn_by states too clock[0] = periods.ImageCache.CHART_TTL + 1 assert cache.get(key) is None for i in range(periods.ImageCache.CHART_IMAGES + 3): @@ -175,11 +228,18 @@ async def test_toggling_back_to_a_period_just_drawn_uses_the_cached_image_and_as async def answer(text=None): answers.append(text) msg.message_id = 101 - for days in (30, 30, 7, 30, 7): - await bot.on_period_button(NS(callback_query=NS(data=f"pd:{days}", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), CONTEXT) - assert len(bot.agent.tools.calls) == 2 # the first send and the first 30d: the rest came from the cache (a press on the shown 30d does nothing) - assert [e[0] for e in edits] == ["Temperature"] * 4 # the repeated 30d press edited nothing and bot.charted[(1, 101)] == "Temperature chart 7d" + for period in ("1m", "1m", "7d", "1m", "7d"): + await bot.on_period_button(press(msg, f"pd:{period}", answer), CONTEXT) + assert len(calls(bot)) == 2 # the first send and the first 1M: the rest came from the cache (a press on the shown 1M does nothing) + assert [e[0] for e in edits] == ["Temperature"] * 4 # the repeated 1M press edited nothing + + +async def test_two_wordings_of_one_chart_share_one_picture(alert_state, monkeypatch): + bot, sent = make_bot(alert_state, monkeypatch), [] + update = pressed(bot, sent) + await bot.respond(update, CONTEXT, "Temperature chart 7d") + await bot.respond(update, CONTEXT, "temperature chart for the last 7 days") + assert len(calls(bot)) == 1 and sent[1][0] == "copy 1" # the same call: drawn once, sent as Telegram's copy async def test_a_chart_once_sent_goes_again_as_telegrams_copy_not_a_new_upload(alert_state, monkeypatch): @@ -199,10 +259,9 @@ async def edit_media(media, reply_markup=None): async def answer(text=None): pass - for days in (30, 7, 30): - await bot.on_period_button(NS(callback_query=NS(data=f"pd:{days}", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), CONTEXT) - assert uploads == [b"png"] and edits == ["upload", "7d", "edit 1"] # 30d drawn and uploaded once; then both by Telegram's copy + for period in ("1m", "7d", "1m"): + await bot.on_period_button(press(msg, f"pd:{period}", answer), CONTEXT) + assert uploads == [b"last 7 days"] and edits == ["upload", "7d", "edit 1"] # 1M drawn and uploaded once; then both by Telegram's copy async def test_redrawing_a_chart_from_a_button_shows_no_typing_or_thinking(alert_state, monkeypatch): @@ -238,42 +297,37 @@ async def test_a_chart_just_drawn_is_sent_again_at_once_and_then_as_telegrams_co bot, sent = make_bot(alert_state, monkeypatch), [] update = pressed(bot, sent) await bot.respond(update, CONTEXT, "Temperature chart 1d") - calls = len(bot.agent.tools.calls) - assert calls >= 1 and sent == [(b"png", "Temperature")] + asked = len(calls(bot)) + assert asked == 1 and sent == [(b"last 24 hours", "Temperature")] await bot.respond(update, CONTEXT, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls and sent[-1] == ("copy 1", "Temperature") # drawn lately: no new question, Telegram's copy + assert len(calls(bot)) == asked and sent[-1] == ("copy 1", "Temperature") # drawn lately: no new call, Telegram's copy history = bot.chats[(1, None)].history - assert history[-1]["role"] == "assistant" and history[-1]["content"] # its text is kept, as a drawn one's is + assert history[-1]["role"] == "assistant" and history[-1]["content"] # its text is kept, as a drawn one's is -async def test_a_chart_is_drawn_again_once_it_is_stale_and_never_answers_other_words(alert_state, monkeypatch): +async def test_a_chart_is_drawn_again_once_it_is_stale_and_never_answers_another_call(alert_state, monkeypatch): clock = [0.0] bot, sent = make_bot(alert_state, monkeypatch), [] bot.images = periods.ImageCache(lambda: clock[0]) await bot.respond(pressed(bot, sent), CONTEXT, "Temperature chart 1d") - calls = len(bot.agent.tools.calls) - await bot.respond(pressed(bot, sent), CONTEXT, "temperature chart today") # kept under the 1d key, but since midnight: drawn - assert len(bot.agent.tools.calls) == calls + 1 - calls = len(bot.agent.tools.calls) + asked = len(calls(bot)) + await bot.respond(pressed(bot, sent), CONTEXT, "temperature chart today") # since midnight: another call, drawn + assert len(calls(bot)) == asked + 1 + asked = len(calls(bot)) clock[0] = periods.ImageCache.FRESH + 1 await bot.respond(pressed(bot, sent), CONTEXT, "Temperature chart 1d") # too old to send as it is - assert len(bot.agent.tools.calls) == calls + 1 + assert len(calls(bot)) == asked + 1 def preloading_bot(alert_state, monkeypatch, refuse=None, clock=None): """A bot with TELEGRAM_PRELOAD_CHAT set, and the (chat, photo, silent) of every upload to it. The periods are uploaded side by side, - in no fixed order, so each period's picture is its question's words and its file id "file " and those words; context.refused.error + in no fixed order, so each period's picture is its period's words and its file id "file " and those words; context.refused.error is what the uploads raise (none: they go through).""" bot, uploads, refused = make_bot(alert_state, monkeypatch), [], NS(error=refuse) bot.cfg = NS(tz=TZ, telegram_preload_chat=-1001) if clock: bot.images = periods.ImageCache(lambda: clock[0]) - draw = bot._draw_ahead - - async def draw_ahead(text, now): - key, _, title, caption, newest = await draw(text, now) - return key, text.encode(), title, caption, newest - bot._draw_ahead = draw_ahead + bot.alert_charts.images = bot.images async def send_photo(chat, photo, caption=None, disable_notification=False): if refused.error: @@ -283,13 +337,12 @@ async def send_photo(chat, photo, caption=None, disable_notification=False): return bot, uploads, NS(bot=NS(send_chat_action=send_chat_action, send_message_draft=send_chat_action, send_photo=send_photo, id=99), refused=refused) -def uploads_of(*days): - """What the uploads to the preload chat are, in any order, when they are the Temperature charts of these periods.""" - return sorted((-1001, f"Temperature chart {d}d".encode(), True) for d in days) +def uploads_of(*periods_): + """What the uploads to the preload chat are, in any order, when they are the charts of these periods.""" + return sorted((-1001, p.encode(), True) for p in periods_) async def settle(bot): - import asyncio await asyncio.gather(*bot.tasks.running) @@ -305,14 +358,14 @@ async def edit_media(media, reply_markup=None): await bot.respond(NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), context, "Temperature chart 7d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 30, 90, 365) # 1D, 1M, 3M, 1Y: not the 7D just sent - calls = len(bot.agent.tools.calls) + assert sorted(uploads) == uploads_of("1d", "1m", "3m", "1y") # 1D, 1M, 3M, 1Y: not the 7D just sent + assert all(c["period"] in ("last 7 days", "1d", "1m", "3m", "1y") for c in calls(bot)) + asked = len(calls(bot)) async def answer(text=None): pass - await bot.on_period_button(NS(callback_query=NS(data="pd:90", message=msg, answer=answer), effective_message=msg, - effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")), context) - assert len(bot.agent.tools.calls) == calls and edits[0] == "file Temperature chart 90d" # Telegram's copy of the 3M, no new question or upload + await bot.on_period_button(press(msg, "pd:3m", answer), context) + assert len(calls(bot)) == asked and edits[0] == "file 3m" # Telegram's copy of the 3M, no new call or upload async def test_nothing_is_uploaded_ahead_without_the_setting_and_a_refused_upload_stops_it_with_one_warning(alert_state, monkeypatch, caplog): @@ -349,46 +402,39 @@ async def test_a_flood_limit_or_a_timeout_skips_those_uploads_and_the_next_chart context.refused.error = None await bot.respond(pressed(bot, []), context, "Temperature chart 90d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 365) # the 7D and the 1M were sent as the questions' own charts + assert sorted(uploads) == uploads_of("1d", "3m", "1y") # the 7D and the 1M were sent as the questions' own charts (3M is 91 days) async def test_a_period_that_cannot_be_drawn_is_left_out_and_the_others_are_uploaded(alert_state, monkeypatch): bot, uploads, context = preloading_bot(alert_state, monkeypatch) - draw = bot._draw_ahead - - async def draw_ahead(text, now): - if text.endswith("90d"): - raise ValueError("no readings") - return await draw(text, now) - bot._draw_ahead = draw_ahead + bot.service["summary"].refuse.add("3m") await bot.respond(pressed(bot, []), context, "Temperature chart 7d") await settle(bot) - assert sorted(uploads) == uploads_of(1, 30, 365) - assert bot.images.has_copy(bot.images.key("Temperature chart 30d", 30, NOW)) and not bot.images.has_copy(bot.images.key("Temperature chart 90d", 90, NOW)) + assert sorted(uploads) == uploads_of("1d", "1m", "1y") + drawn_by = bot.images.held(periods.call_key("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], + "period": "last 7 days", "chart": True})).drawn_by + key = lambda p: periods.call_key("summary", periods.with_period(drawn_by, p)) + assert bot.images.has_copy(key("1m")) and not bot.images.has_copy(key("3m")) async def test_each_period_is_uploaded_as_soon_as_it_is_drawn_not_when_the_slowest_is(alert_state, monkeypatch): - import asyncio bot, uploads, context = preloading_bot(alert_state, monkeypatch) - slow, three, draw, send = asyncio.Event(), asyncio.Event(), bot._draw_ahead, context.bot.send_photo - - async def draw_ahead(text, now): - if text.endswith("chart 1d"): - await slow.wait() - return await draw(text, now) + slow, three, send = asyncio.Event(), asyncio.Event(), context.bot.send_photo + bot.service["summary"].slow["1d"] = slow async def send_photo(chat, photo, **kw): message = await send(chat, photo, **kw) if len(uploads) == 3: three.set() return message - bot._draw_ahead, context.bot.send_photo = draw_ahead, send_photo - bot.preload_soon(context.bot, "Temperature chart 7d") + context.bot.send_photo = send_photo + bot.preload_soon(context.bot, {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "7d", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]}) await asyncio.wait_for(three.wait(), 5) - assert sorted(uploads) == uploads_of(30, 90, 365) # the 1D, first in line, is still being drawn + assert sorted(uploads) == uploads_of("1m", "3m", "1y") # the 1D, first in line, is still being drawn slow.set() await asyncio.wait_for(settle(bot), 5) - assert sorted(uploads) == uploads_of(1, 30, 90, 365) + assert sorted(uploads) == uploads_of("1d", "1m", "3m", "1y") async def test_a_chart_uploaded_ahead_is_used_for_30_minutes_and_then_drawn_afresh(alert_state, monkeypatch): @@ -396,7 +442,7 @@ async def test_a_chart_uploaded_ahead_is_used_for_30_minutes_and_then_drawn_afre bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) await bot.respond(pressed(bot, []), context, "Temperature chart 7d") await settle(bot) - key = bot.images.key("Temperature chart 30d", 30, NOW) + key = periods.call_key("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "1m", "chart": True}) clock[0] = 29 * 60 assert bot.images.has_copy(key) and isinstance(bot.images.get(key)[0], str) clock[0] = 31 * 60 @@ -417,7 +463,9 @@ async def reply_text(text, **kw): async def test_pressing_a_period_under_a_chart_the_model_drew_keeps_its_answer_in_the_caption(alert_state, monkeypatch): + """A chart the model drew with a call the service has no equivalent of: its question is asked again, as before.""" bot, edits, replies = make_bot(alert_state, monkeypatch), [], [] + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") class Agent: ready = True @@ -435,35 +483,67 @@ async def reply_text(text, **kw): async def answer(text=None): pass - update = NS(callback_query=NS(data="pd:7", message=msg, answer=answer), effective_message=msg, effective_chat=msg.chat, - effective_user=NS(username="rob", full_name="Rob")) - await bot.on_period_button(update, CONTEXT) + await bot.on_period_button(press(msg, "pd:7", answer), CONTEXT) assert replies == [] and edits and "Humidity: Ecowitt 72.1% avg." in edits[0][0] +async def test_a_chart_the_model_drew_through_an_old_tool_gets_a_drawn_by_and_its_buttons_replay_it(alert_state, monkeypatch): + from lib.tools import Tool, Tools + bot, sent = make_bot(alert_state, monkeypatch), [] + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") + + async def weather_history(args, turn): + turn.charts.append(Chart("Pressure", "", [Panel("Pressure", "hPa", [Line("Pressure", [1, 2], [1.0, 2.0])])])) + return json.dumps({"period": "Fri 25 Sep 2026 - Thu 1 Oct 2026"}) + tools = Tools([Tool("weather_history", "", {"type": "object", "properties": {}}, weather_history)]) + + class Agent: + ready = True + + async def run(self, working, system, effort, turn=None, **kw): + await tools.call("weather_history", json.dumps({"groups": "pressure", "chart": True, "chart_field": "pressure", + "start_date": "2026-09-25 00:00:00", "end_date": "2026-10-01 23:59:59"}), turn) + return "Pressure fell all week." + bot.agent = Agent() + await bot.respond(pressed(bot, sent), CONTEXT, "how did the pressure change from 25 Sep to 1 Oct, and why?") + record = bot.charted.get(1, 101) + assert record["drawn_by"] == {"tool": "summary", "arguments": {"readings": ["pressure.relative"], "period": "2026-09-25 to 2026-10-01", + "chart": True}, "periods": [dict(p) for p in OVER_TIME]} + assert record["words"] is True + + async def test_the_keyboards_charts_are_drawn_ahead_and_a_press_is_answered_from_them(alert_state, monkeypatch): - from lib.timeutil import now_local clock = [0.0] bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) bot.cfg = NS(tz=TZ) # no preload chat: drawn, not uploaded await bot.draw_buttons_ahead(context.bot) + from lib.timeutil import now_local now = now_local(TZ) - assert uploads == [] and bot.images.ready("Temperature chart 1d", now) # (the stand-in's tools only have temperature) - assert bot.images.ready("Air quality all metrics 1d", now) is None # no air sensor here: nothing to draw - calls, sent = len(bot.agent.tools.calls), [] + assert uploads == [] and bot.images.ready(periods.call_key(*bot._sentence_call("Temperature chart 1d", now))) + assert bot._sentence_call("Air quality all metrics 1d", now) is None # no air sensor here: nothing to draw + asked, sent = len(calls(bot)), [] await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls and sent[0][0] == b"Temperature chart 1d" # the one drawn ahead: no new question + assert len(calls(bot)) == asked and sent[0][0] == b"last 24 hours" # the one drawn ahead: no new call clock[0] += 400 # too old to answer with: the press draws afresh await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert len(bot.agent.tools.calls) == calls + 1 - drawn, draw = [], bot._draw_ahead + assert len(calls(bot)) == asked + 1 + asked = len(calls(bot)) + await bot.draw_buttons_ahead(context.bot) + drawn = [c["readings"] for c in calls(bot)[asked:]] + assert ["outdoor.humidity", "indoor.humidity"] in drawn and ["outdoor.temperature", "indoor.temperature"] not in drawn # just drawn: left alone - async def counting(text, now): - drawn.append(text) - return await draw(text, now) - bot._draw_ahead = counting + +async def test_the_keyboards_charts_are_drawn_ahead_as_background_requests(alert_state, monkeypatch): + bot, _, context = preloading_bot(alert_state, monkeypatch) + metas = [] + call = bot.service["summary"].call + + async def counting(args, meta=None): + metas.append(meta) + return await call(args, meta) + bot.service["summary"].call = counting await bot.draw_buttons_ahead(context.bot) - assert "Humidity chart 1d" in drawn and "Temperature chart 1d" not in drawn # just drawn for the press: left alone this time + assert metas and all(m["priority"] == "background" and m["chart_points"] == "drawn" for m in metas) async def test_the_keyboards_charts_are_uploaded_ahead_only_while_the_bot_is_in_use(alert_state, monkeypatch): @@ -476,10 +556,10 @@ async def test_the_keyboards_charts_are_uploaded_ahead_only_while_the_bot_is_in_ bot.noticed() clock[0] += 120 await bot.draw_buttons_ahead(context.bot) - assert (-1001, b"Temperature chart 1d", True) in uploads + assert (-1001, b"last 24 hours", True) in uploads sent = [] await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert sent[0][0] == "file Temperature chart 1d" # a press sends Telegram's copy + assert sent[0][0] == "file last 24 hours" # a press sends Telegram's copy await settle(bot) # (the press's other periods, uploaded ahead) uploads.clear() clock[0] += 120 @@ -499,36 +579,33 @@ async def test_the_chart_of_an_alert_sent_lately_is_drawn_ahead_with_the_keyboar clock = [0.0] bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) bot.alert_charts.clock = lambda: clock[0] - drawn = [] - - async def counting(text, now): # draws any request (the stand-in's tools draw only temperature) - drawn.append(text) - return bot.images.canonical(text, now), text.encode(), text, "caption", 0 - bot._draw_ahead = counting + uv, temperature = ["solar_and_uvi.uvi"], ["outdoor.temperature", "indoor.temperature"] + drawn = lambda since: [c["readings"] for c in calls(bot)[since:]] await bot.draw_buttons_ahead(context.bot) - assert "UV chart 1d" not in drawn and "Temperature chart 1d" in drawn # UV is no button: not drawn until an alert + assert uv not in drawn(0) and temperature in drawn(0) # UV is no button: not drawn until an alert bot.alert_charts.sent("uv", NS(photo=(NS(file_id="large"),))) bot.alert_charts.sent("temps", NS(photo=(NS(file_id="large"),))) - drawn.clear() + since = len(calls(bot)) clock[0] += 300 await bot.draw_buttons_ahead(context.bot) - assert drawn.count("UV chart 1d") == 1 and drawn.count("Temperature chart 1d") == 1 # the alert's chart too, the button's once + assert drawn(since).count(uv) == 1 and drawn(since).count(temperature) == 1 # the alert's chart too, the button's once bot.noticed() clock[0] += 300 + uploads.clear() + since = len(calls(bot)) await bot.draw_buttons_ahead(context.bot) - assert (-1001, b"UV chart 1d", True) in uploads # uploaded ahead with the keyboard's - drawn.clear() + assert uv in drawn(since) and len(uploads) == len(drawn(since)) # uploaded ahead with the keyboard's + since = len(calls(bot)) clock[0] += AlertCharts.WARM_SECONDS await bot.draw_buttons_ahead(context.bot) - assert "UV chart 1d" not in drawn # six hours on: no longer kept warm + assert uv not in drawn(since) # six hours on: no longer kept warm def test_a_chart_drawn_in_one_theme_is_not_sent_again_after_the_theme_changes(monkeypatch): from lib import charts images = periods.ImageCache(lambda: 0.0) monkeypatch.setattr(charts, "MODE", "off") - images.put("temperature chart 1d", b"light", "T", "caption") - assert images.get("temperature chart 1d") and images.ready("Temperature chart 1d", NOW) + images.put("summary {}", b"light", "T", "caption") + assert images.get("summary {}") and images.ready("summary {}") monkeypatch.setattr(charts, "MODE", "on") # 8pm under DARKMODE=8pm-8am - assert images.ready("Temperature chart 1d", NOW) is None and images.get("temperature chart 1d") is None - + assert images.ready("summary {}") is None and images.get("summary {}") is None diff --git a/tests/test_pollen.py b/tests/test_pollen.py index ce95c4c9..b687f26f 100644 --- a/tests/test_pollen.py +++ b/tests/test_pollen.py @@ -164,7 +164,7 @@ async def test_out_of_season_nothing_is_fetched_not_even_at_start_with_an_empty_ async def test_last_seasons_page_is_not_shown_and_the_report_leaves_the_block_out(tmp_path): - from lib import report + from tests import report_words as report pollen, _ = make_on(tmp_path, date(2026, 12, 20), html=lambda: page(grass="High", day=date(2026, 12, 20))) await pollen.start() assert pollen.lines()[0].startswith("Grass pollen forecast: 🔴 High") diff --git a/tests/test_report.py b/tests/test_report.py index b3cc5f1d..d0e4521f 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -2,6 +2,7 @@ from datetime import date from lib import report +from tests import report_words # (the bot's old report, for text to set bold) # What `python scripts/report_inputs.py` printed on the real station (rain, night), its time as the station now writes it NOW = ('{"time":"Fri 2 Oct 2026 2:21am","outdoor":{"temperature":"12.3 ℃","feels_like":"12.3 ℃","app_temp":"12.7 ℃","dew_point":"11.3 ℃",' @@ -23,103 +24,6 @@ TODAY = date(2026, 10, 2) # the day the results above are from -WEATHER = """\ -• Outdoor: 🧥 12.3 °C, 💦 94 % -• Indoor: 🧥 18.3 °C, 63 % -• Pressure: 🗜️ 1025.0 hPa -• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)""" # night and calm: no Sun or Wind line - - -def test_the_report_is_laid_out_in_code_with_emoji_before_the_readings_they_belong_to(): - got = report.report({"weather_now": NOW, "air_quality": AIR, "pollen_asthma": POLLEN, "weather_forecast": FORECAST}, TODAY) - assert got == f"""Weather station (2:21am) -{WEATHER} - -Air quality (2:22am) -• PM2.5: 1.4 µg/m³ 🟢 good (AQI 8) -• PM10: 3.0 µg/m³ 🟢 good -• PM1: 1.0 µg/m³ 🟢 good -• CO₂: 433 ppm 🟢 good -• VOC index: 88 🟢 good -• NOx index: 1.0 🟢 good - -Pollen & asthma (Melbourne, 6:00pm) -• Grass pollen forecast: 🟢 Low -• Thunderstorm asthma forecast: 🟢 Low - -Forecast (Melbourne, 6:05pm) -• Today: 🌦️ Showers. 11–16°C, 97% chance of rain -• Saturday: ⛈️ Thunderstorm. 12–20°C, 95% chance of rain""" - assert not got.startswith("Current report") - - -def test_weather_now_is_just_the_weather_stations_bullets(): - assert report.weather_now(NOW) == WEATHER - assert report.weather_now("Error calling tool: timed out") is None and report.weather_now(None) is None - - -def test_a_dry_calm_day_has_no_rain_line_noise(): - dry = ('{"outdoor":{"temperature":"21.0 ℃","humidity":"50 %"},"rainfall":{"rain_rate":"0.0 mm/hr","daily":"0.0 mm","monthly":"12.0 mm"},' - '"wind":{"wind_speed":"12.0 km/h","wind_gust":"20.0 km/h","wind_direction":"270 º"},"emoji":{}}') - lines = report.weather_now(dry).splitlines() - assert lines == ["• Outdoor: 21.0 °C, 50 %", "• Rain today: 0.0 mm (month total 12.0 mm)", "• Wind: 12.0 km/h from 270°, gust 20.0 km/h"] - drizzle = dry.replace('"0.0 mm/hr"', '"0.6 mm/hr"').replace('"emoji":{}', '"emoji":{"rainfall.rain_rate":"🌧️"}') - assert "; 🌧️ raining (0.6 mm/h)" in report.weather_now(drizzle) - assert "raining" not in report.weather_now(dry.replace('"0.0 mm/hr"', '"0.00 mm/hr"')) # however the zero is written - - -def test_a_failed_or_missing_source_is_left_out_or_said_so_and_the_forecast_without_a_tag_has_a_plain_heading(): - got = report.report({"weather_now": "Error calling tool: boom", "air_quality": AIR, - "pollen_asthma": '{"error": "No pollen levels are available right now."}', - "weather_forecast": '{"lines": ["Today: ☀️ Sunny. 20–25°C"]}'}, TODAY) - assert got.startswith("Weather station\n• not available right now\n\nAir quality (2:22am)\n• PM2.5:") - assert "Pollen" not in got and got.endswith("Forecast\n• Today: ☀️ Sunny. 20–25°C") - assert report.report({}, TODAY) == "No readings are available right now." - - -def test_sun_uv_and_wind_are_left_out_when_zero_and_shown_when_not(): - day = NOW.replace('"solar":"0.0 W/m²","uvi":"0"', '"solar":"612.5 W/m²","uvi":"7"').replace( - '"wind_speed":"0.0 km/h","wind_gust":"0.0 km/h"', '"wind_speed":"14.0 km/h","wind_gust":"31.0 km/h"') - got = report.weather_now(day).splitlines() - assert got[-2:] == ["• Sun: solar radiation 612.5 W/m² (high), UV index 7", "• Wind: 14.0 km/h from 131°, gust 31.0 km/h"] - only_uv = report.weather_now(NOW.replace('"uvi":"0"', '"uvi":"3"')) - assert "• Sun: UV index 3" in only_uv and "solar" not in only_uv - gusty = report.weather_now(NOW.replace('"wind_gust":"0.0 km/h"', '"wind_gust":"9.0 km/h"')) - assert "• Wind: 0.0 km/h from 131°, gust 9.0 km/h" in gusty - assert "Sun" not in report.weather_now(NOW) and "Wind" not in report.weather_now(NOW) - - -def test_every_emoji_threshold_the_station_reports_shows_in_the_report_at_its_reading(): - from lib.ecowitt.glance import glance - now = ('{"outdoor":{"temperature":"36.0 ℃","humidity":"90 %","dew_point":"18.0 ℃","vpd":"1.300 kPa"},"indoor":{"temperature":"29.0 ℃","humidity":"20 %"},' - '"pressure":{"relative":"1030.0 hPa"},"rainfall":{"rain_rate":"2.0 mm/hr","daily":"3.0 mm","monthly":"9.0 mm"},' - '"solar_and_uvi":{"solar":"800.0 W/m²","uvi":"10"},"wind":{"wind_speed":"55.0 km/h","wind_gust":"70.0 km/h","wind_direction":"90 º"}}') - import json - data = json.loads(now) - data["emoji"] = {f"{g}.{f}": e for g, fields in data.items() for f, v in fields.items() - if (e := glance(g, f, float(v.split()[0])))} - got = report.weather_now(json.dumps(data)) - assert got.splitlines() == [ - "• Outdoor: 🔥 36.0 °C, 💦 90 %", - "• Indoor: 🥵 29.0 °C, 🏜️ 20 %", - "• Pressure: 🗜️ 1030.0 hPa", - "• Rain today: ☔ 3.0 mm (month total 9.0 mm); 🌧️ raining (2.0 mm/h)", - "• Sun: ☀️ solar radiation 800.0 W/m² (high), 🧴 UV index 10", - "• Wind: 🌪️ 55.0 km/h from 90°, gust 🌪️ 70.0 km/h"] - - -def test_solar_radiation_is_rated_low_medium_or_high(): - from lib.ecowitt.glance import solar_band - assert [solar_band(v) for v in (0.1, 40.2, 199.9, 200, 599.9, 600, 1000)] == ["low", "low", "low", "medium", "medium", "high", "high"] - - def sun(solar): - return report.weather_now('{"solar_and_uvi":{"solar":"%s","uvi":"0"},"emoji":{}}' % solar) - assert sun("40.2 W/m²") == "• Sun: solar radiation 40.2 W/m² (low)" - assert sun("350.0 W/m²") == "• Sun: solar radiation 350.0 W/m² (medium)" - assert sun("0.0 W/m²") == "" # zero is left out, so there is no Sun line - assert sun("n/a") == "• Sun: solar radiation n/a" # unreadable: shown as it came, with no rating - - # ---------- chart captions ---------- def _turn(**kw): from types import SimpleNamespace as NS @@ -178,49 +82,7 @@ def test_no_caption_when_the_tool_failed_or_drew_nothing(): assert report.chart_caption("weather_history", {}, json.dumps({"series": {}}), NS(charts=[]), ZoneInfo("UTC")) is None -# ---------- plain lookups ---------- -def test_a_reading_lookup_prints_only_what_was_asked(): - now = json.loads(NOW) - assert report.reading_lines(now, ["temperature"], ["outdoor", "indoor"]) == [ - "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C", "• Indoor: 🧥 18.3 °C, feels like 18.3 °C"] - assert report.reading_lines(now, ["humidity"], ["outdoor"]) == ["• Outdoor: 💦 94 %"] - assert report.reading_lines(now, ["wind"], []) == ["• Wind: calm"] - assert report.reading_lines(now, ["pressure"], []) == ["• Pressure: 🗜️ 1025.0 hPa"] - assert report.reading_lines(now, ["dew_point"], ["indoor"]) == ["• Dew point (indoor): 11.1 °C"] # "indoor dew point" - assert report.reading_lines(now, ["feels_like"], ["outdoor", "indoor"])[0].startswith("• Feels like: ") # unasked: outdoor - assert report.reading_lines(now, ["rain"], [])[0].startswith("• Rain today: ☔ 6.3 mm") and "raining (1.8 mm/h)" in report.reading_lines(now, ["rain"], [])[0] - windy = json.loads(NOW.replace('"wind_speed":"0.0 km/h"', '"wind_speed":"14.0 km/h"')) - assert [line for line in report.weather_lines(windy) if line.startswith(("• Wind", "• Rain"))] == \ - report.reading_lines(windy, ["rain", "wind"], []) # the same words as the report's - - -def test_air_pollen_and_forecast_lookups_print_the_tools_own_lines(): - assert report.lookup("air", AIR, ["pm10"], [], TODAY) == "• PM10: 3.0 µg/m³ 🟢 good" - assert report.lookup("air", AIR, [], [], TODAY).splitlines()[0] == "• PM2.5: 1.4 µg/m³ 🟢 good (AQI 8)" - assert report.lookup("pollen", POLLEN, [], [], TODAY) == "Pollen & asthma (Melbourne, 6:00pm)\n• Grass pollen forecast: 🟢 Low\n• Thunderstorm asthma forecast: 🟢 Low" - assert report.lookup("forecast", FORECAST, [], [], TODAY).startswith("Forecast (Melbourne, 6:05pm)\n• Today: ") - assert report.lookup("pollen", json.dumps({"error": "off season"}), [], [], TODAY) is None - - -def test_a_short_period_highs_and_lows_lookup_gives_each_sides_extremes_with_their_times(): - result = json.dumps({"period": "Fri 02 Oct 2026 - Fri 02 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "9.0", "low_when": "at 5am", "low_date": "Fri 2 Oct 2026", - "high": "16.2", "high_when": "at 2pm", "high_date": "Fri 2 Oct 2026"}, - "outdoor.humidity": {"unit": "%", "low": "40", "high": "95"}}}) - assert report.lookup("extremes", result, [], [], TODAY) == ("Fri 02 Oct – Fri 02 Oct 2026\n" - "• Temperature: low 9.0 °C, Fri 2 Oct at 5am · high 16.2 °C, Fri 2 Oct at 2pm") - - -def test_an_average_or_highs_lookup_covers_the_readings_named(): - result = json.dumps({"period": "Thu 01 Oct 2026 - Thu 01 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "9.0", "high": "16.2", "average": "12.4"}, - "outdoor.humidity": {"unit": "%", "low": "40", "high": "95", "low_when": "at 3pm", "low_date": "Thu 1 Oct 2026", "high_when": "at 5am", "high_date": "Thu 1 Oct 2026"}, - "wind.wind_speed": {"unit": "km/h", "low": "0", "high": "14"}, "wind.wind_gust": {"unit": "km/h", "low": "0", "high": "31", "high_when": "at 2pm", "high_date": "Thu 1 Oct 2026"}}}) - assert report.lookup("extremes", result, ["temperature"], [], TODAY).splitlines()[1] == "• Temperature: average 12.4 °C (low 9.0, high 16.2)" - assert report.lookup("extremes", result, ["humidity"], [], TODAY).splitlines()[1] == "• Humidity: low 40 %, Thu 1 Oct at 3pm · high 95 %, Thu 1 Oct at 5am" - assert [line.split(":")[0] for line in report.lookup("extremes", result, ["wind"], [], TODAY).splitlines()[1:]] == ["• Wind", "• Wind gust"] - - +# ---------- a days lookup (the model's day tools' charts that answer the question) ---------- def test_a_days_count_lookup_gives_the_count_the_condition_and_the_period(): result = json.dumps({"period": "Wed 5 Oct 2022 - Sat 3 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"}) assert report.lookup("days", result, [], [], TODAY) == "137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)." @@ -237,22 +99,6 @@ def test_a_figure_per_period_lookup_gives_the_figure_over_the_whole_period(): assert report.lookup("days", hot, [], [], TODAY).startswith("Highest temperature: 41.2 °C over 3 days") -def test_a_heading_carries_the_place_and_the_time_of_day_of_its_data(): - assert report._heading("Forecast", {"place": "Melbourne", "time": "Fri 2 Oct 2026 6:05pm"}, TODAY) == "Forecast (Melbourne, 6:05pm)" - assert report._heading("Weather station", {"time": "Fri 2 Oct 2026 12:07am"}, TODAY) == "Weather station (12:07am)" - assert report._heading("Weather station", {"time": "Fri 2 Oct 2026 1:30pm"}, TODAY) == "Weather station (1:30pm)" - assert report._heading("Air quality", {"time": "Fri 2 Oct 2026 12:00pm"}, TODAY) == "Air quality (12:00pm)" - assert report._heading("Forecast", {"place": "Melbourne"}, TODAY) == "Forecast (Melbourne)" # no time: as before - assert report._heading("Air quality", {"time": "yesterday"}, TODAY) == "Air quality" and report._heading("Air quality", {"time": None}, TODAY) == "Air quality" - - -def test_a_heading_gives_the_day_of_data_that_is_not_todays(): - stale = report.report({"weather_now": NOW, "pollen_asthma": POLLEN}, date(2026, 10, 4)) # the station has been silent since Friday - assert stale.startswith("Weather station (Fri 2 Oct 2:21am)\n") and "\nPollen & asthma (Melbourne, Fri 2 Oct 6:00pm)\n" in stale - assert report.lookup("forecast", FORECAST, [], [], date(2026, 10, 3)).startswith("Forecast (Melbourne, Fri 2 Oct 6:05pm)\n") - assert [e.length for e in report.heading_entities(stale)] == [len("Weather station"), len("Pollen & asthma")] # still bold - - def test_when_gives_the_form_the_tools_use_in_their_time_field(): from datetime import datetime from lib.timeutil import when @@ -265,7 +111,7 @@ def test_when_gives_the_form_the_tools_use_in_their_time_field(): def test_only_the_name_of_each_heading_is_bold_not_its_brackets_or_time(): - text = report.report({"weather_now": NOW, "air_quality": AIR, "pollen_asthma": POLLEN, "weather_forecast": FORECAST}, TODAY) + text = report_words.report({"weather_now": NOW, "air_quality": AIR, "pollen_asthma": POLLEN, "weather_forecast": FORECAST}, TODAY) units = lambda s: len(s.encode("utf-16-le")) // 2 names = [text.encode("utf-16-le")[2 * e.offset:2 * (e.offset + e.length)].decode("utf-16-le") for e in report.heading_entities(text)] assert names == ["Weather station", "Air quality", "Pollen & asthma", "Forecast"] diff --git a/tests/test_service_current.py b/tests/test_service_current.py index d395ae54..65da2116 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -8,7 +8,7 @@ import pytest -from lib import report +from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.airgradient import AirGradient from lib.ecowitt.days import day_values_on from lib.intent import NOW_GROUPS diff --git a/tests/test_service_days.py b/tests/test_service_days.py index c57aec37..4e088f46 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -9,7 +9,7 @@ import pytest -from lib import report +from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.airgradient.days import find_air_days from lib.airgradient.readings import AirReadings from lib.ecowitt.days import find_days diff --git a/tests/test_service_forecast.py b/tests/test_service_forecast.py index 97e8c607..2054b3ae 100644 --- a/tests/test_service_forecast.py +++ b/tests/test_service_forecast.py @@ -7,7 +7,7 @@ import httpx import pytest -from lib import report +from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.forecast import Forecast from lib.service.common import FRESH, Refusal from lib.service.context import Context diff --git a/tests/test_service_legacy.py b/tests/test_service_legacy.py new file mode 100644 index 00000000..dc460550 --- /dev/null +++ b/tests/test_service_legacy.py @@ -0,0 +1,83 @@ +"""The service's tools registered (lib/service/__init__.py), and the bot's old calls read as the service's (lib/service/legacy.py).""" + +from datetime import datetime +from types import SimpleNamespace as NS + +from lib import intent +from lib.service import ORDER, Service, build, legacy +from lib.service.common import AS_DRAWN, MAX_CHART_POINTS, request_meta +from lib.service.context import Context +from lib.tools import Turn +from tests.fakes import TZ + +NOW = datetime(2026, 11, 10, 14, 5) # Tue 10 Nov 2026 2:05pm + + +def test_the_ten_are_built_in_order_each_where_its_source_is_and_found_by_name(): + station = NS(name="Ecowitt", tz=TZ, storage=None, latitude=-37.8) + everything = build(Context(eco=station, air=NS(name="AirGradient", tz=TZ), forecast=NS(), pollen=NS(), tz=TZ)) + assert [t.name for t in everything] == list(ORDER) + assert [t.name for t in build(Context(tz=TZ))] == ["summary", "readings", "relate", "scan", "about"] # no source: what needs none + service = Service(everything) + assert service["summary"] is service.get("summary") and "days" in service and service.get("nothing") is None + assert [t.name for t in service] == list(ORDER) and service.held(["a"]) == ["a"] # (no context: every name is held) + + +def test_the_bot_asks_for_its_charts_as_drawn(): + assert request_meta({"chart_points": AS_DRAWN})["chart_points"] == AS_DRAWN + assert request_meta({"chart_points": 10_000})["chart_points"] == MAX_CHART_POINTS + + +def read(text): + r = intent.read(text, NOW, ("Ecowitt", "AirGradient", "Pollen", "Forecast")) + return r, Turn.of(r, text) + + +def test_a_chart_asked_for_plainly_is_summarys_call_with_its_period_in_the_services_words(): + for text, want in (("Rain chart 1d", {"readings": ["rainfall.rain"], "period": "last 24 hours", "chart": True}), + ("Temperature chart 7d", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 7 days", "chart": True}), + ("indoor temperature chart 7d", {"readings": ["indoor.temperature"], "period": "last 7 days", "chart": True}), + ("pressure chart this month", {"readings": ["pressure.relative"], "period": "this month", "chart": True}), + ("average temperature 7d", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 7 days", + "chart": True, "average": True}), + ("plot uv and solar on two axes 7d", {"readings": ["solar_and_uvi.uvi", "solar_and_uvi.solar"], "period": "last 7 days", + "chart": True, "layout": "two_axes"}), + ("lowest temperature on record", {"readings": ["outdoor.temperature", "indoor.temperature"], # (the bot's "on record") + "period": "2022-11-12 to 2026-11-10", "chart": True}), + ("Particulates chart 1d", {"readings": ["air.pm2_5", "air.pm10", "air.pm1"], "period": "last 24 hours", "chart": True})): + r, turn = read(text) + assert legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == ("summary", want), text + + +def test_the_lookups_are_the_tools_that_word_them(): + for text, want in (("how hot is it", ("current", {"readings": ["temperature"]})), + ("indoor temperature", ("current", {"readings": ["indoor temperature"]})), + ("co2", ("current", {"readings": ["air.co2"]})), ("air quality now", ("current", {"readings": ["air"]})), + ("what can you do", ("about", {}))): + assert legacy.lookup(read(text)[0]) == want, text + for text, want in (("forecast", ("forecast", {"period": "the next 7 days"})), ("pollen", ("pollen", {})), + ("highest temperature yesterday", ("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], + "period": "yesterday", "chart": False})), + ("rain by month this year", ("days", {"count_only": True, "group_by": "month", "stat": "sum", "of": "rain", + "period": "2026-01-01 to 2026-11-10"}))): + r, turn = read(text) + assert legacy.lookup(r) is None and legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == want, text + assert legacy.report(("Ecowitt", "AirGradient", "Pollen", "Forecast")) == [("current", {}), ("pollen", {}), + ("forecast", {"period": "next 3 days"})] + + +def test_a_period_is_words_the_service_reads_as_the_same_span_else_whole_days_else_times(): + assert legacy.period("2026-11-09 14:05:00", "2026-11-10 14:05:00", ["last 24 hours"], NOW, TZ) == {"period": "last 24 hours"} + assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this week"], NOW, TZ) == {"period": "this week"} + assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this month"], NOW, TZ) == {"period": "2026-11-04 to 2026-11-10"} + assert legacy.period("2026-11-01 00:00:00", None, [], NOW, TZ) == {"period": "2026-11-01 to now"} + assert legacy.period("2026-11-09 06:00:00", "2026-11-09 11:59:59", [], NOW, TZ) == {"start": "2026-11-09 06:00", "end": "2026-11-09 12:00"} + assert legacy.period("2026-01-01", "2026-11-10", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to 2026-11-10"} + + +def test_the_periods_a_chart_the_model_drew_is_worth_drawing_over_are_its_tools(): + assert [p["period"] for p in legacy.periods_of("summary", {"period": "last 7 days"})] == ["1d", "7d", "1m", "3m", "1y"] + assert [p["period"] for p in legacy.periods_of("summary", {"period": "last 7 days", "average": True})] == ["7d", "1m", "3m", "1y"] + assert legacy.periods_of("summary", {"start": "2026-11-09 06:00"}) == [] # a time can't be swapped for a period + assert [p["label"] for p in legacy.periods_of("days", {"group_by": "month"})] == ["3M", "1Y", "All"] + assert legacy.periods_of("days", {"group_by": "year"}) == [] and legacy.translate("plot_chart", {}, now=NOW, tz=TZ) is None diff --git a/tests/test_service_pollen.py b/tests/test_service_pollen.py index 1912044c..d82a8ffd 100644 --- a/tests/test_service_pollen.py +++ b/tests/test_service_pollen.py @@ -4,7 +4,7 @@ import json from datetime import date, datetime, time as dtime, timedelta -from lib import report +from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.pollen.source import OFF_SEASON from lib.service.common import FRESH from lib.service.context import Context diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index 9b51038d..9dde2e51 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -5,7 +5,7 @@ import json from datetime import datetime, timedelta -from lib import report +from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.airgradient import AirGradient from lib.bot import _as_drawn from lib.compose import Composer diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 6d048f14..21f7a6e0 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -131,6 +131,7 @@ class World: def __init__(self): self.charts: list[dict] = [] + self.drawn_by: list[dict | None] = [] # each chart's drawn_by (the service's charts only) self.sheets: list[str] = [] self.sent: list[list] = [] self.edits: list[list] = [] @@ -153,7 +154,7 @@ async def open(self, tmp_path, archive): eco = Ecowitt(cfg, transport=transport) await eco.start() Station(eco, live(FROZEN, **{"solar_and_uvi.solar": "412.5", "solar_and_uvi.uvi": "6", "wind.wind_speed": "14.0", - "wind.wind_gust": "31.0"})) + "wind.wind_gust": "31.0", "indoor.humidity": None})) # (the fake station has no indoor humidity) air_transport_, _ = __import__("tests.fakes", fromlist=["air_transport"]).air_transport() air = AirGradient(cfg, transport=air_transport_, storage=eco.storage, owned=False) await air.start() @@ -164,10 +165,20 @@ async def open(self, tmp_path, archive): pollen.now = lambda: _datetime.fromtimestamp(FROZEN, TZ).replace(tzinfo=None) await pollen.warm(True) self.sources = [eco, air, pollen, forecast] + for source in self.sources: # a question's fetch of the newest readings while it is answered races the answer: not here + source.poke = lambda: None self.eco, self.air, self.pollen, self.forecast = eco, air, pollen, forecast self.composer = Composer(eco, air) history = await History.open(eco, air) self.tools = Tools([t for s in self.sources for t in s.tools] + self.composer.tools + history.tools) + from lib.service.context import Context + try: + from lib.service import Service + except ImportError: # (before the switch, when the answers were recorded: the bot had no service) + self.service = None + else: + self.service = Service.of(await Context.open(eco=eco, air=air, composer=self.composer, forecast=forecast, pollen=pollen, tz=TZ, + clock=lambda: FROZEN)) self.tz, self.cfg = TZ, cfg return self @@ -183,6 +194,7 @@ def bot(self, alert_state, monkeypatch): def render(data, tz, times=None, dark=None): self.charts.append(summary_of(data)) + self.drawn_by.append(data.get("drawn_by")) return b"png" def gauges(sheet): @@ -190,7 +202,8 @@ def gauges(sheet): return b"gauges" monkeypatch.setattr(botmod, "render_data", render) monkeypatch.setattr(botmod.gauges, "render", gauges) - return botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), self.sources, alert_state) + return botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), self.sources, alert_state, + **({"service": self.service} if self.service else {})) def message(self, message_id=50): world = self @@ -234,16 +247,48 @@ def golden() -> dict: return json.loads(GOLDEN.read_text()) if GOLDEN.exists() else {} +def period_rows(sent: list) -> list: + """The period buttons under each message sent (None for a message with none, or with other buttons).""" + return [s[2] if s[2] and all(d.startswith("pd:") for row in s[2] for _, d in row) else None for s in sent] + + +def without_period_rows(record: dict) -> dict: + """What was done, less the period buttons (deliberately changed: they come from the chart's drawn_by now).""" + record = json.loads(json.dumps(record, ensure_ascii=False)) + for s, row in zip(record.get("sent", []), period_rows(record.get("sent", []))): + if row is not None: + s[2] = None + return record + + def pinned(name: str, got: dict): - """Compare what the bot did with the recording (or record it).""" + """Compare what the bot did with the recording (or record it), its period buttons aside (period_buttons_are_drawn_bys).""" if RECORD: data = golden() data[name] = got GOLDEN.write_text(json.dumps(data, indent=1, ensure_ascii=False, sort_keys=True) + "\n") return + if dump := os.environ.get("ECOBOT_SWITCH_DUMP"): # (a folder: what was done, to compare with the recording by hand) + Path(dump).mkdir(parents=True, exist_ok=True) + (Path(dump) / f"{hashlib.sha1(name.encode()).hexdigest()[:10]}.json").write_text( + json.dumps({"name": name, "got": got}, indent=1, ensure_ascii=False, sort_keys=True)) want = golden().get(name) assert want is not None, f"{name} isn't recorded: run with ECOBOT_RECORD_SWITCH=1" - assert json.loads(json.dumps(got, ensure_ascii=False)) == want + assert without_period_rows(got) == without_period_rows(want) + + +def period_buttons_are_drawn_bys(world, got: dict): + """The deliberate change: a single chart's buttons are its drawn_by's periods, each labelled as the service labels it (none when it + lists none: a count per month no longer offers 1D), each button's data the period alone, within Telegram's 64 bytes.""" + rows = [row for row in period_rows(got["sent"]) if row is not None] + photos = [s for s in got["sent"] if s[0] == "photo"] + drawn = [d for d in world.drawn_by if d] + if len(photos) == 1 and len(world.charts) == 1 and drawn: + listed = drawn[0]["periods"] + assert rows == ([[[[p["label"], f"pd:{p['period']}"] for p in listed]]] if listed else []) + assert all(len(d.encode()) <= 64 for row in rows for r in row for _, d in r) + else: + assert rows == [] async def asked(world, alert_state, monkeypatch, text) -> dict: @@ -289,10 +334,13 @@ async def asked(world, alert_state, monkeypatch, text) -> dict: @pytest.mark.parametrize("text", KEYBOARD + SHORTCUTS) async def test_the_bots_own_answers_are_unchanged(world, alert_state, monkeypatch, text): - pinned(text, await asked(world, alert_state, monkeypatch, text)) + got = await asked(world, alert_state, monkeypatch, text) + pinned(text, got) + if not RECORD: + period_buttons_are_drawn_bys(world, got) -@pytest.mark.parametrize("question, press", [("Temperature chart 1d", "7"), ("Rain chart 1d", "30"), ("rain by month this year", "365")]) +@pytest.mark.parametrize("question, press", [("Temperature chart 1d", "7D"), ("Rain chart 1d", "1M"), ("rain by month this year", "1Y")]) async def test_a_period_button_redraws_the_same_chart_as_before(world, alert_state, monkeypatch, question, press): """A press on a period button under a chart: the chart over that period, put into the same message.""" bot = world.bot(alert_state, monkeypatch) @@ -302,7 +350,7 @@ async def test_a_period_button_redraws_the_same_chart_as_before(world, alert_sta sent_id = 100 + len(world.sent) row = next((s[2] for s in world.sent if s[0] == "photo" and s[2]), None) assert row, "a single chart with its period buttons" - data = next(d for r in row for t, d in r if d.removeprefix("pd:").rstrip("dmy") == press or d == f"pd:{press}") + data = next(d for r in row for t, d in r if t == press) under = world.message(sent_id) under.reply_markup = NS(inline_keyboard=[[NS(text=t, callback_data=d) for t, d in r] for r in row]) world.charts.clear() @@ -312,7 +360,21 @@ async def answer(text=None, **k): query = NS(data=data, message=under, answer=answer) await bot.on_period_button(NS(callback_query=query, effective_message=under, effective_chat=under.chat, effective_user=NS(username="rob", full_name="Rob", id=7)), CONTEXT) - pinned(f"press {press} under {question}", {"charts": world.charts, "edits": [e[:2] for e in world.edits]}) + got = {"charts": world.charts, "edits": [e[:2] for e in world.edits]} + name = f"press {press} under {question}" + if RECORD or press != "1Y" or "month" not in question: + pinned(name, got) + return + # The deliberate change: a count per month's buttons are its drawn_by's periods, read by the service: "1y" is the 365 whole days to + # yesterday (the old 1Y asked "... 365d", which the bot read as 364 whole days and today). The chart is otherwise the same. + want = golden()[name] + (chart,), (old,) = got["charts"], want["charts"] + assert chart["period"] == ["2025-11-10", "2026-11-09"] and old["period"] == ["2025-11-11", "2026-11-09"] + assert chart["subtitle"] == old["subtitle"].replace("Tue 11 Nov 2025", "Mon 10 Nov 2025").replace("364 days", "365 days") + assert {k: v for k, v in chart.items() if k not in ("period", "subtitle", "sha", "panels")} == \ + {k: v for k, v in old.items() if k not in ("period", "subtitle", "sha", "panels")} + assert got["edits"] == [["photo", "Total rain, Mon 10 Nov 2025 – Mon 9 Nov 2026\n\nTotal rain: 248 mm over 365 days (Mon 10 Nov 2025 – " + "Mon 9 Nov 2026)."]] @pytest.mark.parametrize("kind", ["gusts", "uv", "temps", "particulates"]) @@ -322,4 +384,17 @@ async def test_an_alerts_chart_is_the_same_as_before(world, monkeypatch, kind): monkeypatch.setattr(pictures, "render_data", lambda data, tz, *a, **k: captured.append(summary_of(data)) or b"png") source = world.air if kind == "particulates" else world.eco picture = await pictures.chart(source, pictures.CHARTS[kind], world.tz) - pinned(f"alert {kind}", {"title": picture.title, "newest": picture.newest, "charts": captured}) + got = {"title": picture.title, "newest": picture.newest, "charts": captured} + if RECORD: + pinned(f"alert {kind}", got) + return + # The deliberate change: an alert's chart is the service's chart of its request, the very chart the keyboard's button draws ("Wind + # chart 1d"), so it names its source under it as that one does (the old drew it through the tool's handler, which named none). + want = golden()[f"alert {kind}"] + (chart,), (old,) = got["charts"], want["charts"] + assert old["source"] == "" and chart["source"] == ("AirGradient sensor" if kind == "particulates" else "Ecowitt weather station") + assert {k: v for k, v in chart.items() if k not in ("source", "sha")} == {k: v for k, v in old.items() if k not in ("source", "sha")} + assert {k: v for k, v in got.items() if k != "charts"} == {k: v for k, v in want.items() if k != "charts"} + keyboard = golden().get(pictures.CHARTS[kind]) + if keyboard: # (the UV chart is no button) + assert chart == keyboard["charts"][0] From 79832160c9b89c7e4100d0d8c360625bcaa6f8aa Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:13:57 +0000 Subject: [PATCH 036/125] Step 2 review fixes: model charts' calls, carried arguments, replay errors, frozen clock - Turn.charts records the call that adds each chart as it is added (a contextvar set in Tools.call), so concurrent tool calls can't claim each other's charts; Turn.chart_calls reads them. - legacy: weather_history's two_axes is the model's too; weather_days and air_days fill group_by from the words and weather_days drops an unasked holiday/weekend filter, as the old tools did. - A period press on a service chart that fails to draw or send is logged and toasted ("Sorry, I couldn't draw that chart, please ask again"), never raised; the chart is drawn before the "Drawing" toast. - A chart the model drew whose call lists no periods keeps the old question replay (and its five buttons) until step 3. - test_service_switch: freeze() keeps the real classes in a tuple and skips its own module, so it reaches every module in any load order. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/bot.py | 17 ++++++++++--- lib/service/legacy.py | 7 +++++- lib/tools.py | 47 ++++++++++++++++++++++++++++++++---- tests/test_bot.py | 17 +++++++++++++ tests/test_periods.py | 26 ++++++++++++++++++++ tests/test_service_legacy.py | 25 +++++++++++++++++++ tests/test_service_switch.py | 38 ++++++++++++++++++++++------- tests/test_tools.py | 41 +++++++++++++++++++++++++++++++ 8 files changed, 199 insertions(+), 19 deletions(-) create mode 100644 tests/test_tools.py diff --git a/lib/bot.py b/lib/bot.py index 489af250..5cb0dd6d 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -65,6 +65,7 @@ NOT_ADMIN = "Sorry, only group admins can use this bot." NOT_ADMIN_TOAST = "Only group admins can use this bot" STALE_BUTTON = "That button is out of date, please ask again" +CHART_FAILED = "Sorry, I couldn't draw that chart, please ask again" # a period button's chart that couldn't be drawn or sent MAX_CALLBACK_BYTES = 64 # Telegram's own limit on a button's data TOAST_LIMIT = 200 # ... and on the text a button's answer shows @@ -475,7 +476,8 @@ def _held_call(self, call: tuple[str, dict] | None) -> tuple[str, dict] | None: def _model_drawn_by(self, turn: Turn, i: int, now: datetime) -> dict | None: """A drawn_by for the i-th chart the model drew through the old tools (it has none of its own until step 3): its call read as the - service's, with the periods that tool would list; None when the call has no service equivalent (its question is asked again).""" + service's, with the periods that tool would list; None when the call has no service equivalent or lists no periods (its question + is asked again).""" if i >= len(turn.chart_calls): return None name, args = turn.chart_calls[i] @@ -489,7 +491,10 @@ def _model_drawn_by(self, turn: Turn, i: int, now: datetime) -> dict | None: tool, arguments = call[0], {k: v for k, v in call[1].items() if k != "chart_answers_it"} if tool == "summary": arguments["chart"] = True - return {"tool": tool, "arguments": arguments, "periods": legacy.periods_of(tool, arguments)} + listed = legacy.periods_of(tool, arguments) + if not listed: # a period the service can't word (times...): its question is asked again, so the chart keeps its buttons + return None + return {"tool": tool, "arguments": arguments, "periods": listed} def _sentence_call(self, text: str, now: datetime) -> tuple[str, dict] | None: """The call a question is read as when it is a chart made in code ("Wind chart 1d"); None for any other.""" @@ -944,7 +949,11 @@ async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_T message = query.message record = self.charted.get(message.chat_id, message.message_id) if message else None if isinstance(record, dict) and record.get("drawn_by"): - await self._replay(query, message, record, context.bot) + try: + await self._replay(query, message, record, context.bot) + except Exception as e: # (a chart that fails to draw, Telegram failing): said on the button, never raised + log.error("Couldn't redraw a chart for its period button (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + await toast_quietly(query, CHART_FAILED) return days = periods.days_in(query.data) question = record if isinstance(record, str) and days else None @@ -993,8 +1002,8 @@ async def _replay(self, query, message: Message, record: dict, bot): if "error" in out or not charts: await toast_quietly(query, fit(str(out.get("error") or "No chart came of it for that period"), TOAST_LIMIT)) return + png, title, newest = await asyncio.to_thread(self._draw, charts[0]) # (drawn before the toast, so a failure can be toasted) await answer_query(query, f"Drawing {listed[period]}...") - png, title, newest = await asyncio.to_thread(self._draw, charts[0]) drawn = charts[0].get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} text = out.get("caption") or out.get("answer") or "" self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn) diff --git a/lib/service/legacy.py b/lib/service/legacy.py index 9d0431a0..efc69e9f 100644 --- a/lib/service/legacy.py +++ b/lib/service/legacy.py @@ -12,6 +12,8 @@ from datetime import datetime, timedelta, tzinfo +from ..daytable import grouped_as_asked +from ..ecowitt.days import HOLIDAY_WORDS from ..ecowitt.query import chart_field, stack_names from ..periods_text import PeriodError, read_period from ..series import INDOOR_READINGS, WEATHER @@ -105,6 +107,9 @@ def translate(name: str, args: dict, turn=None, *, now: datetime, tz: tzinfo) -> return "summary", _flags(out, args) if name in ("weather_days", "air_days"): keep = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "chart_answers_it") + if name == "weather_days" and args.get("only") and text and not HOLIDAY_WORDS.search(text): + args.pop("only") # (as the old tool: a holiday or weekend filter nobody asked for is dropped) + args = grouped_as_asked(args, turn) # (and group_by from the words when the model left it out) out = {k: args[k] for k in keep if args.get(k) not in (None, "", [])} out.update(period(args.get("start_date"), args.get("end_date") or now.strftime("%Y-%m-%d"), [], now, tz, whole_days=True)) return "days", out @@ -141,7 +146,7 @@ def _history(args: dict, turn, now: datetime, tz: tzinfo) -> dict: out["average"] = True if turn.per_day: out["every_day"] = True - if turn.two_axes and len(names) == 2: + if (turn.two_axes or args.get("two_axes")) and len(names) == 2: # (the words', else the model's: as the old tool drew it) out["layout"] = "two_axes" return _flags(out, args) diff --git a/lib/tools.py b/lib/tools.py index 3ba2f68e..3c37e659 100644 --- a/lib/tools.py +++ b/lib/tools.py @@ -4,6 +4,7 @@ import json import logging from collections.abc import Awaitable, Callable +from contextvars import ContextVar from dataclasses import dataclass, field from .logs import BUGS, QUOTES @@ -17,6 +18,39 @@ "Leave out to use the device the tool reads."} +CALL: ContextVar[tuple[str, dict] | None] = ContextVar("tool_call", default=None) # (tool, arguments) of the call being run + + +class Charts(list): + """Turn.charts: the chart specs, each put down to the call that added it (CALL, read as it is added: the model's calls in one step + run together, so counting charts before and after a call would give one call's chart to another). Its `calls` are in the same order.""" + + def __init__(self, charts=()): + super().__init__(charts) + self.calls = [self._call() for _ in self] + + @staticmethod + def _call() -> tuple: + return CALL.get() or (None, {}) # (a chart added another way has no call) + + def append(self, chart): + super().append(chart) + self.calls.append(self._call()) + + def extend(self, charts): + charts = list(charts) + super().extend(charts) + self.calls += [self._call() for _ in charts] + + def __iadd__(self, charts): + self.extend(charts) + return self + + def insert(self, i, chart): + super().insert(i, chart) + self.calls.insert(i, self._call()) + + def json_result(out) -> str: """A tool's result as the model is sent it: compact JSON, with °, ² and emoji written as they are, not escaped.""" return json.dumps(out, ensure_ascii=False, separators=(",", ":")) @@ -25,8 +59,7 @@ def json_result(out) -> str: @dataclass class Turn: """What one question carries between the bot and the tools it calls (nothing is shared between questions).""" - charts: list = field(default_factory=list) # chart specs the tools add; the bot renders them after the answer - chart_calls: list = field(default_factory=list) # (tool, arguments) of the call that drew each chart, in the same order + charts: list = field(default_factory=Charts) # chart specs the tools add; the bot renders them after the answer chart_asked: bool = False # the person's words asked for a chart ("plot"), whatever the model sets chart_field: str | None = None # the one reading the question is about ("humidity"); None: temperature chart_fields: list[str] = field(default_factory=list) # readings asked to be seen together ("temperature and rain") @@ -46,6 +79,11 @@ class Turn: meta: dict = field(default_factory=dict) # the request's metadata, all a service tool reads (lib/service/common.py: chart_points, # fetch, priority); over MCP, the request's _meta + @property + def chart_calls(self) -> list: + """(tool, arguments) of the call that drew each chart, in the same order ((None, {}): added outside any call).""" + return getattr(self.charts, "calls", None) or [(None, {})] * len(self.charts) + @classmethod def of(cls, read, text: str, **more) -> "Turn": """The Turn for a question as intent.read read it (`read`): what its words ask of a chart and of the figures.""" @@ -95,7 +133,7 @@ async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: log.debug("Tool call %s %s", name, raw_args, extra=QUOTES) sourced = CHART_SOURCE.set(source_text(args.get("source") if isinstance(args, dict) else None) or tool.source or "") # the charts this call draws turn = turn or Turn() - before = len(turn.charts) + calling = CALL.set((name, args)) # (each call made together runs in a context of its own: llm gathers them) try: # no time limit of its own: the question's (bot.TURN_SECONDS) runs from before the call out = await tool.handler(args, turn) except Exception as e: @@ -103,8 +141,7 @@ async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: return f"Error calling tool: {e}" finally: CHART_SOURCE.reset(sourced) - calls = (turn.chart_calls + [(None, {})] * before)[:before] # (charts added another way have no call) - turn.chart_calls[:] = calls + [(name, args)] * max(0, len(turn.charts) - before) + CALL.reset(calling) out = out or "(no output)" if len(out) > MAX_OUTPUT_CHARS: log.warning("Tool %s output truncated: %d chars", name, len(out)) diff --git a/tests/test_bot.py b/tests/test_bot.py index 456f3c55..27af5976 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -786,3 +786,20 @@ def chart_service(caption="Fri 25 Sep – Thu 1 Oct 2026\nHumidity: low 50 %, Fr """A stand-in service whose summary draws a chart titled `title` and captions it.""" from tests.fakes import StandInService, chart_data return StandInService(summary=lambda args, meta: {"caption": caption, "charts": [chart_data(title)]}) + + +def test_a_chart_the_model_drew_over_a_period_the_service_cant_word_keeps_its_old_buttons(alert_state): + """Until step 3, every chart the model draws has period buttons: one whose call the service lists no periods for (the last 48 hours as + times) gets no drawn_by, so its question is asked again on a press, as before.""" + from lib.tools import CALL + from tests.fakes import StandInService + bot = Bot(NS(tz=TZ), None, [], alert_state, service=StandInService()) + now = datetime(2026, 11, 10, 14, 5) + turn = Turn(text="how warm was it") + for start in ("2026-11-09 14:05:00", "2026-11-08 14:05:00"): + called = CALL.set(("weather_history", {"start_date": start, "end_date": "2026-11-10 14:05:00", "chart": True})) + turn.charts.append("chart") + CALL.reset(called) + day = bot._model_drawn_by(turn, 0, now) + assert day["tool"] == "summary" and day["arguments"]["period"] == "last 24 hours" and day["periods"] + assert bot._model_drawn_by(turn, 1, now) is None diff --git a/tests/test_periods.py b/tests/test_periods.py index 3fd1fdbb..7a9b43c8 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -12,6 +12,7 @@ from tests.fakes import TZ NOW = datetime(2026, 10, 2, 12, 0) +SORRY = "Sorry, I couldn't draw that chart, please ask again" ROW = [("1D", "pd:1d"), ("7D", "pd:7d"), ("1M", "pd:1m"), ("3M", "pd:3m"), ("1Y", "pd:1y")] # summary's periods, as its drawn_by lists them @@ -181,6 +182,31 @@ async def answer(text=None, **k): assert answers[-1] == "That chart is out of date, please ask again" +async def test_a_replayed_chart_that_cannot_be_drawn_or_sent_says_sorry_on_the_button_and_raises_nothing(alert_state, monkeypatch): + from telegram.error import NetworkError + bot, edits = make_bot(alert_state, monkeypatch), [] + msg = chat_message([], edits) + record = {"drawn_by": {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}, "words": False} + bot.charted.remember(1, 50, record) + answers = [] + + async def answer(text=None, **k): + answers.append(text) + + def broken(data, tz, times=None): + raise ValueError("no panels") + monkeypatch.setattr(botmod, "render_data", broken) + await bot.on_period_button(press(msg, "pd:3m", answer), CONTEXT) # a chart that fails to render + assert answers == [SORRY] and edits == [] + + async def offline(media, reply_markup=None): + raise NetworkError("connection reset") + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") + msg.edit_media, answers[:] = offline, [] + await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) # Telegram failing other than refusing the edit + assert answers == ["Drawing 1Y...", SORRY] + + async def test_a_button_on_a_chart_from_before_a_restart_says_so(alert_state, monkeypatch): bot = make_bot(alert_state, monkeypatch) answers = [] diff --git a/tests/test_service_legacy.py b/tests/test_service_legacy.py index dc460550..5ba9b4fa 100644 --- a/tests/test_service_legacy.py +++ b/tests/test_service_legacy.py @@ -81,3 +81,28 @@ def test_the_periods_a_chart_the_model_drew_is_worth_drawing_over_are_its_tools( assert legacy.periods_of("summary", {"start": "2026-11-09 06:00"}) == [] # a time can't be swapped for a period assert [p["label"] for p in legacy.periods_of("days", {"group_by": "month"})] == ["3M", "1Y", "All"] assert legacy.periods_of("days", {"group_by": "year"}) == [] and legacy.translate("plot_chart", {}, now=NOW, tz=TZ) is None + + +def test_the_models_own_arguments_that_change_its_chart_are_carried_as_the_old_tools_honour_them(): + """weather_history's two_axes is the model's as much as the words' (query: turn.two_axes or args two_axes), with two readings.""" + week = {"start_date": "2026-11-03 14:05:00", "end_date": "2026-11-10 14:05:00", "chart": True} + _, turn = read("plot uv and solar 7d") + assert not turn.two_axes + tool, args = legacy.translate("weather_history", {**week, "chart_fields": ["uv", "solar"], "two_axes": True}, turn, now=NOW, tz=TZ) + assert tool == "summary" and args["layout"] == "two_axes" and args["readings"] == ["solar_and_uvi.uvi", "solar_and_uvi.solar"] + tool, args = legacy.translate("weather_history", {**week, "chart_fields": ["uv", "solar", "temperature"], "two_axes": True}, + Turn(text="plot those"), now=NOW, tz=TZ) + assert len(args["readings"]) == 4 + assert "layout" not in args # (three readings: a panel each, as the old tool drew them) + + +def test_a_days_call_is_grouped_and_filtered_as_the_old_tool_read_it(): + """weather_days and air_days put in group_by from the words when the model left it out, and weather_days drops a holiday or + weekend filter the words never asked for: both change the bars drawn.""" + _, turn = read("days with uv over 9 per month this year") + days = {"start_date": "2026-01-01", "end_date": "2026-11-10", "where": [{"field": "uv_max", "op": ">", "value": 9}]} + for name in ("weather_days", "air_days"): + assert legacy.translate(name, days, turn, now=NOW, tz=TZ)[1].get("group_by") == "month", name + assert "only" not in legacy.translate("weather_days", {**days, "only": "weekend"}, turn, now=NOW, tz=TZ)[1] + _, turn = read("how many weekends had uv over 9 this year") + assert legacy.translate("weather_days", {**days, "only": "weekend"}, turn, now=NOW, tz=TZ)[1]["only"] == "weekend" diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 21f7a6e0..ddf81e35 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -29,15 +29,16 @@ GOLDEN = Path(__file__).with_name("service_switch.json") RECORD = os.environ.get("ECOBOT_RECORD_SWITCH") == "1" FROZEN = _datetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")).timestamp() +_REAL = (_datetime, _date) # the real classes, where freeze() can't rebind them (it rebinds module globals, never a tuple's items) # ---------- the clock, fixed ---------- class _DatetimeType(type): def __instancecheck__(cls, obj): - return isinstance(obj, _datetime) + return isinstance(obj, _REAL[0]) def __subclasscheck__(cls, sub): - return issubclass(sub, _datetime) + return issubclass(sub, _REAL[0]) class FrozenDatetime(_datetime, metaclass=_DatetimeType): @@ -45,25 +46,25 @@ class FrozenDatetime(_datetime, metaclass=_DatetimeType): @classmethod def now(cls, tz=None): - return _datetime.fromtimestamp(FROZEN, tz) + return _REAL[0].fromtimestamp(FROZEN, tz) @classmethod def today(cls): - return _datetime.fromtimestamp(FROZEN) + return _REAL[0].fromtimestamp(FROZEN) class _DateType(type): def __instancecheck__(cls, obj): - return isinstance(obj, _date) + return isinstance(obj, _REAL[1]) def __subclasscheck__(cls, sub): - return issubclass(sub, _date) + return issubclass(sub, _REAL[1]) class FrozenDate(_date, metaclass=_DateType): @classmethod def today(cls): - return _datetime.fromtimestamp(FROZEN).date() + return _REAL[0].fromtimestamp(FROZEN).date() def freeze(patch): @@ -75,14 +76,33 @@ def freeze(patch): for name, module in list(sys.modules.items()): if module is None or not (name == "lib" or name.startswith(("lib.", "tests.")) or name == "ecobot"): continue + if vars(module) is globals(): # (this module keeps the real classes, whatever it is loaded as: the frozen ones are built on them) + continue for attr, value in list(vars(module).items()): - if value is _datetime: + if value is _REAL[0]: patch.setattr(module, attr, FrozenDatetime) - elif value is _date: + elif value is _REAL[1]: patch.setattr(module, attr, FrozenDate) patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: FROZEN) +def test_the_clock_is_fixed_in_every_module_whatever_order_they_were_loaded_in(monkeypatch): + """freeze() reaches a module loaded after this one too (it keeps its own names for the real classes, and leaves this module be), + and the frozen classes still tell real dates and times apart.""" + import datetime as real + import types + late = types.ModuleType("tests._loaded_late") + late.datetime, late.date = real.datetime, real.date + monkeypatch.setitem(sys.modules, "tests.test_service_switch", sys.modules[__name__]) # (as --import-mode=importlib names it) + monkeypatch.setitem(sys.modules, late.__name__, late) # (after this module in sys.modules) + freeze(monkeypatch) + assert late.datetime is FrozenDatetime and late.date is FrozenDate + assert sys.modules[__name__]._datetime is real.datetime and sys.modules[__name__]._date is real.date + now = FrozenDatetime.now(ZoneInfo("Australia/Melbourne")) + assert now.timestamp() == FROZEN and isinstance(now, FrozenDatetime) and isinstance(FrozenDate.today(), FrozenDate) + assert issubclass(real.datetime, FrozenDatetime) and not isinstance(now.date(), FrozenDatetime) + + async def _inline(func, /, *args, **kwargs): return func(*args, **kwargs) diff --git a/tests/test_tools.py b/tests/test_tools.py new file mode 100644 index 00000000..cc2b00cb --- /dev/null +++ b/tests/test_tools.py @@ -0,0 +1,41 @@ +"""Tools.call: which call drew each chart of a question (Turn.chart_calls), when the model's calls in one step run together.""" + +import asyncio +import json + +from lib.tools import Tool, Tools, Turn + +OBJECT = {"type": "object", "properties": {}} + + +async def test_each_chart_is_put_down_to_the_call_that_added_it_when_calls_run_together(): + """The model's calls in one step are made together (llm gathers them): a call that draws nothing but finishes after another drew + its chart doesn't claim that chart.""" + drawn = asyncio.Event() + + async def draws(args, turn): + turn.charts.append("chart") + drawn.set() + return "drew" + + async def waits(args, turn): + await drawn.wait() # (started first, finishes last) + await asyncio.sleep(0) + return "nothing drawn" + tools = Tools([Tool("waits", "", OBJECT, waits), Tool("draws", "", OBJECT, draws)]) + turn = Turn() + await asyncio.gather(tools.call("waits", json.dumps({"a": 1}), turn), tools.call("draws", json.dumps({"b": 2}), turn)) + assert turn.charts == ["chart"] + assert turn.chart_calls == [("draws", {"b": 2})] + + +async def test_charts_added_outside_any_call_have_no_call(): + async def draws(args, turn): + turn.charts.append("theirs") + return "drew" + tools = Tools([Tool("draws", "", OBJECT, draws)]) + turn = Turn() + turn.charts.append("ours") + await tools.call("draws", "{}", turn) + turn.charts.append("ours too") + assert turn.chart_calls == [(None, {}), ("draws", {}), (None, {})] From c4f9d32e53f052bd34d21192f430e9bb5ff0731d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:20:10 +0000 Subject: [PATCH 037/125] The gauges from the service's current with context, laid out bot-side The dashboard and the report's three gauges were still the station's own Ecowitt.dashboard(). They are now current {context: true} (the report's: its three readings named, cut to those the service holds), laid out by the bot as a client would (lib/gauge_sheet.py: GAUGES' scales and colours filled from the result). Ecowitt.dashboard(), dashboard() and sheet() are gone; GAUGES and figures() stay in lib/ecowitt/dashboard.py, which current uses (Gauge.reading names each gauge's reading for both sides). current lacked one thing the sheet needs: a gauge whose reading the station sends but its file hasn't recorded yet (outside the catalogue) was missing, which the dashboard drew. With context and no readings named, those are in sensors too (unrecorded()), documented and tested. The pinned sheets in tests/service_switch.json match unchanged (not re-recorded). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 10 +- lib/bot.py | 29 +++-- lib/ecowitt/dashboard.py | 45 +++----- lib/ecowitt/source.py | 6 -- lib/gauge_sheet.py | 58 ++++++++++ lib/service/current.py | 27 +++-- scripts/bench_storage.py | 10 +- tests/chart_samples.py | 7 +- tests/fakes.py | 15 +++ tests/test_bot.py | 9 +- tests/test_dashboard.py | 196 +++++++++++++++++++++++++--------- tests/test_service_current.py | 39 ++++++- 12 files changed, 328 insertions(+), 123 deletions(-) create mode 100644 lib/gauge_sheet.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 9a44ed5f..9ac2e443 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -75,7 +75,7 @@ All of this is what a client other than the bot would not know, so it has to mov | Stays (the service) | Leaves | |---|---| -| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` and `sheet()` from `lib/ecowitt/dashboard.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | +| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` from `lib/ecowitt/dashboard.py` and `lib/gauge_sheet.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | ### 3.2 An interface any model can use @@ -206,7 +206,8 @@ rain is summarised. **`current`'s result:** `{as_of, sensors: {"outdoor": {"temperature": {value, unit, text: "12.3 °C", [emoji], [today: {low, low_text, low_when, high…}], [month…], [year…]}}, "rainfall": {"rain": {…, [today: {total}], [month: {total, wettest_day}], [year…]}}, "wind": {"wind_speed": {…, [today: {high_gust…}]}}, "air": {"pm2_5": {value, unit, rating, aqi_us, band}}}}`: with `context`, everything the -bot's gauges show (rain as totals and its wettest day, wind's highest gust). +bot's gauges show (rain as totals and its wettest day, wind's highest gust); with `context` and no readings named, every gauge's reading +the station sends now, those its file hasn't recorded yet (outside the catalogue) too, as the gauges show them. **`outlook`'s result** is the prompt's outlook rules, worked out by the service (`lib/outlook.py`) from the reading now and the last 3 hours: `{as_of, verdict: "likely"|"possible"|"unlikely", reason: "pressure down 2.4 hPa in 3 hours, humidity 91%", pressure: {change_hpa, @@ -475,8 +476,9 @@ Each step ships on its own, with the tests and evals green and the bot working t (`lib/service/__init__.py` `build`, `Service`), built in `ecobot.py` and handed to the bot; the bot's own code paths call them, through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in step 3), and quote their words; its answers pinned before and after (`tests/test_service_switch.py`). The bot asks for its charts - as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. Left - for later: the dashboard's gauges still read `Ecowitt.dashboard()` (its sheet is the client's layout, which `current` doesn't give). + as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. Its + gauges (the dashboard, the report's three) are `current` with `context`, laid out bot-side (`lib/gauge_sheet.py`: `GAUGES`' scales + and colours filled from the result; `Ecowitt.dashboard()` and `sheet()` are gone). 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. diff --git a/lib/bot.py b/lib/bot.py index 489af250..3fcc1a4c 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -35,7 +35,7 @@ from .service.common import AS_DRAWN, BACKGROUND from .service.context import Context from .specs import from_json, to_json -from .ecowitt.dashboard import STATUS +from . import gauge_sheet from .ecowitt.query import chart_field, stack_names from .tools import Turn from .config import Config @@ -914,7 +914,7 @@ async def _redraw_dashboard(self, query): await answer_query(query, STALE_BUTTON) return try: - answer = await asyncio.wait_for(self._dashboard(eco), TURN_SECONDS) + answer = await asyncio.wait_for(self._dashboard(), TURN_SECONDS) except Exception as e: log.warning("Dashboard refresh failed: %s: %s", type(e).__name__, e) answer = None @@ -1181,13 +1181,12 @@ async def _report(self, read, turn: Turn, gauges: bool) -> tuple[str, bytes | No return await asyncio.wait_for(written, TURN_SECONDS), None async def _status_gauges(self) -> bytes | None: - """The report's picture: the weather station's temperature, humidity and rain gauges (ecowitt.dashboard.STATUS). None without the - station, or when they can't be drawn (the report then goes as text alone).""" - station = self.by_name.get("Ecowitt") - if station is None: + """The report's picture: the weather station's temperature, humidity and rain gauges (gauge_sheet.STATUS), from the service's + current with context. None without the station, or when they can't be drawn (the report then goes as text alone).""" + if "Ecowitt" not in self.by_name: return None try: - sheet = await station.dashboard(STATUS) + sheet = await self._gauge_sheet(gauge_sheet.STATUS) return await asyncio.to_thread(gauges.render, sheet) if sheet else None except Exception as e: log.error("The report's gauges failed (%s: %s); sending it without them", type(e).__name__, e, exc_info=isinstance(e, BUGS)) @@ -1209,9 +1208,19 @@ async def _chart_in_code(self, call: tuple[str, dict] | None, turn: Turn) -> Mad text, charts = out.get("caption") or out.get("answer"), out.get("charts") or [] return Made(text, charts) if "error" not in out and charts and text else None - async def _dashboard(self, ecowitt) -> Answer: + async def _gauge_sheet(self, titles=None): + """The gauges of these titles (all when None) laid out from the service's current with context (lib/gauge_sheet.py), their + readings named those the service holds; None when the station gives nothing.""" + args = gauge_sheet.call(titles) + if "readings" in args: + args["readings"] = self.service.held(args["readings"]) + if not args["readings"]: + return None + return gauge_sheet.sheet(await self._service_call("current", args), titles) + + async def _dashboard(self) -> Answer: """The station's gauges as one picture, sent with just its title (no period buttons: it is the state now).""" - sheet = await ecowitt.dashboard() + sheet = await self._gauge_sheet() if sheet is None: return Answer("The weather station isn't answering right now.", ok=False) now = now_local(self.cfg.tz) @@ -1466,7 +1475,7 @@ async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], dra made = await asyncio.wait_for(self._chart_in_code(call, turn), TURN_SECONDS) answer = Answer(made.text, silent=not shown, made=time.monotonic() - began, charts=made.charts, key=key) if made else Answer() elif read.dashboard and "Ecowitt" in self.by_name: - answer = await asyncio.wait_for(self._dashboard(self.by_name["Ecowitt"]), TURN_SECONDS) + answer = await asyncio.wait_for(self._dashboard(), TURN_SECONDS) elif read.lookup: made = await asyncio.wait_for(self._lookup_in_code(read, turn, now), TURN_SECONDS) answer = Answer(made.text, charts=made.charts) if made and made.text else Answer() diff --git a/lib/ecowitt/dashboard.py b/lib/ecowitt/dashboard.py index fdc86659..004e5a2a 100644 --- a/lib/ecowitt/dashboard.py +++ b/lib/ecowitt/dashboard.py @@ -1,18 +1,17 @@ -"""The dashboard's gauges from the station: each reading as it is now, with its highest and lowest today, this month and this year. +"""The station's gauges: what each shows (GAUGES: its reading, its scale and colours, the day figures beside it) and their figures, each +reading as it is now with its highest and lowest today, this month and this year (figures()). Now is the live reading. The extremes are the day rows' (days.day_values_on: exact days from the 5- or 30-minute readings where they hold the day, else the daily buckets; today from what there is so far), which take in the bands the bot and Home Assistant saw between the -5-minute readings, with the live reading counted in, so the day's figures are never behind the gauge. A tile is left out when the station -has no such reading at all (no indoor sensor), and drawn dimmed when it has one but not now. +5-minute readings, with the live reading counted in, so the day's figures are never behind the gauge. + +The service's `current` with `context` gives these figures (lib/service/current.py context_of); the bot lays its sheet of gauges out +from that result (lib/gauge_sheet.py), with GAUGES' scales and colours. """ from dataclasses import dataclass from datetime import date, timedelta -from ..specs import Dashboard, Tile -from ..storage import Storage -from .days import day_values_on - COLD_TO_HOT = ("#7DE7FF", "#B2EEFA", "#F7C9C9", "#EE7070", "#D32F27") WATER = ("#DFFBFF", "#B2EEFA", "#80E5FA", "#4FB3D6", "#2C7592") PRESSURE = ("#C5CAFA", "#A5ABF7", "#8087F5", "#5C5CF0", "#3F2FD0") @@ -37,6 +36,13 @@ class Gauge: decimals: int = 1 total: bool = False # rain: the Total column, the sum of the days' figures (its Max is the wettest day's) + @property + def reading(self) -> str: + """The service's name of the reading it shows (lib/service/names.py): its live reading's, the rain gauge's "daily" being + rainfall.rain.""" + group, field = self.live + return f"{group}.{'rain' if field == 'daily' else field}" + GAUGES = ( Gauge("Temperature", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("outdoor", "temperature"), "temp_max", "temp_min"), @@ -88,28 +94,3 @@ def figures(gauge: Gauge, values: dict, days: list[date], now: float | None) -> lows = [values[gauge.lowest][d] for d in days if d in values.get(gauge.lowest, {})] + ([now] if now is not None else []) row.append(min(lows) if lows else None) return tuple(row) - - -def sheet(live: dict, values: dict, today: date, titles=None) -> Dashboard | None: - """The dashboard from a live reading and the days' figures, with the gauges of these titles only (all when None); None when the - station has none of the readings.""" - tiles = [] - days = periods_of(today) - for gauge in gauges_of(titles): - now = live_value(live, gauge.live) - if now is None and not any(values.get(name) for name in (gauge.highest, gauge.lowest) if name): - continue - rows = {name: figures(gauge, values, days[name], None if gauge.total else now) for name in PERIODS} - if gauge.total and now is not None: # today's rain is the gauge's own reading, whatever the day's cached figure lags behind - rows["Daily"] = (None, now) - columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max",) - tiles.append(Tile(gauge.title, gauge.unit, now, gauge.kind, gauge.low, gauge.high, gauge.colours, columns, rows, gauge.ticks, gauge.decimals)) - return Dashboard(tiles) if tiles else None - - -async def dashboard(live: dict, storage: Storage, mac: str, today: date, titles=None) -> Dashboard | None: - """The gauges (of these titles; all when None) for a live reading ({group: {field: {value, unit}}}, as Ecowitt's real_time gives - it), the extremes from the day rows of the year so far: one read.""" - names = sorted({n for g in gauges_of(titles) for n in (g.highest, g.lowest) if n}) - values, _ = await storage.read(day_values_on, mac, names, periods_of(today)["Yearly"]) - return sheet(live, values, today, titles) diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index f2995151..6bb2bfd2 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -22,7 +22,6 @@ from .calendar import PublicHolidays from .link import DESCRIPTION as LINK_DESCRIPTION, PARAMETERS as LINK_PARAMETERS, link_tool from .days import DESCRIPTION as DAYS_DESCRIPTION, PARAMETERS as DAYS_PARAMETERS, days_tool -from .dashboard import dashboard from .glance import glance from .fetch import Fetcher, Recent from .fallback import FallbackAPI, newest @@ -307,11 +306,6 @@ async def _record_live(self, data: dict): except Exception as e: log.warning("Couldn't keep the live readings' ranges: %s", e) - async def dashboard(self, titles=None): - """The station's gauges (specs.Dashboard; those of these titles only, all when None): the live reading and each one's highs and - lows today, this month and this year; None when the station has no reading.""" - return await dashboard(await self._live_data(LIVE_GROUPS), self.storage, self.mac, self.now().date(), titles) - async def watch_live(self): """Ask Home Assistant for the live reading every few seconds, for ever. A reading newer than the last one found is kept for "weather now", the report and the rain alert (which is called at once, not at the next minute's refresh). A failure is logged once, with its diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py new file mode 100644 index 00000000..611e4091 --- /dev/null +++ b/lib/gauge_sheet.py @@ -0,0 +1,58 @@ +"""The gauges' sheet (specs.Dashboard, what lib/gauges.py draws), laid out by the bot as a client of the service (docs/mcp-service.md +3.1, 4): each gauge's scale and colours (lib/ecowitt/dashboard.py GAUGES) filled from the service's `current` with `context`, its reading +now and the highs and lows of today, the month and the year beside it (rain: its totals and wettest day; wind: its highest gust). + +A tile is left out when current has neither a reading nor a figure for it (no indoor sensor), and drawn dimmed when it has figures but +no reading now. The whole dashboard is every gauge's; the report's picture its three (STATUS). +""" + +from .ecowitt.dashboard import GAUGES, PERIODS, STATUS, Gauge, gauges_of +from .specs import Dashboard, Tile + +ROWS = dict(zip(PERIODS, ("today", "month", "year"))) # a tile's rows, as current's context names them +STATION = "station" + + +def call(titles=None) -> dict: + """current's arguments for the gauges of these titles, with context: their readings named; all of them (titles None), every reading, + so that those the station sends but its file hasn't recorded yet are there too (as the station's own dashboard drew them).""" + return {"context": True} if titles is None else {"readings": [g.reading for g in gauges_of(titles)], "context": True} + + +def _row(gauge: Gauge, figures: dict) -> tuple[float | None, ...]: + """A row of a tile's table from current's figures of that period: Max and Min, Max alone, or (rain) its wettest day and Total.""" + if gauge.total: + return (figures.get("wettest_day") or {}).get("rain"), figures.get("total") + high = figures.get("high", figures.get("high_gust")) # (the wind's Max is its highest gust) + return (high, figures.get("low")) if gauge.lowest else (high,) + + +def _value(entry: dict) -> float | None: + try: + return float(entry["value"]) + except (KeyError, TypeError, ValueError): + return None + + +def sheet(result: dict, titles=None) -> Dashboard | None: + """The gauges of these titles (all when None) from current's result with context; None when it has none of them (an error, the + station not answering, nothing read).""" + if "error" in result or STATION in (result.get("unavailable") or {}): + return None + sensors = result.get("sensors") or {} + tiles = [] + for gauge in gauges_of(titles): + group, name = gauge.reading.split(".", 1) + entry = (sensors.get(group) or {}).get(name) + if not isinstance(entry, dict): + continue + now = _value(entry) + rows = {row: _row(gauge, entry.get(key) or {}) for row, key in ROWS.items()} + if now is None and all(f is None for figures in rows.values() for f in figures): + continue + columns = ("Max", "Total") if gauge.total else ("Max", "Min") if gauge.lowest else ("Max",) + tiles.append(Tile(gauge.title, gauge.unit, now, gauge.kind, gauge.low, gauge.high, gauge.colours, columns, rows, gauge.ticks, gauge.decimals)) + return Dashboard(tiles) if tiles else None + + +__all__ = ["GAUGES", "STATUS", "call", "sheet"] diff --git a/lib/service/current.py b/lib/service/current.py index ecf50c31..2c7eecdb 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -2,15 +2,16 @@ named, and with `context` today's, this month's and this year's highs and lows beside each reading, as the gauges show them. It replaces weather_now and air_quality without dates (and the gauges' figures), on their engines: - - the station's reading is its live reading as Ecowitt.dashboard() and weather_now read it (Ecowitt._live_data: the kept reading while it + - the station's reading is its live reading as the gauges and weather_now read it (Ecowitt._live_data: the kept reading while it is fresh, else a request; raw {group: {field: {value, unit, time}}}), each reading with its value, unit, its text as weather_now writes it ("12.3 °C") and its glance emoji (lib/ecowitt/glance.py), when the reading is one to notice; - the air sensor's is AirGradient.latest(): value, unit, rating (held at the better level until two readings agree), PM2.5's US AQI and band, and its text as the report writes it; - - `context` is the gauges' figures (lib/ecowitt/dashboard.py figures(), over the day rows as dashboard() reads them, + - `context` is the gauges' figures (lib/ecowitt/dashboard.py figures(), over the day rows of the year so far, lib/ecowitt/days.day_values_on, the live reading counted in for today's highs and lows), each high and low with when it happened (the day row's own time of it, worded as weather_history words a record) and its day; rain as its totals and its wettest day, wind as its - highest gust. + highest gust. With no readings named, every gauge's reading the station sends now is there, those its file hasn't recorded yet (not + in the catalogue: unrecorded()) too, so a client lays out the gauges (lib/gauge_sheet.py) from this result alone. `lines` are each device's readings as bullets, worded as the bot's report, "weather now" and plain lookups word them today (lib/report.py weather_lines, air_lines, reading_lines, ported here with the same words): every reading (none named) in the report's @@ -39,7 +40,7 @@ from ..timeutil import clock_text, day_text, to_local from .common import BACKGROUND, Refusal, ServiceTool, answer from .context import Context -from .names import AIR_DEVICE, STATION, Reading +from .names import AIR_DEVICE, STATION, Catalogue, Reading log = logging.getLogger(__name__) @@ -223,6 +224,15 @@ def now_shaped(live: dict, tz: tzinfo) -> tuple[dict, int]: return {**out, **({"emoji": emoji} if emoji else {})}, newest +def unrecorded(live: dict, listed: set[str]) -> list[Reading]: + """The station's readings in its live reading that aren't among these names (the catalogue's: what its file has recorded), as the + catalogue would name them once recorded: a sensor sending, or a reading sent, since the file last took the station's fields.""" + sent = {group: {name: obj.get("unit", "") for name, obj in fields.items() if isinstance(obj, dict) and "value" in obj} + for group, fields in live.items() if isinstance(fields, dict)} + return [r for r in Catalogue.of({g: f for g, f in sent.items() if f}, air=False) + if r.sensor in sent and r.name not in listed and live_field(live, r) is not None] + + def live_field(live: dict, reading: Reading) -> str | None: """The live reading's own name for a catalogue reading in its group ("daily" for rainfall.rain, "app_tempin" for indoor.app_temp), or None when the live reading lacks it.""" @@ -259,8 +269,7 @@ def gauge_of(name: str) -> Gauge | None: get the Wind gauge's highest, with the live gust counted in.""" if name == "wind.wind_gust": return replace(next(g for g in GAUGES if g.live == ("wind", "wind_speed")), live=("wind", "wind_gust")) - group, reading = name.split(".", 1) - return next((g for g in GAUGES if g.live == (group, "daily" if reading == "rain" else reading)), None) + return next((g for g in GAUGES if g.reading == name), None) def _times_on(r: Reader, mac: str, names: list[str], days: list[date]) -> dict[str, dict[date, tuple[int, str]]]: @@ -292,7 +301,7 @@ def _times_on(r: Reader, mac: str, names: list[str], days: list[date]) -> dict[s def context_on(r: Reader, mac: str, names: list[str], days: list[date]) -> tuple[dict, dict]: - """(the figures of these days as dashboard() reads them, day_values_on's {figure: {day: value}}; their times, _times_on's).""" + """(the figures of these days as the gauges show them, day_values_on's {figure: {day: value}}; their times, _times_on's).""" values, _ = day_values_on(r, mac, names, days) return values, _times_on(r, mac, names, days) @@ -346,7 +355,7 @@ def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz out = {} for row, key in PERIODS: got = figures(gauge, values, days[row], None if gauge.total else now.value) - if gauge.total and row == "Daily" and now.value is not None: # today's rain is the gauge's own reading (dashboard.sheet) + if gauge.total and row == "Daily" and now.value is not None: # today's rain is the gauge's own reading (as the gauge shows it) got = (None, now.value) entry: dict = {} if gauge.total: @@ -435,6 +444,8 @@ async def _station(self, station: list[Reading], named: bool, context: bool, met return Part.down(STATION, UNAVAILABLE[STATION], today) now, newest = now_shaped(live, tz) at = to_local(newest, tz) if newest else None + if context and not named: # every gauge, as it shows: a gauge's reading sent now that the file hasn't recorded yet too + station = station + [r for r in unrecorded(live, {r.name for r in station}) if gauge_of(r.name)] gauges = await self._context(station) if context else None part, shown = Part(STATION, at=at), [] for r in station: diff --git a/scripts/bench_storage.py b/scripts/bench_storage.py index a4eae441..ba6e1f70 100644 --- a/scripts/bench_storage.py +++ b/scripts/bench_storage.py @@ -11,6 +11,7 @@ import asyncio import dataclasses +import json import logging import os import sqlite3 @@ -148,7 +149,14 @@ async def bench(folder: Path, repeat: int, tz) -> list[tuple[str, float, int]]: ("The alerts' last 3 hours", lambda: eco.recent(3))] for label, run in work: rows.append((label, *await measured(run, repeat, lambda: eco.api.asked))) - rows.append(("/dashboard", *await measured(eco.dashboard, repeat, lambda: eco.api.asked))) + from lib.gauge_sheet import call as gauges_call, sheet + from lib.service.context import Context + from lib.service.current import CurrentTool + current = CurrentTool(Context(eco=eco)).tool() # (the bot's gauges: current with context, laid out bot-side) + + async def dashboard(): + return sheet(json.loads(await current.call(gauges_call(), None))) + rows.append(("/dashboard", *await measured(dashboard, repeat, lambda: eco.api.asked))) await eco.close() if cfg.airgradient_location and cfg.storage_path.exists(): asked = [0] diff --git a/tests/chart_samples.py b/tests/chart_samples.py index 7bf75a03..91f26178 100644 --- a/tests/chart_samples.py +++ b/tests/chart_samples.py @@ -8,7 +8,8 @@ import lib.airgradient # noqa: F401 (imported first: lib.panels and the air package import each other) from lib.panels import panel_for, two_axes -from lib.ecowitt.dashboard import STATUS, sheet +from lib.gauge_sheet import STATUS, sheet +from tests.fakes import gauges_result from lib.specs import Bars, Chart, Compass, Line, Panel, stack from tests.fakes import TZ @@ -134,12 +135,12 @@ def series(base: float, swing: float, dip: float = 0.0) -> dict: def dashboard(): """The station's gauges: thermometers, dials and the rain beaker.""" - return sheet(*_station()) + return sheet(gauges_result(*_station())) def status(): """The report's picture: the temperature, humidity and rain gauges in a row.""" - return sheet(*_station(), STATUS) + return sheet(gauges_result(*_station()), STATUS) SAMPLES = {"temperature": temperature, "humidity_rain": humidity_rain, "all_week": all_week, "quarter": quarter, "air": air, diff --git a/tests/fakes.py b/tests/fakes.py index 1654ce3e..e8671e92 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -46,6 +46,21 @@ def held(self, names): return list(names) +def gauges_result(live: dict, values: dict, today) -> dict: + """current's result with context, as the bot reads it for its gauges, for a live reading ({group: {field: {value, unit}}}) and the + days' figures (days.day_values_on's): each gauge's reading now and its figures (lib/service/current.py context_of), through JSON.""" + import json + from lib.ecowitt.dashboard import GAUGES, live_value + from lib.service.current import context_of + sensors: dict = {} + for gauge in GAUGES: + value, beside = live_value(live, gauge.live), context_of(gauge.reading, live, values, {}, today, TZ) + if value is not None or beside: + group, name = gauge.reading.split(".", 1) + sensors.setdefault(group, {})[name] = {"value": value, "unit": gauge.unit, **beside} + return json.loads(json.dumps({"sensors": sensors})) + + def chart_data(title: str = "Temperature", drawn_by: dict | None = None) -> dict: """A chart as a service tool gives it (specs.to_json), with its drawn_by.""" from lib.specs import Chart, Line, Panel, to_json diff --git a/tests/test_bot.py b/tests/test_bot.py index 456f3c55..82312764 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -223,10 +223,8 @@ async def test_a_report_is_written_in_code_from_the_fast_path_calls_and_the_mode class Agent: async def run(self, *a, **k): raise AssertionError("the model must not be asked for a report") - async def dashboard(titles=None): - return None # the station has no gauges to draw: the report goes as text - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n, dashboard=dashboard) for n in ("Ecowitt", "AirGradient")] - service = StandInService(current={"lines": {"station": ["• Outdoor: 12.3 °C, 💦 94 %"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n) for n in ("Ecowitt", "AirGradient")] + service = StandInService(current={"lines": {"station": ["• Outdoor: 12.3 °C, 💦 94 %"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, # (no gauges: as text) "headings": {"station": "Weather station", "air": "Air quality"}}) agent, replies = Agent(), [] @@ -241,7 +239,8 @@ async def send_chat_action(*a, **k): bot = Bot(NS(tz=TZ), agent, sources, alert_state, service=service) await bot.respond(update, NS(bot=telegram(send_chat_action)), "report") await bot.respond(update, NS(bot=telegram(send_chat_action)), "weather now") - assert service.calls == [("current", {}), ("current", {})] + gauges = ("current", {"readings": ["outdoor.temperature", "outdoor.humidity", "rainfall.rain"], "context": True}) # the report's + assert [c for c in service.calls if c != gauges] == [("current", {}), ("current", {})] and service.calls.count(gauges) == 1 assert replies[0] == "Weather station\n• Outdoor: 12.3 °C, 💦 94 %\n\nAir quality\n• PM10: 3.0 µg/m³ 🟢 good" assert replies[1] == "• Outdoor: 12.3 °C, 💦 94 %" history = bot.chats[(1, None)].history diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 9a28bdf0..b5a3bcc3 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -5,11 +5,16 @@ from PIL import Image from telegram import InlineKeyboardMarkup -from lib import gauges, intent +import json +import time + +from lib import gauge_sheet, gauges, intent from lib.bot import Bot from lib.ecowitt import dashboard as dash +from lib.service import current as cur +from lib.service.context import Context from lib.specs import Dashboard, Tile -from tests.fakes import TZ, archived_station +from tests.fakes import TZ, StandInService, archived_station, gauges_result TODAY = date(2026, 10, 27) NOW = datetime(2026, 10, 27, 12, tzinfo=TZ) @@ -41,7 +46,7 @@ def test_a_tile_has_the_live_reading_and_its_extremes_with_the_live_reading_coun values = {"temp_max": {first: 38.0, today: 25.0}, "temp_min": {first: -1.0, today: 9.0}, "humidity_max": {today: 80.0}, "humidity_min": {today: 40.0}, "rain": {first: 12.0, date(2026, 10, 3): 6.0, today: 0.4}, "rain_rate_max": {first: 30.0}} - tiles = {t.title: t for t in dash.sheet(live, values, today).tiles} + tiles = {t.title: t for t in gauge_sheet.sheet(gauges_result(live, values, today)).tiles} temperature = tiles["Temperature"] assert temperature.value == 31.0 and temperature.columns == ("Max", "Min") assert temperature.rows == {"Daily": (31.0, 9.0), "Monthly": (31.0, 9.0), "Yearly": (38.0, -1.0)} # 31 is now: higher than today's 25 @@ -53,11 +58,11 @@ def test_a_tile_has_the_live_reading_and_its_extremes_with_the_live_reading_coun def test_a_reading_the_station_never_had_is_left_out_and_one_it_lacks_just_now_is_dimmed(): live = {"outdoor": {"temperature": reading(12.0)}} - sheet = dash.sheet(live, {"solar_max": {TODAY: 900.0}}, TODAY) + sheet = gauge_sheet.sheet(gauges_result(live, {"solar_max": {TODAY: 900.0}}, TODAY)) titles = [t.title for t in sheet.tiles] assert titles == ["Temperature", "Solar radiation"] and sheet.tiles[1].value is None # no indoor sensor, no wind assert sheet.tiles[1].rows["Daily"] == (900.0,) - assert dash.sheet({}, {}, TODAY) is None + assert gauge_sheet.sheet(gauges_result({}, {}, TODAY)) is None def test_the_gauges_are_drawn_as_a_png_of_the_size_their_tiles_make(): @@ -68,9 +73,14 @@ def test_the_gauges_are_drawn_as_a_png_of_the_size_their_tiles_make(): assert image.convert("RGB").getpixel((2, 2)) == (0x14, 0x19, 0x1D) +async def current_of(eco, args: dict) -> dict: + """The service's current over this station, called with these arguments.""" + return json.loads(await cur.CurrentTool(Context(eco=eco)).tool().call(args, None)) + + async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache(tmp_path, archived_cache): eco, _ = await archived_station(tmp_path, archived_cache) - sheet = await eco.dashboard() + sheet = gauge_sheet.sheet(await current_of(eco, gauge_sheet.call())) temperature = next(t for t in sheet.tiles if t.title == "Temperature") assert temperature.value == 12.3 # the fake station's live reading high, low = temperature.rows["Yearly"] @@ -87,19 +97,16 @@ async def call(self, *a, **k): async def test_the_dashboard_command_sends_one_picture_with_no_period_buttons_and_asks_no_model(alert_state, monkeypatch): - sent, asked = [], [] - - async def sheet(): - asked.append(1) - return Dashboard([Tile("Humidity", "%", 70, "dial", 0, 100, ("#DFFBFF", "#2C7592"), ("Max",), {"Daily": (87,)}, (0, 100), 0)]) + sent = [] + service = StandInService(current={"sensors": {"outdoor": {"humidity": {"value": 70, "unit": "%", "today": {"high": 87, "low": 60}}}}}) class Agent: tools = Tools() async def run(self, *a, **k): raise AssertionError("no model for the dashboard") - source = NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=sheet) - bot = Bot(NS(tz=TZ), Agent(), [source], alert_state) + source = NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt") + bot = Bot(NS(tz=TZ), Agent(), [source], alert_state, service=service) async def reply_photo(photo, caption=None, **kw): sent.append((photo[:4], caption, kw.get("reply_markup"))) @@ -110,7 +117,7 @@ async def reply_photo(photo, caption=None, **kw): context = CONTEXT update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) await bot.respond(update, context, "Dashboard") - assert asked == [1] and len(sent) == 1 + assert service.calls == [("current", {"context": True})] and len(sent) == 1 photo, caption, markup = sent[0] assert photo == b"\x89PNG" and caption.startswith("Weather station dashboard, ") assert not isinstance(markup, InlineKeyboardMarkup) # a chat whose keyboard is out of date gets that instead @@ -125,7 +132,7 @@ async def reply_photo(photo, caption=None, **kw): async def test_the_dashboards_refresh_draws_it_again_in_the_same_message_and_a_station_that_fails_leaves_it(alert_state): from lib import report_menu from lib.bot import STALE_BUTTON - bot, _ = report_bot(alert_state, three_tiles) + bot, now = report_bot(alert_state, three_gauges) edits = [] class Query: @@ -142,9 +149,9 @@ async def edit_message_media(self, media, reply_markup=None): assert photo == b"\x89PNG" and caption.startswith("Weather station dashboard, ") and query.toast is None assert markup.inline_keyboard[0][0].callback_data == report_menu.DASHBOARD # the 🔄 stays - async def failing(titles=None): + def failing(): raise RuntimeError("station down") - bot.by_name["Ecowitt"].dashboard = failing + now.gauges = failing query = Query() await bot.on_report_button(NS(callback_query=query), CONTEXT) assert len(edits) == 1 and "Couldn't refresh" in query.toast # left as it was @@ -157,44 +164,47 @@ async def failing(titles=None): def test_the_reports_gauges_are_temperature_humidity_and_rain_in_a_row(): live = {"outdoor": {"temperature": reading(12.0), "humidity": reading(70)}, "rainfall": {"daily": reading(0.2)}, "pressure": {"relative": reading(1020)}} - sheet = dash.sheet(live, {}, TODAY, dash.STATUS) + sheet = gauge_sheet.sheet(gauges_result(live, {}, TODAY), dash.STATUS) assert [t.title for t in sheet.tiles] == ["Temperature", "Humidity", "Rain"] and sheet.per_row == 3 image = Image.open(io.BytesIO(gauges.render(sheet))) assert image.size == (3 * gauges.CELL_W + 2 * gauges.MARGIN, gauges.CELL_H + 2 * gauges.MARGIN) # one row -async def test_the_dashboard_reads_the_years_day_rows_in_one_go_and_only_what_its_gauges_show(monkeypatch): - calls = [] - - def day_values_on(r, mac, names, days): - calls.append((tuple(names), min(days), max(days))) - return {n: {d: 1.0 for d in days} for n in names}, {} - monkeypatch.setattr(dash, "day_values_on", day_values_on) +async def test_the_reports_gauges_read_the_years_day_rows_in_one_go_and_only_what_its_three_show(tmp_path, archived_cache): + from tests.test_service_current import Station, live + eco, _ = await archived_station(tmp_path, archived_cache) + Station(eco, live(time.time())) + reads, read = [], eco.storage.read + + async def counted(fn, *args): + reads.append((fn, args)) + return await read(fn, *args) + eco.storage.read = counted + out = await current_of(eco, gauge_sheet.call(dash.STATUS)) + (mac, names, days), = [args for fn, args in reads if fn is cur.context_on] # one read, the year + today = Context(eco=eco).now().date() + assert names == ["humidity_max", "humidity_min", "rain", "temp_max", "temp_min"] and (days[0], days[-1]) == (date(today.year, 1, 1), today) + assert [t.title for t in gauge_sheet.sheet(out, dash.STATUS).tiles] == list(dash.STATUS) + await eco.close() - class Storage: - async def read(self, fn, *args): - return fn(None, *args) - sheet = await dash.dashboard({"outdoor": {"temperature": reading(12.0)}}, Storage(), "mac", TODAY, dash.STATUS) - assert calls == [(("humidity_max", "humidity_min", "rain", "temp_max", "temp_min"), date(2026, 1, 1), TODAY)] # one read, the year - assert [t.title for t in sheet.tiles] == list(dash.STATUS) +def report_bot(alert_state, gauges_now): + """A bot whose service gives the report's readings now (its `reading`, the outdoor temperature, which a test may change) and, with + context, its gauges (`gauges`: current's result with context, or raises; gauges_now to begin with).""" + now = NS(reading="12.3 °C", gauges=gauges_now) -def report_bot(alert_state, sheet): - """A bot whose service gives the report's readings now (its `reading`, the outdoor temperature, which a test may change) and whose - station gives, through dashboard(), its gauges (`sheet()`: a Dashboard, or raises).""" - from tests.fakes import StandInService - now = NS(reading="12.3 °C") - service = StandInService(current=lambda args, meta: { - "lines": {"station": [f"• Outdoor: {now.reading}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, - "headings": {"station": "Weather station", "air": "Air quality"}}) + def current(args, meta): + if args.get("context"): + assert args.get("readings") in (gauge_sheet.call(dash.STATUS)["readings"], None) # the report's three gauges, or all + return now.gauges() + return {"lines": {"station": [f"• Outdoor: {now.reading}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, + "headings": {"station": "Weather station", "air": "Air quality"}} + service = StandInService(current=current) class Agent: pass - async def dashboard(titles=None): - assert titles in (dash.STATUS, None) # the report's three gauges, or the whole dashboard - return sheet() - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=dashboard), + sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt"), NS(name="AirGradient", wants=lambda t: True, poke=lambda: None, describe=lambda: "AirGradient")] bot = Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service) alert_state.add_chat(1, "Rob") @@ -202,9 +212,10 @@ async def dashboard(titles=None): return bot, now -def three_tiles(): - tile = Tile("Humidity", "%", 70, "dial", 0, 100, ("#DFFBFF", "#2C7592"), ("Max",), {"Daily": (87,)}, (0, 100), 0) - return Dashboard([tile, tile, tile]) +def three_gauges(): + """current's result with context for the report's three gauges.""" + return {"sensors": {"outdoor": {"temperature": {"value": 12.3, "unit": "°C"}, "humidity": {"value": 70, "unit": "%"}}, + "rainfall": {"rain": {"value": 0.2, "unit": "mm"}}}} def chat(sent): @@ -228,7 +239,7 @@ async def no_action(*a, **k): async def test_the_report_is_its_gauges_with_the_report_as_their_caption_and_refresh_redraws_both(alert_state, monkeypatch): from lib import report_menu - bot, tools = report_bot(alert_state, three_tiles) + bot, tools = report_bot(alert_state, three_gauges) sent = [] msg, update = chat(sent) await bot.respond(update, CONTEXT, "report") @@ -258,9 +269,9 @@ async def edit_message_caption(self, caption=None, caption_entities=None, reply_ assert what == "media" and "13.0 °C" in caption and [e.type for e in entities] == ["bold", "bold"] assert markup.inline_keyboard[0][0].callback_data == report_menu.REFRESH - async def failing(titles=None): + def failing(): raise RuntimeError("cache gone") - bot.by_name["Ecowitt"].dashboard = failing + tools.gauges = failing tools.reading = "14.0 °C" await bot.on_report_button(NS(callback_query=Query()), CONTEXT) assert edits[-1][0] == "caption" and "14.0 °C" in edits[-1][1] # no new picture: the caption alone @@ -276,7 +287,7 @@ def broken(): msg, update = chat(sent) await bot.respond(update, CONTEXT, "report") assert [k for k, *_ in sent] == ["text"] and sent[0][3]["reply_markup"].inline_keyboard[0][0].callback_data == report_menu.REFRESH - assert "gauges failed" in caplog.text + assert "Service tool current failed: RuntimeError: no cache" in caplog.text async def test_a_report_too_long_for_a_caption_goes_after_its_gauges_with_the_refresh_button_on_the_text(): @@ -306,6 +317,7 @@ def test_a_refreshed_report_too_long_for_its_caption_keeps_its_first_sections(): async def test_the_bands_the_bot_saw_widen_the_gauges_figures_and_the_year_takes_in_the_month(tmp_path): """Between its 5-minute readings the bot (and Home Assistant) saw lower and higher: the day rows take those bands in, so the gauges' Daily and Monthly highs and lows do, and the year's.""" + from lib.ecowitt.days import day_values_on from lib.storage import Storage from lib.timeutil import day_bounds from tests.fakes import MAC @@ -320,9 +332,89 @@ def day(w, d, low, high, band): w.put_ranges(MAC, {"outdoor.temperature": {start + 43200: (4, *band)}}) storage.writer.run(lambda w: (day(w, earlier, 5.0, 28.0, (3.5, 30.0)), day(w, TODAY, 15.0, 20.0, (14.0, 21.5))), ()) live = {"outdoor": {"temperature": reading(18.0)}} - tile = (await dash.dashboard(live, storage, MAC, TODAY, ("Temperature",))).tiles[0] + values, _ = await storage.read(day_values_on, MAC, ["temp_max", "temp_min"], dash.periods_of(TODAY)["Yearly"]) + tile = gauge_sheet.sheet(gauges_result(live, values, TODAY), ("Temperature",)).tiles[0] assert tile.rows == {"Daily": (21.5, 14.0), "Monthly": (30.0, 3.5), "Yearly": (30.0, 3.5)} values = {"temp_max": {earlier: 28.0, TODAY: 20.0}, "temp_min": {earlier: 5.0, TODAY: 15.0}} - plain = dash.sheet(live, values, TODAY, ("Temperature",)).tiles[0] + plain = gauge_sheet.sheet(gauges_result(live, values, TODAY), ("Temperature",)).tiles[0] assert plain.rows == {"Daily": (20.0, 15.0), "Monthly": (28.0, 5.0), "Yearly": (28.0, 5.0)} # the readings alone storage.close() + + +# ---------- the gauges from the service's current, with context (docs/mcp-service.md 3.1, 6 step 2) ---------- +STATUS_TITLES = ("Temperature", "Humidity", "Rain") +GAUGE_RESULT = { + "sensors": { + "outdoor": {"temperature": {"value": 12.3, "unit": "°C", "text": "12.3 °C", + "today": {"high": 14.0, "low": 9.5}, "month": {"high": 21.0, "low": 4.0}, + "year": {"high": 38.0, "low": -1.0}}, + "humidity": {"value": 94, "unit": "%", "text": "94 %", "today": {"high": 94, "low": 60}}}, + "rainfall": {"rain": {"value": 6.3, "unit": "mm", "text": "6.3 mm", "today": {"total": 6.3}, + "month": {"total": 49.8, "wettest_day": {"rain": 20.1}}, "year": {"total": 400.2, "wettest_day": {"rain": 41.0}}}}, + "wind": {"wind_speed": {"value": 14, "unit": "km/h", "today": {"high_gust": 31.0}}}, + "indoor": {"temperature": {"value": None, "unit": "°C", "year": {"high": 30.0, "low": 12.0}}}, # no reading now: dimmed + "solar_and_uvi": {"uvi": {"value": None, "unit": ""}}}, # nothing at all: left out + "lines": {"station": []}, "headings": {"station": "Weather station"}} + + +def test_the_gauges_sheet_is_drawn_from_currents_readings_and_their_context(): + from lib import gauge_sheet + sheet = gauge_sheet.sheet(GAUGE_RESULT) + tiles = {t.title: t for t in sheet.tiles} + assert list(tiles) == ["Temperature", "Humidity", "Wind", "Rain", "Indoor temperature"] # the dashboard's order (GAUGES) + t = tiles["Temperature"] + assert (t.value, t.unit, t.kind, t.columns) == (12.3, "°C", "thermometer", ("Max", "Min")) + assert t.rows == {"Daily": (14.0, 9.5), "Monthly": (21.0, 4.0), "Yearly": (38.0, -1.0)} + assert tiles["Humidity"].value == 94.0 and isinstance(tiles["Humidity"].value, float) # as the station's reading was read + assert tiles["Humidity"].rows["Monthly"] == (None, None) + assert tiles["Wind"].rows == {"Daily": (31.0,), "Monthly": (None,), "Yearly": (None,)} # its highest gust + assert tiles["Rain"].rows == {"Daily": (None, 6.3), "Monthly": (20.1, 49.8), "Yearly": (41.0, 400.2)} + assert tiles["Indoor temperature"].value is None and tiles["Indoor temperature"].rows["Yearly"] == (30.0, 12.0) + status = gauge_sheet.sheet(GAUGE_RESULT, STATUS_TITLES) + assert [t.title for t in status.tiles] == list(STATUS_TITLES) + assert gauge_sheet.sheet({"sensors": {}}) is None and gauge_sheet.sheet({"error": "x"}) is None + assert gauge_sheet.sheet({**GAUGE_RESULT, "unavailable": {"station": "The weather station isn't answering right now."}}) is None + + +async def test_the_dashboard_and_the_reports_gauges_are_the_services_current_with_context(alert_state, monkeypatch): + """The bot draws its gauges from current {context: true} (the station's own dashboard() is not asked): the whole dashboard from + every gauge's reading, the report's from its three.""" + from tests.fakes import StandInService + drawn = [] + monkeypatch.setattr(gauges, "render", lambda sheet: drawn.append(sheet) or b"\x89PNG") + + def current(args, meta): + if args.get("context"): + return GAUGE_RESULT + return {"lines": {"station": ["• Outdoor: 12.3 °C"]}, "headings": {"station": "Weather station"}} + service = StandInService(current=current) + + async def no_dashboard(titles=None): + raise AssertionError("the gauges come from the service's current") + sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt", dashboard=no_dashboard)] + bot = Bot(NS(tz=TZ), NS(), sources, alert_state, service=service) + sent = [] + msg, update = chat(sent) + await bot.respond(update, CONTEXT, "dashboard") + assert [k for k, *_ in sent] == ["photo"] and sent[0][2].startswith("Weather station dashboard, ") + from lib import gauge_sheet + assert drawn[-1] == gauge_sheet.sheet(GAUGE_RESULT) + assert ("current", {"context": True}) in service.calls # every reading, the air's aside + await bot.respond(update, CONTEXT, "report") + assert sent[-1][0] == "photo" and [t.title for t in drawn[-1].tiles] == list(STATUS_TITLES) + assert ("current", {"readings": ["outdoor.temperature", "outdoor.humidity", "rainfall.rain"], "context": True}) in service.calls + + +async def test_a_station_that_gives_nothing_is_not_answering_and_its_report_goes_without_gauges(alert_state): + from tests.fakes import StandInService + down = {"sensors": {}, "lines": {"station": ["• not available right now"]}, "headings": {"station": "Weather station"}, + "unavailable": {"station": "The weather station isn't answering right now."}} + service = StandInService(current=down) + sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] + bot = Bot(NS(tz=TZ), NS(), sources, alert_state, service=service) + sent = [] + msg, update = chat(sent) + await bot.respond(update, CONTEXT, "dashboard") + assert [(k, text) for k, _, text, _ in sent] == [("text", "The weather station isn't answering right now.")] + await bot.respond(update, CONTEXT, "report") + assert sent[-1][0] == "text" # the report as text alone diff --git a/tests/test_service_current.py b/tests/test_service_current.py index 65da2116..6847c84e 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -248,10 +248,27 @@ def test_the_heading_has_the_time_of_the_reading_with_its_day_when_that_isnt_tod # ---------- context: the gauges' figures ---------- +async def gauge_rows(eco, data: dict) -> dict: + """{title: {row: figures}}: each gauge's rows as the station's own dashboard drew them before step 2 (dashboard.figures over the + year's day rows, the live reading counted in; today's rain the gauge's own reading).""" + from lib.ecowitt.dashboard import GAUGES, PERIODS, figures, live_value, periods_of + days = periods_of(eco.now().date()) + names = sorted({n for g in GAUGES for n in (g.highest, g.lowest) if n}) + values, _ = await eco.storage.read(day_values_on, eco.mac, names, days["Yearly"]) + out = {} + for g in GAUGES: + now = live_value(data, g.live) + out[g.title] = {row: figures(g, values, days[row], None if g.total else now) for row in PERIODS} + if g.total and now is not None: + out[g.title]["Daily"] = (None, now) + return out + + async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, archived_cache): - tool, _, _ = await world(tmp_path, archived_cache, live(time.time(), **DAY)) + data = live(time.time(), **DAY) + tool, _, _ = await world(tmp_path, archived_cache, data) got = await call(tool, context=True) - tiles = {t.title: t.rows for t in (await tool.ctx.eco.dashboard()).tiles} + tiles = await gauge_rows(tool.ctx.eco, data) s = got["sensors"] for title, (sensor, reading) in (("Temperature", ("outdoor", "temperature")), ("Humidity", ("outdoor", "humidity")), ("Atmospheric pressure", ("pressure", "relative")), ("Dew point", ("outdoor", "dew_point")), @@ -276,6 +293,24 @@ async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, a await close(tool) +async def test_with_context_every_gauge_the_station_sends_is_there_though_its_file_hasnt_recorded_it_yet(tmp_path, archived_cache): + """The catalogue is what the file has recorded; with context, a gauge's reading the station sends now but the file doesn't hold yet + (the archived fake has no feels like, rain rate nor indoor humidity) is there too, with its figures (the reading now alone), as the + gauges show every reading the station sends. Without context, or with readings named, only the catalogue's.""" + tool, _, _ = await world(tmp_path, archived_cache, catalogue="file") + held = tool.ctx.readings() + assert not {"outdoor.feels_like", "rainfall.rain_rate", "indoor.humidity"} & set(held.names) + s = (await call(tool, context=True))["sensors"] + feels, rate, inside = s["outdoor"]["feels_like"], s["rainfall"]["rain_rate"], s["indoor"]["humidity"] + assert (feels["value"], feels["text"]) == (12.3, "12.3 °C") and rate["value"] == 1.8 and inside["value"] == 63 + assert feels["today"]["high"] == feels["today"]["low"] == 12.3 and rate["year"]["high"] == 1.8 + assert "app_temp" not in s["outdoor"] and "vpd" not in s["outdoor"] # (no gauge: only the catalogue's) + assert "feels_like" not in (await call(tool))["sensors"]["outdoor"] + named = (await call(tool, readings=["outdoor temperature"], context=True))["sensors"] + assert list(named) == ["outdoor"] and list(named["outdoor"]) == ["temperature"] # named: just those + await close(tool) + + async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, archived_cache): tool, station, _ = await world(tmp_path, archived_cache) got = await call(tool, readings=["outdoor temperature"], context=True) From 6bed9bd7bbc773218220fd497bd4ac7e52787d3f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:24:02 +0000 Subject: [PATCH 038/125] Service evals: conditions matched by keys, periods by start/end too, fixed clock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `where` expectations use a structural {"conditions": [...]} matcher instead of a regex over Python's repr: keys in any order, other keys ignored, values as numbers (9, 9.0, "9"), ops as days.py reads them (>= ≥ =>), each condition once. - `means` looks at the whole call: with no `period`, start/end are read by read_period with the tool's whole_days setting (days, relate, scan) and compared by span. The start/end alternatives that only restated the period are gone (rainy-days-in-september, weather-on-june-11, what-it-would-have-been-like, most-rain-days-jja, rain-on-a-named-day, temperature-every-30-minutes); a lone start for one day now fails, as it reads to now. - think-hottest-week accepts days (sort_by temp_max optional, this week), as hottest-coldest-this-month does. - The answered-not-refused test runs at the evals' NOW (Tue 29 Sep 2026 14:05 Melbourne): Context(clock=...), the clock fixed in lib/ and tests/, and its own archive built under it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- tests/evalkit.py | 123 ++++++++++++--- tests/evals/service_cases.json | 281 +++++++++++++-------------------- tests/test_service_evals.py | 181 +++++++++++++++++++-- 3 files changed, 383 insertions(+), 202 deletions(-) diff --git a/tests/evalkit.py b/tests/evalkit.py index 36903a45..f461c55c 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -100,16 +100,22 @@ def content(case: Case) -> str: return f'(replying to your earlier message: "{case.reply_to}") {case.ask}' if case.reply_to else case.ask -def _matches(actual, want) -> str | None: +def _matches(actual, want, args: dict | None = None, tool: str | None = None) -> str | None: """None if `actual` satisfies `want`, else why not. want: a value, {"regex"}, {"absent"}, {"has"}, {"any_of"} (or "one_of"), or - the service's {"reads"} / {"reads_any"} (_reads). Any of them with "optional": true also takes no value at all.""" + the service's {"reads"} / {"reads_any"} (_reads), {"means"} (_means: over the whole call, `args`, as `tool` reads a period) and + {"conditions"} (_conditions). Any of them with "optional": true also takes no value at all.""" if isinstance(want, dict): + if "means" in want: # (the period may be sent as start and end instead: an optional one is absent only if neither is) + sent = {k: (args or {}).get(k) for k in ("period", "start", "end")} if args is not None else {"period": actual} + if want.get("optional") and not any(v not in (None, "") for v in sent.values()): + return None + return _means(sent, want["means"], tool) if want.get("optional") and actual in (None, "", [], {}): return None if "reads" in want or "reads_any" in want: return _reads(actual, want) - if "means" in want: - return _means(actual, want["means"]) + if "conditions" in want: + return _conditions(actual, want["conditions"]) if "one_of" in want: return None if actual in want["one_of"] else f"{actual!r} not one of {want['one_of']}" if "absent" in want: @@ -123,8 +129,10 @@ def _matches(actual, want) -> str | None: return None if actual == want else f"expected {want!r}, got {actual!r}" -def check_args(args: dict, want: dict) -> list[str]: - return [f"{k}: {why}" for k, w in want.items() if (why := _matches(args.get(k), w))] +def check_args(args: dict, want: dict, tool: str | None = None) -> list[str]: + """Failures of one call's arguments against one alternative of its expected arguments; `tool` is the tool called (a period is + read as that tool reads it).""" + return [f"{k}: {why}" for k, w in want.items() if (why := _matches(args.get(k), w, args, tool))] def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: @@ -145,8 +153,8 @@ def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: for tool, want in expect.get("args", {}).items(): made = [a for n, a in calls if n == tool] alternatives = want if isinstance(want, list) else [want] - if made and not any(not check_args(a, w) for a in made for w in alternatives): - fails.append(f"{tool} arguments: " + " | or: ".join("; ".join(check_args(made[0], w)) for w in alternatives)) + if made and not any(not check_args(a, w, tool) for a in made for w in alternatives): + fails.append(f"{tool} arguments: " + " | or: ".join("; ".join(check_args(made[0], w, tool)) for w in alternatives)) return fails @@ -286,31 +294,98 @@ def _reads(actual, want: dict) -> str | None: FIRST_HELD = date(2022, 10, 1) # where "on record" starts when a case's period is read (the station's record, as the cases have it) -def _period_span(words) -> tuple | str: - """(start, end) of a `period` as the service reads it at NOW in the station's zone (lib/periods_text.py), or why it can't.""" +WHOLE_DAY_TOOLS = {"days", "relate", "scan"} # the tools that read a period as whole days to yesterday (read_period's whole_days) + + +def _period_span(period, start=None, end=None, whole_days: bool = False) -> tuple | str: + """(start, end) of a `period` in words, or of `start` and `end`, as the service reads them at NOW in the station's zone + (lib/periods_text.py; whole_days as a whole-day tool reads them), or why they can't be read.""" from zoneinfo import ZoneInfo from lib.periods_text import PeriodError, read_period - if not isinstance(words, str) or not words.strip(): - return f"{words!r} is not a period in words" + if period is not None and (not isinstance(period, str) or not period.strip()): + return f"{period!r} is not a period in words" + if period is None and start in (None, ""): + return "no period sent (neither `period` nor `start`)" + what = repr(period) if period is not None else f"start {start!r}" + (f", end {end!r}" if end else "") try: - p = read_period(words, None, None, now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), tz=ZoneInfo(NOW_TZ), default="today", - first_held=FIRST_HELD) + p = read_period(period, start, end, now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), tz=ZoneInfo(NOW_TZ), default="today", + whole_days=whole_days, first_held=FIRST_HELD) except PeriodError as e: - return f"{words!r} can't be read: {e.message.split('. ')[0]}" + return f"{what} can't be read: {e.message.split('. ')[0]}" return p.start, p.end -def _means(actual, refs) -> str | None: - """{"means": words or [words]}: the `period` sent reads, at NOW, as the same span as (one of) these words: "past week", "this week" - and "7d" are the same period, "last week" is another.""" - got = _period_span(actual) +def _means(sent, refs, tool: str | None = None) -> str | None: + """{"means": words or [words]}: the period sent ({"period", "start", "end"} of the call; a bare value is a `period`) reads, at NOW + and as `tool` reads it (whole days for WHOLE_DAY_TOOLS), as the same span as (one of) these words: "past week", "this week" and + "7d" are the same period, "last week" is another; to days, start "2026-09-01" is "September" (to yesterday).""" + sent = sent if isinstance(sent, dict) else {"period": sent} + whole = tool in WHOLE_DAY_TOOLS + if sent.get("period") is not None and str(sent["period"]).strip() == "": + sent = {**sent, "period": None} + got = _period_span(sent.get("period"), sent.get("start"), sent.get("end"), whole) if isinstance(got, str): return got refs = refs if isinstance(refs, list) else [refs] - if any(_period_span(r) == got for r in refs): + if any(_period_span(r, whole_days=whole) == got for r in refs): return None - return f"{actual!r} ({got[0]:%a %d %b %Y %H:%M} to {got[1]:%a %d %b %Y %H:%M}) is not the period of {' or '.join(map(repr, refs))}" + what = repr(sent["period"]) if sent.get("period") is not None else f"start {sent.get('start')!r}, end {sent.get('end')!r}" + return f"{what} ({got[0]:%a %d %b %Y %H:%M} to {got[1]:%a %d %b %Y %H:%M}) is not the period of {' or '.join(map(repr, refs))}" + + +def _op(op) -> str: + """An op as lib/service/days.py reads it (OP_WORDS: "≥" and "=>" are ">=").""" + from lib.service.days import OP_WORDS + return OP_WORDS.get(str(op).strip(), str(op).strip()) + + +def _number(value) -> float | None: + """A condition's value as days.py reads it (a number, or a string of one), else None.""" + if isinstance(value, str): + try: + value = float(value) + except ValueError: + return None + return None if isinstance(value, bool) or not isinstance(value, int | float) else float(value) + + +def _condition_fails(c, want: dict) -> str | None: + if not isinstance(c, dict): + return f"{c!r} is not a condition" + fields = want["field"] if isinstance(want["field"], list) else [want["field"]] + ops = [_op(o) for o in (want["op"] if isinstance(want.get("op"), list) else [want["op"]] if "op" in want else [])] + if str(c.get("field", "")).strip() not in fields: + return f"field {c.get('field')!r} is not {' or '.join(fields)}" + if ops and _op(c.get("op")) not in ops: + return f"op {c.get('op')!r} is not {' or '.join(ops)}" + if (n := _number(c.get("value"))) is None: + return f"value {c.get('value')!r} is not a number" + if "value" in want and n != float(want["value"]): + return f"value {c.get('value')!r} is not {want['value']:g}" + return None + + +def _conditions(actual, want: list[dict]) -> str | None: + """{"conditions": [{"field": name or [names], "op": [ops], "value": number}]}: the `where` sent (a list of conditions, or one) is + these conditions, each once, in any order, compared by their keys as days.py reads them: a value as a number (9, 9.0 and "9" are + the same), an op by its meaning (">=", "≥", "=>"), any other key ignored. With no "op" any op will do, with no "value" any number.""" + sent = [actual] if isinstance(actual, dict) else actual + if not isinstance(sent, list): + return f"{actual!r} is not a list of conditions" + left = list(sent) + for w in want: + hit = next((c for c in left if _condition_fails(c, w) is None), None) + if hit is None: + why = "; ".join(f"{c!r}: {_condition_fails(c, w)}" for c in left) or "none left" + return f"no condition on {w['field']} as {w} ({why})" + left.remove(hit) + return f"conditions not asked for: {left!r}" if left else None + + +def _example_conditions(want: list[dict]) -> list[dict]: + return [{"field": w["field"][0] if isinstance(w["field"], list) else w["field"], + "op": (w["op"][0] if isinstance(w["op"], list) else w["op"]) if "op" in w else ">=", "value": w.get("value", 1)} for w in want] ABSENT = object() # (example_value: the argument is best left out) @@ -318,7 +393,7 @@ def _means(actual, refs) -> str | None: def example_value(want): """A concrete value that satisfies `want` (_matches), to call the tool with: a matcher's own "e.g.", else the first of any_of / - one_of, the names of reads / has; ABSENT where the argument is best left out.""" + one_of, the names of reads / has, the conditions given; ABSENT where the argument is best left out.""" if not isinstance(want, dict): return want if "e.g." in want: @@ -332,6 +407,8 @@ def example_value(want): return list(want.get("reads") or want["reads_any"][:1]) if "means" in want: return want["means"][0] if isinstance(want["means"], list) else want["means"] + if "conditions" in want: + return _example_conditions(want["conditions"]) if "has" in want: return list(want["has"]) raise ValueError(f"no example for {want!r}: give it an \"e.g.\"") @@ -372,7 +449,7 @@ def service_problems(expect: dict | None) -> list[str]: except ValueError as e: fails.append(f"{tool}.{k}: {e}") continue - if v is not ABSENT and (why := _matches(v, w)): + if v is not ABSENT and (why := _matches(v, w, {k: v}, tool)): fails.append(f"{tool}.{k}: its example doesn't satisfy it ({why})") return fails diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index baa07934..87caed32 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -155,12 +155,13 @@ ] }, "where": { - "regex": "'field': 'rain', 'op': '>=?'", - "e.g.": [ + "conditions": [ { "field": "rain", - "op": ">=", - "value": 1 + "op": [ + ">=", + ">" + ] } ] } @@ -418,36 +419,22 @@ "days" ], "args": { - "days": [ - { - "where": { - "regex": "'field': 'rain', 'op': '>=?'", - "e.g.": [ - { - "field": "rain", - "op": ">=", - "value": 1 - } - ] - }, - "period": { - "means": "September" - } + "days": { + "where": { + "conditions": [ + { + "field": "rain", + "op": [ + ">=", + ">" + ] + } + ] }, - { - "where": { - "regex": "'field': 'rain', 'op': '>=?'", - "e.g.": [ - { - "field": "rain", - "op": ">=", - "value": 1 - } - ] - }, - "start": "2026-09-01" + "period": { + "means": "September" } - ] + } }, "note": "days found by a condition, over September (this month: to yesterday)" }, @@ -480,32 +467,16 @@ "days" ], "args": { - "summary": [ - { - "period": { - "means": "11 June" - } - }, - { - "start": { - "regex": "^2026-06-11", - "e.g.": "2026-06-11" - } + "summary": { + "period": { + "means": "11 June" } - ], - "days": [ - { - "period": { - "means": "11 June" - } - }, - { - "start": { - "regex": "^2026-06-11", - "e.g.": "2026-06-11" - } + }, + "days": { + "period": { + "means": "11 June" } - ] + } }, "note": "one known day: its figures and its look (summary), or its day row (days {period: \"5 Sep\"})" }, @@ -515,32 +486,16 @@ "days" ], "args": { - "summary": [ - { - "period": { - "means": "10 Aug" - } - }, - { - "start": { - "regex": "^2026-08-10", - "e.g.": "2026-08-10" - } + "summary": { + "period": { + "means": "10 Aug" } - ], - "days": [ - { - "period": { - "means": "10 Aug" - } - }, - { - "start": { - "regex": "^2026-08-10", - "e.g.": "2026-08-10" - } + }, + "days": { + "period": { + "means": "10 Aug" } - ] + } }, "note": "a hypothetical about one day: that day's figures" }, @@ -579,21 +534,14 @@ "days" ], "args": { - "days": [ - { - "sort_by": "rain", - "period": { - "means": "June to August 2026" - } - }, - { - "sort_by": "rain", - "start": "2026-06-01", - "end": "2026-08-31" + "days": { + "sort_by": "rain", + "period": { + "means": "June to August 2026" } - ] + } }, - "note": "days ranked by rain over three months: \"June to August 2026\", or start and end" + "note": "days ranked by rain over three months: \"June to August 2026\", or the same as start and end" }, "fastest-gust": { "any_tools": [ @@ -671,29 +619,16 @@ "summary" ], "args": { - "days": [ - { - "period": { - "means": "5 Sep" - } - }, - { - "start": "2026-09-05" + "days": { + "period": { + "means": "5 Sep" } - ], - "summary": [ - { - "period": { - "means": "5 Sep" - } - }, - { - "start": { - "regex": "^2026-09-05", - "e.g.": "2026-09-05" - } + }, + "summary": { + "period": { + "means": "5 Sep" } - ] + } }, "note": "one known day: its figures, not a search of the month" }, @@ -1064,8 +999,9 @@ "note": "sitrep is a report: current, forecast (today) and pollen" }, "think-hottest-week": { - "tools": [ - "summary" + "any_tools": [ + "summary", + "days" ], "args": { "summary": { @@ -1078,9 +1014,20 @@ ], "optional": true } + }, + "days": { + "sort_by": { + "one_of": [ + "temp_max", + null + ] + }, + "period": { + "means": "this week" + } } }, - "note": "the hottest of a period with when it was is summary (a record), not days" + "note": "the hottest of a period with when it was is summary's; the hottest day found by ranking its days is days' (as hottest-coldest-this-month)" }, "button-rain-chart": { "tools": [ @@ -1525,11 +1472,12 @@ "args": { "days": { "where": { - "regex": "'field': 'uv_max', 'op': '>=', 'value': '?9(\\.0)?'?\\}", - "e.g.": [ + "conditions": [ { "field": "uv_max", - "op": ">=", + "op": [ + ">=" + ], "value": 9 } ] @@ -1554,11 +1502,13 @@ "args": { "days": { "where": { - "regex": "'field': 'uv_max', 'op': '>=?', 'value': '?10(\\.0)?'?\\}", - "e.g.": [ + "conditions": [ { "field": "uv_max", - "op": ">", + "op": [ + ">", + ">=" + ], "value": 10 } ] @@ -1612,11 +1562,16 @@ "args": { "days": { "where": { - "regex": "'field': 'pm2_5_(max|avg)', 'op': '>=?', 'value': '?25(\\.0)?'?\\}", - "e.g.": [ + "conditions": [ { - "field": "pm2_5_max", - "op": ">", + "field": [ + "pm2_5_max", + "pm2_5_avg" + ], + "op": [ + ">", + ">=" + ], "value": 25 } ] @@ -1637,11 +1592,16 @@ "args": { "days": { "where": { - "regex": "'field': 'pm2_5_(max|avg)', 'op': '>=?', 'value': '?90(\\.0)?'?\\}", - "e.g.": [ + "conditions": [ { - "field": "pm2_5_max", - "op": ">", + "field": [ + "pm2_5_max", + "pm2_5_avg" + ], + "op": [ + ">", + ">=" + ], "value": 90 } ] @@ -1662,11 +1622,13 @@ "args": { "days": { "where": { - "regex": "'field': 'uv_max', 'op': '>=?', 'value': '?10(\\.0)?'?\\}", - "e.g.": [ + "conditions": [ { "field": "uv_max", - "op": ">", + "op": [ + ">", + ">=" + ], "value": 10 } ] @@ -1687,17 +1649,21 @@ "args": { "days": { "where": { - "regex": "(?s)(?=.*'field': 'temp_max', 'op': '>=?', 'value': '?35)(?=.*'field': 'rain', 'op': '>=?')", - "e.g.": [ + "conditions": [ { "field": "temp_max", - "op": ">", + "op": [ + ">", + ">=" + ], "value": 35 }, { "field": "rain", - "op": ">=", - "value": 1 + "op": [ + ">=", + ">" + ] } ] } @@ -2014,36 +1980,17 @@ "readings" ], "args": { - "readings": [ - { - "reading": { - "reads": [ - "outdoor.temperature" - ] - }, - "interval": "30min", - "period": { - "means": "today" - } + "readings": { + "reading": { + "reads": [ + "outdoor.temperature" + ] }, - { - "reading": { - "reads": [ - "outdoor.temperature" - ] - }, - "interval": "30min", - "start": { - "regex": "^2026-09-29( 00:00)?$", - "e.g.": "2026-09-29" - }, - "end": { - "regex": "^2026-09-29", - "e.g.": "2026-09-29 14:05", - "optional": true - } + "interval": "30min", + "period": { + "means": "today" } - ] + } }, "note": "values every 30 minutes, not a highs-and-lows summary" }, diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 104366b8..60ecdd05 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -3,17 +3,25 @@ describes, made concrete, is one the real tool answers rather than refuses; the tool list itself is one any model can read. (What a real model does with the ten is `scripts/eval_prompts.py --live --service`; its plumbing is tested here with a scripted model.) -The expectations are written for evalkit.NOW (Tue 29 Sep 2026 14:05), and a period is matched by what it means then ({"means"}). The -real tools are called on the real clock over the fake station (its history runs to now), so that check is of the arguments being taken -(names, words, forms, start and end), not of the figures.""" - +The expectations are written for evalkit.NOW (Tue 29 Sep 2026 14:05), and a period is matched by what it means then ({"means"}), sent +in words or as start and end. The real tools are called with the clock fixed at that time (at_eval_now) over the fake station built +under it, so that check is of the arguments being taken (names, words, forms, start and end), not of the figures, and holds on any +real date.""" + +import asyncio +import datetime as _dt +import importlib import json import os +import pkgutil import subprocess import sys +import time as _time from datetime import datetime, time as dtime from pathlib import Path from types import SimpleNamespace as NS +from unittest import mock +from zoneinfo import ZoneInfo import pytest @@ -68,6 +76,70 @@ def test_the_checker_reads_names_words_and_periods_as_the_service_does(): assert check({"x": 1}, {"x": {"one_of": [1, 2]}}) == [] and check({"x": 3}, {"x": {"one_of": [1, 2]}}) +def test_a_condition_list_is_matched_by_its_keys_and_numbers_not_its_spelling(): + check = evalkit.check_args + want = {"where": {"conditions": [{"field": "uv_max", "op": [">=", ">"], "value": 9}]}} + for same in ([{"field": "uv_max", "op": ">=", "value": 9}], [{"value": 9, "op": ">=", "field": "uv_max"}], + [{"field": "uv_max", "op": ">=", "value": 9.0}], [{"field": "uv_max", "op": "≥", "value": "9"}], + [{"field": " uv_max", "op": "=>", "value": 9, "note": "after value"}], {"field": "uv_max", "op": ">", "value": 9}): + assert check({"where": same}, want) == [], same + for wrong in ([{"field": "uv_avg", "op": ">=", "value": 9}], [{"field": "uv_max", "op": "<", "value": 9}], + [{"field": "uv_max", "op": ">=", "value": 10}], [{"field": "uv_max", "op": ">=", "value": "nine"}], + [{"field": "uv_max", "op": ">=", "value": True}], [{"field": "uv_max", "op": ">="}], [], None, "uv_max >= 9", + [{"field": "uv_max", "op": ">=", "value": 9}, {"field": "rain", "op": ">=", "value": 1}]): + assert check({"where": wrong}, want), wrong + two = {"where": {"conditions": [{"field": "temp_max", "op": [">", ">="], "value": 35}, {"field": "rain", "op": [">", ">="]}]}} + assert check({"where": [{"op": ">", "value": 0.2, "field": "rain"}, {"field": "temp_max", "value": 35.0, "op": "≥"}]}, two) == [] + assert check({"where": [{"field": "temp_max", "op": ">", "value": 35}]}, two) # (the rain condition missing) + either = {"where": {"conditions": [{"field": ["pm2_5_max", "pm2_5_avg"], "op": [">"], "value": 25}]}} + assert check({"where": [{"field": "pm2_5_avg", "op": ">", "value": 25}]}, either) == [] + assert evalkit.example_value(two["where"]) == [{"field": "temp_max", "op": ">", "value": 35}, {"field": "rain", "op": ">", "value": 1}] + + +def test_every_where_is_matched_as_conditions_so_a_correct_call_in_any_key_order_passes(): + wheres = {cid: w for cid, expect in EXPECT.items() for alternatives in expect.get("args", {}).values() + for alt in (alternatives if isinstance(alternatives, list) else [alternatives]) if (w := alt.get("where"))} + assert wheres and all(set(w) <= {"conditions", "e.g."} and "conditions" in w for w in wheres.values()), wheres + for cid in ("uv-days-two-years", "uv-days-per-year", "days-over-limit-by-year", "air-days-per-year", "count-pm25-days-per-year", + "days-two-readings-go-to-the-model", "hottest-day-that-rained", "rainy-days-in-september"): + (name, args), *_ = evalkit.example_calls(EXPECT[cid]) + backwards = {**args, "where": [{"note": "x", **dict(reversed(list(c.items())))} for c in args["where"]]} + assert evalkit.check_calls([(name, backwards)], EXPECT[cid]) == [], cid + + +def test_a_period_sent_as_start_and_end_is_matched_by_what_it_means_as_the_tool_reads_it(): + check = evalkit.check_calls + # days reads whole days to yesterday: September from its first day is the month to the 28th, as "September" is + assert check([("days", {"start": "2026-09-01"})], {"args": {"days": {"period": {"means": "September"}}}}) == [] + assert check([("days", {"start": "2026-09-01", "end": "2026-09-28"})], {"args": {"days": {"period": {"means": "this month"}}}}) == [] + assert check([("days", {"start": "2026-08-01"})], {"args": {"days": {"period": {"means": "September"}}}}) + # summary reads to the minute: one day is that day's start and end; a start alone runs to now + assert check([("summary", {"start": "2026-06-11", "end": "2026-06-11"})], {"args": {"summary": {"period": {"means": "11 June"}}}}) == [] + assert check([("summary", {"start": "2026-06-11"})], {"args": {"summary": {"period": {"means": "11 June"}}}}) + assert check([("readings", {"start": "2026-09-29"})], {"args": {"readings": {"period": {"means": "today"}}}}) == [] + assert "no period sent" in check([("days", {})], {"args": {"days": {"period": {"means": "September"}}}})[0] + assert check([("days", {})], {"args": {"days": {"period": {"means": "on record", "optional": True}}}}) == [] + for cid, call in (("most-rain-days-jja", ("days", {"sort_by": "rain", "start": "2026-06-01", "end": "2026-08-31"})), + ("rainy-days-in-september", ("days", {"where": [{"field": "rain", "op": ">=", "value": 1}], "start": "2026-09-01"})), + ("rain-on-a-named-day", ("days", {"start": "2026-09-05", "end": "2026-09-05"})), + ("weather-on-june-11", ("summary", {"start": "2026-06-11", "end": "2026-06-11"})), + ("temperature-every-30-minutes", + ("readings", {"reading": "temperature", "interval": "30min", "start": "2026-09-29"}))): + assert check([call], EXPECT[cid]) == [], cid + + +def test_the_whole_day_tools_are_those_whose_period_is_described_as_whole_days(): + tools = {t.name: t for t in evalkit.service_tools()} + assert evalkit.WHOLE_DAY_TOOLS == {n for n, t in tools.items() if "Whole days only" in t.parameters.get("properties", {}) + .get("period", {}).get("description", "")} + + +def test_a_hottest_day_of_a_period_may_be_found_by_days_as_well(): + for cid, period in (("think-hottest-week", "this week"), ("hottest-coldest-this-month", "this month")): + assert evalkit.check_calls([("days", {"sort_by": "temp_max", "period": period})], EXPECT[cid]) == [], cid + assert evalkit.check_calls([("days", {"period": period})], EXPECT[cid]) == [], cid + + def test_alternatives_pass_when_any_one_does(): expect = {"args": {"days": [{"period": {"means": "September"}}, {"start": "2026-09-01"}]}} assert evalkit.check_calls([("days", {"period": "this month"})], expect) == [] @@ -131,23 +203,106 @@ def test_each_description_is_short_and_each_schema_is_json_schema(name): # ---------- every expected call is one the real tool answers ---------- +# At the evals' NOW (Tue 29 Sep 2026 14:05, Melbourne), whatever the real date: the expectations are written for it ("this month" is +# September to the 28th, "June to August 2026" is in the fake's history). Every datetime.now(), date.today() and time.time() in lib/ +# and tests/ reads it, and the fake station's archive is built under it (the idea of tests/test_service_switch.py's freeze, kept here). +EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() + + +class _DatetimeType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.datetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.datetime) + + +class _EvalDatetime(_dt.datetime, metaclass=_DatetimeType): + @classmethod + def now(cls, tz=None): + return _dt.datetime.fromtimestamp(EVAL_NOW, tz) + + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW) + + +class _DateType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.date) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.date) + + +class _EvalDate(_dt.date, metaclass=_DateType): + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW).date() + + +def at_eval_now(patch: pytest.MonkeyPatch): + """The clock fixed at EVAL_NOW in every module of lib/ and tests/ (and this one, whatever pytest names it): every module of lib/ is + imported first (whatever was imported before), then every name bound to datetime or date is the fixed one, and time.time() (and + the archive's epoch_now) returns EVAL_NOW.""" + import lib + import tests.fakes, tests.test_pollen, tests.test_service_forecast # noqa: F401 + for info in pkgutil.walk_packages(lib.__path__, "lib."): + importlib.import_module(info.name) + patch.setattr(_time, "time", lambda: EVAL_NOW) + for name, module in list(sys.modules.items()): + if module is None or not (name in ("lib", __name__) or name.startswith(("lib.", "tests."))): + continue + for attr, value in list(vars(module).items()): + if value is _dt.datetime: + patch.setattr(module, attr, _EvalDatetime) + elif value is _dt.date: + patch.setattr(module, attr, _EvalDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: EVAL_NOW) + + +async def _inline(func, /, *args, **kwargs): + return func(*args, **kwargs) + + +@pytest.fixture(scope="module") +def eval_archive(tmp_path_factory): + """The fake station's whole archive (its ecobot.sqlite) built at EVAL_NOW, once for the module.""" + from lib.ecowitt import Archive, Ecowitt, api, archive + from tests.fakes import ecowitt_transport + + async def build(path): + transport, _ = ecowitt_transport() + eco = Ecowitt(config(path), transport=transport) + await eco.start() + await Archive(eco).run_once() + await eco.close() + return config(path).storage_path + path = tmp_path_factory.mktemp("eval-now") + with pytest.MonkeyPatch.context() as patch: + at_eval_now(patch) + with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ + mock.patch.object(asyncio, "to_thread", _inline): + return asyncio.run(build(path)) + + def calls_for(tool: str) -> list[tuple[str, dict]]: return [(cid, args) for cid, expect in EXPECT.items() for name, args in evalkit.example_calls(expect) if name == tool] -async def real_context(tmp_path, archived_cache) -> Context: - """The ten tools' sources, faked: the archived station, an AirGradient on the same file, both together, Open-Meteo, the pollen page - in season.""" +async def real_context(tmp_path, archive) -> Context: + """The ten tools' sources, faked, at the clock as it is (at_eval_now): the archived station, an AirGradient on the same file, both + together, Open-Meteo, the pollen page in season; the context's own clock is EVAL_NOW.""" from tests.test_pollen import make as pollen_source from tests.test_service_forecast import open_meteo - eco, _ = await archived_station(tmp_path, archived_cache) + eco, _ = await archived_station(tmp_path, archive) air = AirGradient(config(tmp_path), transport=air_transport(rows_per_day=24)[0], storage=eco.storage) await air.start() forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, open_meteo([])) - noon = datetime.combine(datetime.now(TZ).date(), dtime(12, 0)) + noon = datetime.combine(evalkit.NOW.date(), dtime(12, 0)) forecast.now = lambda: noon pollen, _ = pollen_source(tmp_path) - ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen) + ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen, clock=lambda: EVAL_NOW) (summary,) = [t for t in evalkit.service_tools(ctx) if t.name == "summary"] held = json.loads(await summary.call({"readings": ["air"], "period": "last 30 days", "chart": False})) # (the air's month, held) assert "error" not in held @@ -155,11 +310,13 @@ async def real_context(tmp_path, archived_cache) -> Context: @pytest.mark.parametrize("tool", evalkit.service_tool_names()) -async def test_every_expected_call_is_answered_not_refused(tool, tmp_path, archived_cache): +async def test_every_expected_call_is_answered_not_refused(tool, tmp_path, eval_archive, monkeypatch): calls = calls_for(tool) if not calls: pytest.skip(f"no case expects {tool}") - ctx = await real_context(tmp_path, archived_cache) + at_eval_now(monkeypatch) + assert datetime.now(TZ).strftime("%a %d %b %Y %H:%M") == "Tue 29 Sep 2026 14:05" + ctx = await real_context(tmp_path, eval_archive) try: (service_tool,) = [t for t in evalkit.service_tools(ctx) if t.name == tool] refused = {} From 0b4839cd19e01f80fd019dcbfaf1e16757f79d18 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:26:37 +0000 Subject: [PATCH 039/125] docs/mcp-service.md step 5: warm_up() split between the service and the bot; the poke goes Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 9a44ed5f..ad298fbc 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -485,7 +485,10 @@ Each step ships on its own, with the tests and evals green and the bot working t 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the - alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). Then the irrigation server is built in its own + alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). `ecobot.py`'s `warm_up()` is split: the first + fetch, the archive, the backfill, the Home Assistant imports and the startup line go to the service; the bot keeps only its charts + drawn ahead, as `summary` calls at background priority, failing quietly until the service has warmed. The bot's poke of the sources + when a question arrives goes: the service's keep-warm and the tools' own fetches cover it. Then the irrigation server is built in its own repository against it, the bot connects to both, and `lib/irrigation` goes from here. The service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. From 8efe4da1c5d0163ebbc43f6f5de2e19cab0714be Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:38:01 +0000 Subject: [PATCH 040/125] Step 2 done: the review's last three, and the plan marked - A period press is answered once: a chart that can't be sent after "Drawing ..." says so in the chat (a second answer to the press would be refused); the test's fake now refuses a second answer. - current answers a reading named in full that the file hasn't recorded yet, from the reading now; the gauges name their readings, so the dashboard reads only the station (a slow air sensor no longer holds it up) and the report's gauges need no held filter. - Evals: a period in words is compared as words ("last 28 days" is no longer September on the 29th); the hottest-day days call must rank the hottest first (not asc, a count or a statistic). - docs/mcp-service.md: step 2 marked done, with its deliberate changes and what is left; lib/outlook.py is lib/service/outlook.py. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 53 +++++++++++++++++++--------------- lib/bot.py | 39 +++++++++++++++---------- lib/gauge_sheet.py | 6 ++-- lib/service/current.py | 18 ++++++++++-- tests/evalkit.py | 8 +++-- tests/evals/service_cases.json | 15 ++++++++++ tests/test_dashboard.py | 6 ++-- tests/test_periods.py | 14 ++++++--- tests/test_service_current.py | 20 +++++++++++++ tests/test_service_evals.py | 24 +++++++++++++++ 10 files changed, 149 insertions(+), 54 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 491596a9..82dcdc12 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -75,7 +75,7 @@ All of this is what a client other than the bot would not know, so it has to mov | Stays (the service) | Leaves | |---|---| -| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` from `lib/ecowitt/dashboard.py` and `lib/gauge_sheet.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | +| `lib/storage`, `lib/ecowitt` (less the gauges' look), `lib/airgradient`, `lib/forecast`, `lib/pollen`, `lib/snapshots.py`, `lib/warm.py`, `lib/history.py`, `lib/compose.py`, `lib/daytable.py`, `lib/analysis`, `lib/lines.py`, `lib/panels.py`, `lib/rain.py`, `lib/specs.py` (chart data), the alert rules (`lib/alerts/weather.py`, `particulates.py`, `forecast.py`, `pollen_and_asthma.py`, `rules.py`), and new: `lib/mcp_server.py`, `lib/periods_text.py` (3.2), `lib/service/` (the tools of 3.3 and what they share), `lib/service/outlook.py` (3.3), `lib/alert_log.py` (3.6) | **To each client:** Telegram, the model loop, the persona and style of answers, drawing (`lib/charts.py`, `lib/draw.py`, `lib/gauges.py`, and the gauges' layout and colours, `GAUGES` from `lib/ecowitt/dashboard.py` and `lib/gauge_sheet.py`), delivering alerts, per-chat state. **To the irrigation server's repository:** `lib/irrigation`, `lib/alerts/irrigation.py`. **Deleted with the bot:** `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, `lib/report.py`, the menus and keyboards | ### 3.2 An interface any model can use @@ -209,10 +209,10 @@ low_when, high…}], [month…], [year…]}}, "rainfall": {"rain": {…, [today: bot's gauges show (rain as totals and its wettest day, wind's highest gust); with `context` and no readings named, every gauge's reading the station sends now, those its file hasn't recorded yet (outside the catalogue) too, as the gauges show them. -**`outlook`'s result** is the prompt's outlook rules, worked out by the service (`lib/outlook.py`) from the reading now and the last 3 -hours: `{as_of, verdict: "likely"|"possible"|"unlikely", reason: "pressure down 2.4 hPa in 3 hours, humidity 91%", pressure: {change_hpa, -tendency, level, text}, moisture: {humidity, dew_point_spread}, recent_rain, wind_trend, forecast: [today's and tomorrow's lines, when -the forecast is on]}`. With the forecast off, the station's read is the whole answer. +**`outlook`'s result** is the prompt's outlook rules, worked out by the service (`lib/service/outlook.py`) from the reading now and +the last 3 hours: `{as_of, verdict: "likely"|"possible"|"unlikely", reason: "pressure down 2.4 hPa in 3 hours, humidity 91%", +pressure: {change_hpa, tendency, level, text}, moisture: {humidity, dew_point_spread}, recent_rain, wind_trend, forecast: [today's and +tomorrow's lines, when the forecast is on]}`. With the forecast off, the station's read is the whole answer. **`days` over both sensors:** the fields shown and the default sort come from the sensor of the fields named (an air-only question shows and ranks by `pm2_5_max`); `days_checked` counts the days on which every sensor named has a day row; each listed day carries each @@ -460,25 +460,30 @@ Each step ships on its own, with the tests and evals green and the bot working t `lib/periods_text.py` reads the periods table, tested by hand against it at fixed times (a Monday, a Tuesday, the 1st of a month, 1 January, 29 February, 00:30, both clock-change days), with whole-day tools cut to yesterday and errors for phrases outside the table and for the future. No tool interface changes. -2. **The ten tools, beside the twelve.** The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, ready - lines, captions), charts, descriptions and errors, and `lib/outlook.py`; offered to no model yet. Contract tests; the evals run - against them with the tool list alone. The bot's own code paths call them instead of the twelve: its shortcuts, report, - lookups, gauges and alert charts, and the calls behind its period buttons (a press replays the chart's `drawn_by` with a new - `period`; the buttons themselves, their keyboard and picture cache stay in the bot, and go with it). The service knows nothing of - buttons. Everything the bot draws ahead replays a call too: the other periods preloaded after a chart is sent (`drawn_by` with - `1d`, `7d`, `1m`, `3m`, `1y`), the keyboard's charts every 5 minutes (each button a fixed `summary` call), recent alerts' charts - (their `drawn_by`). The picture cache and the pre-upload are keyed by the call (tool and arguments), not the question's words, so - two chats asking the same thing share a picture. A single chart gets a button for each of its `drawn_by.periods`, labelled as the - service labels them, and none when it lists none (today every single chart gets all five, so a count per month offers a 1D that - draws nothing); a replay the service still refuses shows its error on the button. - Begun: what the tools share, in `lib/service/` (`common.py`: a tool and its request metadata, answers, refusals, periods, chart - data; `names.py`: the reading names and the words for them; `daylook.py`: a day's look by its rule). Done: the ten, registered - (`lib/service/__init__.py` `build`, `Service`), built in `ecobot.py` and handed to the bot; the bot's own code paths call them, - through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in - step 3), and quote their words; its answers pinned before and after (`tests/test_service_switch.py`). The bot asks for its charts - as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. Its - gauges (the dashboard, the report's three) are `current` with `context`, laid out bot-side (`lib/gauge_sheet.py`: `GAUGES`' scales - and colours filled from the result; `Ecowitt.dashboard()` and `sheet()` are gone). +2. **The ten tools, beside the twelve** (done). The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, + ready lines, captions), charts, descriptions and errors, in `lib/service/` (what they share: `common.py`, `names.py`, `daylook.py`, + `context.py`; the outlook's rules in `outlook.py`), registered (`__init__.py`: `build`, `Service`), built in `ecobot.py` and handed + to the bot; offered to no model yet. Contract tests per tool; every chart validates against `schemas/chart.json`, `drawn_by` + included, and replays to the same chart and over each of its `periods` without a refusal. The evals have the service's + expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks offline that the tools + accept each expected call; `--live --service` asks a model with the tool list alone (not yet run: it needs the OpenRouter key). + The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and alert charts, through + `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in step 3), + quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but for the deliberate changes + below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' readings named (the air sensor + isn't read), laid out bot-side (`lib/gauge_sheet.py`); `Ecowitt.dashboard()` and `sheet()` are gone. It asks for its charts as + drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. + Period buttons replay the chart's `drawn_by` with a new `period` (the buttons, their keyboard and the picture cache stay in the + bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label, none when it lists + none; a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. + What the bot draws ahead replays calls at background priority: the other periods after a chart is sent, the keyboard's charts + every 5 minutes, recent alerts' charts. The picture cache and the pre-upload are keyed by the call, so two wordings or two chats + share a picture. Deliberate changes: a count per month offers 3M, 1Y and All (never 1D), per year none; whole-day `1y` is the 365 + days to yesterday (364 and today before); alert charts name their source. Until step 3, a chart the model draws through the + twelve gets a `drawn_by` from `legacy.py` when its call translates and lists periods; otherwise (`plot_chart`, the links and the + scan, a period given as times) its buttons ask its question again, as before. Left for later: `current` and `outlook` read the + sources' kept live readings through private members (`Ecowitt._live`, `AirGradient._current`); `fetch: false` doesn't stop the + air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. diff --git a/lib/bot.py b/lib/bot.py index 4190c179..83771adc 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -949,11 +949,16 @@ async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_T message = query.message record = self.charted.get(message.chat_id, message.message_id) if message else None if isinstance(record, dict) and record.get("drawn_by"): + answered: list[str] = [] # what the press was answered with (Telegram takes one answer per press) try: - await self._replay(query, message, record, context.bot) - except Exception as e: # (a chart that fails to draw, Telegram failing): said on the button, never raised + await self._replay(query, message, record, context.bot, answered) + except Exception as e: # (a chart that fails to draw, Telegram failing): said, never raised log.error("Couldn't redraw a chart for its period button (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - await toast_quietly(query, CHART_FAILED) + if not answered: # on the button + await toast_quietly(query, CHART_FAILED) + else: # the button already said "Drawing ...": a second answer would be refused, so in the chat + with contextlib.suppress(TelegramError): + await message.reply_text(CHART_FAILED) return days = periods.days_in(query.data) question = record if isinstance(record, str) and days else None @@ -969,8 +974,17 @@ async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_T log.debug("Period button %s: %s", periods.NAMES[days], question, extra=QUOTES) await self.respond(update, context, asked, redraw=message) - async def _replay(self, query, message: Message, record: dict, bot): - """A period button under a chart the service drew: its drawn_by replayed with the period pressed, into the same message.""" + async def _replay(self, query, message: Message, record: dict, bot, answered: list[str] | None = None): + """A period button under a chart the service drew: its drawn_by replayed with the period pressed, into the same message. + answered: given the "Drawing ..." toast once it is sent (the press is answered once, even when the cached chart can't be put + in and it is drawn again).""" + answered = [] if answered is None else answered + + async def drawing(label: str): + if not answered: + await answer_query(query, f"Drawing {label}...") + answered.append(label) + drawn_by, words = record["drawn_by"], bool(record.get("words")) period = periods.period_in(query.data) listed = {p["period"]: p["label"] for p in drawn_by.get("periods") or ()} @@ -985,7 +999,7 @@ async def _replay(self, query, message: Message, record: dict, bot): key = periods.call_key(tool, args) log.debug("Period button %s: %s", listed[period], key, extra=QUOTES) if (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: nothing is asked again - await answer_query(query, f"Drawing {listed[period]}...") + await drawing(listed[period]) began = time.monotonic() row = periods.periods_keyboard(held.drawn_by, period) if await self._redraw(message, (held.caption or "") if words else "", held.photo, held.title, row, @@ -1003,7 +1017,7 @@ async def _replay(self, query, message: Message, record: dict, bot): await toast_quietly(query, fit(str(out.get("error") or "No chart came of it for that period"), TOAST_LIMIT)) return png, title, newest = await asyncio.to_thread(self._draw, charts[0]) # (drawn before the toast, so a failure can be toasted) - await answer_query(query, f"Drawing {listed[period]}...") + await drawing(listed[period]) drawn = charts[0].get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} text = out.get("caption") or out.get("answer") or "" self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn) @@ -1218,14 +1232,9 @@ async def _chart_in_code(self, call: tuple[str, dict] | None, turn: Turn) -> Mad return Made(text, charts) if "error" not in out and charts and text else None async def _gauge_sheet(self, titles=None): - """The gauges of these titles (all when None) laid out from the service's current with context (lib/gauge_sheet.py), their - readings named those the service holds; None when the station gives nothing.""" - args = gauge_sheet.call(titles) - if "readings" in args: - args["readings"] = self.service.held(args["readings"]) - if not args["readings"]: - return None - return gauge_sheet.sheet(await self._service_call("current", args), titles) + """The gauges of these titles (all when None) laid out from the service's current with context (lib/gauge_sheet.py); None when + the station gives nothing.""" + return gauge_sheet.sheet(await self._service_call("current", gauge_sheet.call(titles)), titles) async def _dashboard(self) -> Answer: """The station's gauges as one picture, sent with just its title (no period buttons: it is the state now).""" diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py index 611e4091..055d2a3e 100644 --- a/lib/gauge_sheet.py +++ b/lib/gauge_sheet.py @@ -14,9 +14,9 @@ def call(titles=None) -> dict: - """current's arguments for the gauges of these titles, with context: their readings named; all of them (titles None), every reading, - so that those the station sends but its file hasn't recorded yet are there too (as the station's own dashboard drew them).""" - return {"context": True} if titles is None else {"readings": [g.reading for g in gauges_of(titles)], "context": True} + """current's arguments for the gauges of these titles (all when None), with context: their readings named, so only the weather + station is read (the air sensor isn't asked), and those the station sends but its file hasn't recorded yet are there too.""" + return {"readings": [g.reading for g in gauges_of(titles)], "context": True} def _row(gauge: Gauge, figures: dict) -> tuple[float | None, ...]: diff --git a/lib/service/current.py b/lib/service/current.py index 2c7eecdb..d6066182 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -40,7 +40,7 @@ from ..timeutil import clock_text, day_text, to_local from .common import BACKGROUND, Refusal, ServiceTool, answer from .context import Context -from .names import AIR_DEVICE, STATION, Catalogue, Reading +from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue, Reading, _split log = logging.getLogger(__name__) @@ -224,6 +224,20 @@ def now_shaped(live: dict, tz: tzinfo) -> tuple[dict, int]: return {**out, **({"emoji": emoji} if emoji else {})}, newest +def _resolve(catalogue, names, *, default) -> list[Reading]: + """The readings named, as the catalogue reads them; a reading's full name that the file hasn't recorded yet but the service knows + (names.CATALOGUE) counts too, since current answers from the reading now (a new station's first minutes, a gauge's reading).""" + known = [w for w in _split(names) if " ".join(w.lower().split()) not in catalogue and " ".join(w.lower().split()) in CATALOGUE] + if not known: + return catalogue.resolve(names, default=default) + out: dict[str, Reading] = {} + for word in _split(names): + exact = " ".join(word.lower().split()) + for r in [CATALOGUE.get(exact)] if word in known else catalogue.resolve(word, default=[]): + out.setdefault(r.name, r) + return list(out.values()) + + def unrecorded(live: dict, listed: set[str]) -> list[Reading]: """The station's readings in its live reading that aren't among these names (the catalogue's: what its file has recorded), as the catalogue would name them once recorded: a sensor sending, or a reading sent, since the file last took the station's fields.""" @@ -406,7 +420,7 @@ def _asked(self, args: dict) -> tuple[list[Reading], bool, bool]: catalogue = self.ctx.readings() here = [r for r in catalogue if r.device in self.devices] named = args.get("readings") not in (None, "", []) - asked = catalogue.resolve(args.get("readings"), default=[r.name for r in here]) + asked = _resolve(catalogue, args.get("readings"), default=[r.name for r in here]) if named and (absent := [r for r in asked if r.device not in self.devices]): device = "weather station" if absent[0].device == STATION else "air sensor" raise Refusal(f"{absent[0].name} is the {device}'s, and this service has no {device}.", names=[r.name for r in here]) diff --git a/tests/evalkit.py b/tests/evalkit.py index f461c55c..715ea7ff 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -317,13 +317,15 @@ def _period_span(period, start=None, end=None, whole_days: bool = False) -> tupl def _means(sent, refs, tool: str | None = None) -> str | None: - """{"means": words or [words]}: the period sent ({"period", "start", "end"} of the call; a bare value is a `period`) reads, at NOW - and as `tool` reads it (whole days for WHOLE_DAY_TOOLS), as the same span as (one of) these words: "past week", "this week" and + """{"means": words or [words]}: the period sent ({"period", "start", "end"} of the call; a bare value is a `period`) reads, at NOW, + as the same span as (one of) these words (a period in words as words; start and end as `tool` reads them, whole days for + WHOLE_DAY_TOOLS): "past week", "this week" and "7d" are the same period, "last week" is another; to days, start "2026-09-01" is "September" (to yesterday).""" sent = sent if isinstance(sent, dict) else {"period": sent} - whole = tool in WHOLE_DAY_TOOLS if sent.get("period") is not None and str(sent["period"]).strip() == "": sent = {**sent, "period": None} + # words are compared as words (whole days would make "last 28 days" September on the 29th); dates as the tool reads them + whole = tool in WHOLE_DAY_TOOLS and sent.get("period") is None got = _period_span(sent.get("period"), sent.get("start"), sent.get("end"), whole) if isinstance(got, str): return got diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index 87caed32..e351cde2 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -1022,6 +1022,21 @@ null ] }, + "order": { + "one_of": [ + "desc", + null + ] + }, + "count_only": { + "one_of": [ + false, + null + ] + }, + "stat": { + "absent": true + }, "period": { "means": "this week" } diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index b5a3bcc3..1bd32bee 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -117,7 +117,7 @@ async def reply_photo(photo, caption=None, **kw): context = CONTEXT update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) await bot.respond(update, context, "Dashboard") - assert service.calls == [("current", {"context": True})] and len(sent) == 1 + assert service.calls == [("current", gauge_sheet.call())] and len(sent) == 1 photo, caption, markup = sent[0] assert photo == b"\x89PNG" and caption.startswith("Weather station dashboard, ") assert not isinstance(markup, InlineKeyboardMarkup) # a chat whose keyboard is out of date gets that instead @@ -195,7 +195,7 @@ def report_bot(alert_state, gauges_now): def current(args, meta): if args.get("context"): - assert args.get("readings") in (gauge_sheet.call(dash.STATUS)["readings"], None) # the report's three gauges, or all + assert args.get("readings") in (gauge_sheet.call(dash.STATUS)["readings"], gauge_sheet.call()["readings"]) # the report's three gauges, or all return now.gauges() return {"lines": {"station": [f"• Outdoor: {now.reading}"], "air": ["• PM10: 3.0 µg/m³ 🟢 good"]}, "headings": {"station": "Weather station", "air": "Air quality"}} @@ -399,7 +399,7 @@ async def no_dashboard(titles=None): assert [k for k, *_ in sent] == ["photo"] and sent[0][2].startswith("Weather station dashboard, ") from lib import gauge_sheet assert drawn[-1] == gauge_sheet.sheet(GAUGE_RESULT) - assert ("current", {"context": True}) in service.calls # every reading, the air's aside + assert ("current", {"readings": [g.reading for g in dash.GAUGES], "context": True}) in service.calls # every gauge's: the air isn't asked await bot.respond(update, CONTEXT, "report") assert sent[-1][0] == "photo" and [t.title for t in drawn[-1].tiles] == list(STATUS_TITLES) assert ("current", {"readings": ["outdoor.temperature", "outdoor.humidity", "rainfall.rain"], "context": True}) in service.calls diff --git a/tests/test_periods.py b/tests/test_periods.py index 7a9b43c8..c711081d 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -190,7 +190,9 @@ async def test_a_replayed_chart_that_cannot_be_drawn_or_sent_says_sorry_on_the_b bot.charted.remember(1, 50, record) answers = [] - async def answer(text=None, **k): + async def answer(text=None, **k): # Telegram takes one answer per press + if answers: + raise BadRequest("Query is too old and response timeout expired or query id is invalid") answers.append(text) def broken(data, tz, times=None): @@ -202,9 +204,13 @@ def broken(data, tz, times=None): async def offline(media, reply_markup=None): raise NetworkError("connection reset") monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") - msg.edit_media, answers[:] = offline, [] - await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) # Telegram failing other than refusing the edit - assert answers == ["Drawing 1Y...", SORRY] + said = [] + + async def reply_text(text, **k): + said.append(text) + msg.edit_media, msg.reply_text, answers[:] = offline, reply_text, [] + await bot.on_period_button(press(msg, "pd:1y", answer), CONTEXT) # Telegram failing other than refusing the edit, after "Drawing" + assert answers == ["Drawing 1Y..."] and said == [SORRY] # (the press is answered once: the sorry goes in the chat) async def test_a_button_on_a_chart_from_before_a_restart_says_so(alert_state, monkeypatch): diff --git a/tests/test_service_current.py b/tests/test_service_current.py index 6847c84e..fd7279be 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -311,6 +311,26 @@ async def test_with_context_every_gauge_the_station_sends_is_there_though_its_fi await close(tool) +async def test_a_reading_named_in_full_that_the_file_hasnt_recorded_is_answered_from_the_reading_now(tmp_path, archived_cache): + """current is about now: a reading the service knows, named in full, that the station sends but the file hasn't recorded yet (a new + station's first minutes) is answered, not refused; a word still reads the file's catalogue. So the gauges name their readings and + only the station is read: the air sensor isn't asked (a slow one doesn't hold up the dashboard).""" + from lib import gauge_sheet + tool, _, sensor = await world(tmp_path, archived_cache, catalogue="file") + assert "outdoor.feels_like" not in tool.ctx.readings() + got = await call(tool, readings=["outdoor.feels_like", "rainfall.rain_rate", "temperature"]) + assert got["sensors"]["outdoor"]["feels_like"]["text"] == "12.3 °C" and got["sensors"]["rainfall"]["rain_rate"]["value"] == 1.8 + assert got["sensors"]["outdoor"]["temperature"]["value"] == 12.3 and "error" not in got + + async def no_air(*a, **k): + raise AssertionError("the gauges don't read the air sensor") + sensor.latest = no_air + gauges = await call(tool, **gauge_sheet.call()) + assert "air" not in gauges["sensors"] and gauges["sensors"]["outdoor"]["feels_like"]["today"]["high"] == 12.3 + assert gauge_sheet.sheet(gauges) is not None + await close(tool) + + async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, archived_cache): tool, station, _ = await world(tmp_path, archived_cache) got = await call(tool, readings=["outdoor temperature"], context=True) diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 60ecdd05..402e3621 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -399,3 +399,27 @@ def test_the_script_runs_the_service_evals_offline_and_needs_a_key_to_ask_a_mode assert run.returncode == 0 and "2 of 2 cases pass (the service's ten tools alone)" in run.stdout run = script("--live", "--service") assert run.returncode != 0 and "--live needs OPENROUTER_API_KEY" in run.stderr + + +def test_a_rolling_period_in_words_is_not_a_month_that_its_days_happen_to_cover(): + """A period sent in words is read as words: "last 28 days" is not "September", though on the 29th its whole days to yesterday are + 1 to 28 September; start and end are still read in whole days as days reads them.""" + from tests import evalkit as ek + for words in ("last 28 days", "4w", "past 4 weeks"): + assert ek._means({"period": words}, "September", "days") is not None + assert ek._means({"period": words}, "this month", "days") is not None + assert ek._means({"period": "September"}, "September", "days") is None + assert ek._means({"start": "2026-09-01"}, "September", "days") is None + + +def test_the_hottest_day_ranked_by_days_must_be_the_hottest(): + """think-hottest-week's days call ranks the hottest first: the coldest (order asc), a count or a statistic isn't the answer.""" + from tests import evalkit as ek + want = ek.load_service_cases()["think-hottest-week"]["args"]["days"] + + def fails(args): + return [k for k, w in want.items() if k != "period" and ek._matches(args.get(k), w)] + assert fails({"sort_by": "temp_max", "period": "this week"}) == [] + assert fails({"sort_by": "temp_max", "order": "asc"}) == ["order"] + assert fails({"sort_by": "temp_max", "count_only": True}) == ["count_only"] + assert fails({"stat": "avg", "of": "temp_avg"}) == ["stat"] From 1d7911746b85651442ab9aa63f38ee34ce8ad1ea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:45:21 +0000 Subject: [PATCH 041/125] =?UTF-8?q?A=20=F0=9F=94=84=20under=20a=20chart=20?= =?UTF-8?q?with=20no=20periods=20to=20offer=20whose=20period=20runs=20to?= =?UTF-8?q?=20now?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A chart whose drawn_by lists no periods (a count per year, a chart from a set time such as since 9am) now gets a 🔄 when its period runs to the present: to now, or through yesterday for a tool of whole days. Pressing it replays the call as it is, past the picture cache, and puts the new chart in the same message with the 🔄 under it again. A chart over a fixed past stretch still gets no buttons. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 4 ++-- lib/bot.py | 23 ++++++++++--------- lib/periods.py | 45 +++++++++++++++++++++++++++++++------ tests/test_periods.py | 52 ++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 102 insertions(+), 22 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 82dcdc12..105ad61b 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -474,8 +474,8 @@ Each step ships on its own, with the tests and evals green and the bot working t isn't read), laid out bot-side (`lib/gauge_sheet.py`); `Ecowitt.dashboard()` and `sheet()` are gone. It asks for its charts as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. Period buttons replay the chart's `drawn_by` with a new `period` (the buttons, their keyboard and the picture cache stay in the - bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label, none when it lists - none; a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. + bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label; when it lists + none, a 🔄 that replays the call as it is if its period runs to now (through yesterday for a whole-day tool), else nothing; a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. What the bot draws ahead replays calls at background priority: the other periods after a chart is sent, the keyboard's charts every 5 minutes, recent alerts' charts. The picture cache and the pre-upload are keyed by the call, so two wordings or two chats share a picture. Deliberate changes: a count per month offers 3M, 1Y and All (never 1D), per year none; whole-day `1y` is the 365 diff --git a/lib/bot.py b/lib/bot.py index 83771adc..259f8d29 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -988,20 +988,23 @@ async def drawing(label: str): drawn_by, words = record["drawn_by"], bool(record.get("words")) period = periods.period_in(query.data) listed = {p["period"]: p["label"] for p in drawn_by.get("periods") or ()} - if period not in listed: + reload = period == periods.RELOAD and not listed # the 🔄 under a chart with no periods that runs to now: drawn again as it is + if period not in listed and not reload: await answer_query(query, "That chart is out of date, please ask again") return now = now_local(self.cfg.tz) - if periods.own_period(drawn_by, now, self.cfg.tz) == period: # the chart already shows this period + if not reload and periods.own_period(drawn_by, now, self.cfg.tz) == period: # the chart already shows this period await answer_query(query) return - tool, args = drawn_by["tool"], periods.with_period(drawn_by, period) + tool = drawn_by["tool"] + args = dict(drawn_by["arguments"]) if reload else periods.with_period(drawn_by, period) + label = "again" if reload else listed[period] key = periods.call_key(tool, args) - log.debug("Period button %s: %s", listed[period], key, extra=QUOTES) - if (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: nothing is asked again - await drawing(listed[period]) + log.debug("Period button %s: %s", label, key, extra=QUOTES) + if not reload and (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: nothing is asked again + await drawing(label) began = time.monotonic() - row = periods.periods_keyboard(held.drawn_by, period) + row = periods.periods_keyboard(held.drawn_by, period, now, self.cfg.tz) if await self._redraw(message, (held.caption or "") if words else "", held.photo, held.title, row, {"drawn_by": held.drawn_by, "words": words}, key, TelegramError, "drawing it again"): self.preload_soon(bot, held.drawn_by) @@ -1017,11 +1020,11 @@ async def drawing(label: str): await toast_quietly(query, fit(str(out.get("error") or "No chart came of it for that period"), TOAST_LIMIT)) return png, title, newest = await asyncio.to_thread(self._draw, charts[0]) # (drawn before the toast, so a failure can be toasted) - await drawing(listed[period]) + await drawing(label) drawn = charts[0].get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} text = out.get("caption") or out.get("answer") or "" self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn) - row = periods.periods_keyboard(drawn, period) + row = periods.periods_keyboard(drawn, period, now, self.cfg.tz) if not await self._redraw(message, text if words else "", png, title, row, {"drawn_by": drawn, "words": words}, key): sent = await deliver(message, text if words else "", [png], titles=[title], period_row=row) if sent.photo: @@ -1541,7 +1544,7 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added single = len(photos) == 1 and not (read.dashboard or read.report) # a single chart: its period buttons go under it drawn_by = answer.drawn_by[0] if single and answer.drawn_by else None if drawn_by: # the periods its call lists, the chart's own shaded; none when it lists none - row = periods.periods_keyboard(drawn_by, periods.own_period(drawn_by, now, self.cfg.tz)) + row = periods.periods_keyboard(drawn_by, periods.own_period(drawn_by, now, self.cfg.tz), now, self.cfg.tz) record = {"drawn_by": drawn_by, "words": bool(reply.strip())} else: # a chart the service can't replay (the model's, through a call it has no equivalent of): its question asked again row = periods.keyboard(intent.period_days(text, now)) if single else None diff --git a/lib/periods.py b/lib/periods.py index 8711501b..a46c15ca 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -2,8 +2,9 @@ A chart the service drew carries `drawn_by` (docs/mcp-service.md 3.7): the call that drew it and the periods it is worth drawing over, each with its label ("7d", "7D"). Its buttons are those periods, the chart's own shaded (the blue of an alert toggle that is on), and -none when it lists none; a button's data is the period ("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one -replays the call with that period (Bot.on_period_button); what drew each chart is remembered for that (Charted). +none when it lists none (but a 🔄, "pd:reload", that draws it again when its period runs to now); a button's data is the period +("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one replays the call with that period +(Bot.on_period_button); what drew each chart is remembered for that (Charted). A chart the model drew through the old tools whose call has no service equivalent keeps the old buttons, 1D / 7D / 1M / 3M / 1Y (1, 7, 30, 90 and 365 days, "pd:7"), which ask its question again with that period.""" @@ -12,7 +13,7 @@ import time from collections import OrderedDict from dataclasses import dataclass -from datetime import datetime, tzinfo +from datetime import date, datetime, timedelta, tzinfo from telegram import InlineKeyboardMarkup from telegram.constants import KeyboardButtonStyle @@ -25,6 +26,7 @@ PREFIX = "pd:" REMEMBERED = 300 # charts whose call is kept, newest first to stay WHOLE_DAY_TOOLS = ("days", "relate", "scan") # the tools that read a period as whole days, up to yesterday +RELOAD = "reload" # the 🔄 under a chart with no periods to offer whose period runs to now: its call replayed as it is ("pd:reload") def keyboard(current: int | None = None) -> InlineKeyboardMarkup: @@ -83,12 +85,41 @@ def span(words: str): return None -def periods_keyboard(drawn_by: dict, current: str | None = None) -> InlineKeyboardMarkup | None: - """One button for each period the chart's drawn_by lists, labelled as the service labels it, the chart's own (`current`) shaded; - None when it lists none.""" +def _span(drawn_by: dict, now: datetime, tz: tzinfo): + """(start, end) of the chart's call's period as the service reads it now; None when it can't be read here.""" + from .periods_text import read_period + args = drawn_by.get("arguments") or {} + period, start, end = args.get("period"), args.get("start"), args.get("end") + if not (period or start): + return None + try: + read = read_period(period or None, start, end, now=now, tz=tz, default=period or "today", + whole_days=drawn_by.get("tool") in WHOLE_DAY_TOOLS, first_held=date(2000, 1, 1)) # (only the end matters) + except Exception: # (PeriodError, or words only a tool with the file can read) + return None + return read.start, read.end + + +def ends_now(drawn_by: dict | None, now: datetime, tz: tzinfo) -> bool: + """Whether the chart's period runs to the present, so drawing it again can show more: to now, or (a tool of whole days) through + yesterday, the last whole day. "Yesterday" on a chart of readings, or a range of past dates, doesn't.""" + span = _span(drawn_by, now, tz) if drawn_by else None + if span is None: + return False + def aware(t: datetime) -> datetime: # (naive: the station's clock) + return t if t.tzinfo else t.replace(tzinfo=tz) + end, now = aware(span[1]), aware(now).astimezone(aware(span[1]).tzinfo) + whole = drawn_by.get("tool") in WHOLE_DAY_TOOLS + return end >= (now.replace(hour=0, minute=0, second=0, microsecond=0) if whole else now - timedelta(minutes=1)) + + +def periods_keyboard(drawn_by: dict, current: str | None = None, now: datetime | None = None, + tz: tzinfo | None = None) -> InlineKeyboardMarkup | None: + """One button for each period the chart's drawn_by lists, labelled as the service labels it, the chart's own (`current`) shaded. + When it lists none: a 🔄 that draws it again if its period runs to now (ends_now; `now` and `tz` given), else None.""" listed = drawn_by.get("periods") or [] if not listed: - return None + return InlineKeyboardMarkup([[button("🔄", f"{PREFIX}{RELOAD}")]]) if now and tz and ends_now(drawn_by, now, tz) else None return InlineKeyboardMarkup([[button(p["label"], f"{PREFIX}{p['period']}", KeyboardButtonStyle.PRIMARY if p["period"] == current else None) for p in listed]]) diff --git a/tests/test_periods.py b/tests/test_periods.py index c711081d..92f1ee7d 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -88,8 +88,11 @@ async def call(self, args, meta=None): if period in self.refuse: return json.dumps({"error": f"Nothing is held for {period}."}) chart = Chart("Temperature", "", [Panel("Temperature", "°C", [Line("Outdoor", [1, 2], [1.0, 2.0])])]) - arguments = {**{k: v for k, v in args.items() if k not in ("start", "end")}, "period": period} - data = {**to_json(chart, TZ), "drawn_by": {"tool": "summary", "arguments": arguments, "periods": [dict(p) for p in OVER_TIME]}} + if args.get("start"): # set times, as the real summary keeps them: no periods to offer + arguments, listed = dict(args), [] + else: + arguments, listed = {**{k: v for k, v in args.items() if k not in ("start", "end")}, "period": period}, [dict(p) for p in OVER_TIME] + data = {**to_json(chart, TZ), "drawn_by": {"tool": "summary", "arguments": arguments, "periods": listed}} return json.dumps({"caption": "Fri 25 Sep – Thu 1 Oct 2026\nTemperature: low 1 °C · high 2 °C", "charts": [data]}) @@ -97,7 +100,8 @@ def make_bot(alert_state, monkeypatch): class Agent: async def run(self, *a, **k): raise AssertionError("no model for a plain chart") - monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: data["drawn_by"]["arguments"]["period"].encode()) + monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: str(data["drawn_by"]["arguments"].get("period") + or data["drawn_by"]["arguments"]["start"]).encode()) sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] return Bot(NS(tz=TZ), Agent(), sources, alert_state, service=Service([Summary()])) @@ -641,3 +645,45 @@ def test_a_chart_drawn_in_one_theme_is_not_sent_again_after_the_theme_changes(mo assert images.get("summary {}") and images.ready("summary {}") monkeypatch.setattr(charts, "MODE", "on") # 8pm under DARKMODE=8pm-8am assert images.ready("summary {}") is None and images.get("summary {}") is None + + +def test_a_chart_with_no_periods_to_offer_gets_a_reload_when_its_period_runs_to_now(): + """A chart whose call lists no periods gets a 🔄 when its period runs to the present (to now; for a tool of whole days, through + yesterday), so it can be drawn again with what has come in since; one over a fixed past stretch gets nothing.""" + reload = [[("🔄", "pd:reload")]] + + def row(tool, **arguments): + markup = periods.periods_keyboard({"tool": tool, "arguments": arguments, "periods": []}, None, NOW, TZ) + return labels(markup) if markup else None + assert row("summary", readings=["outdoor.temperature"], start="2026-10-02 09:00") == reload # since 9am: to now + assert row("summary", start="2026-10-01 09:00", end="2026-10-01 18:00") is None # a fixed stretch + assert row("summary", period="today") == reload and row("summary", period="yesterday") is None + assert row("days", group_by="year", period="on record") == reload # through yesterday + assert row("days", group_by="year", period="2024-01-01 to 2025-12-31") is None + assert row("days", group_by="year", period="2025-01-01 to 2026-12-31") == reload # (cut to yesterday) + assert periods.periods_keyboard({"tool": "summary", "arguments": {"start": "2026-10-02 09:00"}, "periods": []}) is None # no clock: none + listed = {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]} + assert labels(periods.periods_keyboard(listed, "7d", NOW, TZ)) == [ROW] # periods listed: those + + +async def test_pressing_reload_draws_the_same_call_again_in_place_with_the_reload_under_it(alert_state, monkeypatch): + bot, edits, sent = make_bot(alert_state, monkeypatch), [], [] + msg = chat_message(sent, edits) + start = f"{datetime.now(TZ):%Y-%m-%d} 00:00" + drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "start": start, "chart": True}, "periods": []} + bot.charted.remember(1, 50, {"drawn_by": drawn_by, "words": False}) + key = periods.call_key("summary", drawn_by["arguments"]) + bot.images.put(key, b"old picture", "Temperature", drawn_by=drawn_by) # drawn a moment ago: a reload draws it afresh all the same + answers = [] + + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:reload", answer), CONTEXT) + assert calls(bot) == [drawn_by["arguments"]] and answers == ["Drawing again..."] + caption, markup = edits[0] + assert caption == "Temperature" and labels(markup) == [[("🔄", "pd:reload")]] + assert bot.charted.get(1, 50)["drawn_by"]["arguments"] == drawn_by["arguments"] and bot.images.held(key).png == start.encode() + listed = {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": listed, "words": False}) + await bot.on_period_button(press(msg, "pd:reload", answer), CONTEXT) # a chart with periods has no 🔄 + assert answers[-1] == "That chart is out of date, please ask again" and len(calls(bot)) == 1 From f4f6161d4b754a59bbde261296ff47fc41076261 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 06:51:21 +0000 Subject: [PATCH 042/125] =?UTF-8?q?The=20=F0=9F=94=84=20only=20on=20charts?= =?UTF-8?q?=20whose=20period=20moves=20on=20with=20the=20clock?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of 1d79117: a chart whose call carried fixed dates ending today or yesterday got a 🔄 that could never show more (the bot's own per-year charts were translated to "2022-11-12 to 2026-11-10"; days turned a start with no end into fixed dates). - legacy.period and days.drawn_by word a period that runs to today or later as " to now", so a replay reads up to the new now (or yesterday) instead of the day it was first drawn. - ends_now also asks that the period's end move when the clock does: fixed dates ("October", "last month", "2025", "2026-09-01 to 2026-10-01") get no 🔄 even when they end yesterday. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/periods.py | 9 ++++++--- lib/service/days.py | 5 ++++- lib/service/legacy.py | 5 +++-- tests/test_periods.py | 4 +++- tests/test_service_days.py | 3 +++ tests/test_service_legacy.py | 9 +++++---- 6 files changed, 24 insertions(+), 11 deletions(-) diff --git a/lib/periods.py b/lib/periods.py index a46c15ca..40743725 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -101,11 +101,14 @@ def _span(drawn_by: dict, now: datetime, tz: tzinfo): def ends_now(drawn_by: dict | None, now: datetime, tz: tzinfo) -> bool: - """Whether the chart's period runs to the present, so drawing it again can show more: to now, or (a tool of whole days) through - yesterday, the last whole day. "Yesterday" on a chart of readings, or a range of past dates, doesn't.""" + """Whether the chart's period runs to the present and moves on with the clock, so drawing it again can show more: to now, or (a + tool of whole days) through yesterday, the last whole day. Fixed dates don't ("October", "2026-11-01 to 2026-11-09", even on the + 10th), nor does "yesterday" on a chart of readings.""" span = _span(drawn_by, now, tz) if drawn_by else None - if span is None: + later = _span(drawn_by, now + timedelta(days=1), tz) if span else None + if span is None or later is None or later[1] <= span[1]: # fixed dates ("October", "2026-11-01 to 2026-11-09"): never more return False + def aware(t: datetime) -> datetime: # (naive: the station's clock) return t if t.tzinfo else t.replace(tzinfo=tz) end, now = aware(span[1]), aware(now).astimezone(aware(span[1]).tzinfo) diff --git a/lib/service/days.py b/lib/service/days.py index fdaa280c..d6fb63ee 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -520,7 +520,10 @@ def drawn_by(self, call: Call, args: dict, period, first: date, last: date, firs """The call that drew the chart as the tool read it (3.7), every default filled in, the period in words, and the periods it is worth drawing over: per month, 3 months, a year and the whole record (with hours, only while that is within its 400 days); per year, none.""" - words = f"{first.isoformat()} to {last.isoformat()}" if args.get("start") else period.asked + words = period.asked + if args.get("start"): # dates as words; one that runs to today or later as "to now", so a replay moves on with the clock + open_ended = not args.get("end") or str(args["end"])[:10] >= today.isoformat() + words = f"{first.isoformat()} to {'now' if open_ended else last.isoformat()}" arguments = {"where": call.where, "sort_by": self.sort_of(call), "order": call.order, "count_only": call.count_only, "group_by": call.group_by, "stat": call.stat, **({"of": call.of} if call.of else {}), "limit": call.limit, **({"only": call.only} if call.only else {}), **({"hours": _stretch_words(call.stretch)} if call.stretch else {}), diff --git a/lib/service/legacy.py b/lib/service/legacy.py index efc69e9f..3db44e86 100644 --- a/lib/service/legacy.py +++ b/lib/service/legacy.py @@ -62,8 +62,9 @@ def period(start: str | None, end: str | None, words: list[str], now: datetime, first, last = _when(start) if start else None, _when(end) if end else None if first is None: return {} + open_ended = last is None or last.date() >= now.date() # (to today or later: to now, so a replay moves on with the clock) if whole_days: - return {"period": f"{first:%Y-%m-%d} to {last:%Y-%m-%d}" if last else f"{first:%Y-%m-%d} to now"} + return {"period": f"{first:%Y-%m-%d} to now" if open_ended else f"{first:%Y-%m-%d} to {last:%Y-%m-%d}"} now = now.replace(tzinfo=None, microsecond=0) until = min(last, now) if last else now for said in words: @@ -75,7 +76,7 @@ def period(start: str | None, end: str | None, words: list[str], now: datetime, return {"period": said} whole_end = last is None or last >= now or last.strftime("%H:%M:%S") == "23:59:59" if first.time() == datetime.min.time() and whole_end: # whole days, as words the service can swap for another period - return {"period": f"{first:%Y-%m-%d} to {last:%Y-%m-%d}" if last else f"{first:%Y-%m-%d} to now"} + return {"period": f"{first:%Y-%m-%d} to now" if open_ended else f"{first:%Y-%m-%d} to {last:%Y-%m-%d}"} out = {"start": first.strftime("%Y-%m-%d") if first.time() == datetime.min.time() else first.strftime("%Y-%m-%d %H:%M")} if last is not None and last < now: out["end"] = last.strftime("%Y-%m-%d") if last.strftime("%H:%M:%S") == "23:59:59" else \ diff --git a/tests/test_periods.py b/tests/test_periods.py index 92f1ee7d..6673305c 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -660,7 +660,9 @@ def row(tool, **arguments): assert row("summary", period="today") == reload and row("summary", period="yesterday") is None assert row("days", group_by="year", period="on record") == reload # through yesterday assert row("days", group_by="year", period="2024-01-01 to 2025-12-31") is None - assert row("days", group_by="year", period="2025-01-01 to 2026-12-31") == reload # (cut to yesterday) + assert row("days", group_by="year", period="2025-01-01 to now") == reload + for fixed in ("2026-09-01 to 2026-10-01", "September", "last month", "2025"): # fixed dates, even ending yesterday: never more + assert row("days", group_by="year", period=fixed) is None, fixed assert periods.periods_keyboard({"tool": "summary", "arguments": {"start": "2026-10-02 09:00"}, "periods": []}) is None # no clock: none listed = {"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]} assert labels(periods.periods_keyboard(listed, "7d", NOW, TZ)) == [ROW] # periods listed: those diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 4e088f46..32b2bc1a 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -378,6 +378,9 @@ async def test_a_chart_drawn_with_dates_names_them_as_its_period_and_per_year_it assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to {ago(2).isoformat()}" and drawn["periods"] == [] assert chart_of(await ask(world, **drawn["arguments"])) == chart_of(out) assert "complete" not in out # (chart_answers_it wasn't set) + for end in ({}, {"end": str(ago(-3))}): # a start with no end, or an end today or later: "to now", so a replay moves on with the clock + drawn = chart_of(await ask(world, start=str(ago(200)), where=[{"field": "rain", "op": ">=", "value": 1}], group_by="year", **end))["drawn_by"] + assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to now" async def test_a_chart_is_not_the_whole_answer_when_a_note_needs_the_models_words(world): diff --git a/tests/test_service_legacy.py b/tests/test_service_legacy.py index 5ba9b4fa..8c1f1163 100644 --- a/tests/test_service_legacy.py +++ b/tests/test_service_legacy.py @@ -43,7 +43,7 @@ def test_a_chart_asked_for_plainly_is_summarys_call_with_its_period_in_the_servi ("plot uv and solar on two axes 7d", {"readings": ["solar_and_uvi.uvi", "solar_and_uvi.solar"], "period": "last 7 days", "chart": True, "layout": "two_axes"}), ("lowest temperature on record", {"readings": ["outdoor.temperature", "indoor.temperature"], # (the bot's "on record") - "period": "2022-11-12 to 2026-11-10", "chart": True}), + "period": "2022-11-12 to now", "chart": True}), ("Particulates chart 1d", {"readings": ["air.pm2_5", "air.pm10", "air.pm1"], "period": "last 24 hours", "chart": True})): r, turn = read(text) assert legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == ("summary", want), text @@ -59,7 +59,7 @@ def test_the_lookups_are_the_tools_that_word_them(): ("highest temperature yesterday", ("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "yesterday", "chart": False})), ("rain by month this year", ("days", {"count_only": True, "group_by": "month", "stat": "sum", "of": "rain", - "period": "2026-01-01 to 2026-11-10"}))): + "period": "2026-01-01 to now"}))): r, turn = read(text) assert legacy.lookup(r) is None and legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == want, text assert legacy.report(("Ecowitt", "AirGradient", "Pollen", "Forecast")) == [("current", {}), ("pollen", {}), @@ -69,10 +69,11 @@ def test_the_lookups_are_the_tools_that_word_them(): def test_a_period_is_words_the_service_reads_as_the_same_span_else_whole_days_else_times(): assert legacy.period("2026-11-09 14:05:00", "2026-11-10 14:05:00", ["last 24 hours"], NOW, TZ) == {"period": "last 24 hours"} assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this week"], NOW, TZ) == {"period": "this week"} - assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this month"], NOW, TZ) == {"period": "2026-11-04 to 2026-11-10"} + assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this month"], NOW, TZ) == {"period": "2026-11-04 to now"} assert legacy.period("2026-11-01 00:00:00", None, [], NOW, TZ) == {"period": "2026-11-01 to now"} assert legacy.period("2026-11-09 06:00:00", "2026-11-09 11:59:59", [], NOW, TZ) == {"start": "2026-11-09 06:00", "end": "2026-11-09 12:00"} - assert legacy.period("2026-01-01", "2026-11-10", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to 2026-11-10"} + assert legacy.period("2026-01-01", "2026-11-10", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to now"} + assert legacy.period("2026-01-01", "2026-10-31", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to 2026-10-31"} # past: fixed def test_the_periods_a_chart_the_model_drew_is_worth_drawing_over_are_its_tools(): From ef0a2c210ddbb60a3fa29faaf6eb34729dd71ff0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 10:03:44 +0000 Subject: [PATCH 043/125] The shaded 1D under a chart that runs to now draws it again Pressing a chart's own period button did nothing ("already shows this period"). For 1D, the one period where a few minutes' readings show, it now replays the chart's call past the picture cache, with the latest readings. A longer period's own button still does nothing, and so does a 1D over a stretch that is over. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 50 ++++++++++++++++++++++--------------------- lib/bot.py | 11 ++++++---- lib/periods.py | 1 + tests/test_periods.py | 29 +++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 28 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 105ad61b..a3ec9e98 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -460,30 +460,32 @@ Each step ships on its own, with the tests and evals green and the bot working t `lib/periods_text.py` reads the periods table, tested by hand against it at fixed times (a Monday, a Tuesday, the 1st of a month, 1 January, 29 February, 00:30, both clock-change days), with whole-day tools cut to yesterday and errors for phrases outside the table and for the future. No tool interface changes. -2. **The ten tools, beside the twelve** (done). The tools of 3.3, built once with their arguments, periods, worded results (`day_look`, - ready lines, captions), charts, descriptions and errors, in `lib/service/` (what they share: `common.py`, `names.py`, `daylook.py`, - `context.py`; the outlook's rules in `outlook.py`), registered (`__init__.py`: `build`, `Service`), built in `ecobot.py` and handed - to the bot; offered to no model yet. Contract tests per tool; every chart validates against `schemas/chart.json`, `drawn_by` - included, and replays to the same chart and over each of its `periods` without a refusal. The evals have the service's - expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks offline that the tools - accept each expected call; `--live --service` asks a model with the tool list alone (not yet run: it needs the OpenRouter key). - The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and alert charts, through - `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in step 3), - quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but for the deliberate changes - below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' readings named (the air sensor - isn't read), laid out bot-side (`lib/gauge_sheet.py`); `Ecowitt.dashboard()` and `sheet()` are gone. It asks for its charts as - drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more points than 500. - Period buttons replay the chart's `drawn_by` with a new `period` (the buttons, their keyboard and the picture cache stay in the - bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label; when it lists - none, a 🔄 that replays the call as it is if its period runs to now (through yesterday for a whole-day tool), else nothing; a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. - What the bot draws ahead replays calls at background priority: the other periods after a chart is sent, the keyboard's charts - every 5 minutes, recent alerts' charts. The picture cache and the pre-upload are keyed by the call, so two wordings or two chats - share a picture. Deliberate changes: a count per month offers 3M, 1Y and All (never 1D), per year none; whole-day `1y` is the 365 - days to yesterday (364 and today before); alert charts name their source. Until step 3, a chart the model draws through the - twelve gets a `drawn_by` from `legacy.py` when its call translates and lists periods; otherwise (`plot_chart`, the links and the - scan, a period given as times) its buttons ask its question again, as before. Left for later: `current` and `outlook` read the - sources' kept live readings through private members (`Ecowitt._live`, `AirGradient._current`); `fetch: false` doesn't stop the - air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. +2. **The ten tools, beside the twelve** (done). The tools of 3.3, built once with their arguments, periods, worded results + (`day_look`, ready lines, captions), charts, descriptions and errors, in `lib/service/` (what they share: `common.py`, `names.py`, + `daylook.py`, `context.py`; the outlook's rules in `outlook.py`), registered (`__init__.py`: `build`, `Service`), built in + `ecobot.py` and handed to the bot; offered to no model yet. Contract tests per tool; every chart validates against + `schemas/chart.json`, `drawn_by` included, and replays to the same chart and over each of its `periods` without a refusal. The + evals have the service's expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks + offline that the tools accept each expected call; `--live --service` asks a model with the tool list alone (not yet run: it needs + the OpenRouter key). The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and + alert charts, through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, + deleted whole in step 3), quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but + for the deliberate changes below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' + readings named (the air sensor isn't read), laid out bot-side (`lib/gauge_sheet.py`); `Ecowitt.dashboard()` and `sheet()` are gone. + It asks for its charts as drawn (request `_meta` `chart_points: "drawn"`), since a chart of each day's average over years has more + points than 500. Period buttons replay the chart's `drawn_by` with a new `period` (the buttons, their keyboard and the picture + cache stay in the bot; the service knows nothing of buttons), one button per `drawn_by.periods` entry with the service's label; + when it lists none, a 🔄 that replays the call as it is if its period runs to now (through yesterday for a whole-day tool), else + nothing; the chart's own shaded 1D, when it runs to now, draws it again with the latest readings (a longer period's does nothing); + a replay the service refuses shows its refusal on the button, and one that fails after "Drawing ..." says so in the chat. What the + bot draws ahead replays calls at background priority: the other periods after a chart is sent, the keyboard's charts every 5 + minutes, recent alerts' charts. The picture cache and the pre-upload are keyed by the call, so two wordings or two chats share a + picture. Deliberate changes: a count per month offers 3M, 1Y and All (never 1D), per year a 🔄 (its period runs to now); whole-day + `1y` is the 365 days to yesterday (364 and today before); alert charts name their source. Until step 3, a chart the model draws + through the twelve gets a `drawn_by` from `legacy.py` when its call translates and lists periods; otherwise (`plot_chart`, the + links and the scan, a period given as times) its buttons ask its question again, as before. Left for later: `current` and `outlook` + read the sources' kept live readings through private members (`Ecowitt._live`, `AirGradient._current`); `fetch: false` doesn't stop + the air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. diff --git a/lib/bot.py b/lib/bot.py index 259f8d29..3583426a 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -993,15 +993,18 @@ async def drawing(label: str): await answer_query(query, "That chart is out of date, please ask again") return now = now_local(self.cfg.tz) + refresh = False # the chart's own shaded 1D pressed: drawn again with the latest readings if not reload and periods.own_period(drawn_by, now, self.cfg.tz) == period: # the chart already shows this period - await answer_query(query) - return + if period != periods.REFRESHED or not periods.ends_now(drawn_by, now, self.cfg.tz): # (longer: a few minutes more barely show) + await answer_query(query) + return + refresh = True tool = drawn_by["tool"] - args = dict(drawn_by["arguments"]) if reload else periods.with_period(drawn_by, period) + args = dict(drawn_by["arguments"]) if reload or refresh else periods.with_period(drawn_by, period) label = "again" if reload else listed[period] key = periods.call_key(tool, args) log.debug("Period button %s: %s", label, key, extra=QUOTES) - if not reload and (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: nothing is asked again + if not (reload or refresh) and (held := self.images.held(key)) is not None and held.drawn_by: # drawn lately: not asked again await drawing(label) began = time.monotonic() row = periods.periods_keyboard(held.drawn_by, period, now, self.cfg.tz) diff --git a/lib/periods.py b/lib/periods.py index 40743725..851271de 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -26,6 +26,7 @@ PREFIX = "pd:" REMEMBERED = 300 # charts whose call is kept, newest first to stay WHOLE_DAY_TOOLS = ("days", "relate", "scan") # the tools that read a period as whole days, up to yesterday +REFRESHED = "1d" # the period whose own shaded button draws the chart again with the latest readings (longer ones barely change) RELOAD = "reload" # the 🔄 under a chart with no periods to offer whose period runs to now: its call replayed as it is ("pd:reload") diff --git a/tests/test_periods.py b/tests/test_periods.py index 6673305c..773dd4b8 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -689,3 +689,32 @@ async def answer(text=None, **k): bot.charted.remember(1, 50, {"drawn_by": listed, "words": False}) await bot.on_period_button(press(msg, "pd:reload", answer), CONTEXT) # a chart with periods has no 🔄 assert answers[-1] == "That chart is out of date, please ask again" and len(calls(bot)) == 1 + + +async def test_pressing_a_1d_charts_own_button_draws_it_again_and_a_longer_ones_does_nothing(alert_state, monkeypatch): + """The shaded 1D under a chart that runs to now draws it again, past the picture cache, with the latest readings; the shaded + button of a longer period changes nothing (a few minutes more barely show on a week).""" + bot, edits = make_bot(alert_state, monkeypatch), [] + msg = chat_message([], edits) + day = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 24 hours", "chart": True}, + "periods": [dict(p) for p in OVER_TIME]} + bot.charted.remember(1, 50, {"drawn_by": day, "words": False}) + key = periods.call_key("summary", day["arguments"]) + bot.images.put(key, b"old picture", "Temperature", drawn_by=day) + answers = [] + + async def answer(text=None, **k): + answers.append(text) + await bot.on_period_button(press(msg, "pd:1d", answer), CONTEXT) + assert calls(bot) == [day["arguments"]] and answers == ["Drawing 1D..."] + caption, markup = edits[0] + assert labels(markup) == [ROW] and shaded(markup) == ["1D"] and bot.images.held(key).png == b"last 24 hours" + week = {**day, "arguments": {**day["arguments"], "period": "7d"}} + bot.charted.remember(1, 50, {"drawn_by": week, "words": False}) + await bot.on_period_button(press(msg, "pd:7d", answer), CONTEXT) + assert len(calls(bot)) == 1 and answers[-1] is None and len(edits) == 1 + yesterday = {**day, "arguments": {**day["arguments"], "period": "yesterday"}} # (a 1D over a day that is over: nothing new) + bot.charted.remember(1, 50, {"drawn_by": yesterday, "words": False}) + if periods.own_period(yesterday, botmod.now_local(TZ), TZ) == "1d": + await bot.on_period_button(press(msg, "pd:1d", answer), CONTEXT) + assert len(calls(bot)) == 1 From 459e458123f2c4992617bc3741c9e224a7118e96 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 10:45:51 +0000 Subject: [PATCH 044/125] Step 3 gate: period wins over start/end, days description, server instructions The first live service run (86/94 on deepseek-v4.1-flash) failed where: - the model sent `period` with `start` and `end` (once start 'count_only', end 'cancel'), and every tool refused "not both". common.read_period now lets `period` win: start and end are ignored, and the result's `period.note` says so. The replays (days drawn_by, relate/scan whole_day_words, summary _period_words) follow the period too; the eval checker scores the period. - days got no sort_by for "most rain" and no group_by for "per year": its description says what sort_by ranks by and when to use group_by, with an example each (still under 1500 chars). - metrics-bare, weather-report-for-a-day, only-that-its-cold and now-what expected what only the bot's prompt and fast path gave; relaxed for a plain client with only the tool list, each with a note saying why (a period's history is still wrong for all of them). The server's instructions (docs 3.2): lib/service/instructions.py, instructions(ctx) from the sources and the catalogue (devices and their nicknames, Indoor and Outdoor, units, the zone), INSTRUCTIONS by default. `scripts/eval_prompts.py --live --service --instructions` adds them after the neutral system line. A failing live run now prints the calls made. Live: deepseek 92/94 alone, 92/94 with the instructions; gpt-6-luna 89/94 alone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 8 ++-- lib/periods_text.py | 4 +- lib/service/common.py | 38 ++++++++++----- lib/service/days.py | 35 +++++++------- lib/service/instructions.py | 76 ++++++++++++++++++++++++++++++ lib/service/relate.py | 4 +- lib/service/summary.py | 2 +- scripts/eval_prompts.py | 8 +++- tests/evalkit.py | 69 +++++++++++++++++---------- tests/evals/service_cases.json | 28 ++++------- tests/test_service_base.py | 18 +++++-- tests/test_service_days.py | 12 +++++ tests/test_service_evals.py | 43 +++++++++++++++++ tests/test_service_instructions.py | 39 +++++++++++++++ tests/test_service_readings.py | 3 +- tests/test_service_relate.py | 8 ++++ tests/test_service_summary.py | 2 + 17 files changed, 314 insertions(+), 83 deletions(-) create mode 100644 lib/service/instructions.py create mode 100644 tests/test_service_instructions.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a3ec9e98..a50a39d3 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -149,7 +149,8 @@ and no falling back to a default: anything else is an error that lists the forms | `since 6am`, `since Monday` | from the latest such time (or that day's 00:00) to now | | `on record`, `all time`, `ever` | from the first reading held, for the sensors asked about, to now | -- **`period` or `start`**, never both (both is an error). `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD +- **`period` or `start`**: when both are sent, `period` wins, `start` and `end` are ignored, and the result's `period.note` says so + (models fill in every argument they see, sometimes with junk). `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD HH:MM`; one with an offset or `Z` is moved into local time. An `end` that is a date includes that whole day; one with a time stops at it. No `end` means to now; `end` without `start` is an error. - **Whole-day tools** (`days`, `relate`, `scan`) take whole days ending yesterday, because today is still settling: a rolling phrase is @@ -466,8 +467,9 @@ Each step ships on its own, with the tests and evals green and the bot working t `ecobot.py` and handed to the bot; offered to no model yet. Contract tests per tool; every chart validates against `schemas/chart.json`, `drawn_by` included, and replays to the same chart and over each of its `periods` without a refusal. The evals have the service's expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks - offline that the tools accept each expected call; `--live --service` asks a model with the tool list alone (not yet run: it needs - the OpenRouter key). The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and + offline that the tools accept each expected call; `--live --service` asks a model with the tool list alone, and `--instructions` + adds the server's instructions (`lib/service/instructions.py`) after the neutral line. First full runs (10 Nov 2026, one run each): + deepseek-v4.1-flash 92/94 alone and 92/94 with the instructions, gpt-6-luna 89/94 alone. The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and alert charts, through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in step 3), quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but for the deliberate changes below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' diff --git a/lib/periods_text.py b/lib/periods_text.py index 717fd485..f556e09d 100644 --- a/lib/periods_text.py +++ b/lib/periods_text.py @@ -110,12 +110,14 @@ def _either(words) -> str: @dataclass(frozen=True) class Period: """A period as read: the words asked (or "start/end"), its start and end on the station's clock (the end not included), how it - was read, ready to pass on, and, when a whole-day tool cut it to yesterday, a note saying so.""" + was read, ready to pass on, and, when a whole-day tool cut it to yesterday, a note saying so. `note`: anything else the reader of the + result should know about how the call's period was taken (lib/service/common.read_period: `start` and `end` ignored beside `period`).""" asked: str start: datetime end: datetime text: str cut: str | None = None + note: str | None = None @property def first_day(self) -> date: diff --git a/lib/service/common.py b/lib/service/common.py index 3106a6d8..b8b890d6 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -15,8 +15,8 @@ "chart_note": CHART_NOTE, "charts": [...]} - `period`: how the words were read (lib/periods_text.Period): `asked` the words (or "start/end"), `text` how they were read, ready - to pass on, `start` and `end` ISO local times with their offset (the end not included), and `cut` only when a whole-day tool cut - today off. Left out by a tool that takes no period. + to pass on, `start` and `end` ISO local times with their offset (the end not included), `cut` only when a whole-day tool cut + today off, and `note` only when `start` and `end` were sent beside `period` and ignored (read_period). Left out by a tool that takes no period. - `as_of`: the time of the figures, `text` written as the tools write a time (timeutil.when), `time` ISO. - `fresh`: one fixed line for the model: the figures are as of `as_of`, and a follow-up or a challenge needs the tool called again. - `chart_note` and `charts` (`with_charts`): the charts as data (specs.to_json, bucketed to the request's `chart_points`), and the @@ -29,7 +29,7 @@ import inspect from collections.abc import Awaitable, Callable -from dataclasses import dataclass +from dataclasses import dataclass, replace from datetime import date, datetime, tzinfo from .. import specs @@ -162,11 +162,11 @@ def period_properties(default: str, whole_days: bool = False) -> dict: if whole_days: forms, days = WHOLE_DAY_FORMS, (" Whole days only, up to yesterday, as today isn't over: a rolling period is that many whole days " "to yesterday (\"last 7 days\" is the 7 days before today).") - start = "Instead of `period`, never with it: the first day, 'YYYY-MM-DD'." + start = "Instead of `period` (ignored when `period` is sent): the first day, 'YYYY-MM-DD'." end = "With `start`: the last day, 'YYYY-MM-DD', up to yesterday. Default: yesterday." else: forms, days = PERIOD_FORMS, "" - start = ("Instead of `period`, never with it: when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " + start = ("Instead of `period` (ignored when `period` is sent): when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " "'YYYY-MM-DD HH:MM'.") end = "With `start`: when it ends, local time, 'YYYY-MM-DD' (to the end of that day) or 'YYYY-MM-DD HH:MM'. Default: now." return { @@ -178,16 +178,30 @@ def period_properties(default: str, whole_days: bool = False) -> dict: } +IGNORED_DATES = "`start` and `end` were ignored: `period` was sent too, and the period is read from it." + + +def sends_period(args: dict) -> bool: + """Whether the call sends `period` (words, not empty): it then wins over any `start` and `end` sent beside it (read_period).""" + return args.get("period") is not None and str(args["period"]).strip() != "" + + def read_period(args: dict, *, tz: tzinfo, now: datetime, default: str, whole_days: bool = False, first_held: date | datetime | None = None) -> Period: """The period a call asks for, from its `period`, or `start` and `end`, else `default` (words), read by lib/periods_text.py at `now` (aware, or naive on the station's clock) in the station's zone. `first_held`: the first reading held for the readings asked about - ("on record"). Raises Refusal (refuse_period) when it can't be read.""" + ("on record"). When `period` is sent, it wins: any `start` and `end` beside it are ignored (a model may fill in every argument it + sees), and the Period's `note` says so (IGNORED_DATES; the result's `period.note`). Raises Refusal (refuse_period) when the period + can't be read.""" + period, start, end = args.get("period"), args.get("start"), args.get("end") + ignored = sends_period(args) and any(x is not None and str(x).strip() for x in (start, end)) + if ignored: + start = end = None try: - return read_words(args.get("period"), args.get("start"), args.get("end"), now=now, tz=tz, default=default, whole_days=whole_days, - first_held=first_held) + read = read_words(period, start, end, now=now, tz=tz, default=default, whole_days=whole_days, first_held=first_held) except PeriodError as e: raise Refusal.of_period(e) from None + return replace(read, note=IGNORED_DATES) if ignored else read # ---------- an answer ---------- @@ -209,10 +223,12 @@ def iso(t: datetime | int | float, tz: tzinfo | None = None) -> str: def period_field(period: Period) -> dict: - """{"asked", "text", "start", "end", ["cut"]}: how the period was read.""" + """{"asked", "text", "start", "end", ["cut"], ["note"]}: how the period was read.""" out = {"asked": period.asked, "text": period.text, "start": iso(period.start), "end": iso(period.end)} if period.cut: out["cut"] = period.cut + if period.note: + out["note"] = period.note return out @@ -258,6 +274,6 @@ def complete(reply: str) -> dict: return {"reply": reply, "complete": True} -__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", +__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "IGNORED_DATES", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_field", "complete", "iso", "period_field", "period_properties", - "read_period", "refuse", "refuse_period", "request_meta", "turn_meta", "with_charts"] + "read_period", "refuse", "sends_period", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/service/days.py b/lib/service/days.py index d6fb63ee..bdcb03bf 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -39,7 +39,7 @@ from ..storage.read import Reader from ..timeutil import day_text from ..tools import Turn -from .common import Refusal, ServiceTool, answer, complete, period_properties, read_period, with_charts +from .common import Refusal, ServiceTool, answer, complete, period_properties, read_period, sends_period, with_charts from .context import Context from .daylook import FIGURES as LOOK_FIGURES, day_look from .names import AIR_DEVICE, STATION @@ -90,17 +90,18 @@ # ---------- the description and the input schema ---------- DESCRIPTION = ( "Days found, ranked, counted or totalled by their figures, from the weather station's and the air sensor's (AirGradient's) days, " - "midnight to midnight. The wettest day: {sort_by: \"rain\"}. The hottest day it also rained: {where: [{field: \"rain\", op: \">=\", " - "value: 1}], sort_by: \"temp_max\"}. How many days over 35°C this year: {where: [{field: \"temp_max\", op: \">\", value: 35}], " - "period: \"this year\", count_only: true}. Rain per month: {stat: \"sum\", of: \"rain\", group_by: \"month\", period: \"past " - "year\"}. Days PM2.5 passed 25: {where: [{field: \"pm2_5_max\", op: \">\", value: 25}]}. The windiest weekend day: {sort_by: " - "\"wind_gust\", only: \"weekend\"}. One day's figures: {period: \"5 Sep\"}. Part of each day, with hours: nights below 5°C " - "{hours: \"night\", where: [{field: \"temp_min\", op: \"<\", value: 5}]}; the average 3pm temperature in October {hours: " - "\"15:00\", stat: \"avg\", of: \"temp_avg\", period: \"October\"}. No period: every day on record (with hours, the last 30 " - "days). Not for: a period's highest or lowest reading with when it happened, or a chart over time (summary); values at set " - "times (readings); rain against a reading (relate). Result: answer, a line ready to pass on; matching_days of days_checked; " - "days, the top ones, each with its day_look (the day's weather word and emoji: put it before the day); by_month or by_year, a " - "figure each, drawn as bars (charts); note_*: mention briefly. A rainy day is rain >= 1; above 0 is only a trace.") + "midnight to midnight. sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: \"rain\"}; the hottest " + "day it rained {where: [{field: \"rain\", op: \">=\", value: 1}], sort_by: \"temp_max\"}. Days over 35°C this year: {where: " + "[{field: \"temp_max\", op: \">\", value: 35}], period: \"this year\", count_only: true}. Per month or year (\"per year\", \"each " + "year\", \"by month\"), group_by: rain per month {stat: \"sum\", of: \"rain\", group_by: \"month\"}; average temperature per " + "year {stat: \"avg\", of: \"temp_avg\", group_by: \"year\"}. PM2.5 over 25: {where: [{field: \"pm2_5_max\", op: \">\", value: " + "25}]}. The windiest weekend day: {sort_by: \"wind_gust\", only: \"weekend\"}. One day: {period: \"5 Sep\"}. Part of each day, " + "hours: nights below 5°C {hours: \"night\", where: [{field: \"temp_min\", op: \"<\", value: 5}]}; 3pm in October {hours: " + "\"15:00\", stat: \"avg\", of: \"temp_avg\", period: \"October\"}. No period: every day on record (with hours, 30 days). Not " + "for: a period's highest or lowest reading with when, or a chart over time (summary); values at set times (readings); rain " + "against a reading (relate). Result: answer, a line to pass on; matching_days of days_checked; days, the top ones, each with " + "day_look (weather word and emoji: put it before the day); by_month or by_year, drawn as bars (charts); note_*: mention " + "briefly. A rainy day is rain >= 1.") STATION_WHERE = ("Weather station: temp_max, temp_min, temp_avg (outdoor °C), rain (mm that fell), wind_gust (km/h, the highest); a " "day's highest (_max), lowest (_min) and mean (_avg) of humidity, pressure, dew_point, feels_like, vpd, indoor_temp, " @@ -132,14 +133,16 @@ def parameters(fields: list[str]) -> dict: "items": {"type": "object", "properties": {"field": one, "op": {"type": "string", "enum": list(OPS)}, "value": {"type": "number"}}, "required": ["field", "op", "value"]}}, - "sort_by": {**one, "description": "Rank the days by this field. Default: the first condition's field, else `of`, else " + "sort_by": {**one, "description": "The field the days are ranked by (\"most rain\", \"wettest\": rain; \"hottest\": temp_max; " + "\"windiest\": wind_gust). Default: the first condition's field, else `of`, else " f"{default_sort}" + (" (pm2_5_max when only air fields are named)." if len(devices) > 1 else ".")}, "order": {"type": "string", "enum": list(ORDERS), "description": "desc: highest first (default); asc: lowest first."}, "count_only": {"type": "boolean", "description": "true for \"how many days\": the counts alone, no days listed."}, "group_by": {"type": "string", "enum": ["month", "year"], - "description": "A figure per month or year (those with none included), drawn as a bar chart: \"rain per " - "month\", \"days over 35°C per year\"."}, + "description": "A figure per month or year (those with none included), drawn as a bar chart, whenever the " + "question asks per month or per year (\"rain per month\", \"by month\", \"days over 35°C " + "per year\", \"each year\", \"average temperature per year\")."}, "stat": {"type": "string", "enum": list(STATS), "description": "What the period, or each month or year, gives: count (default: the matching days), or the max, min, " "avg or sum of `of` over the matching days (\"rain per month\": sum of rain; \"the hottest day each " @@ -521,7 +524,7 @@ def drawn_by(self, call: Call, args: dict, period, first: date, last: date, firs worth drawing over: per month, 3 months, a year and the whole record (with hours, only while that is within its 400 days); per year, none.""" words = period.asked - if args.get("start"): # dates as words; one that runs to today or later as "to now", so a replay moves on with the clock + if args.get("start") and not sends_period(args): # dates as words; one that runs to today or later as "to now", so a replay moves on with the clock open_ended = not args.get("end") or str(args["end"])[:10] >= today.isoformat() words = f"{first.isoformat()} to {'now' if open_ended else last.isoformat()}" arguments = {"where": call.where, "sort_by": self.sort_of(call), "order": call.order, "count_only": call.count_only, diff --git a/lib/service/instructions.py b/lib/service/instructions.py new file mode 100644 index 00000000..b576615e --- /dev/null +++ b/lib/service/instructions.py @@ -0,0 +1,76 @@ +"""The server's instructions (docs/mcp-service.md 3.2): a short summary of what the tools read, for a client that passes it to its model +(over MCP a client gets it by asking: `server/discover`). Nothing depends on it: every rule a choice of tool or the reading of a result +depends on is in the tool's description or in the result, and the evals are run with and without it (`--live --service +--instructions`, docs 7). + +It says: the devices there are (the Context's sources) and the nicknames people use for them, which readings are Indoor and Outdoor, +the units each reading comes in (from the catalogue: only the readings held), the station's time zone, and that a period is passed on +in the person's own words. `instructions(ctx)` builds it; INSTRUCTIONS is it for every device and every reading the service knows. +""" + +from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue + +PLAIN = ("Outdoor ", "Indoor ", "AirGradient ", "Piezo ", "Absolute ") # (a label's side or device, left out where units are listed) +KEEP_CASE = ("PM", "CO", "UV", "VOC", "NOx") # (labels that keep their capitals) + + +def _plain(label: str) -> str: + for prefix in PLAIN: + label = label.removeprefix(prefix) + return label if label.startswith(KEEP_CASE) else label[:1].lower() + label[1:] + + +def units(catalogue: Catalogue) -> str: + """"°C: temperature, dew point …; %: humidity; …; no unit: UV index …": each unit with what comes in it, in the catalogue's + order, sides and devices aside.""" + by_unit: dict[str, list[str]] = {} + for r in catalogue: + what = by_unit.setdefault(r.unit, []) + if (plain := _plain(r.label)) not in what: + what.append(plain) + listed = [f"{unit}: {', '.join(what)}" for unit, what in by_unit.items() if unit] + if "" in by_unit: + listed.append(f"no unit (an index): {', '.join(by_unit[''])}") + return "; ".join(listed) + + +def instructions(ctx=None) -> str: + """The instructions for the service over this Context (lib/service/context.py): its sources, the readings its catalogue holds and + its zone. With no ctx: every source, every reading the service knows, no zone named.""" + catalogue = ctx.readings() if ctx is not None else CATALOGUE + station = ctx.eco is not None if ctx is not None else True + air = ctx.air is not None if ctx is not None else True + forecast = ctx.forecast is not None if ctx is not None else True + pollen = ctx.pollen is not None if ctx is not None else True + station = station and any(r.device == STATION for r in catalogue) + air = air and any(r.device == AIR_DEVICE for r in catalogue) + + devices = [] + if station: + devices.append("the weather station (Ecowitt; people call it \"ecowitt\", \"the weather station\" or \"the station\"), " + "outdoors, with an indoor sensor in the house") + if air: + devices.append("the outdoor air-quality sensor (AirGradient; \"ag\", \"airgradient\", \"air gradient\", \"the air sensor\")") + extra = [*(["the weather forecast for the station's location (Open-Meteo)"] if forecast else []), + *(["Melbourne's grass pollen and thunderstorm asthma forecast (October to December)"] if pollen else [])] + lines = [f"The devices: {'; '.join(devices) or 'none'}." + (f" Also: {'; '.join(extra)}." if extra else "")] + if station: + sides = ("Indoor and Outdoor: a reading named bare is the weather station's, and temperature and humidity mean both its outdoor " + "and its indoor sensor (outdoor.temperature, indoor.temperature); dew point, feels like and the rest are outdoor's.") + if air: + sides += (" The air sensor is outdoors: its own temperature and humidity are only ever air.temperature and air.humidity, " + "and there is no indoor air quality.") + lines.append(sides) + held = Catalogue(r for r in catalogue if (r.device == STATION and station) or (r.device == AIR_DEVICE and air)) + if held.names: + lines.append(f"Units: {units(held)}. Rain is the mm that fell.") + zone = getattr(ctx.zone, "key", None) if ctx is not None and (ctx.tz or ctx.eco or ctx.air) else None + when = f"The station's clock is {zone} time; " if zone else "Times are the station's local time; " + lines.append(when + "pass a period on in the person's own words (`period`: \"this week\", \"yesterday afternoon\"): the tools " + "read it and say how. Each tool's description says what it answers.") + return "\n".join(lines) + + +INSTRUCTIONS = instructions() # every device and every reading the service knows (the evals; a server that hasn't read its file) + +__all__ = ["INSTRUCTIONS", "instructions", "units"] diff --git a/lib/service/relate.py b/lib/service/relate.py index a718adc0..ab003650 100644 --- a/lib/service/relate.py +++ b/lib/service/relate.py @@ -23,7 +23,7 @@ from ..specs import ECOWITT_SOURCE, Chart from ..timeutil import local_date, local_epoch from ..tools import Turn -from .common import Refusal, ServiceTool, answer, period_properties, read_period, with_charts +from .common import Refusal, ServiceTool, answer, period_properties, read_period, sends_period, with_charts from .context import Context from .names import Catalogue, Reading from .readings import first_day @@ -78,7 +78,7 @@ def drawn_charts(charts: list[Chart], ctx: Context, meta: dict, tool: str, argum def whole_day_words(args: dict, period: Period) -> str: """The period of a whole-day call as words a replay reads the same: the words asked (or the default), or, for one made with `start` and `end`, " to ".""" - if str(args.get("start") or "").strip(): + if str(args.get("start") or "").strip() and not sends_period(args): # (`period` wins: common.read_period) return f"{period.first_day.isoformat()} to {period.last_day.isoformat()}" return period.asked diff --git a/lib/service/summary.py b/lib/service/summary.py index 989a486f..997fca08 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -156,7 +156,7 @@ def _period_words(args: dict) -> dict: to 2026-11-05", "2026-11-01 to now"), so another period can be swapped in; a start or end with a time as it came.""" period, start, end = (str(args[k]).strip() if args.get(k) is not None and str(args[k]).strip() else None for k in ("period", "start", "end")) - if start is None: + if start is None or period: # (`period` wins over start and end sent beside it: common.read_period) return {"period": period} if DATE.fullmatch(start) and (end is None or DATE.fullmatch(end)): return {"period": f"{start} to {end or 'now'}"} diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 484bf29d..ff119962 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -15,6 +15,8 @@ python scripts/eval_prompts.py --service # every case has a service expectation, each one the tools take python scripts/eval_prompts.py --live --service # and the model, with the ten tools alone + python scripts/eval_prompts.py --live --service --instructions # ... and the server's instructions (lib/service/instructions.py) + # after the neutral line, as a client that passes them on would """ import asyncio @@ -33,7 +35,10 @@ async def main() -> int: ap.add_argument("--repeat", type=int, default=1, help="ask the model this many times per case") ap.add_argument("--effort", choices=["none", "low", "medium"], help="force this reasoning effort for every case") ap.add_argument("--service", action="store_true", help="the service's ten tools alone, scored against tests/evals/service_cases.json") + ap.add_argument("--instructions", action="store_true", help="with --service: add the server's instructions to the system line") args = ap.parse_args() + if args.instructions and not args.service: + sys.exit("--instructions goes with --service") cases = evalkit.load_cases() if args.ids: wanted = set(args.ids.split(",")) @@ -46,7 +51,8 @@ async def main() -> int: client = AsyncOpenAI(api_key=os.environ["OPENROUTER_API_KEY"], base_url=os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")) model = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") if args.service: - failed = await evalkit.run_service(cases, evalkit.load_service_cases(), client, model, repeat=args.repeat, effort=args.effort) + failed = await evalkit.run_service(cases, evalkit.load_service_cases(), client, model, repeat=args.repeat, effort=args.effort, + instructions=evalkit.service_instructions() if args.instructions else None) return 1 if failed else 0 failed = 0 for case in cases: diff --git a/tests/evalkit.py b/tests/evalkit.py index 715ea7ff..45dc5b15 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -5,7 +5,8 @@ - what the model does with them (which tool, which arguments): `python scripts/eval_prompts.py --live`, against the real model with recording stand-in tools (nothing is fetched). tests/evals/service_cases.json holds, for the same case ids, what a model offered only the service's ten tools (lib/service) should -call: checked offline by tests/test_service_evals.py, and asked of the model by `python scripts/eval_prompts.py --live --service`. +call: checked offline by tests/test_service_evals.py, and asked of the model by `python scripts/eval_prompts.py --live --service` +(with `--instructions`, the server's instructions, lib/service/instructions.py, after the neutral system line). """ import json @@ -229,19 +230,29 @@ def service_tool_names() -> list[str]: return ["current", "summary", "readings", "days", "relate", "scan", "outlook", "forecast", "pollen", "about"] +def eval_context(): + """The Context the service's evals build the tools over: stand-ins for every source (nothing behind them: the tools are built, never + run), the catalogue of every reading the service knows, the station's zone and NOW.""" + from zoneinfo import ZoneInfo + + from lib.service.context import Context + tz = ZoneInfo(NOW_TZ) + return Context(eco=object(), air=object(), composer=object(), forecast=object(), pollen=object(), tz=tz, + clock=lambda: NOW.replace(tzinfo=tz).timestamp()) + + def service_tools(ctx=None) -> list: - """The ten ServiceTools, each module's tools(ctx). With no ctx: over stand-ins for every source (nothing behind them: the tools are - built, never run), the catalogue of every reading the service knows, the station's zone and NOW.""" - if ctx is None: - from zoneinfo import ZoneInfo - - from lib.service.context import Context - tz = ZoneInfo(NOW_TZ) - ctx = Context(eco=object(), air=object(), composer=object(), forecast=object(), pollen=object(), tz=tz, - clock=lambda: NOW.replace(tzinfo=tz).timestamp()) + """The ten ServiceTools, each module's tools(ctx), over eval_context() when no ctx is given.""" + ctx = ctx if ctx is not None else eval_context() return [t for module in service_modules() for t in module.tools(ctx)] +def service_instructions() -> str: + """The server's instructions (lib/service/instructions.py) over eval_context(), as a `--instructions` run adds them.""" + from lib.service.instructions import instructions + return instructions(eval_context()) + + def make_service_tools(calls: list) -> Tools: """The ten tools as a model is offered them (name, description, parameters from lib/service), with handlers that record the call.""" def recorder(name): @@ -252,9 +263,11 @@ async def handler(args, turn=None): return Tools([Tool(t.name, t.description, t.parameters, recorder(t.name)) for t in service_tools()]) -def service_system(now: datetime = NOW) -> str: - """The whole system prompt of a service run: the neutral line, and the date, time and zone now.""" - return f"{SERVICE_SYSTEM}\nNow: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M} ({NOW_TZ} time)." +def service_system(now: datetime = NOW, instructions: str | None = None) -> str: + """The whole system prompt of a service run: the neutral line, and the date, time and zone now; with `instructions` (the server's, + service_instructions()), those after it, as a client that passes them on to its model would (docs/mcp-service.md 3.2, 7).""" + system = f"{SERVICE_SYSTEM}\nNow: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M} ({NOW_TZ} time)." + return f"{system}\n\n{instructions}" if instructions else system def load_service_cases(path: Path = SERVICE_CASES) -> dict[str, dict]: @@ -324,6 +337,8 @@ def _means(sent, refs, tool: str | None = None) -> str | None: sent = sent if isinstance(sent, dict) else {"period": sent} if sent.get("period") is not None and str(sent["period"]).strip() == "": sent = {**sent, "period": None} + if sent.get("period") is not None: # the period wins over start and end sent beside it, as the tools read it (common.read_period) + sent = {"period": sent["period"]} # words are compared as words (whole days would make "last 28 days" September on the 29th); dates as the tool reads them whole = tool in WHOLE_DAY_TOOLS and sent.get("period") is None got = _period_span(sent.get("period"), sent.get("start"), sent.get("end"), whole) @@ -456,21 +471,27 @@ def service_problems(expect: dict | None) -> list[str]: return fails -async def run_live_service(case: Case, client, model: str, effort: str | None = None) -> tuple[list[tuple[str, dict]], str]: - """Ask the model with the ten tools alone and the neutral system line; returns the tool calls it made and its final reply. It may - answer with no tool at all (tool_choice auto): a plain client forces nothing.""" +async def run_live_service(case: Case, client, model: str, effort: str | None = None, + instructions: str | None = None) -> tuple[list[tuple[str, dict]], str]: + """Ask the model with the ten tools alone and the neutral system line (with `instructions` after it, when given); returns the tool + calls it made and its final reply. It may answer with no tool at all (tool_choice auto): a plain client forces nothing.""" calls: list[tuple[str, dict]] = [] messages = [*case.history, {"role": "user", "content": content(case)}] - reply = await Agent(client, model, make_service_tools(calls)).run(messages, service_system(), effort or SERVICE_EFFORT, - tool_choice="auto") + reply = await Agent(client, model, make_service_tools(calls)).run(messages, service_system(instructions=instructions), + effort or SERVICE_EFFORT, tool_choice="auto") return calls, reply +def calls_text(calls: list[tuple[str, dict]]) -> str: + """The calls a model made, one line: `days {"sort_by": "rain"}; pollen {}`.""" + return "; ".join(f"{n} {json.dumps(a, ensure_ascii=False)}" for n, a in calls) or "nothing" + + async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, - effort: str | None = None, out=print) -> int: + effort: str | None = None, instructions: str | None = None, out=print) -> int: """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times with - the ten tools alone and its calls scored against it (check_calls), as `--live` scores cases.json. Prints a line per case (`out`); - returns how many cases fail.""" + the ten tools alone (and the server's `instructions`, when given) and its calls scored against it (check_calls), as `--live` scores + cases.json. Prints a line per case (`out`), with the calls of a run that fails; returns how many cases fail.""" failed = 0 for case in cases: expect = expectations.get(case.id) @@ -479,14 +500,14 @@ async def run_service(cases: list[Case], expectations: dict[str, dict], client=N if client and not problems: passes = 0 for _ in range(repeat): - calls, _reply = await run_live_service(case, client, model, effort) + calls, _reply = await run_live_service(case, client, model, effort, instructions) why = check_calls(calls, expect) passes += not why - problems += [f" run: {w}" for w in why[:3]] if why else [] + problems += [*(f" run: {w}" for w in why[:3]), f" called: {calls_text(calls)}"] if why else [] line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") out(f"{line:>10} {case.id} ({case.ask})") for p in problems: out(f" {p}") failed += bool(problems) - out(f"\n{len(cases) - failed} of {len(cases)} cases pass (the service's ten tools alone)") + out(f"\n{len(cases) - failed} of {len(cases)} cases pass (the service's ten tools alone{', with its instructions' if instructions else ''})") return failed diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index e351cde2..4d62371c 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -517,8 +517,9 @@ "note": "alerts can't be added by asking: about lists those there are, with their thresholds" }, "metrics-bare": { - "tools": [ - "about" + "any_tools": [ + "about", + "current" ], "not_tools": [ "summary", @@ -527,7 +528,7 @@ "relate", "scan" ], - "note": "what is measured is about's (the bot answered it from its prompt)" + "note": "\"metrics\" alone is what is measured (about; the bot answered it from its prompt) or the metrics now (current): a plain client with only the tool list may read it either way, and both answer it (the first live run called current {}); never a period's history" }, "most-rain-days-jja": { "tools": [ @@ -784,9 +785,6 @@ "days", "forecast" ], - "not_tools": [ - "pollen" - ], "args": { "summary": { "period": { @@ -808,7 +806,7 @@ } } }, - "note": "asked on a Tuesday: last Tuesday's figures, or today's forecast; not the full report" + "note": "asked on a Tuesday: last Tuesday's figures, or today's report (current, forecast \"today\", pollen: the report as the tool descriptions give it, so pollen is no longer refused). The bot's case kept its own fast path (wants_report) from taking it as the bare report; a plain client has no fast path, and Tuesday is today" }, "air-quality-vs-rain": { "tools": [ @@ -1174,17 +1172,13 @@ }, "only-that-its-cold": { "not_tools": [ - "current", "summary", "readings", "days", "relate", - "scan", - "outlook", - "forecast", - "pollen" + "scan" ], - "note": "a chat reply, not a request (the bot once answered it with the temperatures)" + "note": "a chat reply, not a request (the bot once answered it with the temperatures). With no conversation before it and only the tool list, a plain client may take it as a look at now (current, forecast, outlook, pollen: the first live run did, every time), which costs a call but answers nothing wrong; keeping the model from it is the client's prompt (the bot's needs_data), not a tool description. What it must not do is read a period's history" }, "how-cold-is-it": { "tools": [ @@ -1204,17 +1198,13 @@ }, "now-what": { "not_tools": [ - "current", "summary", "readings", "days", "relate", - "scan", - "outlook", - "forecast", - "pollen" + "scan" ], - "note": "'now' alone is not a weather question" + "note": "'now' alone is not a weather question. With no conversation before it and only the tool list, a plain client may take it as a look at now (current, forecast, outlook, pollen: the first live run did, every time), which costs a call but answers nothing wrong; keeping the model from it is the client's prompt (the bot's needs_data), not a tool description. What it must not do is read a period's history" }, "chart-with-forecast": { "tools": [ diff --git a/tests/test_service_base.py b/tests/test_service_base.py index 40bc5e46..3a31f623 100644 --- a/tests/test_service_base.py +++ b/tests/test_service_base.py @@ -136,9 +136,19 @@ def test_words_that_are_no_form_are_refused_with_every_form_and_what_it_means_no with pytest.raises(Refusal) as e: read_period({"period": "next week"}, tz=TZ, now=NOW, default="today") assert "use forecast" in e.value.message and "forms" not in got(e.value.text) - with pytest.raises(Refusal) as e: - read_period({"period": "this week", "start": "2026-11-01"}, tz=TZ, now=NOW, default="today") - assert "not both" in e.value.message + + +def test_a_period_sent_beside_start_and_end_wins_and_the_result_says_they_were_ignored(): + # a model may fill in every argument it sees: the live evals sent period with start 'count_only', end 'cancel' + for dates in ({"start": "2026-11-01"}, {"end": "2026-11-03"}, {"start": "count_only", "end": "cancel"}): + read = read_period({"period": "this week", **dates}, tz=TZ, now=NOW, default="today") + assert read.text == "the last 7 days: Wed 4 – Tue 10 Nov 2026" and read.note == common.IGNORED_DATES, dates + assert common.period_field(read)["note"] == common.IGNORED_DATES + alone = read_period({"period": "this week", "start": "", "end": None}, tz=TZ, now=NOW, default="today") + assert alone.note is None and "note" not in common.period_field(alone) + with pytest.raises(Refusal) as e: # the period itself can't be read: still refused, as words + read_period({"period": "the other week", "start": "2026-11-01"}, tz=TZ, now=NOW, default="today") + assert "'the other week' isn't a period" in e.value.message def test_a_whole_day_tool_refuses_what_leaves_no_whole_day_and_points_elsewhere(): @@ -162,7 +172,7 @@ def test_the_period_properties_tell_a_model_the_forms_the_dates_and_the_default( "yesterday afternoon", "last night", "since 6am", "Christmas Day", "on record", "A to B"): assert form in words, form assert "own words" in words and "unchanged" in words and words.endswith("Default: last 24 hours.") - assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "never with it" in props["start"]["description"] + assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "ignored when `period` is sent" in props["start"]["description"] assert "Default: now." in props["end"]["description"] whole = period_properties("on record", whole_days=True) assert "yesterday" in whole["period"]["description"] and whole["period"]["description"].endswith("Default: on record.") diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 32b2bc1a..7874b006 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -126,6 +126,10 @@ async def test_the_tool_offers_the_fields_of_the_sensors_there_are_and_says_what assert "Whole days only" in props["period"]["description"] and "night (22:00-06:00" in props["hours"]["description"] d = t.description assert len(d) < 1500 and all(word in d for word in ("summary", "readings", "relate", "day_look", "hours", "only", "count_only")) + # the live evals: "days with most rain" sent no sort_by (ranked by temp_max), "average temperature per year" no group_by + assert 'sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: "rain"}' in d + assert '"per year", "each year", "by month"), group_by' in d and '{stat: "avg", of: "temp_avg", group_by: "year"}' in d + assert '"most rain"' in props["sort_by"]["description"] and '"each year"' in props["group_by"]["description"] station_only = days_tool.tools(Context(eco=world.eco))[0].parameters["properties"] assert "pm2_5_max" not in station_only["where"]["items"]["properties"]["field"]["enum"] assert "Air sensor" not in station_only["where"]["description"] @@ -383,6 +387,14 @@ async def test_a_chart_drawn_with_dates_names_them_as_its_period_and_per_year_it assert drawn["arguments"]["period"] == f"{ago(200).isoformat()} to now" +async def test_a_period_sent_with_start_and_end_beside_it_wins_and_its_chart_is_drawn_by_the_words(world): + # the live evals: period with start 'count_only', end 'cancel' (a model filling in every argument) + out = await ask(world, period="last 30 days", start="count_only", end="cancel", where=[{"field": "rain", "op": ">=", "value": 1}], + group_by="month") + assert "error" not in out and out["period"]["asked"] == "last 30 days" and "were ignored" in out["period"]["note"] + assert chart_of(out)["drawn_by"]["arguments"]["period"] == "last 30 days" + + async def test_a_chart_is_not_the_whole_answer_when_a_note_needs_the_models_words(world): out = await ask(world, period="on record", stat="max", of="temp_max", group_by="month", chart_answers_it=True) assert "charts" in out and "note_daily" in out and "complete" not in out and "reply" not in out diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 402e3621..0449b848 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -377,6 +377,20 @@ async def test_a_live_service_run_offers_the_ten_tools_alone_with_no_prompt_of_o assert first["messages"][1:] == [{"role": "user", "content": "average temp 3m"}] follow_up = next(r for r in model.requests if r["messages"][-1].get("content") == "Wrong. It was cooler this week") assert [m["role"] for m in follow_up["messages"]] == ["system", "user", "assistant", "user"] # (the case's history, as it was) + assert 'called: forecast {}' in text # a run that fails shows what was called + + +async def test_with_the_instructions_the_system_line_carries_the_servers_instructions_after_the_neutral_line(): + from lib.service.instructions import instructions + model = ScriptedModel({"average temp 3m": [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})]}) + lines = [] + told = evalkit.service_instructions() + assert told == instructions(evalkit.eval_context()) and "AirGradient" in told and "Australia/Melbourne" in told + assert await evalkit.run_service([case("3m-average")], EXPECT, model, "m", instructions=told, out=lines.append) == 0 + system = model.requests[0]["messages"][0]["content"] + assert system == evalkit.service_system(instructions=told) == f"{evalkit.service_system()}\n\n{told}" + assert system.startswith(evalkit.SERVICE_SYSTEM) and lines[-1].endswith("(the service's ten tools alone, with its instructions)") + assert [t["function"]["name"] for t in model.requests[0]["tools"]] == evalkit.service_tool_names() # (the same tools) async def test_without_a_model_the_service_run_checks_only_the_expectations(): @@ -399,6 +413,10 @@ def test_the_script_runs_the_service_evals_offline_and_needs_a_key_to_ask_a_mode assert run.returncode == 0 and "2 of 2 cases pass (the service's ten tools alone)" in run.stdout run = script("--live", "--service") assert run.returncode != 0 and "--live needs OPENROUTER_API_KEY" in run.stderr + run = script("--service", "--instructions", "--ids", "hello") # (offline it checks the expectations, as without) + assert run.returncode == 0 and "1 of 1 cases pass (the service's ten tools alone, with its instructions)" in run.stdout + run = script("--instructions") + assert run.returncode != 0 and "--instructions goes with --service" in run.stderr def test_a_rolling_period_in_words_is_not_a_month_that_its_days_happen_to_cover(): @@ -412,6 +430,31 @@ def test_a_rolling_period_in_words_is_not_a_month_that_its_days_happen_to_cover( assert ek._means({"start": "2026-09-01"}, "September", "days") is None +def test_what_a_plain_client_fairly_reads_into_a_bare_word_or_a_chat_line_passes_and_history_does_not(): + """The calls the first live run made that answer the question as a client with only the tool list reads it (each case's note says + why): "metrics" as the readings now, a weather report for today (Tuesday) as the report, a chat line with nothing before it as a + look at now. A period's history is still wrong for all of them.""" + check = evalkit.check_calls + assert check([("current", {})], EXPECT["metrics-bare"]) == [] and check([("about", {})], EXPECT["metrics-bare"]) == [] + report = [("current", {}), ("forecast", {"period": "today"}), ("pollen", {})] + assert check(report, EXPECT["weather-report-for-a-day"]) == [] + for cid in ("only-that-its-cold", "now-what"): + assert check(report, EXPECT[cid]) == [] and check([("current", {"readings": ["temperature"]})], EXPECT[cid]) == [], cid + assert check([], EXPECT[cid]) == [], cid + assert check([("summary", {"period": "today"})], EXPECT[cid]), cid + assert check([("summary", {})], EXPECT["metrics-bare"]) + + +def test_a_period_sent_with_start_and_end_beside_it_is_scored_by_the_period_as_the_tools_read_it(): + """common.read_period: `period` wins and start and end are ignored, so the checker scores the period (the live run's + most-rain-days-jja sent period with start 'count_only', end 'cancel').""" + from tests import evalkit as ek + assert ek._means({"period": "June to August", "start": "count_only", "end": "cancel"}, "June to August", "days") is None + assert ek._means({"period": "this week", "start": "2026-06-01", "end": "2026-08-31"}, "June to August", "days") is not None + call = ("days", {"sort_by": "rain", "period": "June to August", "start": "count_only", "end": "cancel"}) + assert ek.check_calls([call], EXPECT["most-rain-days-jja"]) == [] + + def test_the_hottest_day_ranked_by_days_must_be_the_hottest(): """think-hottest-week's days call ranks the hottest first: the coldest (order asc), a count or a statistic isn't the answer.""" from tests import evalkit as ek diff --git a/tests/test_service_instructions.py b/tests/test_service_instructions.py new file mode 100644 index 00000000..51ac7470 --- /dev/null +++ b/tests/test_service_instructions.py @@ -0,0 +1,39 @@ +"""The server's instructions (lib/service/instructions.py; docs/mcp-service.md 3.2): the devices and their nicknames, Indoor and Outdoor, +the units, built from the Context's sources and the catalogue.""" + +from zoneinfo import ZoneInfo + +from lib.service.context import Context +from lib.service.instructions import INSTRUCTIONS, instructions, units +from lib.service.names import CATALOGUE, Catalogue + +MELBOURNE = ZoneInfo("Australia/Melbourne") + + +def test_the_default_names_every_device_its_nicknames_indoor_and_outdoor_and_the_units(): + text = INSTRUCTIONS + for words in ('"ecowitt"', '"the weather station"', "AirGradient", '"ag"', '"airgradient"', '"air gradient"', "Open-Meteo", + "pollen", "Indoor and Outdoor", "outdoor.temperature, indoor.temperature", "air.temperature and air.humidity", + "no indoor air quality", "°C: temperature", "%: humidity", "hPa: pressure", "km/h: wind speed, wind gust", + "mm: rain", "µg/m³: PM2.5, PM10, PM1", "ppm: CO₂", "no unit (an index): UV index, VOC index, NOx index", + "person's own words"): + assert words in text, words + assert len(text) < 1500 and text == instructions() + + +def test_units_list_each_unit_once_with_its_readings_sides_and_devices_aside(): + listed = units(CATALOGUE) + assert listed.count("°C:") == 1 and "Outdoor" not in listed and "Indoor" not in listed and "AirGradient" not in listed + assert listed.split("; ")[0] == "°C: temperature, dew point, feels like, apparent temperature" + + +def test_a_service_without_the_air_sensor_forecast_or_pollen_names_only_what_it_has_and_its_zone(): + station = Catalogue(r for r in CATALOGUE if not r.name.startswith("air.")) + text = instructions(Context(eco=object(), catalogue=station, tz=MELBOURNE)) + assert "Ecowitt" in text and "AirGradient" not in text and "µg/m³" not in text and "air.temperature" not in text + assert "Open-Meteo" not in text and "pollen" not in text + assert "The station's clock is Australia/Melbourne time" in text + # the catalogue isn't read yet (every reading known): only the devices there are give units + assert "ppm" not in instructions(Context(eco=object(), tz=MELBOURNE)) + air = instructions(Context(air=object(), tz=MELBOURNE)) + assert "AirGradient" in air and "Ecowitt" not in air and "Indoor and Outdoor" not in air and "°C: temperature" in air diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py index d8128e47..87d75a0e 100644 --- a/tests/test_service_readings.py +++ b/tests/test_service_readings.py @@ -172,7 +172,8 @@ async def test_a_period_it_cant_read_says_what_it_can(storage): assert "isn't a period" in out["error"] and any(form.startswith("last N hours") for form in out["forms"]) assert "It is now Mon 9 Nov 2026 1:47am." in out["error"] assert "use forecast" in (await ask(storage, reading="humidity", period="tomorrow", interval="1hour"))["error"] - assert "not both" in (await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour"))["error"] + both = await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour") # period wins, said so + assert "error" not in both and both["period"]["asked"] == "today" and "were ignored" in both["period"]["note"] out = await ask(storage, reading="humidity", period="on record", interval="1day") assert "Nothing is held yet" in out["error"] diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py index 1528f17a..8c7a89cc 100644 --- a/tests/test_service_relate.py +++ b/tests/test_service_relate.py @@ -221,3 +221,11 @@ async def test_a_chart_is_sent_in_the_points_the_request_asks_for_and_only_when_ asked = json.loads(await Tools([made.tool()]).call("relate", "{}", Turn(text="plot pressure against rain", chart_asked=True))) assert "charts" not in asked # the words of the question never reach it: only `chart` draws await eco.close() + + +def test_a_period_sent_beside_start_and_end_is_the_words_a_replay_is_drawn_by(): + from datetime import datetime + from lib.periods_text import Period + period = Period("this week", datetime(2026, 11, 3), datetime(2026, 11, 10), "the last 7 days") + assert relate.whole_day_words({"period": "this week", "start": "2026-11-01", "end": "2026-11-02"}, period) == "this week" + assert relate.whole_day_words({"start": "2026-11-03"}, period) == "2026-11-03 to 2026-11-09" diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index 9dde2e51..9695d384 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -206,6 +206,8 @@ async def test_whole_days_sent_as_dates_are_drawn_by_as_words_and_a_time_lists_n assert [p["period"] for p in words["periods"]] == ["1d", "7d", "1m", "3m", "1y"] again = await ask(tool, **words["arguments"]) assert without_drawn_by(again["charts"][0]) == without_drawn_by(dated["charts"][0]) and again["period"]["text"] == dated["period"]["text"] + beside = await ask(tool, readings=["pressure"], period="this week", start=days_ago(9), end=days_ago(5), chart=True) # period wins + assert "were ignored" in beside["period"]["note"] and beside["charts"][0]["drawn_by"]["arguments"]["period"] == "this week" since = await ask(tool, readings=["pressure"], start=days_ago(4)) assert since["charts"][0]["drawn_by"]["arguments"]["period"] == f"{days_ago(4)} to now" timed = await ask(tool, readings=["pressure"], start=f"{days_ago(4)} 06:00", chart=True) From 10bbb7fc139d3620b91ea62a01bab67e405603c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 10:58:06 +0000 Subject: [PATCH 045/125] Period beside start/end: real dates that disagree are refused, naming both MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit common.read_period, when `period` and `start`/`end` are both sent: - start/end that aren't dates or times (junk such as 'count_only'): the period is read, period.note says they were ignored (IGNORED_DATES); - start/end that read as the same span (within 15 minutes at each end, "on record" from the first reading held): the period, note SAME_DATES; - start/end that read as another span: refused, naming both spans as read ("`period` 'on record' is Sat 1 Oct 2022 – Mon 9 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – Mon 9 Nov 2026: send one of them"); - an unreadable period beside readable dates: refused with its forms and SET_ASIDE (the dates were set aside because period was sent; send them without period to use them). A note on the period keeps summary's and days' chart_answers_it from marking the result complete, so the model reads it. evalkit._means fails a call whose start/end the tools would refuse beside its period. The evals test docstring now credits the junk call to uv-days-two-years (most-rain-days-jja sent matching dates). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 10 ++-- lib/service/common.py | 94 ++++++++++++++++++++++++++++------ lib/service/days.py | 2 +- lib/service/summary.py | 2 +- tests/evalkit.py | 18 ++++++- tests/test_service_base.py | 52 ++++++++++++++++--- tests/test_service_days.py | 5 ++ tests/test_service_evals.py | 11 ++-- tests/test_service_readings.py | 6 ++- tests/test_service_summary.py | 6 ++- 10 files changed, 171 insertions(+), 35 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a50a39d3..798db450 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -149,9 +149,13 @@ and no falling back to a default: anything else is an error that lists the forms | `since 6am`, `since Monday` | from the latest such time (or that day's 00:00) to now | | `on record`, `all time`, `ever` | from the first reading held, for the sensors asked about, to now | -- **`period` or `start`**: when both are sent, `period` wins, `start` and `end` are ignored, and the result's `period.note` says so - (models fill in every argument they see, sometimes with junk). `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD - HH:MM`; one with an offset or `Z` is moved into local time. An `end` that is a date includes that whole day; one with a time stops at +- **`period` or `start`**: models fill in every argument they see, sometimes with junk, so when both are sent: `start` and `end` that + aren't dates or times (`count_only`), or that read as the same span as the period (within 15 minutes at each end), are set aside, the + period is read and the result's `period.note` says so; dates that read as another span are refused, naming both spans as read ("`period` + 'on record' is Sat 1 Oct 2022 – Mon 9 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – now: send one of them"), since real dates are the + person's; a period that can't be read beside readable dates is refused with its forms, saying the dates were set aside because `period` + was sent and to send them without it to use them. A note on the period keeps a chart from being complete (3.7): the model reads it. + `start` and `end` are the station's local time, `YYYY-MM-DD` or `YYYY-MM-DD HH:MM`; one with an offset or `Z` is moved into local time. An `end` that is a date includes that whole day; one with a time stops at it. No `end` means to now; `end` without `start` is an error. - **Whole-day tools** (`days`, `relate`, `scan`) take whole days ending yesterday, because today is still settling: a rolling phrase is that many whole days to yesterday (`last 7 days`: Tue 3 – Mon 9 Nov), a calendar one runs to yesterday, and the result's `period` diff --git a/lib/service/common.py b/lib/service/common.py index b8b890d6..c8c1f154 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -16,7 +16,7 @@ - `period`: how the words were read (lib/periods_text.Period): `asked` the words (or "start/end"), `text` how they were read, ready to pass on, `start` and `end` ISO local times with their offset (the end not included), `cut` only when a whole-day tool cut - today off, and `note` only when `start` and `end` were sent beside `period` and ignored (read_period). Left out by a tool that takes no period. + today off, and `note` only when `start` and `end` were sent beside `period` and set aside (read_period). Left out by a tool that takes no period. - `as_of`: the time of the figures, `text` written as the tools write a time (timeutil.when), `time` ISO. - `fresh`: one fixed line for the model: the figures are as of `as_of`, and a follow-up or a challenge needs the tool called again. - `chart_note` and `charts` (`with_charts`): the charts as data (specs.to_json, bucketed to the request's `chart_points`), and the @@ -30,7 +30,7 @@ import inspect from collections.abc import Awaitable, Callable from dataclasses import dataclass, replace -from datetime import date, datetime, tzinfo +from datetime import date, datetime, timedelta, tzinfo from .. import specs from ..periods_text import Period, PeriodError, read_period as read_words @@ -162,11 +162,11 @@ def period_properties(default: str, whole_days: bool = False) -> dict: if whole_days: forms, days = WHOLE_DAY_FORMS, (" Whole days only, up to yesterday, as today isn't over: a rolling period is that many whole days " "to yesterday (\"last 7 days\" is the 7 days before today).") - start = "Instead of `period` (ignored when `period` is sent): the first day, 'YYYY-MM-DD'." + start = "Instead of `period`, never with it: the first day, 'YYYY-MM-DD'." end = "With `start`: the last day, 'YYYY-MM-DD', up to yesterday. Default: yesterday." else: forms, days = PERIOD_FORMS, "" - start = ("Instead of `period` (ignored when `period` is sent): when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " + start = ("Instead of `period`, never with it: when it starts, the station's local time, 'YYYY-MM-DD' (from midnight) or " "'YYYY-MM-DD HH:MM'.") end = "With `start`: when it ends, local time, 'YYYY-MM-DD' (to the end of that day) or 'YYYY-MM-DD HH:MM'. Default: now." return { @@ -178,30 +178,92 @@ def period_properties(default: str, whole_days: bool = False) -> dict: } -IGNORED_DATES = "`start` and `end` were ignored: `period` was sent too, and the period is read from it." +IGNORED_DATES = ("`start` and `end` were ignored: `period` was sent too, and they can't be read as dates or times. The period is read " + "from `period`.") +SAME_DATES = "`start` and `end` were set aside: `period` was sent too, and they read as the same span. The period is read from `period`." +SET_ASIDE = ("`start` and `end` were set aside because `period` was sent too: send them without `period` to use them, or send a " + "`period` in one of the forms.") +SAME_WITHIN = timedelta(minutes=15) # start/end this close to the period's span at both ends read as the same span def sends_period(args: dict) -> bool: - """Whether the call sends `period` (words, not empty): it then wins over any `start` and `end` sent beside it (read_period).""" + """Whether the call sends `period` (words, not empty): a call read at all then reads its period from it (read_period).""" return args.get("period") is not None and str(args["period"]).strip() != "" +def _sent(x) -> str | None: + return str(x).strip() if x is not None and str(x).strip() else None + + +def _a_moment(text: str | None) -> bool: + """Is it readable as a date or a time ('YYYY-MM-DD', 'YYYY-MM-DD HH:MM', ISO with an offset)?""" + try: + datetime.fromisoformat(text) + except (TypeError, ValueError): + return False + return True + + +def _moment_text(t: datetime, whole_days: bool, words: bool = False) -> str: + """A start as a call sends it ('YYYY-MM-DD', or with ' HH:MM' when it isn't midnight and the tool takes times), or in words.""" + at_midnight = t.time() == datetime.min.time() + if words: + return day_text(t) if at_midnight else f"{day_text(t)} {clock_text(t)}" + return f"{t:%Y-%m-%d}" if whole_days or at_midnight else f"{t:%Y-%m-%d %H:%M}" + + +def _span(text: str) -> str: + """A Period's text without its label: "the last 7 days: Wed 4 – Tue 10 Nov 2026" -> "Wed 4 – Tue 10 Nov 2026".""" + return text.rsplit(": ", 1)[-1] + + def read_period(args: dict, *, tz: tzinfo, now: datetime, default: str, whole_days: bool = False, first_held: date | datetime | None = None) -> Period: """The period a call asks for, from its `period`, or `start` and `end`, else `default` (words), read by lib/periods_text.py at `now` (aware, or naive on the station's clock) in the station's zone. `first_held`: the first reading held for the readings asked about - ("on record"). When `period` is sent, it wins: any `start` and `end` beside it are ignored (a model may fill in every argument it - sees), and the Period's `note` says so (IGNORED_DATES; the result's `period.note`). Raises Refusal (refuse_period) when the period - can't be read.""" - period, start, end = args.get("period"), args.get("start"), args.get("end") - ignored = sends_period(args) and any(x is not None and str(x).strip() for x in (start, end)) - if ignored: - start = end = None + ("on record"). Raises Refusal (refuse_period) when the period can't be read. + + `period` with `start`/`end` beside it (a model may fill in every argument it sees, sometimes with junk such as 'count_only'): + - start/end that aren't dates or times (each sent one read by datetime.fromisoformat): the period is read, its `note` says the + dates were ignored (IGNORED_DATES); + - start/end that read as the same span as the period (within SAME_WITHIN at each end; "on record" from the first reading held): + the period is read, with the note SAME_DATES; + - start/end that read as another span: refused, naming both spans as read, so the model sends the one it meant; + - a period that can't be read beside readable start/end: refused, its forms listed and SET_ASIDE added. + A note on the period keeps a chart from answering the question by itself (summary, days: the model reads the note).""" + period, start, end = (_sent(args.get(k)) for k in ("period", "start", "end")) + both = period is not None and (start is not None or end is not None) + dates = both and all(_a_moment(x) for x in (start, end) if x is not None) + + def read(p, s, e) -> Period: + return read_words(p, s, e, now=now, tz=tz, default=default, whole_days=whole_days, first_held=first_held) + try: - read = read_words(period, start, end, now=now, tz=tz, default=default, whole_days=whole_days, first_held=first_held) + words = read(period, None, None) if both else read(period, start, end) except PeriodError as e: + if dates and e.forms: # the words aren't a form: say why the dates weren't used + raise Refusal(f"{e.message} {SET_ASIDE}", forms=dict(e.forms)) from None raise Refusal.of_period(e) from None - return replace(read, note=IGNORED_DATES) if ignored else read + if not both: + return words + if not dates: + return replace(words, note=IGNORED_DATES) + try: + as_dates = read(None, start or _moment_text(words.start, whole_days), end) # (`end` alone: from the period's start) + except PeriodError as e: + why = e.message if start else f"`end` {end!r} is before the period's start." + raise Refusal(f"`period` {period!r} is {_span(words.text)}, and `start`/`end` can't be read as this tool takes them: " + f"{why} Send one of them.") from None + floor = None if first_held is None else first_held if isinstance(first_held, datetime) else \ + datetime.combine(first_held, datetime.min.time(), tzinfo=tz) + if floor is not None and floor.tzinfo is None: + floor = floor.replace(tzinfo=tz) + starts = [p.start if floor is None else max(p.start, floor) for p in (words, as_dates)] + if abs(starts[0] - starts[1]) <= SAME_WITHIN and abs(words.end - as_dates.end) <= SAME_WITHIN: + return replace(words, note=SAME_DATES) + said = f"{_moment_text(as_dates.start, False, words=True)} – now" if not end and not whole_days else _span(as_dates.text) + raise Refusal(f"`period` {period!r} is {_span(words.text)} but `start`/`end` say {said}: send one of them (`period` alone, or " + f"`start` and `end` without it).") # ---------- an answer ---------- @@ -274,6 +336,6 @@ def complete(reply: str) -> dict: return {"reply": reply, "complete": True} -__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "IGNORED_DATES", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", +__all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "IGNORED_DATES", "SAME_DATES", "SET_ASIDE", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_field", "complete", "iso", "period_field", "period_properties", "read_period", "refuse", "sends_period", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/service/days.py b/lib/service/days.py index bdcb03bf..432b4fa4 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -464,7 +464,7 @@ def row_extra(d: date) -> dict: drawn = self.drawn_by(call, args, period, first, last, first_held, now.date()) for chart in charts["charts"]: chart["drawn_by"] = drawn - finished = complete(line) if call.chart_answers_it and charts and not needs_words(out) else {} + finished = complete(line) if call.chart_answers_it and charts and not needs_words(out) and not period.note else {} return answer(period=period, as_of=now, **fields, **charts, **finished) def _notes(self, call: Call, asked, held: "Held", got, checked: list[date], days: list[date], daily_out: set[date], diff --git a/lib/service/summary.py b/lib/service/summary.py index 997fca08..ec854b42 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -555,7 +555,7 @@ async def handle(self, args: dict, meta: dict) -> str: fields["caption"] = caption elif not charts and (text := self._text(call, q, out, air_out)): fields["text"] = text - finished = call.answers and charts and caption and not self._needs_words(fields) + finished = call.answers and charts and caption and not self._needs_words(fields) and not call.period.note # (the model reads it) fields.update(self._charts(call, route, charts, meta)) if finished: fields.update(complete(caption)) diff --git a/tests/evalkit.py b/tests/evalkit.py index 45dc5b15..617b43b0 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -329,6 +329,20 @@ def _period_span(period, start=None, end=None, whole_days: bool = False) -> tupl return p.start, p.end +def _disagree(sent: dict, tool: str | None) -> str | None: + """Why `period` with `start`/`end` beside it is refused as `tool` reads them at NOW (common.read_period): dates that read as + another span than the period's, or a period that can't be read; None when the period is read (the dates junk or the same span).""" + from zoneinfo import ZoneInfo + + from lib.service.common import Refusal, read_period + try: + read_period(sent, tz=ZoneInfo(NOW_TZ), now=NOW.replace(tzinfo=ZoneInfo(NOW_TZ)), default="today", + whole_days=tool in WHOLE_DAY_TOOLS, first_held=FIRST_HELD) + except Refusal as e: + return f"`period` with `start`/`end` beside it is refused: {e.message.split(chr(10))[0]}" + return None + + def _means(sent, refs, tool: str | None = None) -> str | None: """{"means": words or [words]}: the period sent ({"period", "start", "end"} of the call; a bare value is a `period`) reads, at NOW, as the same span as (one of) these words (a period in words as words; start and end as `tool` reads them, whole days for @@ -337,7 +351,9 @@ def _means(sent, refs, tool: str | None = None) -> str | None: sent = sent if isinstance(sent, dict) else {"period": sent} if sent.get("period") is not None and str(sent["period"]).strip() == "": sent = {**sent, "period": None} - if sent.get("period") is not None: # the period wins over start and end sent beside it, as the tools read it (common.read_period) + if sent.get("period") is not None: # beside start and end, the period is read if they are junk or the same span (common.read_period) + if any(str(sent.get(k) or "").strip() for k in ("start", "end")) and (why := _disagree(sent, tool)): + return why sent = {"period": sent["period"]} # words are compared as words (whole days would make "last 28 days" September on the 29th); dates as the tool reads them whole = tool in WHOLE_DAY_TOOLS and sent.get("period") is None diff --git a/tests/test_service_base.py b/tests/test_service_base.py index 3a31f623..5540ffe0 100644 --- a/tests/test_service_base.py +++ b/tests/test_service_base.py @@ -138,17 +138,55 @@ def test_words_that_are_no_form_are_refused_with_every_form_and_what_it_means_no assert "use forecast" in e.value.message and "forms" not in got(e.value.text) -def test_a_period_sent_beside_start_and_end_wins_and_the_result_says_they_were_ignored(): - # a model may fill in every argument it sees: the live evals sent period with start 'count_only', end 'cancel' - for dates in ({"start": "2026-11-01"}, {"end": "2026-11-03"}, {"start": "count_only", "end": "cancel"}): +def test_a_period_sent_beside_start_and_end_that_are_junk_or_the_same_span_is_read_with_a_note(): + # a model may fill in every argument it sees: the live evals' uv-days-two-years sent period with start 'count_only', end 'cancel', + # and most-rain-days-jja 'June to August 2026' with start 2026-06-01, end 2026-08-31 (the same span) + for dates in ({"start": "count_only", "end": "cancel"}, {"start": "count_only"}, {"start": "2026-11-04", "end": "cancel"}): read = read_period({"period": "this week", **dates}, tz=TZ, now=NOW, default="today") assert read.text == "the last 7 days: Wed 4 – Tue 10 Nov 2026" and read.note == common.IGNORED_DATES, dates assert common.period_field(read)["note"] == common.IGNORED_DATES + for dates in ({"start": "2026-11-04"}, {"start": "2026-11-04", "end": "2026-11-10"}, {"start": "2026-11-04 00:10"}): + read = read_period({"period": "this week", **dates}, tz=TZ, now=NOW, default="today") + assert read.asked == "this week" and read.note == common.SAME_DATES, dates + jja = read_period({"period": "June to August 2026", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, + default="on record", whole_days=True) + assert jja.text == "June 2026 to August 2026: Mon 1 Jun – Mon 31 Aug 2026" and jja.note == common.SAME_DATES + held = read_period({"period": "on record", "start": "2020-01-01"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) # before the first reading held: the same span as on record + assert held.note == common.SAME_DATES alone = read_period({"period": "this week", "start": "", "end": None}, tz=TZ, now=NOW, default="today") assert alone.note is None and "note" not in common.period_field(alone) - with pytest.raises(Refusal) as e: # the period itself can't be read: still refused, as words - read_period({"period": "the other week", "start": "2026-11-01"}, tz=TZ, now=NOW, default="today") - assert "'the other week' isn't a period" in e.value.message + + +def test_a_period_and_dates_that_read_as_different_spans_are_refused_naming_both(): + # the live evals' use-five-minute-data sent days {period: "on record", start: "2025-01-01", end: "2026-09-28"} + with pytest.raises(Refusal) as e: + read_period({"period": "on record", "start": "2025-01-01"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) + assert e.value.message == ("`period` 'on record' is Sat 1 Oct 2022 – Mon 9 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – " + "Mon 9 Nov 2026: send one of them (`period` alone, or `start` and `end` without it).") + with pytest.raises(Refusal) as e: + read_period({"period": "on record", "start": "2025-01-01"}, tz=TZ, now=NOW, default="today", first_held=date(2022, 10, 1)) + assert "is Sat 1 Oct 2022 – Tue 10 Nov 2026 but `start`/`end` say Wed 1 Jan 2025 – now: send one of them" in e.value.message + with pytest.raises(Refusal) as e: + read_period({"period": "this week", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, default="today") + assert "`period` 'this week' is Wed 4 – Tue 10 Nov 2026 but `start`/`end` say Mon 1 Jun – Mon 31 Aug 2026" in e.value.message + with pytest.raises(Refusal) as e: # dates this tool can't take (a time, to a whole-day tool): refused too, not set aside + read_period({"period": "on record", "start": "2025-01-01 06:00"}, tz=TZ, now=NOW, default="on record", whole_days=True, + first_held=date(2022, 10, 1)) + assert "can't be read as this tool takes them" in e.value.message and "has a time" in e.value.message + + +def test_a_period_that_cant_be_read_beside_dates_says_the_dates_were_set_aside_and_how_to_use_them(): + with pytest.raises(Refusal) as e: + read_period({"period": "JJA 2026", "start": "2026-06-01", "end": "2026-08-31"}, tz=TZ, now=NOW, default="on record", + whole_days=True) + out = got(e.value.text) + assert "'JJA 2026' isn't a period" in out["error"] and out["error"].endswith(common.SET_ASIDE) and out["forms"] + assert "send them without `period` to use them" in common.SET_ASIDE + with pytest.raises(Refusal) as e: # junk beside it: the plain refusal of the words + read_period({"period": "the other week", "start": "count_only"}, tz=TZ, now=NOW, default="today") + assert "'the other week' isn't a period" in e.value.message and common.SET_ASIDE not in e.value.message def test_a_whole_day_tool_refuses_what_leaves_no_whole_day_and_points_elsewhere(): @@ -172,7 +210,7 @@ def test_the_period_properties_tell_a_model_the_forms_the_dates_and_the_default( "yesterday afternoon", "last night", "since 6am", "Christmas Day", "on record", "A to B"): assert form in words, form assert "own words" in words and "unchanged" in words and words.endswith("Default: last 24 hours.") - assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "ignored when `period` is sent" in props["start"]["description"] + assert "'YYYY-MM-DD HH:MM'" in props["start"]["description"] and "never with it" in props["start"]["description"] assert "Default: now." in props["end"]["description"] whole = period_properties("on record", whole_days=True) assert "yesterday" in whole["period"]["description"] and whole["period"]["description"].endswith("Default: on record.") diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 7874b006..ce61ca95 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -393,6 +393,11 @@ async def test_a_period_sent_with_start_and_end_beside_it_wins_and_its_chart_is_ group_by="month") assert "error" not in out and out["period"]["asked"] == "last 30 days" and "were ignored" in out["period"]["note"] assert chart_of(out)["drawn_by"]["arguments"]["period"] == "last 30 days" + noted = await ask(world, period="last 30 days", start="count_only", where=[{"field": "rain", "op": ">=", "value": 1}], + group_by="month", chart_answers_it=True) + assert "charts" in noted and noted["period"]["note"] and "complete" not in noted and "reply" not in noted # the model reads it + other = await ask(world, period="on record", start=str(ago(20)), sort_by="rain") + assert "but `start`/`end` say" in other["error"] # real dates that disagree: refused, naming both async def test_a_chart_is_not_the_whole_answer_when_a_note_needs_the_models_words(world): diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 0449b848..762d4877 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -445,12 +445,17 @@ def test_what_a_plain_client_fairly_reads_into_a_bare_word_or_a_chat_line_passes assert check([("summary", {})], EXPECT["metrics-bare"]) -def test_a_period_sent_with_start_and_end_beside_it_is_scored_by_the_period_as_the_tools_read_it(): - """common.read_period: `period` wins and start and end are ignored, so the checker scores the period (the live run's - most-rain-days-jja sent period with start 'count_only', end 'cancel').""" +def test_a_period_sent_with_start_and_end_beside_it_is_scored_as_the_tools_read_it(): + """common.read_period: beside junk start and end, or dates that read as the same span, the period is read, so the checker scores + the period (the live run's uv-days-two-years sent period with start 'count_only', end 'cancel'; most-rain-days-jja sent 'June to + August 2026' with the matching start 2026-06-01, end 2026-08-31). Dates that read as another span are refused by the tools, so the + checker fails them (use-five-minute-data sent days {period: "on record", start: "2025-01-01", end: "2026-09-28"}).""" from tests import evalkit as ek assert ek._means({"period": "June to August", "start": "count_only", "end": "cancel"}, "June to August", "days") is None + assert ek._means({"period": "June to August 2026", "start": "2026-06-01", "end": "2026-08-31"}, "June to August", "days") is None assert ek._means({"period": "this week", "start": "2026-06-01", "end": "2026-08-31"}, "June to August", "days") is not None + disagree = ek._means({"period": "on record", "start": "2025-01-01", "end": "2026-09-28"}, "on record", "days") + assert disagree and "refused" in disagree and "but `start`/`end` say" in disagree call = ("days", {"sort_by": "rain", "period": "June to August", "start": "count_only", "end": "cancel"}) assert ek.check_calls([call], EXPECT["most-rain-days-jja"]) == [] diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py index 87d75a0e..175af216 100644 --- a/tests/test_service_readings.py +++ b/tests/test_service_readings.py @@ -172,8 +172,10 @@ async def test_a_period_it_cant_read_says_what_it_can(storage): assert "isn't a period" in out["error"] and any(form.startswith("last N hours") for form in out["forms"]) assert "It is now Mon 9 Nov 2026 1:47am." in out["error"] assert "use forecast" in (await ask(storage, reading="humidity", period="tomorrow", interval="1hour"))["error"] - both = await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour") # period wins, said so - assert "error" not in both and both["period"]["asked"] == "today" and "were ignored" in both["period"]["note"] + both = await ask(storage, reading="humidity", period="today", start="2026-11-08", interval="1hour") # two spans: refused + assert "`period` 'today' is Mon 9 Nov 2026 but `start`/`end` say Sun 8 Nov 2026 – now: send one of them" in both["error"] + junk = await ask(storage, reading="humidity", period="today", start="count_only", interval="1hour") # junk: the period, said so + assert "error" not in junk and junk["period"]["asked"] == "today" and "were ignored" in junk["period"]["note"] out = await ask(storage, reading="humidity", period="on record", interval="1day") assert "Nothing is held yet" in out["error"] diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index 9695d384..58f8210b 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -206,8 +206,10 @@ async def test_whole_days_sent_as_dates_are_drawn_by_as_words_and_a_time_lists_n assert [p["period"] for p in words["periods"]] == ["1d", "7d", "1m", "3m", "1y"] again = await ask(tool, **words["arguments"]) assert without_drawn_by(again["charts"][0]) == without_drawn_by(dated["charts"][0]) and again["period"]["text"] == dated["period"]["text"] - beside = await ask(tool, readings=["pressure"], period="this week", start=days_ago(9), end=days_ago(5), chart=True) # period wins + beside = await ask(tool, readings=["pressure"], period="this week", start="count_only", end="cancel", chart=True) # junk dates assert "were ignored" in beside["period"]["note"] and beside["charts"][0]["drawn_by"]["arguments"]["period"] == "this week" + other = await ask(tool, readings=["pressure"], period="this week", start=days_ago(30), end=days_ago(20), chart=True) + assert "send one of them" in other["error"] and "charts" not in other # dates that disagree with the period: refused since = await ask(tool, readings=["pressure"], start=days_ago(4)) assert since["charts"][0]["drawn_by"]["arguments"]["period"] == f"{days_ago(4)} to now" timed = await ask(tool, readings=["pressure"], start=f"{days_ago(4)} 06:00", chart=True) @@ -384,6 +386,8 @@ async def test_a_chart_that_answers_the_question_comes_with_its_reply_unless_a_n assert out["charts"][0]["drawn_by"]["arguments"]["chart_answers_it"] is True assert "complete" not in await ask(tool, readings=["pressure"], period="this week") # not asked assert "complete" not in await ask(tool, readings=["pressure"], period="yesterday", chart_answers_it=True) # no chart + noted = await ask(tool, readings=["pressure"], period="this week", start="count_only", chart_answers_it=True) + assert noted["period"]["note"] and "caption" in noted and "complete" not in noted and "reply" not in noted # the model reads it hourly = await ask(tool, readings=["pm2.5"], period="last 7 days", chart_answers_it=True) assert "resolution" in hourly["notes"]["air"] and "caption" in hourly and "complete" not in hourly # the model words the note assert summary.Summary._needs_words({"warning": "x", "missing": ["y"], "notes": {"air": {"missing": "z"}, "chart": "c"}}) is False From cb96b661eaaa29b468d809b40558ef5448c38662 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:04:27 +0000 Subject: [PATCH 046/125] Descriptions for what the gate runs got wrong; summary takes a rating in readings - summary: a device or reading with a period ("weather week", "ecowitt week") is the past, charted; `period` is the person's words unchanged ("past week" is the last 7 days, "last week" the previous Monday to Sunday); a record with when ("hottest record", "highest ever", "use 5 minute data") is summary on record, records being 5-minute where held. - summary takes ":rating" in `readings` too: summarised as the reading, drawn as its rating when chart_readings isn't sent, and the chart is on. rating-against-rainfall takes either place (noted). - current and forecast send " week" to summary (forecast is only what is ahead); readings and days send a record (and days the most common wind direction) to summary. - every `period` property: "past week" is never sent as "last week". - instructions: the readings' names, sensors alike together (a run made up rain.rain_rate). Every description stays under 1500 characters; the default instructions too (1496). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 5 +-- lib/service/common.py | 3 +- lib/service/current.py | 6 ++-- lib/service/days.py | 8 ++--- lib/service/forecast.py | 3 +- lib/service/instructions.py | 38 +++++++++++++------- lib/service/readings.py | 11 +++--- lib/service/summary.py | 40 ++++++++++++--------- tests/evals/service_cases.json | 57 +++++++++++++++++++++--------- tests/test_service_current.py | 2 +- tests/test_service_days.py | 1 + tests/test_service_evals.py | 12 +++++++ tests/test_service_forecast.py | 1 + tests/test_service_instructions.py | 11 +++++- tests/test_service_readings.py | 2 ++ tests/test_service_summary.py | 11 ++++++ 16 files changed, 148 insertions(+), 63 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 798db450..85b52e64 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -85,7 +85,7 @@ answer the question right in one round of calls? Section 7's evals ask exactly t - **The tool descriptions and the results are the contract.** Every rule a choice of tool or the reading of a result depends on is in that tool's description (which questions it answers, an example call for each, how to read what comes back) or in the result itself (`value_is`, `how_to_read`, `note_*`, `missing`, `warning`). The server's `instructions` repeat a short summary (the devices and their - nicknames, Indoor and Outdoor, units), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking + nicknames, Indoor and Outdoor, the readings' names, units), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking (`server/discover`), and many don't pass them to their model. The persona (a friendly Telegram bot, plain text, bullets) is the client's. - **Periods in words, worked out by the service.** Every tool that takes a period takes `period`, the person's own words for it, passed @@ -195,7 +195,8 @@ Ten tools in place of twelve: one per kind of question, each over both sensors w - `layout`: `auto` draws one reading as a line for each sensor that has it, plus the compass rose when wind direction is among them; more than one reading as panels, one each, on one time axis; `two_axes` puts two on one panel with a scale each; `same_axis` two of one unit over each other; `invert_second_axis` modifies `two_axes`. A reading can be drawn as its traffic-light rating - (`air.pm2_5:rating`). `all` draws every reading in the station's usual order (temperature, humidity, solar, pressure, rain, dew point, + (`air.pm2_5:rating`), in `chart_readings` or in `readings` (summarised as the reading, and drawn as its rating when + `chart_readings` isn't sent; a model sends it either way). `all` draws every reading in the station's usual order (temperature, humidity, solar, pressure, rain, dew point, then feels-like and VPD where configured, then wind), as "weather all week" does today. - `chart` defaults to on for periods of 3 days or more. `average: true` adds each reading's average to the figures and draws the chart as each day's average. diff --git a/lib/service/common.py b/lib/service/common.py index c8c1f154..15761398 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -171,7 +171,8 @@ def period_properties(default: str, whole_days: bool = False) -> dict: end = "With `start`: when it ends, local time, 'YYYY-MM-DD' (to the end of that day) or 'YYYY-MM-DD HH:MM'. Default: now." return { "period": {"type": "string", "description": "The period in the person's own words, passed on unchanged (\"this week\", \"in the " - "last year\", \"past two years\"): the service reads them, and the result says how. " + "last year\", \"past two years\"): the service reads them, and the result says how. \"past week\" (the " + "last 7 days) is never sent as \"last week\" (the previous Monday to Sunday). " f"Forms: {forms}.{days} Default: {default}."}, "start": {"type": "string", "description": start}, "end": {"type": "string", "description": end}, diff --git a/lib/service/current.py b/lib/service/current.py index d6066182..ce79d4aa 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -60,10 +60,10 @@ "(\"weather now\", \"how's it outside\"): {}. How hot is it: {readings: [\"temperature\"]}. Is it raining: {readings: [\"rain\"]}. " "The air now: {readings: [\"air\"]}. With today's, this month's and this year's highs and lows beside each reading, as gauges show " "them (rain: its totals and wettest day; wind: its highest gust): {context: true}. A report, status or sitrep: current, forecast " - "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows, averages or a chart " - "(summary); values at set times (readings); the days ahead (forecast). Result: sensors.. (sensors.outdoor." + "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows, averages or a chart, " + "a device or reading with a period, \"ecowitt week\", \"weather week\" (summary); values at set times (readings); the days ahead (forecast). Result: sensors.. (sensors.outdoor." "temperature) with value, unit, text ready to quote (\"12.3 °C\") and emoji when the reading is one to notice (put it right " - "before the reading, copied; none otherwise); rainfall.rain is today's rain so far; wind_direction has its compass point; the air " + "before the reading); rainfall.rain is today's rain so far; wind_direction has its compass point; the air " "sensor's have their rating (put it beside the value) and PM2.5 its US aqi_us and band. With context: today, month and year, each " "with high and low (_text to quote, _when copied as written, \"at 3:05pm\" or \"around 3:30pm\", _date the day). lines: each " "device's readings as bullet lines, to pass on as they are (headings: each one's heading for a report). missing: readings asked " diff --git a/lib/service/days.py b/lib/service/days.py index 432b4fa4..8fb04d2b 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -89,8 +89,8 @@ # ---------- the description and the input schema ---------- DESCRIPTION = ( - "Days found, ranked, counted or totalled by their figures, from the weather station's and the air sensor's (AirGradient's) days, " - "midnight to midnight. sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: \"rain\"}; the hottest " + "Days found, ranked, counted or totalled by their figures, from the weather station's and the air sensor's days, midnight to " + "midnight. sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: \"rain\"}; the hottest " "day it rained {where: [{field: \"rain\", op: \">=\", value: 1}], sort_by: \"temp_max\"}. Days over 35°C this year: {where: " "[{field: \"temp_max\", op: \">\", value: 35}], period: \"this year\", count_only: true}. Per month or year (\"per year\", \"each " "year\", \"by month\"), group_by: rain per month {stat: \"sum\", of: \"rain\", group_by: \"month\"}; average temperature per " @@ -98,9 +98,9 @@ "25}]}. The windiest weekend day: {sort_by: \"wind_gust\", only: \"weekend\"}. One day: {period: \"5 Sep\"}. Part of each day, " "hours: nights below 5°C {hours: \"night\", where: [{field: \"temp_min\", op: \"<\", value: 5}]}; 3pm in October {hours: " "\"15:00\", stat: \"avg\", of: \"temp_avg\", period: \"October\"}. No period: every day on record (with hours, 30 days). Not " - "for: a period's highest or lowest reading with when, or a chart over time (summary); values at set times (readings); rain " + "for: a period's highest or lowest reading with when, a record (\"hottest ever\"), wind direction or a chart over time (summary); values at set times (readings); rain " "against a reading (relate). Result: answer, a line to pass on; matching_days of days_checked; days, the top ones, each with " - "day_look (weather word and emoji: put it before the day); by_month or by_year, drawn as bars (charts); note_*: mention " + "day_look (word and emoji: put it before the day); by_month or by_year, drawn as bars (charts); note_*: mention " "briefly. A rainy day is rain >= 1.") STATION_WHERE = ("Weather station: temp_max, temp_min, temp_avg (outdoor °C), rain (mm that fell), wind_gust (km/h, the highest); a " diff --git a/lib/service/forecast.py b/lib/service/forecast.py index 3268867c..05eaaddb 100644 --- a/lib/service/forecast.py +++ b/lib/service/forecast.py @@ -182,7 +182,8 @@ def section(heading: str, lines: list[str], *, place: str | None, fetched_at: fl "forecast for the weekend\": {\"period\": \"this weekend\"}; \"will it rain this week\", \"forecast\": {} (the next 7 days). A " "report (\"report\", \"status\", \"sitrep\") is current, forecast {\"period\": \"today\"} and pollen, called together.\n" "Not for: the next few hours from the station's own readings (\"will it rain soon\", \"do I need an umbrella\": outlook); what was " - "measured (summary; days, for days ranked or counted).\n" + "measured, a device or reading with a period (\"weather week\", \"ecowitt week\": the past week, summary; days, for days " + "ranked or counted). Only what is ahead is forecast.\n" "Result: `period` (how the words were read, with the dates); `text`, the whole answer for the person, ready to send; `lines`, one a " "day, emoji included: copy them as they are, with the place in parentheses after the heading, e.g. Forecast (Melbourne); `days`, " "each day's figures (min and max °C, rain_chance: Open-Meteo's chance of rain, rain_1mm_pct: the chance of at least 1 mm, the one " diff --git a/lib/service/instructions.py b/lib/service/instructions.py index b576615e..be98db7b 100644 --- a/lib/service/instructions.py +++ b/lib/service/instructions.py @@ -4,7 +4,7 @@ --instructions`, docs 7). It says: the devices there are (the Context's sources) and the nicknames people use for them, which readings are Indoor and Outdoor, -the units each reading comes in (from the catalogue: only the readings held), the station's time zone, and that a period is passed on +the readings' names, the units each reading comes in (from the catalogue: only the readings held), the station's time zone, and that a period is passed on in the person's own words. `instructions(ctx)` builds it; INSTRUCTIONS is it for every device and every reading the service knows. """ @@ -34,6 +34,19 @@ def units(catalogue: Catalogue) -> str: return "; ".join(listed) +def names(catalogue: Catalogue) -> str: + """"outdoor and indoor: temperature, humidity …; pressure: relative, absolute; …": each sensor with its readings' names, in the + catalogue's order, sensors with the same readings together (a model must not make up a name: rain.rain_rate).""" + by_sensor: dict[str, list[str]] = {} + for r in catalogue: + sensor, _, reading = r.name.partition(".") + by_sensor.setdefault(sensor, []).append(reading) + alike: dict[tuple[str, ...], list[str]] = {} + for sensor, readings in by_sensor.items(): + alike.setdefault(tuple(readings), []).append(sensor) + return "; ".join(f"{' and '.join(sensors)}: {', '.join(readings)}" for readings, sensors in alike.items()) + + def instructions(ctx=None) -> str: """The instructions for the service over this Context (lib/service/context.py): its sources, the readings its catalogue holds and its zone. With no ctx: every source, every reading the service knows, no zone named.""" @@ -47,30 +60,31 @@ def instructions(ctx=None) -> str: devices = [] if station: - devices.append("the weather station (Ecowitt; people call it \"ecowitt\", \"the weather station\" or \"the station\"), " - "outdoors, with an indoor sensor in the house") + devices.append("the weather station (Ecowitt; \"ecowitt\", \"the weather station\", \"the station\"), outdoors, with an " + "indoor sensor") if air: - devices.append("the outdoor air-quality sensor (AirGradient; \"ag\", \"airgradient\", \"air gradient\", \"the air sensor\")") - extra = [*(["the weather forecast for the station's location (Open-Meteo)"] if forecast else []), + devices.append("the air-quality sensor (AirGradient; \"ag\", \"airgradient\", \"air gradient\", \"the air sensor\")") + extra = [*(["the forecast for the station's place (Open-Meteo)"] if forecast else []), *(["Melbourne's grass pollen and thunderstorm asthma forecast (October to December)"] if pollen else [])] lines = [f"The devices: {'; '.join(devices) or 'none'}." + (f" Also: {'; '.join(extra)}." if extra else "")] if station: - sides = ("Indoor and Outdoor: a reading named bare is the weather station's, and temperature and humidity mean both its outdoor " - "and its indoor sensor (outdoor.temperature, indoor.temperature); dew point, feels like and the rest are outdoor's.") + sides = ("Indoor and Outdoor: a bare reading is the weather station's: temperature and humidity are both outdoor and indoor " + "(outdoor.temperature, indoor.temperature); dew point, feels like and the rest outdoor.") if air: - sides += (" The air sensor is outdoors: its own temperature and humidity are only ever air.temperature and air.humidity, " - "and there is no indoor air quality.") + sides += (" The air sensor is outdoors: its own temperature and humidity are only air.temperature and air.humidity; " + "no indoor air quality.") lines.append(sides) held = Catalogue(r for r in catalogue if (r.device == STATION and station) or (r.device == AIR_DEVICE and air)) if held.names: + lines.append(f"Names (sensor.reading): {names(held)}.") lines.append(f"Units: {units(held)}. Rain is the mm that fell.") zone = getattr(ctx.zone, "key", None) if ctx is not None and (ctx.tz or ctx.eco or ctx.air) else None when = f"The station's clock is {zone} time; " if zone else "Times are the station's local time; " - lines.append(when + "pass a period on in the person's own words (`period`: \"this week\", \"yesterday afternoon\"): the tools " - "read it and say how. Each tool's description says what it answers.") + lines.append(when + "pass a period on in the person's own words (`period`: \"past week\", \"since 6am\"): the tools " + "read it and say how.") return "\n".join(lines) INSTRUCTIONS = instructions() # every device and every reading the service knows (the evals; a server that hasn't read its file) -__all__ = ["INSTRUCTIONS", "instructions", "units"] +__all__ = ["INSTRUCTIONS", "instructions", "names", "units"] diff --git a/lib/service/readings.py b/lib/service/readings.py index 4e6e98aa..3aa3bde2 100644 --- a/lib/service/readings.py +++ b/lib/service/readings.py @@ -25,20 +25,21 @@ NO_ROWS = "No readings are stored for this period at this interval: say so; never fill the gap." DESCRIPTION = ( - "The stored values of ONE reading at a fixed interval, a row per interval with its time: for values at set times or per interval, " - "or a table of values. Examples: \"humidity each hour for the last 5 hours\" {reading: \"outdoor.humidity\", period: \"last 5 " + "The stored values of ONE reading at a fixed interval, a row per interval with its time: values at set times or per interval. " + "Examples: \"humidity each hour for the last 5 hours\" {reading: \"outdoor.humidity\", period: \"last 5 " "hours\", interval: \"1hour\"}; \"PM2.5 every 30 minutes this morning\" {reading: \"pm2.5\", period: \"this morning\", interval: " "\"30min\"}; \"rain each hour today\" {reading: \"rain\", period: \"today\", interval: \"1hour\"}; \"the temperature at 3pm " "yesterday\" {reading: \"outdoor.temperature\", period: \"yesterday afternoon\", interval: \"5min\"}, then its 3:00pm row. One " - "reading a call: outdoor and indoor are two calls, made together. " + "reading a call: outdoor and indoor are two calls. " f"At most {MAX_ROWS} rows: 5min for up to a day, 30min up to 6 days, 1hour up to 12 days, 4hour up to 7 weeks, 1day up to 300 " "days; more is refused with the interval that fits (`fits`). " - "Not for: a period's highs and lows with when, averages, totals or a chart (summary); days ranked, counted or totalled, a figure " + "Not for: a period's highs and lows with when, a record (\"hottest ever\", even \"use 5 minute data\": summary, period \"on " + "record\"), averages, totals or a chart (summary); days ranked, counted or totalled, a figure " "per month or year (days); how it is now (current). " "Result: `columns` names each row's values and `value_is` what `value` is: an interval's average with its lowest and highest; rain " "the mm that fell in it; gusts the highest; wind direction the reading at its end; at 1day the day's figures and when its lowest " "and highest happened. Only what is stored is read, nothing is fetched: an empty row is `missing` (say so, never fill it), and " - "`note_coarser` with `fits` names the interval those times are held at.") + "`note_coarser` with `fits` names the interval held.") def parameters(catalogue: Catalogue) -> dict: diff --git a/lib/service/summary.py b/lib/service/summary.py index ec854b42..a1003e79 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -60,20 +60,21 @@ DATE = re.compile(r"\d{4}-\d\d-\d\d") DESCRIPTION = ( - "A period's figures from the Ecowitt weather station and the AirGradient air sensor: each reading's lowest and highest with " - "when they happened and that day's look, averages, a breakdown by day (up to 31 days) or by month, wind direction, the rain " - "that fell, air ratings and AQI; and a chart of any readings from either sensor or both.\n" - "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; \"coldest on record\" " - "{readings: [\"outdoor.temperature\"], period: \"on record\"}; \"average humidity last month\" {readings: [\"humidity\"], " - "period: \"last month\", average: true}; \"rain since Monday\" {readings: [\"rain\"], period: \"since Monday\"}; \"plot " - "pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, chart_answers_it: true}; \"PM2.5 and rain, " - "3 months\" {readings: [\"pm2.5\", \"rain\"], period: \"3m\", chart: true}; \"weather all week\" {readings: [\"all\"], period: " - "\"this week\", chart: true}.\n" - "Not for: days ranked, counted or filtered by a day's figures (the wettest day, days over 35°C, rain per month): days. " + "What was measured over a period (Ecowitt weather station, AirGradient air sensor): each reading's low and high with " + "when, averages, a by-day or by-month breakdown, the most common wind direction, rain that fell, air ratings " + "and AQI; and a chart of any readings.\n" + "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; a record with when (\"hottest " + "record\", \"highest ever\", \"use 5 minute data\": records are 5-minute where held) {readings: [\"outdoor.temperature\"], " + "period: \"on record\"}; \"average humidity last month\" {readings: [\"humidity\"], period: \"last month\", average: true}; \"plot " + "pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, chart_answers_it: true}; a device or reading " + "and a period (\"weather week\", \"ecowitt week\"): the past, charted {readings: [\"all\"], period: \"week\", chart: true}; a " + "rating and rain {readings: [\"pm2.5:rating\", \"rain\"]}.\n" + "`period` is the person's words unchanged: \"past week\" is the last 7 days, \"last week\" the previous Monday to Sunday: never " + "one for the other.\n" + "Not for: days ranked, counted or filtered by a day's figures (wettest day, days over 35°C, rain per month): days. " "Values at set times: readings. Rain against a reading: relate. Now: current. Ahead: forecast.\n" - "Reading it: `series` by reading name; quote low_text and high_text with their low_when and low_date as given, and a day's " - "day_look emoji beside it. rain_total_mm is the rain that fell. A note says what the figures lack. With a chart, `caption` is " - "its caption, ready; with complete: true, `reply` is the whole answer.") + "Reading it: `series` by name; quote low_text and high_text with low_when and low_date, and day_look's emoji. rain_total_mm: rain " + "that fell. A chart's `caption` is ready; with complete: true, `reply` is the answer.") def _boolean(description: str) -> dict: @@ -376,9 +377,11 @@ def __init__(self, ctx: Context): def parameters(self) -> dict: names = self.ctx.readings().description() + rating = (" An air-quality reading with \":rating\" (\"air.pm2_5:rating\") is summarised and drawn as its traffic-light " + "rating.") if self.ctx.air is not None else "" return {"type": "object", "properties": { "readings": {"type": "array", "items": {"type": "string"}, - "description": f"What to summarise. {names} Default: outdoor and indoor temperature and humidity."}, + "description": f"What to summarise. {names}{rating} Default: outdoor and indoor temperature and humidity."}, **period_properties("today; with chart true and no period, the last 24 hours"), **ARGUMENTS}} @@ -393,8 +396,11 @@ async def read(self, args: dict) -> Call: raise Refusal(f"summary doesn't take {', '.join(map(repr, unknown))}.{hint}", arguments=list(props)) catalogue = ctx.readings() default = list(DEFAULT_READINGS) if ctx.eco else "air" - readings = catalogue.resolve(args.get("readings"), default=default) - drawn = self._drawn(args.get("chart_readings"), readings) + sent = _words(args.get("readings")) + rated = any(w.lower().endswith(RATING) for w in sent) # "air.pm2_5:rating" in readings: summarised, and drawn as its rating + plain = [w[:-len(RATING)].strip() if w.lower().endswith(RATING) else w for w in sent] + readings = catalogue.resolve(plain if rated else args.get("readings"), default=default) + drawn = self._drawn(args.get("chart_readings") if _words(args.get("chart_readings")) or not rated else sent, readings) for r in {r for r in [*readings, *(r for r, _ in drawn)]}: if (r.device == STATION and ctx.eco is None) or (r.device == AIR_DEVICE and ctx.air is None): device = "weather station" if r.device == STATION else "air sensor" @@ -403,6 +409,8 @@ async def read(self, args: dict) -> Call: if layout not in LAYOUTS: raise Refusal(f"`layout` is one of {', '.join(LAYOUTS)}, not {args.get('layout')!r}.", layouts=list(LAYOUTS)) chart = _flag(args, "chart") + if chart is None and any(rating for _, rating in drawn): # a rating is only ever drawn + chart = True asked = any(str(args.get(k) or "").strip() for k in ("period", "start", "end")) period = read_period(args, tz=ctx.zone, now=ctx.now(), default="last 24 hours" if chart and not asked else "today", first_held=await self._first_held([*readings, *(r for r, _ in drawn)])) diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index 4d62371c..d2d067d6 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -829,26 +829,49 @@ "summary" ], "args": { - "summary": { - "chart_readings": { - "regex": "(?s)(?=.*:rating)(?=.*rain)", - "e.g.": [ - "air.pm2_5:rating", - "rainfall.rain" - ] - }, - "period": { - "means": "last 30 days" + "summary": [ + { + "chart_readings": { + "regex": "(?s)(?=.*:rating)(?=.*rain)", + "e.g.": [ + "air.pm2_5:rating", + "rainfall.rain" + ] + }, + "period": { + "means": "last 30 days" + }, + "chart": { + "one_of": [ + true, + null + ] + } }, - "chart": { - "one_of": [ - true, - null - ] + { + "readings": { + "regex": "(?s)(?=.*:rating)(?=.*rain)", + "e.g.": [ + "air.pm2_5:rating", + "rain" + ] + }, + "chart_readings": { + "absent": true + }, + "period": { + "means": "last 30 days" + }, + "chart": { + "one_of": [ + true, + null + ] + } } - } + ] }, - "note": "the rating drawn over time is summary's chart (\":rating\"), with rain in a panel below; relate would draw PM2.5, not its rating" + "note": "the rating drawn over time is summary's chart (\":rating\"), with rain in a panel below; relate would draw PM2.5, not its rating. summary also takes the \":rating\" in `readings` (summarised, and drawn as its rating when chart_readings isn't sent), as deepseek sent it on 10 Nov 2026" }, "air-quality-vs-everything": { "tools": [ diff --git a/tests/test_service_current.py b/tests/test_service_current.py index fd7279be..13acc14f 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -105,7 +105,7 @@ def test_the_description_says_what_it_answers_with_an_example_each_and_where_the d = cur.DESCRIPTION assert len(d) < 1500 for said in ("{}", "{readings: [\"temperature\"]}", "{readings: [\"rain\"]}", "{context: true}", "report, status or sitrep", - "forecast", "pollen", "will it rain (outlook)", "(summary)", "(readings)", "lines", "missing", "unavailable"): + "forecast", "pollen", "will it rain (outlook)", "(summary)", "\"ecowitt week\", \"weather week\" (summary)", "(readings)", "lines", "missing", "unavailable"): assert said in d, said schema = cur.parameters("Readings, as `sensor.reading`.") assert set(schema["properties"]) == {"readings", "context"} and "required" not in schema diff --git a/tests/test_service_days.py b/tests/test_service_days.py index ce61ca95..76187c63 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -127,6 +127,7 @@ async def test_the_tool_offers_the_fields_of_the_sensors_there_are_and_says_what d = t.description assert len(d) < 1500 and all(word in d for word in ("summary", "readings", "relate", "day_look", "hours", "only", "count_only")) # the live evals: "days with most rain" sent no sort_by (ranked by temp_max), "average temperature per year" no group_by + assert 'a record ("hottest ever"), wind direction or a chart over time (summary)' in d assert 'sort_by is the field the days are ranked by: the wettest days, most rain {sort_by: "rain"}' in d assert '"per year", "each year", "by month"), group_by' in d and '{stat: "avg", of: "temp_avg", group_by: "year"}' in d assert '"most rain"' in props["sort_by"]["description"] and '"each year"' in props["group_by"]["description"] diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 762d4877..aa7cabb7 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -460,6 +460,18 @@ def test_a_period_sent_with_start_and_end_beside_it_is_scored_as_the_tools_read_ assert ek.check_calls([call], EXPECT["most-rain-days-jja"]) == [] +def test_a_rating_with_rain_passes_in_chart_readings_or_in_readings_but_not_as_pm25_alone(): + """rating-against-rainfall: deepseek put "air.pm2_5:rating" in `readings` (10 Nov 2026); summary takes it there too (summarised, + drawn as its rating), so the case takes either place, but not a rating dropped by chart_readings sent without it.""" + from tests import evalkit as ek + want = EXPECT["rating-against-rainfall"] + base = {"period": "last 30 days", "chart": True} + assert ek.check_calls([("summary", {**base, "chart_readings": ["air.pm2_5:rating", "rainfall.rain"]})], want) == [] + assert ek.check_calls([("summary", {**base, "readings": ["air.pm2_5:rating", "rain"]})], want) == [] + assert ek.check_calls([("summary", {**base, "readings": ["air.pm2_5:rating", "rain"], "chart_readings": ["pm2.5", "rain"]})], want) + assert ek.check_calls([("summary", {**base, "readings": ["pm2.5", "rain"]})], want) + + def test_the_hottest_day_ranked_by_days_must_be_the_hottest(): """think-hottest-week's days call ranks the hottest first: the coldest (order asc), a count or a statistic isn't the answer.""" from tests import evalkit as ek diff --git a/tests/test_service_forecast.py b/tests/test_service_forecast.py index 2054b3ae..e5536f50 100644 --- a/tests/test_service_forecast.py +++ b/tests/test_service_forecast.py @@ -221,4 +221,5 @@ async def test_refusals_teach_the_call_that_works(tmp_path): def test_it_is_offered_only_with_a_forecast_and_its_description_carries_the_rules(): assert tools(Context(tz=TZ)) == [] assert len(DESCRIPTION) < 1500 and "outlook" in DESCRIPTION and "summary" in DESCRIPTION and '{"period": "tomorrow"}' in DESCRIPTION + assert '"weather week", "ecowitt week": the past week, summary' in DESCRIPTION and "Only what is ahead is forecast." in DESCRIPTION assert list(PARAMETERS["properties"]) == ["period"] and "Default: the next 7 days." in PARAMETERS["properties"]["period"]["description"] diff --git a/tests/test_service_instructions.py b/tests/test_service_instructions.py index 51ac7470..618f6012 100644 --- a/tests/test_service_instructions.py +++ b/tests/test_service_instructions.py @@ -4,7 +4,7 @@ from zoneinfo import ZoneInfo from lib.service.context import Context -from lib.service.instructions import INSTRUCTIONS, instructions, units +from lib.service.instructions import INSTRUCTIONS, instructions, names, units from lib.service.names import CATALOGUE, Catalogue MELBOURNE = ZoneInfo("Australia/Melbourne") @@ -19,6 +19,15 @@ def test_the_default_names_every_device_its_nicknames_indoor_and_outdoor_and_the "person's own words"): assert words in text, words assert len(text) < 1500 and text == instructions() + # every reading's name (a live run made up rain.rain_rate for rainfall.rain_rate) + assert "Names (sensor.reading): outdoor and indoor: temperature, humidity, dew_point" in text + assert "rainfall and rainfall_piezo: rain_rate, rain" in text and "air: pm2_5, pm10" in text + + +def test_names_list_each_sensor_with_its_readings_sensors_alike_together(): + listed = names(CATALOGUE) + assert listed.startswith("outdoor and indoor: temperature, humidity") and "; pressure: relative, absolute; " in listed + assert all(n.partition(".")[2] in listed for n in CATALOGUE.names) def test_units_list_each_unit_once_with_its_readings_sides_and_devices_aside(): diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py index 175af216..45e6dbfe 100644 --- a/tests/test_service_readings.py +++ b/tests/test_service_readings.py @@ -92,6 +92,8 @@ def test_it_takes_one_reading_a_period_in_words_and_an_interval(storage): assert "Default: last 24 hours" in props["period"]["description"] and "this week" in props["period"]["description"] assert "outdoor.humidity" in props["reading"]["description"] and "ONE reading" in props["reading"]["description"] assert len(made.description) < 1500 and all(f"({tool})" in made.description for tool in ("summary", "days", "current")) + assert 'a record ("hottest ever", even "use 5 minute data": summary, period "on record")' in made.description + assert '"past week" (the last 7 days) is never sent as "last week"' in props["period"]["description"] assert made.description.count("{reading:") >= 3 and "`value_is`" in made.description and "`fits`" in made.description assert made.annotations == {"readOnlyHint": True, "openWorldHint": False} # it reads the file only diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index 58f8210b..b36c136d 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -60,6 +60,10 @@ async def test_the_tool_says_what_it_answers_what_it_is_not_for_and_how_to_read_ for words in ("{readings: [\"temperature\"], period: \"this week\"}", "chart_answers_it: true", "average: true", "\"all\"", "pm2.5", ": days", ": readings", ": relate", ": current", ": forecast", "low_text", "day_look", "rain_total_mm", "complete"): assert words in text, words + # what the live runs got wrong: a device and a period is the past; "past week" isn't "last week"; a record with when is summary's + for words in ('"weather week"', '"ecowitt week"', 'the past, charted', '"past week" is the last 7 days', + '"last week" the previous Monday to Sunday', '"use 5 minute data"', 'period: "on record"', '"pm2.5:rating"'): + assert words in text, words readings = tool.parameters["properties"]["readings"]["description"] assert "outdoor.temperature" in readings and "air.pm2_5" not in readings and readings.endswith( # (what this station holds) "Default: outdoor and indoor temperature and humidity.") @@ -314,6 +318,13 @@ async def test_a_chart_of_both_sensors_or_a_rating_is_drawn_over_whole_days_and_ assert list(out["series"]) == ["air.pm2_5", "rainfall.rain"] and out["rain_total_mm"] >= 0 by = await replays(tool, out) assert by["arguments"]["chart_readings"] == ["air.pm2_5:rating", "rainfall.rain"] + # the live evals' rating-against-rainfall put the rating in `readings`: summarised as the reading, drawn as its rating + sent = await ask(tool, readings=["air.pm2_5:rating", "rain"], period="this week") + assert list(sent["series"]) == ["air.pm2_5", "rainfall.rain"] and sent["charts"][0]["panels"][0]["series"][0]["kind"] == "rating" + assert sent["charts"][0]["drawn_by"]["arguments"]["chart_readings"] == ["air.pm2_5:rating", "rainfall.rain"] + assert sent["charts"][0]["drawn_by"]["arguments"]["readings"] == ["air.pm2_5", "rainfall.rain"] + short = await ask(tool, readings=["pm2.5:rating"], period="yesterday") # a rating is only ever drawn: chart on + assert short["charts"][0]["panels"][0]["series"][0]["kind"] == "rating" await close(ctx) From b6b368991d5b88f4dd62055e588acb803b1bcbb6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:16:39 +0000 Subject: [PATCH 047/125] Descriptions for the gate's repeated failures Each failure of the four gate2 runs was asked 3 times more; those that failed 2 of 3 or worse are fixed here, and each then passed 3 of 3: - wind 3m (deepseek read "3m" as 3 minutes, gpt-6-luna called current): summary has "wind 3m" {readings: ["wind"], period: "3m", chart: true}; the period forms say 3m is 3 months, never minutes, and list N min. - a traffic-light rating against rainfall (gpt-6-luna called relate): relate's Not-for sends it to summary {readings: ["pm2.5:rating", "rain"]}. - "lowest and highest humidity" (gpt-6-luna called current context): summary's example {readings: ["humidity"]} (today); current's Not-for names it. - air quality against precipitation (gpt-6-luna called scan): relate's example, scan's Not-for. - "is today hotter than yesterday" (deepseek: current + days): summary {readings: ["temperature"], period: "yesterday to today", every_day}. summary's description was trimmed to fit (1496 characters). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 2 +- lib/service/common.py | 5 +++-- lib/service/current.py | 7 ++++--- lib/service/relate.py | 5 +++-- lib/service/scan.py | 2 +- lib/service/summary.py | 30 +++++++++++++++--------------- tests/test_service_relate.py | 1 + tests/test_service_summary.py | 5 +++-- 8 files changed, 31 insertions(+), 26 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 85b52e64..0ab1326f 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -474,7 +474,7 @@ Each step ships on its own, with the tests and evals green and the bot working t evals have the service's expectations (`tests/evals/service_cases.json`, every case) and `scripts/eval_prompts.py --service` checks offline that the tools accept each expected call; `--live --service` asks a model with the tool list alone, and `--instructions` adds the server's instructions (`lib/service/instructions.py`) after the neutral line. First full runs (10 Nov 2026, one run each): - deepseek-v4.1-flash 92/94 alone and 92/94 with the instructions, gpt-6-luna 89/94 alone. The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and + deepseek-v4.1-flash 92/94 alone and 92/94 with the instructions, gpt-6-luna 89/94 alone. The gate's second round (the same day, after the period rule and the descriptions above): deepseek 90/94 alone and 90/94 with the instructions, gpt-6-luna 90/94 and 87/94; each failure asked 3 times more, those that failed 2 of 3 or worse fixed in the descriptions (wind 3m, a rating against rain, lowest and highest, air quality against rain, today against yesterday) and then passing 3 of 3. The bot's own code paths call the ten instead of the twelve: its shortcuts, report, lookups, Help, gauges and alert charts, through `lib/service/legacy.py` (the old call and the `Turn`'s inputs read as the service's call, in one place, deleted whole in step 3), quoting their words; its answers pinned before and after (`tests/test_service_switch.py`), unchanged but for the deliberate changes below. Its gauges (the dashboard, the report's three) are `current` with `context` and the gauges' diff --git a/lib/service/common.py b/lib/service/common.py index 15761398..642db055 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -145,11 +145,12 @@ async def handle(args: dict, turn: Turn | None = None) -> str: # ---------- periods ---------- -PERIOD_FORMS = ("today, yesterday, last N hours/days/weeks/months/years (or Nh, Nd, Nw, Nm, Ny), this week, last week, week to date, " +PERIOD_FORMS = ("today, yesterday, last N minutes (N min), last N hours/days/weeks/months/years (or Nh, Nd, Nw, Nm, Ny: 3m is 3 " + "months, never minutes), this week, last week, week to date, " "this month, last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, " "2026-09-05), a weekday (Saturday), this morning, yesterday afternoon, last night, since 6am, a public holiday " "(Christmas Day), on record, A to B (June to August)") -WHOLE_DAY_FORMS = ("yesterday, last N days/weeks/months/years (or Nd, Nw, Nm, Ny), this week, last week, week to date, this month, " +WHOLE_DAY_FORMS = ("yesterday, last N days/weeks/months/years (or Nd, Nw, Nm, Ny: 3m is 3 months), this week, last week, week to date, this month, " "last month, this year, last year, a month or a year (October, October 2025, 2025), a date (5 Sep, 2026-09-05), " "a weekday (Saturday), a public holiday (Christmas Day), on record, A to B (June to August)") diff --git a/lib/service/current.py b/lib/service/current.py index ce79d4aa..08a759ba 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -60,13 +60,14 @@ "(\"weather now\", \"how's it outside\"): {}. How hot is it: {readings: [\"temperature\"]}. Is it raining: {readings: [\"rain\"]}. " "The air now: {readings: [\"air\"]}. With today's, this month's and this year's highs and lows beside each reading, as gauges show " "them (rain: its totals and wettest day; wind: its highest gust): {context: true}. A report, status or sitrep: current, forecast " - "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows, averages or a chart, " + "(period \"today\") and pollen, called together. Not for: will it rain (outlook); a period's highs, lows (\"lowest and highest " + "humidity\"), averages or a chart, " "a device or reading with a period, \"ecowitt week\", \"weather week\" (summary); values at set times (readings); the days ahead (forecast). Result: sensors.. (sensors.outdoor." "temperature) with value, unit, text ready to quote (\"12.3 °C\") and emoji when the reading is one to notice (put it right " "before the reading); rainfall.rain is today's rain so far; wind_direction has its compass point; the air " "sensor's have their rating (put it beside the value) and PM2.5 its US aqi_us and band. With context: today, month and year, each " - "with high and low (_text to quote, _when copied as written, \"at 3:05pm\" or \"around 3:30pm\", _date the day). lines: each " - "device's readings as bullet lines, to pass on as they are (headings: each one's heading for a report). missing: readings asked " + "with high and low (_text to quote, _when copied as written, _date the day). lines: each " + "device's readings as bullet lines, to pass on as they are (headings for a report). missing: readings asked " "for that aren't being read now; unavailable: a device not answering.") CONTEXT = {"type": "boolean", "description": "true to add today's, this month's and this year's highs and lows beside each of the " "weather station's readings that has them (temperature, humidity, pressure, dew point, " diff --git a/lib/service/relate.py b/lib/service/relate.py index ab003650..bf9bf37d 100644 --- a/lib/service/relate.py +++ b/lib/service/relate.py @@ -43,9 +43,10 @@ "PM10: is the air cleaner after rain (the 6 hours after each rain against the 6 before, wet days against dry). Any \"X against " "rain\" is this tool. Examples: \"does rain follow a pressure drop?\", \"is there a correlation between pressure and rainfall?\" " "{reading: \"pressure\"}; \"does humidity go with rain over the past year?\" {reading: \"humidity\", period: \"past year\"}; " - "\"does rain clear the air?\" {reading: \"pm2.5\"}; \"plot pressure against rainfall\" {reading: \"pressure\", chart: true}. " + "\"does rain clear the air?\", \"is there a correlation between air quality and precipitation?\" {reading: \"pm2.5\"}; \"plot pressure against rainfall\" {reading: \"pressure\", chart: true}. " "Not for: each air reading against every weather reading (scan); a chart of readings over time with no question of rain " - "(summary); rain totals, wet days or rain per month (days). " + "(summary); an air-quality rating drawn beside rain (\"plot the traffic light rating against rainfall\": summary {readings: " + "[\"pm2.5:rating\", \"rain\"]}); rain totals, wet days or rain per month (days). " "Result: open with `verdict` (yes, no or weak) in your own words, then the evidence in `findings`, as `how_to_read` says; " "say the two go together or not, never that one causes the other. `note` when there was nothing to compare: say exactly that.") diff --git a/lib/service/scan.py b/lib/service/scan.py index 90692bab..af82995f 100644 --- a/lib/service/scan.py +++ b/lib/service/scan.py @@ -35,7 +35,7 @@ "other readings?\" {reading: \"co2\"}; \"what goes with PM2.5 over the past year? show me\" {reading: \"pm2.5\", period: \"past " "year\", chart: true}. " f"At most {SCAN_MAX_DAYS} days: a longer period is cut to its latest {SCAN_MAX_DAYS}, and the result says so. " - "Not for: whether rain clears the air, or rain against any one reading (relate); a chart of readings over time (summary); the air " + "Not for: air quality against rain or precipitation, whether rain clears the air, or rain against any one reading (relate); a chart of readings over time (summary); the air " "now (current). " "Result: open with `verdict`, then the relationships in `findings`, strongest first, as `how_to_read` says: they go together, " "they don't cause each other. With `chart`, the strongest pair over time (none when nothing stands out).") diff --git a/lib/service/summary.py b/lib/service/summary.py index a1003e79..91a6dbb6 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -60,21 +60,21 @@ DATE = re.compile(r"\d{4}-\d\d-\d\d") DESCRIPTION = ( - "What was measured over a period (Ecowitt weather station, AirGradient air sensor): each reading's low and high with " - "when, averages, a by-day or by-month breakdown, the most common wind direction, rain that fell, air ratings " - "and AQI; and a chart of any readings.\n" - "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; a record with when (\"hottest " - "record\", \"highest ever\", \"use 5 minute data\": records are 5-minute where held) {readings: [\"outdoor.temperature\"], " - "period: \"on record\"}; \"average humidity last month\" {readings: [\"humidity\"], period: \"last month\", average: true}; \"plot " - "pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, chart_answers_it: true}; a device or reading " - "and a period (\"weather week\", \"ecowitt week\"): the past, charted {readings: [\"all\"], period: \"week\", chart: true}; a " - "rating and rain {readings: [\"pm2.5:rating\", \"rain\"]}.\n" - "`period` is the person's words unchanged: \"past week\" is the last 7 days, \"last week\" the previous Monday to Sunday: never " - "one for the other.\n" - "Not for: days ranked, counted or filtered by a day's figures (wettest day, days over 35°C, rain per month): days. " - "Values at set times: readings. Rain against a reading: relate. Now: current. Ahead: forecast.\n" - "Reading it: `series` by name; quote low_text and high_text with low_when and low_date, and day_look's emoji. rain_total_mm: rain " - "that fell. A chart's `caption` is ready; with complete: true, `reply` is the answer.") + "What was measured over a period: each reading's lowest and highest with when, " + "averages, a by-day or by-month breakdown, wind direction, rain that fell, air ratings and AQI; a chart of any.\n" + "Examples: \"how hot did it get this week\" {readings: [\"temperature\"], period: \"this week\"}; \"lowest and highest humidity\" " + "{readings: [\"humidity\"]} (today); \"is today hotter than yesterday\" {readings: [\"temperature\"], period: \"yesterday to " + "today\", every_day: true}; a record with when (\"hottest record\", \"highest ever\", \"use 5 minute data\") {readings: " + "[\"outdoor.temperature\"], period: \"on record\"}; average {readings: [\"humidity\"], period: \"last " + "month\", average: true}; \"plot pressure this week\" {readings: [\"pressure\"], period: \"this week\", chart: true, " + "chart_answers_it: true}; a device or reading and a period is the past, charted: \"weather week\", \"ecowitt week\" {readings: " + "[\"all\"], period: \"week\", chart: true}, \"wind 3m\" {readings: [\"wind\"], period: \"3m\", chart: true}; a rating and rain " + "{readings: [\"pm2.5:rating\", \"rain\"]}.\n" + "`period` is the person's words unchanged: \"past week\" is the last 7 days, \"last week\" the previous Monday to Sunday.\n" + "Not for: days ranked, counted or filtered (wettest day, days over 35°C, rain per month): days. Values at set times: readings. " + "A reading against rain: relate. Now: current. Ahead: forecast.\n" + "Result: `series` by name; quote low_text, high_text with low_when, low_date, and day_look's emoji. A chart's `caption` is " + "ready; with complete: true, `reply` is the answer.") def _boolean(description: str) -> dict: diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py index 8c7a89cc..4ec60dc6 100644 --- a/tests/test_service_relate.py +++ b/tests/test_service_relate.py @@ -74,6 +74,7 @@ async def test_it_takes_a_reading_whole_days_and_a_chart_and_says_what_it_is_not assert "Whole days only, up to yesterday" in props["period"]["description"] and "the last 90 days" in props["period"]["description"] assert all(name in props["reading"]["description"] for name in ("pressure.relative", "outdoor.humidity", "wind.wind_speed", "air.pm2_5", "air.pm10")) assert len(made.description) < 1500 and "\"X against rain\" is this tool" in made.description + assert '"plot the traffic light rating against rainfall": summary' in made.description # (a live run sent it here) assert all(f"({tool})" in made.description for tool in ("scan", "summary", "days")) and made.description.count("{reading:") >= 3 assert made.annotations == {"readOnlyHint": True, "openWorldHint": True} # the air sensor's missing days are fetched (station_only,) = relate.tools(Context(eco=eco, tz=TZ)) diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index b36c136d..e1f33442 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -58,11 +58,12 @@ async def test_the_tool_says_what_it_answers_what_it_is_not_for_and_how_to_read_ text = tool.description assert len(text) <= 1500 for words in ("{readings: [\"temperature\"], period: \"this week\"}", "chart_answers_it: true", "average: true", "\"all\"", "pm2.5", - ": days", ": readings", ": relate", ": current", ": forecast", "low_text", "day_look", "rain_total_mm", "complete"): + ": days", ": readings", ": relate", ": current", ": forecast", "low_text", "day_look", "complete"): assert words in text, words # what the live runs got wrong: a device and a period is the past; "past week" isn't "last week"; a record with when is summary's for words in ('"weather week"', '"ecowitt week"', 'the past, charted', '"past week" is the last 7 days', - '"last week" the previous Monday to Sunday', '"use 5 minute data"', 'period: "on record"', '"pm2.5:rating"'): + '"last week" the previous Monday to Sunday', '"use 5 minute data"', 'period: "on record"', '"pm2.5:rating"', + '"wind 3m" {readings: ["wind"], period: "3m", chart: true}', '"lowest and highest humidity"', 'period: "yesterday to today"'): assert words in text, words readings = tool.parameters["properties"]["readings"]["description"] assert "outdoor.temperature" in readings and "air.pm2_5" not in readings and readings.endswith( # (what this station holds) From 2a2f632391bf66efa045ed176ee67b5a74ac4ea0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:24:59 +0000 Subject: [PATCH 048/125] Step 3, the swap: the model gets the service's ten tools; the bot keeps its persona and a few shortcuts - lib/model_tools.py offers lib/service's ten tools as they are: each result kept whole on the Turn (charts as drawn, for drawing, period buttons, the complete result and the forecast days shown); the model is sent it with each chart as its title and period. - lib/prompt.py: the persona (a friendly Telegram bot, plain text, bullets, the caption a photo allows), then the server's instructions and the time. The rules about tools, periods, outlook, capabilities, hints and RIGHT NOW are gone. - lib/intent.py: the reasoning effort from the words, and the shortcuts as fixed service calls built directly: a named reading's chart and a period (summary with the words as said; the keyboard's and alerts' sentences), weather now, the report, the gauges. Every other question goes to the model; tool_choice is always auto. - The turn ends on a step whose every result is complete (its reply); the model's charts are drawn from their JSON with their own drawn_by behind the period buttons, and their other periods are uploaded ahead. A chart recorded by its question before the swap is out of date. - The twelve tools' definitions and handlers go (Ecowitt, AirGradient, Composer, History, Forecast, Pollen), with lib/service/legacy.py, the topic memory, the Turn's word inputs and the corrections from the words; the engines the service calls stay. report.py keeps only the heading entities. - Tests: rewritten onto the engines (tests/old_tools.py keeps the old handlers as the oracles); the pinned answers keep every shortcut byte-identical but "air quality chart 7d" (every air reading now); what goes to the model is listed. Evals: --live asks the model as the bot does (its prompt, the ten tools, its effort; a shortcut scored by its fixed calls); cases.json keeps the surviving decisions. - Scripts ported to the service: bench_storage, dump_specs, show_request, report_inputs. lib/service/summary.py: Turn's text is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 4 +- docs/mcp-service.md | 9 +- ecobot.py | 11 +- lib/airgradient/days.py | 22 +- lib/airgradient/source.py | 67 +- lib/alerts/pictures.py | 15 +- lib/bot.py | 379 ++---- lib/captions.py | 15 +- lib/compose.py | 80 +- lib/daytable.py | 52 +- lib/ecowitt/days.py | 38 +- lib/ecowitt/link.py | 35 +- lib/ecowitt/query.py | 4 +- lib/ecowitt/source.py | 104 +- lib/forecast/source.py | 31 - lib/history.py | 135 +- lib/intent.py | 873 ++---------- lib/llm.py | 28 +- lib/model_tools.py | 43 + lib/periods.py | 22 +- lib/pollen/source.py | 34 +- lib/prompt.py | 250 +--- lib/report.py | 132 +- lib/service/__init__.py | 4 +- lib/service/legacy.py | 198 --- lib/service/summary.py | 2 +- lib/sources.py | 10 +- lib/timeutil.py | 6 - lib/tools.py | 118 +- lib/topicmemory.py | 23 - scripts/bench_storage.py | 52 +- scripts/dump_specs.py | 124 +- scripts/eval_prompts.py | 58 +- scripts/report_inputs.py | 21 +- scripts/show_request.py | 62 +- tests/evalkit.py | 184 +-- tests/evals/cases.json | 844 +++--------- tests/old_tools.py | 257 ++++ tests/service_switch.json | 2293 +++++++------------------------- tests/test_admin_only.py | 15 +- tests/test_agent.py | 194 +-- tests/test_airgradient.py | 60 +- tests/test_alert_menu.py | 10 +- tests/test_alerts.py | 8 +- tests/test_bench_storage.py | 2 +- tests/test_bot.py | 305 ++--- tests/test_chart_answers.py | 219 +-- tests/test_chart_source.py | 24 - tests/test_compose.py | 21 - tests/test_contract.py | 24 - tests/test_days.py | 69 +- tests/test_ecowitt.py | 145 +- tests/test_evals.py | 34 +- tests/test_forecast.py | 15 +- tests/test_forecast_alert.py | 31 +- tests/test_history.py | 12 +- tests/test_intent.py | 663 ++------- tests/test_live_bands.py | 5 +- tests/test_minute_lines.py | 3 +- tests/test_periods.py | 122 +- tests/test_pollen.py | 23 +- tests/test_report.py | 66 - tests/test_service_about.py | 8 +- tests/test_service_base.py | 30 +- tests/test_service_current.py | 11 +- tests/test_service_evals.py | 3 - tests/test_service_forecast.py | 13 +- tests/test_service_legacy.py | 109 -- tests/test_service_pollen.py | 11 +- tests/test_service_readings.py | 5 +- tests/test_service_relate.py | 2 +- tests/test_service_summary.py | 15 +- tests/test_service_switch.py | 80 +- tests/test_snapshots.py | 6 +- tests/test_templates.py | 32 +- tests/test_tools.py | 41 - 76 files changed, 2135 insertions(+), 6940 deletions(-) create mode 100644 lib/model_tools.py delete mode 100644 lib/service/legacy.py delete mode 100644 lib/topicmemory.py create mode 100644 tests/old_tools.py delete mode 100644 tests/test_service_legacy.py delete mode 100644 tests/test_tools.py diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index c4093606..8a2fc025 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -6,7 +6,7 @@ How to test the bot and what the GitHub checks do. (Running it is in `README.md` ``` pip install -r requirements-dev.txt python -m pytest # runs in parallel (pytest.ini); `-n0` for one process -python scripts/eval_prompts.py # the saved questions: decisions made in code, no key needed +python scripts/eval_prompts.py # the saved questions: decisions made in code and the service expectations, no key needed ``` The suite takes about 25 s on four cores. The slowest fixture, the fake station's 18-month archive (`archived_cache` in `tests/conftest.py`), is built once an hour and shared by the workers and by later runs: it lives under pytest's own temp folder (`/tmp/pytest-of-/ecobot-archive-*.sqlite`), @@ -21,7 +21,7 @@ The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build t |---|---|---| | `test` | every push to `main` and every pull request | the exact versions in `requirements.txt`: pytest (chart pictures included) and the offline evals. The gate. | | `newest` | Sundays 21:17 UTC, or the Run workflow button | the tests with the newest Pillow. Advisory. | -| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` (`python scripts/eval_prompts.py --live`) and checks which tool it calls; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 87. Skipped until the secrets below exist. | +| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` as the bot asks it (`python scripts/eval_prompts.py --live`: its prompt and the service's ten tools) and checks which tool it calls against `tests/evals/service_cases.json`; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 94. Skipped until the secrets below exist. | | `image` | pushes that change `Dockerfile`, `.dockerignore` or `requirements.txt` (any branch), or the Run workflow button | builds the Docker image, checks the bot starts in it and names the commit, draws the sample charts in it (they must be in Inter and match `tests/charts`); the image's size goes in the run's summary. | Repository secrets (Settings, Secrets and variables, Actions, New repository secret): diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a50a39d3..59e76828 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -490,7 +490,14 @@ Each step ships on its own, with the tests and evals green and the bot working t the air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period - hints, the prefetch and the corrections from the words go. + hints, the prefetch and the corrections from the words go. The bot offers the ten as they are (`lib/model_tools.py`: each result + kept whole for drawing and its buttons, the model sent it with each chart as its title and period), with its persona, the server's + instructions and the time (`lib/prompt.py`); tool_choice is the model's own, the reasoning effort still comes from the words. Its + shortcuts (`lib/intent.py`) are fixed calls built directly: a named reading's chart and a period (summary with the person's words + for both, the keyboard's and the alerts' sentences among them), weather now, the report (current, pollen, the next 3 days' + forecast) and the gauges; everything else it answered in code goes to the model. The turn ends on a step whose every result is + complete. `lib/service/legacy.py` is gone; the `Turn` is only the engines' options, set by the service from its arguments. `--live` + asks the model as the bot does (its prompt, the ten tools; a question answered in code is scored by its fixed calls). 4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the diff --git a/ecobot.py b/ecobot.py index b1b84837..4ec8e523 100644 --- a/ecobot.py +++ b/ecobot.py @@ -42,10 +42,9 @@ from lib.service import names as service_names from lib.service.context import Context from lib.compose import Composer -from lib.history import History from lib.sources import Source from lib.storage import Storage -from lib.tools import Tools +from lib import model_tools from lib.warm import every, safely @@ -254,8 +253,6 @@ async def main(): eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") charts.configure(cfg.dark_mode, cfg.tz) # DARKMODE (in the station's time zone, as everything from here on) composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources - history = await History.open(eco, air) if eco or air else None # the readings tool: values at an interval, from the file - tools = Tools([t for s in sources for t in s.tools] + (composer.tools if composer else []) + (history.tools if history else [])) client = _client(cfg) if cfg.openrouter_api_key else None # without a key the bot answers only what it works out in code if client: stack.push_async_callback(safely, client.close) @@ -269,12 +266,12 @@ async def main(): if irrigation: stack.push_async_callback(safely, irrigation.close) tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) - # The service's ten tools over the sources that started (lib/service): the bot's own code paths call them (its shortcuts, lookups, - # report, alert charts and period buttons); the model is still offered the old tools above, until step 3 + # The service's ten tools over the sources that started (lib/service): the model is offered them (lib/model_tools.py), and the + # bot's own code paths call them (its shortcuts, report, gauges, alert charts and period buttons) service = Service.of(await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), pollen=by_name.get("Pollen"), tz=cfg.tz)) log.info("Service tools: %s", ", ".join(t.name for t in service)) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, tools), sources, state, irrigation, tasks, service=service) + bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(service)), sources, state, irrigation, tasks, service=service) bot.register(app) stop = asyncio.Event() diff --git a/lib/airgradient/days.py b/lib/airgradient/days.py index fa8469b0..59af30b5 100644 --- a/lib/airgradient/days.py +++ b/lib/airgradient/days.py @@ -1,14 +1,12 @@ -"""air_days: find, rank, count and total days by the air-quality sensor's readings, from the day rows alone (it never asks +"""Find, rank, count and total days by the air-quality sensor's readings, from the day rows alone (it never asks AirGradient; storage.days works each day out as its readings are written, the sensor's glitches taken out). The same fields as a day's highest (_max), lowest (_min) or mean (_avg) of each metric, e.g. pm2_5_max > 25 for the days particles passed 25 µg/m³. The counting, -ranking, grouping and bar charts are shared with weather_days (lib/daytable.py).""" +ranking, grouping and bar charts are shared with the station's (lib/daytable.py); lib/service/days.py reads the day rows itself.""" import logging from datetime import datetime, tzinfo -from ..daytable import analyse, grouped_as_asked, parameters, prepare -from ..timeutil import now_local -from ..tools import json_result +from ..daytable import analyse, prepare from .metrics import ALL_METRICS, CHART_UNITS log = logging.getLogger(__name__) @@ -17,16 +15,6 @@ FIELDS = {f"{m}_{kind}": CHART_UNITS[m] for m in ALL_METRICS for kind in SUFFIX_KIND} ALWAYS_SHOWN = ("pm2_5_max",) # every listed day shows it; days rank by it when nothing else is named -PARAMETERS = parameters(list(FIELDS), "pm2_5_max > 25 and co2_max > 800") -DESCRIPTION = ("Find, rank or count DAYS by the air-quality sensor's readings, from the stored history (any period, fast): for " - "questions like \"how many days was PM2.5 over 25\", \"the worst air day each month\", \"days CO2 passed 800\". " - "Fields: for each of pm1, pm2_5, pm10, co2, voc_index, nox_index a day's highest (_max), lowest (_min) or mean (_avg), " - "e.g. pm2_5_max >= 25 (µg/m³; a rating's limits are 9 and 55.4 for PM2.5). For \"how many\" use count_only; group_by " - "month or year breaks it down and draws a bar chart. For a highest, lowest, average or total per month or year use stat " - "and of (\"worst PM2.5 each month\": stat max, of pm2_5_max; \"average CO2 per year\": stat avg, of co2_avg). Returns the " - "total of matching days and the top ones.") - - async def find_air_days(store, tz: tzinfo, args: dict, now: datetime, turn=None) -> dict: """The answer, from one read of the day rows (readings.AirReadings.day_figures).""" asked = prepare(args, FIELDS, ALWAYS_SHOWN, now.date()) @@ -49,7 +37,3 @@ async def find_air_days(store, tz: tzinfo, args: dict, now: datetime, turn=None) out["note"] = "No stored readings for this period yet (the bot may still be downloading history)." log.info("Air days %s to %s: %d checked, %d match", asked.first, asked.last, len(checked), len(got.matches)) return out - - -async def air_days_tool(store, tz: tzinfo, args: dict, turn=None) -> str: - return json_result(await find_air_days(store, tz, grouped_as_asked(args, turn), now_local(tz), turn)) diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 55743019..11836878 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -20,7 +20,6 @@ """ import asyncio -import copy import statistics import logging import time @@ -31,7 +30,7 @@ import httpx from .. import intent -from ..captions import CHART_ANSWERS_IT, CHART_HINT, wants_chart +from ..captions import CHART_HINT, wants_chart from ..config import Config from ..sources import Source from ..ecowitt.homeassistant import HomeAssistant @@ -39,13 +38,12 @@ from ..ecowitt.query import KEEP_HOURS, MINUTE_HOURS from ..lines import RANGE_KEEP_DAYS, Plotted, Sample, build_line, readings_mean from ..panels import panel_for -from ..specs import AIR_SOURCE, Chart, Line +from ..specs import Chart, Line from ..storage import Storage from ..storage.catalogue import BOT, CLOUD, HOME_ASSISTANT from ..timeutil import day_bounds, day_text, local_date, local_epoch, parse_local, to_local, when -from ..tools import Tool, Turn, json_result +from ..tools import Turn from ..warm import Warmer -from .days import DESCRIPTION as DAYS_DESCRIPTION, PARAMETERS as DAYS_PARAMETERS, air_days_tool from . import metrics from .metrics import AIR_PANELS, ALL_METRICS, EXTRA, EXTRA_LABELS, EXTRA_UNITS, MARK_LOW, LABELS, METRICS, STORED, normalise, pm25_aqi, rating, value_of, without_spikes from .homeassistant import (ANCHORS, MIN_COMPARED, checked, entity_ids, find_prefix, live as ha_live, minutes as ha_minutes, ranges as ha_ranges, @@ -78,37 +76,8 @@ BACKFILL_FAIL_STOP = 3 # this many failed requests in a row: give up until the next start BACKFILL_MAX_DAYS = 1460 -PARAMETERS = { - "type": "object", - "properties": { - "chart": {"type": "boolean", "description": "Set true to send a chart (graph) with the answer. Without dates, " - "it covers the last 24 hours."}, - "chart_answers_it": CHART_ANSWERS_IT, - "metrics": {"type": "array", "items": {"type": "string", "enum": list(LABELS)}, - "description": "Which metrics to chart (several are drawn as panels in one image; " - "for 'all', list all six). Default: the reading the person named, else pm2_5."}, - "start_date": {"type": "string", "description": "Start of a past period, 'YYYY-MM-DD HH:MM:SS' local time. " - "Omit (with end_date) for the current reading."}, - "end_date": {"type": "string", "description": "End of the past period, 'YYYY-MM-DD HH:MM:SS' local time."}, - }, -} -DESCRIPTION = ("Air quality from the owner's AirGradient outdoor sensor: PM2.5 (with US AQI and band), PM10, " - "PM1, CO2, VOC and NOx indexes, each with a traffic-light rating. No dates: the current reading. " - "With start_date/end_date (up to about a year): lowest, highest and average of each, with when they " - "happened. chart=true sends a graph.") - - -def asked() -> tuple[str, dict]: - """air_quality as a question about the sensor's own temperature or humidity is offered it: those two as metrics too.""" - parameters = copy.deepcopy(PARAMETERS) - parameters["properties"]["metrics"]["items"]["enum"] = [*LABELS, *EXTRA] - parameters["properties"]["metrics"]["description"] += " air_temperature and air_humidity are the sensor's own temperature and humidity." - return (DESCRIPTION + " With metrics air_temperature / air_humidity it gives the sensor's own temperature (°C) and humidity (%), only " - "when the question names the AirGradient's.", parameters) - - class Latest(NamedTuple): - """The latest reading as the air_quality tool gives it, and what the particulates alert also needs.""" + """The latest reading (as the service's current reads it), and what the particulates alert also needs.""" reading: dict # the sensor, the time, and each metric's value, unit and rating at: datetime | None # when it was taken (UTC) sustained: dict[str, float] # each metric's lowest over the last REQUIRE_CONSECUTIVE readings: what the air has been that long @@ -153,8 +122,6 @@ def __init__(self, cfg: Config, transport=None, ha: HomeAssistant | None = None, self._ha_said: set[str] = set() # what was said once about it: no sensor, a metric that is another variant self._verdict: dict[int, dict[str, tuple[int, int]]] = {HOME_ASSISTANT: {}, CLOUD: {}} # per source, per metric: (five minutes compared, agreed) self._correction: str | None = None # how the monitor corrects its PM2.5, from its own configuration - self.tools = [Tool("air_quality", DESCRIPTION, PARAMETERS, self.handle, asked=asked, source=AIR_SOURCE), - Tool("air_days", DAYS_DESCRIPTION, DAYS_PARAMETERS, self._days, source=AIR_SOURCE)] async def start(self): try: @@ -307,9 +274,6 @@ def _judge(self, src: int, rows: list[dict], others: list[dict]) -> list[dict]: SOURCE_NAMES[src], label, v[1], v[0], FIX.get(name, "check the correction each applies")) return [row for r in rows if len(row := self._allowed(r, src)) > 1] - def describe(self) -> str: - return f"AirGradient outdoor air-quality sensor (location {self.loc}) (people say \"ag\", \"airgradient\", \"air gradient\", \"aq\" or \"air quality\")" - def wants(self, text: str) -> bool: """Should a question start refreshing this source? Only air-quality questions.""" return intent.mentions_air(text) @@ -577,25 +541,6 @@ async def backfill(self, pace: float | None = None, empty_stop: int | None = Non return fetched, failed, total return fetched, failed, total - # ---------- the tool ---------- - async def handle(self, args: dict, turn: Turn | None = None) -> str: - """The air_quality tool: current reading, or a summary of a past period.""" - turn = turn or Turn() - try: - turn.air_extra_used = turn.air_extra_used or any(m in EXTRA for m in args.get("metrics") or []) - chart = wants_chart(args, turn) - if args.get("start_date") or args.get("end_date") or chart: - return json_result(await self.history(args.get("start_date"), args.get("end_date"), - chart=chart, metrics=args.get("metrics"), turn=turn)) - return json_result(await self.current([m for m in args.get("metrics") or [] if m in EXTRA])) - except Exception as e: - log.warning("AirGradient request failed: %s", e) - return f"Error: couldn't read the air-quality sensor ({e})" - - async def _days(self, args: dict, turn: Turn | None = None) -> str: - """The air_days tool: count, rank and total days from the stored readings.""" - return await air_days_tool(self.store, self.tz, args, turn) - async def _previous_rows(self, ts: int, count: int) -> list[dict]: """Up to `count` of today's cached readings just before `ts`, each within MAX_GAP_SECONDS of the next, oldest first.""" today = to_local(ts, self.tz).date() @@ -640,10 +585,6 @@ async def latest(self, extras: list[str] = ()) -> Latest: reading[name] = {"value": v, "unit": EXTRA_UNITS[name]} return Latest(reading, at, sustained) - async def current(self, extras: list[str] = ()) -> dict: - """The latest reading as the air_quality tool gives it (see latest); `extras`: the sensor's own temperature and humidity, if asked.""" - return (await self.latest(extras)).reading - async def rows(self, t0: datetime, t1: datetime) -> tuple[list[dict], int, list[date]]: """(readings in [t0, t1] (naive local times), days that only exist as hourly averages, older days still waiting for the backfill and left out). Finished days not yet stored are fetched first, up to MAX_INLINE_DAYS. A single-reading spike diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index f70963b4..39e1e89a 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -1,6 +1,6 @@ """The chart that goes with an alert: the same picture a typed request for it would give ("Wind chart 1d" is what the Wind button sends), so what an -alert shows is defined once, by the button sentences, which the bot reads as a service call (lib/intent, lib/service/legacy.py: "Wind chart 1d" is -summary over the wind for the last 24 hours) and the service draws. AlertCharts keeps those charts with the bot's other charts (the ImageCache, +alert shows is defined once, by the button sentences, each a fixed service call (lib/intent.chart_call: "Wind chart 1d" is summary +{readings: ["wind"], period: "1d", chart: true}), which the service draws. AlertCharts keeps those charts with the bot's other charts (the ImageCache, by call), so one is drawn once and uploaded once however many times it is sent.""" import asyncio @@ -15,7 +15,6 @@ from ..periods import call_key from ..specs import from_json from ..timeutil import now_local -from ..tools import Turn log = logging.getLogger(__name__) @@ -34,13 +33,7 @@ class Picture(NamedTuple): def call_of(text: str, now: datetime, tz: tzinfo) -> tuple[str, dict] | None: """The service call a chart's request is read as (`now`: the station's local time), or None.""" - from ..service import legacy - if now.tzinfo is not None: - now = now.astimezone(tz).replace(tzinfo=None) - read = intent.read(text, now) - if not read.fast: - return None - return legacy.translate(read.fast[0], read.fast[1], Turn.of(read, text), now=now, tz=tz) + return intent.chart_call(text, now, tz) def _service_of(source, tz): @@ -57,8 +50,6 @@ async def chart(source, text: str, tz, service=None) -> Picture | None: try: tool, args = call_of(text, now_local(tz), tz) service = service or _service_of(source, tz) - if isinstance(args.get("readings"), list): # (those the service holds: a side the station has nothing of is left out) - args = {**args, "readings": service.held(args["readings"]) or args["readings"]} out = json.loads(await service[tool].call(args, {"chart_points": CHART_POINTS})) if "error" in out: raise ValueError(out["error"]) diff --git a/lib/bot.py b/lib/bot.py index 3583426a..20953c05 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -13,7 +13,7 @@ import time from collections import defaultdict from collections.abc import Coroutine -from dataclasses import dataclass, field, replace +from dataclasses import dataclass, field from datetime import datetime, UTC from typing import NamedTuple @@ -31,19 +31,17 @@ from . import gauges from .charts import render_data from .service import Service -from .service import legacy from .service.common import AS_DRAWN, BACKGROUND from .service.context import Context -from .specs import from_json, to_json +from .service.instructions import instructions +from .specs import from_json from . import gauge_sheet -from .ecowitt.query import chart_field, stack_names from .tools import Turn from .config import Config from .entities import utf16_len, with_link from .sources import Source from .timeutil import clock_text, day_text, now_local from .llm import Agent, shorten_old, strip_tool_turns, trim_history -from .topicmemory import TopicMemory from .logs import BUGS, QUOTES, fit log = logging.getLogger(__name__) @@ -51,8 +49,6 @@ TG_LIMIT = 4000 CAPTION_LIMIT = 1024 # what Telegram lets a photo's caption hold MAX_CHARTS = 3 -DAY_TOOLS = ("weather_days", "air_days") -ANSWERING_CHARTS = ("weather_history", "air_quality", *DAY_TOOLS) # the tools whose chart can be the whole answer (chart_answers_it) RETRY_SECONDS = 60 # the second try, one reasoning step lower, after a question timed out PENDING_MAX_SECONDS = 10 * 60 # a message that waited longer (the bot was down) is not answered: its moment has passed TURN_SECONDS = 90 # a question that takes longer is given up on, so the ones queued behind it in the chat are not stuck @@ -74,16 +70,16 @@ "In a private chat the buttons under the message box ask common questions; /keyboard off hides them.\n" "Your user ID: {user} | Chat ID: {chat}") NO_MODEL = ("Sorry, that one needs the AI model, and this bot has none set up.\n" - "Without it I can still do: /report, the chart commands (/rain, /weather, /temperature, /humidity, /air_quality, /particulates, " - "/wind) and plain questions like \"how hot is it?\", \"is it raining?\", \"air quality now\", \"highest humidity yesterday\", " - "\"rain chart 7d\" or \"forecast\", as well as all the alerts.") + "Without it I can still do: /report, /dashboard, the chart commands (/rain, /weather, /temperature, /humidity, /air_quality, " + "/particulates, /wind), \"weather now\" and a reading's chart over a period like \"rain chart 7d\" or \"humidity 30d\", " + "as well as all the alerts.") +OUT_OF_DATE = "That chart is out of date, please ask again" @dataclass class ChatState: history: list[dict] = field(default_factory=list) lock: asyncio.Lock = field(default_factory=asyncio.Lock) - topics: TopicMemory = field(default_factory=TopicMemory) # the guidance topics this chat is still on (the air sensor's own readings among them) @dataclass @@ -191,35 +187,30 @@ def strip_chart_talk(text: str) -> str: return "\n".join(lines).strip() or text -# The notes a caption written here passes on itself (report.chart_caption, report.lookup); any other note needs the model's words -CAPTIONED_NOTES = {"weather_history": {"note_missing", "warning", "missing"}, "air_quality": {"note_missing", "warning", "missing"}, - **{tool: {"note_averaged"} for tool in DAY_TOOLS}} - - -def _drew_chart(result: str) -> bool: - """Does this tool result say it drew a chart (the "chart" note a tool adds when it does)?""" - try: - data = json.loads(result) - except ValueError: - return False - return isinstance(data, dict) and "chart" in data and "error" not in data - - -def _needs_words(tool: str, result: str) -> bool: - """Does this result carry a note the person should hear that a caption written here would leave out (a month's figures without - dates, the older days held only as daily records or hourly averages, a rarer day that nearly counted ...)? Then the model answers.""" - data = json.loads(result) - notes = {k for k in data if k.startswith("note") or k.endswith("_note") or k in ("warning", "missing", "exact_from", "trace_rain_days")} - return bool(notes - CAPTIONED_NOTES.get(tool, set())) +def complete_reply(results: list[str]) -> str | None: + """The reply of a step whose every result is complete (docs/mcp-service.md 3.7: `complete: true`, a chart made and its `reply` + ready): the replies in order; None when any isn't.""" + replies = [] + for result in results: + try: + data = json.loads(result) + except ValueError: + return None + if not isinstance(data, dict) or data.get("complete") is not True or not data.get("reply") or not data.get("charts"): + return None + replies.append(str(data["reply"])) + return "\n\n".join(replies) if replies else None -def _as_drawn(tool: str, args: dict, turn: Turn) -> tuple[dict, Turn]: - """(args, turn) as the tool read them to draw its chart, so its caption speaks of what the chart shows: the readings the person's - words name, else the model's (air quality: its metrics, else those named, else PM2.5), and an average if either asked for one.""" - if tool == "air_quality": - return {**args, "metrics": args.get("metrics") or turn.air_named or ["pm2_5"]}, turn - return args, replace(turn, chart_field=chart_field(args, turn), chart_fields=stack_names(args, turn), - average_asked=turn.average_asked or bool(args.get("average"))) +def reads_air(result: dict) -> bool: + """Did this result read the air sensor (a reading of it, or a chart or a day from it)?""" + def walk(value) -> bool: + if isinstance(value, dict): + return any(str(k).startswith("air.") or k == "air" or walk(v) for k, v in value.items()) + if isinstance(value, list): + return any(walk(v) for v in value) + return isinstance(value, str) and "AirGradient" in value + return walk(result) def chat_tag(chat_id: int) -> str: @@ -411,8 +402,8 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); its own when none is given. service: the service's tools (lib/service), which the bot's own code paths call (its shortcuts, - lookups, report, alert charts and period buttons); built over `sources` when none is given. The model is offered the old - tools (agent.tools), not these, until step 3.""" + report, gauges, alert charts and period buttons); built over `sources` when none is given. The model is offered the same tools + (agent.tools: lib/model_tools.py), with the server's instructions (instructions(service.ctx)) after the bot's persona.""" self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation self._service = service self.tasks = tasks or Tasks() @@ -456,50 +447,22 @@ async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dic return {"error": f"{type(e).__name__}: {e}"} return out if isinstance(out, dict) else {"error": "not an answer"} - def _call_of(self, read, turn: Turn, now: datetime) -> tuple[str, dict] | None: - """The service's call for the fast path's old tool call (lib/service/legacy.py), or None.""" - if not read.fast: - return None - try: - return self._held_call(legacy.translate(read.fast[0], read.fast[1], turn, now=now, tz=self.cfg.tz)) - except Exception as e: - log.error("Couldn't read %s as a service call (%s: %s)", read.fast[0], type(e).__name__, e, exc_info=isinstance(e, BUGS)) - return None + def _catalogue(self): + """The readings the service holds (the words of a shortcut are read against them): its Context's, else those of the sources the + bot has.""" + ctx = getattr(self.service, "ctx", None) + if ctx is not None: + return ctx.readings() + from .service.names import Catalogue + return Catalogue.of(station="Ecowitt" in self.by_name, air="AirGradient" in self.by_name) - def _held_call(self, call: tuple[str, dict] | None) -> tuple[str, dict] | None: - """The call with its readings (full names) cut to those the service holds: the old tools read whichever groups the station has, - so "temperature" was outdoor and indoor, and a side with nothing held was left out quietly.""" - if call is None or call[0] != "summary" or not isinstance(call[1].get("readings"), list): - return call - held = self.service.held(call[1]["readings"]) - return (call[0], {**call[1], "readings": held}) if held else call - - def _model_drawn_by(self, turn: Turn, i: int, now: datetime) -> dict | None: - """A drawn_by for the i-th chart the model drew through the old tools (it has none of its own until step 3): its call read as the - service's, with the periods that tool would list; None when the call has no service equivalent or lists no periods (its question - is asked again).""" - if i >= len(turn.chart_calls): - return None - name, args = turn.chart_calls[i] - try: - call = self._held_call(legacy.translate(name, args if isinstance(args, dict) else {}, turn, now=now, tz=self.cfg.tz)) - except Exception as e: - log.debug("The model's %s chart has no service call (%s: %s)", name, type(e).__name__, e) - return None - if call is None or call[0] not in ("summary", "days"): - return None - tool, arguments = call[0], {k: v for k, v in call[1].items() if k != "chart_answers_it"} - if tool == "summary": - arguments["chart"] = True - listed = legacy.periods_of(tool, arguments) - if not listed: # a period the service can't word (times...): its question is asked again, so the chart keeps its buttons - return None - return {"tool": tool, "arguments": arguments, "periods": listed} + def _instructions(self) -> str: + """The server's instructions (lib/service/instructions.py) over the service's Context.""" + return instructions(getattr(self.service, "ctx", None)) def _sentence_call(self, text: str, now: datetime) -> tuple[str, dict] | None: - """The call a question is read as when it is a chart made in code ("Wind chart 1d"); None for any other.""" - read = intent.read(text, now, self.by_name) - return self._call_of(read, Turn.of(read, text), now) if read.chart_in_code else None + """The call a keyboard sentence ("Wind chart 1d") is: a named reading's chart and a period (intent.chart_call); None for any other.""" + return intent.chart_call(text, now, self.cfg.tz, self._catalogue()) def _draw(self, chart: dict, times: dict | None = None) -> tuple[bytes, str, int]: """(PNG, title, the time of its newest reading) of a chart given as data.""" @@ -897,10 +860,9 @@ async def on_report_button(self, update: Update, context: ContextTypes.DEFAULT_T if query.data == report_menu.DASHBOARD: await self._redraw_dashboard(query) return - read = intent.read("Report", now_local(self.cfg.tz), self.by_name) pictured = bool(getattr(getattr(query, "message", None), "photo", None)) # the report is the caption of its gauges: they are drawn again too try: - text, gauge = await self._report(read, Turn(text="Report"), pictured) + text, gauge = await self._report(True, [], pictured) except Exception as e: # the message stays as it was log.warning("Report refresh failed: %s", e) await answer_query(query, "Couldn't refresh, please try again", show_alert=True) @@ -943,8 +905,7 @@ async def _recaption(query, text: str, photo: bytes | None): async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """A press on a period button under a chart: the chart's call (its drawn_by) replayed with that period, by the service, and the new chart put in the same message (from the picture cache when it was drawn lately). A replay the service refuses shows its - refusal on the button. A chart the service can't replay (one the model drew with a call it has no equivalent of) asks its - question again for that period instead.""" + refusal on the button. A chart recorded before its drawn_by was kept (its question, from before step 3) is out of date.""" query = update.callback_query message = query.message record = self.charted.get(message.chat_id, message.message_id) if message else None @@ -960,19 +921,7 @@ async def on_period_button(self, update: Update, context: ContextTypes.DEFAULT_T with contextlib.suppress(TelegramError): await message.reply_text(CHART_FAILED) return - days = periods.days_in(query.data) - question = record if isinstance(record, str) and days else None - if not question: - await answer_query(query, "That chart is out of date, please ask again") - return - now = now_local(self.cfg.tz) - if intent.period_days(question, now) == days: # the chart already shows this period - await answer_query(query) - return - await answer_query(query, f"Drawing {periods.NAMES[days]}...") - asked = intent.with_period(question, days, now) - log.debug("Period button %s: %s", periods.NAMES[days], question, extra=QUOTES) - await self.respond(update, context, asked, redraw=message) + await answer_query(query, OUT_OF_DATE) async def _replay(self, query, message: Message, record: dict, bot, answered: list[str] | None = None): """A period button under a chart the service drew: its drawn_by replayed with the period pressed, into the same message. @@ -990,7 +939,7 @@ async def drawing(label: str): listed = {p["period"]: p["label"] for p in drawn_by.get("periods") or ()} reload = period == periods.RELOAD and not listed # the 🔄 under a chart with no periods that runs to now: drawn again as it is if period not in listed and not reload: - await answer_query(query, "That chart is out of date, please ask again") + await answer_query(query, OUT_OF_DATE) return now = now_local(self.cfg.tz) refresh = False # the chart's own shaded 1D pressed: drawn again with the latest readings @@ -1178,33 +1127,37 @@ def _content(self, msg: Message, text: str, bot_id: int) -> str: sender = msg.from_user.full_name if msg.from_user else "Someone" return f"{sender} ({reply}): {text}" if reply else f"{sender}: {text}" - async def _written_in_code(self, read, turn: Turn) -> str: + async def _written_in_code(self, report: bool, shown: list, ahead: bool = False) -> str: """The report, or "weather now", in the service's words: the readings now (current: each device's heading and lines), then the - pollen's and the forecast's own text, the calls made together.""" - calls = legacy.report(self.by_name) if read.report else [("current", {})] - results = await asyncio.gather(*(self._service_call(name, args, ahead=turn.ahead) for name, args in calls)) + pollen's and the forecast's own text, the calls made together (intent.report_calls; "weather now": current {}). The forecast + days it shows go into `shown`.""" + calls = intent.report_calls(self.by_name) if report else [intent.WEATHER_NOW_CALL] + results = await asyncio.gather(*(self._service_call(name, args, ahead=ahead) for name, args in calls)) by_tool = {name: out for (name, _), out in zip(calls, results)} now = by_tool.get("current") or {"error": "none"} - if not read.report: + if not report: if "error" in now or "station" in (now.get("unavailable") or {}) or not (now.get("lines") or {}).get("station"): return "The weather station isn't answering right now." return "\n".join(now["lines"]["station"]) sections = [] if "error" in now else [ "\n".join([now["headings"][device], *now["lines"][device]]) for device in ("station", "air") if device in now.get("lines", {})] sections += [out["text"] for name in ("pollen", "forecast") if (out := by_tool.get(name)) and out.get("text")] - self._shown_forecast(by_tool.get("forecast"), turn) + shown.extend(self._shown_forecast(by_tool.get("forecast"))) return "\n\n".join(sections) or "No readings are available right now." - def _shown_forecast(self, out: dict | None, turn: Turn): - """The forecast days an answer shows, remembered for the chat once it is sent (a later revision of them is worth telling it).""" + def _shown_forecast(self, out: dict | None) -> list: + """The forecast days a forecast result shows (the Forecast source's own), remembered for the chat once the answer is sent (a later + revision of them is worth telling it).""" source = self.by_name.get("Forecast") - if source is not None and out and "error" not in out and out.get("days"): - shown = {day["date"] for day in out["days"]} - turn.forecast_shown.extend(d for d in source.days or [] if d["date"].isoformat() in shown) - - async def _report(self, read, turn: Turn, gauges: bool) -> tuple[str, bytes | None]: - """The report (or "weather now") written in code and, with `gauges`, its picture drawn alongside (None without one), in TURN_SECONDS.""" - written = self._written_in_code(read, turn) + if source is None or not out or "error" in out or not out.get("days"): + return [] + shown = {day.get("date") for day in out["days"] if isinstance(day, dict)} + return [d for d in source.days or [] if d["date"].isoformat() in shown] + + async def _report(self, report: bool, shown: list, gauges: bool) -> tuple[str, bytes | None]: + """The report (or "weather now") written in code and, with `gauges`, its picture drawn alongside (None without one), in + TURN_SECONDS. The forecast days it shows go into `shown`.""" + written = self._written_in_code(report, shown) if gauges: return tuple(await asyncio.wait_for(asyncio.gather(written, self._status_gauges()), TURN_SECONDS)) return await asyncio.wait_for(written, TURN_SECONDS), None @@ -1228,12 +1181,10 @@ async def _warn(self, msg: Message, tokens: int): with contextlib.suppress(TelegramError): await msg.reply_text(text) - async def _chart_in_code(self, call: tuple[str, dict] | None, turn: Turn) -> Made | None: - """A chart asked for plainly: the service tool the fast path's call means (summary, days ...) draws it and its caption (days: - its answer) goes with it. None (the model then takes the question) when it drew nothing or has nothing to say.""" - if call is None: - return None - out = await self._service_call(*call, ahead=turn.ahead) + async def _chart_in_code(self, call: tuple[str, dict]) -> Made | None: + """A named reading's chart and a period (intent.chart_call): the service draws it and its caption goes with it. None (the model + then takes the question) when it drew nothing or has nothing to say.""" + out = await self._service_call(*call) text, charts = out.get("caption") or out.get("answer"), out.get("charts") or [] return Made(text, charts) if "error" not in out and charts and text else None @@ -1251,73 +1202,32 @@ async def _dashboard(self) -> Answer: title = f"Weather station dashboard, {day_text(now)} {clock_text(now)}" return Answer(title, [await asyncio.to_thread(gauges.render, sheet)], [title], silent=True) - async def _lookup_in_code(self, read, turn: Turn, now: datetime) -> Made | None: - """A plain lookup (a reading, the air, a day's figures or a count, a short period's highs and lows, the pollen, the forecast, - what the bot can do) answered in its service tool's own words: current's lines, days' answer (with its chart, if it drew one), - summary's text, pollen's and forecast's text, about's lines. None (the model then takes the question) when it can't be.""" - call = legacy.lookup(read) or self._call_of(read, turn, now) - if call is None: - return None - out = await self._service_call(*call, ahead=turn.ahead) - if "error" in out: - return None - tool, kind = call[0], read.lookup - if tool == "current": - device = "air" if kind == "air" else "station" - lines = (out.get("lines") or {}).get(device) - return Made("\n".join(lines)) if lines and device not in (out.get("unavailable") or {}) else None - if tool == "about": - return Made("\n".join(out.get("lines") or []) or None) - if tool == "forecast": - self._shown_forecast(out, turn) - return Made(out.get("answer") or out.get("text") or None, out.get("charts") or []) - - def _chart_answer(self, turn: Turn): - """The model loop's finish: when each call the model made in a step set chart_answers_it, drew its chart and can be captioned - here, their captions in order are the reply and the model is asked nothing more; else None, and the model answers as usual.""" - def finish(calls: list[dict], results: list[str]) -> str | None: - try: - captions = [self._answer_caption(call, result, turn) for call, result in zip(calls, results)] - except Exception as e: # the model answers instead - log.error("Couldn't caption a chart that answers the question (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - return None - return None if None in captions else "\n\n".join(captions) - return finish - - def _answer_caption(self, call: dict, result: str, turn: Turn) -> str | None: - """One call's chart as the whole answer: its caption, written from the tool's result as for a chart made in code (the day tools: - as for a days lookup); None when the call didn't set chart_answers_it, drew no chart, failed or left nothing to caption.""" - try: - args = json.loads(call["arguments"] or "{}") - except ValueError: - return None - if (call["name"] not in ANSWERING_CHARTS or not isinstance(args, dict) or args.get("chart_answers_it") is not True - or not _drew_chart(result) or _needs_words(call["name"], result)): - return None - if call["name"] in DAY_TOOLS: - return report.lookup("days", result, [], [], now_local(self.cfg.tz).date()) - args, drawn = _as_drawn(call["name"], args, turn) - return report.chart_caption(call["name"], args, result, drawn, self.cfg.tz) + @staticmethod + def _complete(calls: list[dict], results: list[str]) -> str | None: + """The model loop's finish: when every call of a step gave a complete result (docs/mcp-service.md 3.7: its chart and its ready + reply), their replies in order are the answer and the model is asked nothing more; else None, and the model answers as usual.""" + return complete_reply(results) async def _ask_model(self, working: list[dict], system: str, read, turn: Turn, draft, on_heavy=None) -> str: - """The model's answer. If it has not answered in TURN_SECONDS, ask again once with one reasoning step less (medium > low > - none), for RETRY_SECONDS; a question already at no reasoning just times out. A chart that answers the question by itself - ends the turn with its caption written here (_chart_answer).""" - first = [*([read.fast[:2], *read.more] if read.fast else []), *read.extra] or None + """The model's answer, with the service's tools. If it has not answered in TURN_SECONDS, ask again once with one reasoning step + less (medium > low > none), for RETRY_SECONDS; a question already at no reasoning just times out. A step whose results are all + complete ends the turn with their replies (_complete). No draft streams once a result has a chart: the reply is its caption.""" before, effort, budget, retried = list(working), read.effort, TURN_SECONDS, False + charted = lambda: any(r and r[2].get("charts") for r in turn.results) while True: try: return await asyncio.wait_for( - self.agent.run(working, system, effort, first_call=first, tool_choice=read.tool_choice, turn=turn, - on_heavy=on_heavy, finish=self._chart_answer(turn), - **({"on_text": lambda text: None if turn.chart_asked or turn.charts else draft.update(text)} if draft else {})), - budget) + self.agent.run(working, system, effort, tool_choice="auto", turn=turn, on_heavy=on_heavy, finish=self._complete, + **({"on_text": lambda text: None if charted() else draft.update(text)} if draft else {})), + budget) except TimeoutError: lower = intent.lower_effort(effort) if not lower or retried: raise log.warning("No answer in %ds at reasoning %s; asking again at %s", budget, effort, lower) working[:] = before # the unfinished attempt's turns are dropped + turn.results.clear() + turn.result_chars = 0 effort, budget, retried = lower, RETRY_SECONDS, True def preload_soon(self, bot, drawn_by: dict | None): @@ -1416,49 +1326,37 @@ async def draw_buttons_ahead(self, bot): if skipped: log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the button charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) - async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text: str, redraw: Message | None = None): - """Answer `text` (redraw: a chart's message, when a period button asks for that chart again in place).""" + async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text: str): + """Answer `text`.""" msg = update.effective_message text = text.strip() if not text: return stop_typing = asyncio.Event() # "typing..." from the first moment, even while this question waits its turn - typing = None if redraw is not None else asyncio.create_task( # a chart redrawn in place from a button shows no "typing..." - keep_typing(context.bot, msg.chat_id, self._thread(msg), stop_typing)) + typing = asyncio.create_task(keep_typing(context.bot, msg.chat_id, self._thread(msg), stop_typing)) await asyncio.sleep(0) now = now_local(self.cfg.tz) - read = intent.read(text, now, self.by_name) + read = intent.read(text, now, self.by_name, self.cfg.tz, self._catalogue()) log.info("%s%s: %s", describe_source(update), f" (reasoning: {read.effort})" if read.effort != intent.EFFORT_DEFAULT else "", text, extra=QUOTES) for source in self.sources: # fetch recent readings while the model thinks - if source.wants(text) and not read.chart_in_code: # a chart made in code reads just what it needs, first in line + if source.wants(text) and not read.chart: # a chart made in code reads just what it needs, first in line source.poke() - if read.fast: - log.debug("Fast path: %s", read.fast[2]) + if read.chart: + log.debug("Shortcut: %s %s", read.chart[0], json.dumps(read.chart[1], ensure_ascii=False), extra=QUOTES) chat = self.chats[self._key(msg)] started = time.monotonic() + turn, shown = Turn(), [] # (shown: the forecast days the answer shows) async with chat.lock: - draft = Draft(context.bot, msg.chat_id, self._thread(msg)) if redraw is None and msg.chat.type == ChatType.PRIVATE else None + draft = Draft(context.bot, msg.chat_id, self._thread(msg)) if msg.chat.type == ChatType.PRIVATE else None drafting = asyncio.create_task(draft.run(stop_typing)) if draft else None # a private chat also gets the "Thinking..." draft working = [*chat.history, {"role": "user", "content": self._content(msg, text, context.bot.id)}] new_from = len(working) - turn = Turn.of(read, text) - earlier = working[:-1] - recent = ([str(m["content"]) for m in earlier if m["role"] == "user"][-2:] - + [str(m["content"]) for m in earlier if m["role"] == "assistant"][-1:]) - # the topics of the last messages (the person's last two, the bot's last reply) and those this chat is still on - turn.topics = chat.topics.active().union(*(intent.topics_in(said) for said in recent)) - said = [str(m["content"]) for m in earlier if m["role"] == "user"][-2:] # the air readings named: now, else just before - turn.air_named = next(filter(None, map(intent.air_named, [text, *reversed(said)])), []) try: - answer = await self._answer(msg, read, turn, working, draft, now, redraw) - tools_used = {tc["function"]["name"] for m in working[new_from:] for tc in m.get("tool_calls") or []} - chat.topics.update(turn.topics, intent.topics_in(text) | intent.topics_in(answer.reply or "") - | {intent.TOOL_TOPICS[t] for t in tools_used if t in intent.TOOL_TOPICS} - | ({"air_extra"} if turn.air_extra_used else set())) + answer = await self._answer(msg, read, turn, shown, working, draft) chat.history = shorten_old(trim_history(strip_tool_turns(working))) - for chart in answer.charts[:MAX_CHARTS]: # a service tool's charts, drawn from their data while "typing..." is still showing + for chart in answer.charts[:MAX_CHARTS]: # the charts, drawn from their data while "typing..." is still showing try: png, title, _ = await asyncio.to_thread(self._draw, chart, turn.times) answer.photos.append(png) @@ -1466,13 +1364,6 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text answer.drawn_by.append(chart.get("drawn_by")) except Exception as e: log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - for i, spec in enumerate(turn.charts[:MAX_CHARTS - len(answer.photos)]): # the model's (old tools): drawn from their JSON too - try: - answer.photos.append(await asyncio.to_thread(render_data, to_json(spec, self.cfg.tz), self.cfg.tz, turn.times)) - answer.titles.append(spec.caption(now.date())) - answer.drawn_by.append(self._model_drawn_by(turn, i, now)) - except Exception as e: - log.error("Chart failed (%s: %s); sending the answer without it", type(e).__name__, e, exc_info=isinstance(e, BUGS)) except TimeoutError: log.error("%s: gave up after %ds on: %s", chat_tag(msg.chat_id), TURN_SECONDS, text, extra=QUOTES) answer = Answer("Sorry, that took too long. Please try again in a moment.", ok=False) @@ -1483,30 +1374,23 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text finally: stop_typing.set() await asyncio.gather(*[t for t in (typing, drafting) if t]) # wait for any in-flight "typing" or draft so none is sent after the reply - await self._send(msg, context.bot, read, turn, answer, working[new_from:], now, redraw, started) - - async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], draft, now: datetime, redraw: Message | None) -> Answer: - """The answer, from the first way that gives one: a chart drawn moments ago, a chart made in code, a lookup, the report - written in code, else the model. `working` is the conversation, the question last; the answer joins it.""" - shown = bool(intent.HILO.search(turn.text)) # "when was CO2 highest": the answer is a chart's figures, so they go with it - call = self._call_of(read, turn, now) if read.chart_in_code else None # the service's call the chart is (its cache key) - key = periods.call_key(*call) if call else None - if read.chart_in_code and redraw is None and (ready := self.images.ready(key)): # drawn ahead, or for someone's same call - answer = Answer(ready.caption, [ready.photo], [ready.title], silent=not shown or not ready.caption, ready=ready, - drawn_by=[ready.drawn_by], key=key) - elif read.chart_in_code: # drawn by the service; the chart goes out with just its title (the text is kept for the history) + await self._send(msg, context.bot, read, turn, shown, answer, working[new_from:], now, started) + + async def _answer(self, msg: Message, read, turn: Turn, shown: list, working: list[dict], draft) -> Answer: + """The answer, from the first way that gives one: a chart drawn moments ago, a named reading's chart drawn by the service, the + gauges, the report or "weather now" written in code, else the model with the service's tools. `working` is the conversation, the + question last; the answer joins it.""" + key = periods.call_key(*read.chart) if read.chart else None # the call the chart is (its cache key) + if read.chart and (ready := self.images.ready(key)): # drawn ahead, or for someone's same call + answer = Answer(ready.caption, [ready.photo], [ready.title], silent=True, ready=ready, drawn_by=[ready.drawn_by], key=key) + elif read.chart: # drawn by the service; the chart goes out with just its title (the text is kept for the history) began = time.monotonic() - made = await asyncio.wait_for(self._chart_in_code(call, turn), TURN_SECONDS) - answer = Answer(made.text, silent=not shown, made=time.monotonic() - began, charts=made.charts, key=key) if made else Answer() - elif read.dashboard and "Ecowitt" in self.by_name: + made = await asyncio.wait_for(self._chart_in_code(read.chart), TURN_SECONDS) + answer = Answer(made.text, silent=True, made=time.monotonic() - began, charts=made.charts, key=key) if made else Answer() + elif read.dashboard: answer = await asyncio.wait_for(self._dashboard(), TURN_SECONDS) - elif read.lookup: - made = await asyncio.wait_for(self._lookup_in_code(read, turn, now), TURN_SECONDS) - answer = Answer(made.text, charts=made.charts) if made and made.text else Answer() - if answer.reply is None: - turn.forecast_shown.clear() - elif read.fast and (read.report or read.weather_now): # written in code from the tools' results, no model (the report: with its gauges) - text, gauge = await self._report(read, turn, read.report) + elif read.report or read.weather_now: # written in code from the service's results, no model (the report: with its gauges) + text, gauge = await self._report(read.report, shown, read.report) answer = Answer(text, [gauge] if gauge else [], [""] if gauge else []) else: answer = Answer() @@ -1517,21 +1401,21 @@ async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], dra answer.reply = NO_MODEL working.append({"role": "assistant", "content": answer.reply}) return answer - before = [str(m["content"]) for m in working[:-1] if m["role"] == "user"][-2:] - found = intent.topics(str(working[-1]["content"]), before) | turn.topics - turn.topics = found - turn.air_extra = turn.air_extra or "air_extra" in found # the tools offer the air sensor's own readings whenever the prompt tells of them - system = prompt.build(datetime.now(self.cfg.tz), {s.name: s.describe() for s in self.sources}, read.hints, - read.about_the_bot, read.rain_caption, found) + system = prompt.build(datetime.now(self.cfg.tz), self._instructions()) answer.reply = await self._ask_model(working, system, read, turn, draft, lambda tokens: self._warn(msg, tokens)) + kept = [r for r in turn.results if r] + answer.charts = [chart for _, _, out in kept for chart in out.get("charts") or [] if isinstance(chart, dict)] + for name, _, out in kept: + if name == "forecast": + shown.extend(self._shown_forecast(out)) return answer - async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added: list[dict], now: datetime, - redraw: Message | None, started: float): - """Send the answer, a single chart with the period buttons under it (in place of `redraw` when a button asked for it), the - keyboard if the chat's is out of date; then keep what follows from it: the chart for its period buttons and the next to - ask, the question behind it, the forecast days shown. `added`: the messages the answer added to the conversation.""" - text, reply, photos, titles = turn.text, answer.reply, answer.photos, answer.titles + async def _send(self, msg: Message, bot, read, turn: Turn, shown: list, answer: Answer, added: list[dict], now: datetime, + started: float): + """Send the answer, a single chart with the period buttons under it, the keyboard if the chat's is out of date; then keep what + follows from it: the chart for its period buttons and the next to ask, its other periods drawn ahead, the forecast days shown + (`shown`). `added`: the messages the answer added to the conversation.""" + reply, photos, titles = answer.reply, answer.photos, answer.titles caption = reply if answer.silent else None # a chart made in code: its text, kept with the chart for the next to ask the same if answer.silent and photos: reply = "" @@ -1540,7 +1424,7 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added used = [m for m in added if m["role"] == "tool"] log.info("%s: %s in %.1fs, tools %d, charts %d, %d chars", chat_tag(msg.chat_id), "Replied" if answer.ok else "Error reply", time.monotonic() - started, len(used), len(photos), len(reply)) - used_air = any(tc["function"]["name"] == "air_quality" for m in added for tc in m.get("tool_calls") or []) + used_air = any(r and r[0] in ("current", "summary", "readings", "days", "relate", "scan") and reads_air(r[2]) for r in turn.results) air = self.by_name.get("AirGradient") markup = templates.keyboard(self.irrigation is not None) if self._keyboard_stale(msg) else None refresh = answer.ok and read.report and 0 < len(reply) <= TG_LIMIT and not markup # the report, to be refreshed in place @@ -1549,9 +1433,8 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added if drawn_by: # the periods its call lists, the chart's own shaded; none when it lists none row = periods.periods_keyboard(drawn_by, periods.own_period(drawn_by, now, self.cfg.tz), now, self.cfg.tz) record = {"drawn_by": drawn_by, "words": bool(reply.strip())} - else: # a chart the service can't replay (the model's, through a call it has no equivalent of): its question asked again - row = periods.keyboard(intent.period_days(text, now)) if single else None - record = text + else: # (a chart with no drawn_by: no buttons) + row = record = None drawn = list(photos) kept = (answer.key or periods.drawn_key(drawn_by)) if single and answer.ok and (drawn_by or not reply.strip()) else None if kept and not answer.ready: # kept for the period buttons, and (made in code) for the next to ask for the same call @@ -1560,12 +1443,10 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added self.images.alias(kept, periods.call_key(drawn_by["tool"], periods.with_period(drawn_by, own))) try: began = time.monotonic() - if redraw is not None and row and await self._redraw(redraw, reply, photos[0], titles[0], row, record, kept): - reply, photos, row = "", [], None sent = await deliver(msg, reply, photos, link=air.link if air and used_air else None, markup=markup or (report_menu.keyboard() if refresh else report_menu.dashboard_keyboard() if answer.ok and read.dashboard and photos else None), titles=titles, period_row=row, - bold_headings=answer.ok and bool(read.report or read.lookup in ("pollen", "forecast")), photos_first=read.report) + bold_headings=answer.ok and read.report, photos_first=read.report) carried_keyboard = sent.carried and bool(markup) # the refresh button is not the chat's keyboard if answer.ready: log.debug("Chart ms: drawn %.0fs ago, send %.0f%s", self.images.age(answer.ready), (time.monotonic() - began) * 1000, @@ -1575,10 +1456,10 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added if sent.photo and row is not None: self.charted.remember(msg.chat_id, sent.photo.message_id, record) self.images.sent(kept, sent.photo) - if kept and row is not None and drawn_by and read.chart_in_code: # made in code: its other periods are uploaded ahead + if kept and row is not None and drawn_by: # its other periods are uploaded ahead self.preload_soon(bot, drawn_by) - if answer.ok and turn.forecast_shown: # it was sent: a later revision of these days is worth telling this chat - self.state.record_forecast(msg.chat_id, turn.forecast_shown, now_local(self.cfg.tz).date()) + if answer.ok and shown: # it was sent: a later revision of these days is worth telling this chat + self.state.record_forecast(msg.chat_id, shown, now_local(self.cfg.tz).date()) if carried_keyboard: log.info("Buttons: sent keyboard %s to chat %s (it had %s)", self.keyboard_version, msg.chat_id, self.state.keyboard(msg.chat_id)) self.state.set_keyboard(msg.chat_id, self.keyboard_version) diff --git a/lib/captions.py b/lib/captions.py index 74fc6e3e..5dcf8e68 100644 --- a/lib/captions.py +++ b/lib/captions.py @@ -1,5 +1,5 @@ -"""When a chart is drawn, and what the model is told about it: a tool that made a chart adds one of these hints to its -result, so the reply becomes a good caption for the picture (see specs.py for the chart itself, charts.py for drawing it).""" +"""When an engine draws a chart, and the note it adds to its result when it does (the service's tools drop these notes and write +their own, lib/service/common.py CHART_NOTE; see specs.py for the chart itself, charts.py for drawing it).""" from datetime import datetime @@ -7,7 +7,7 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | None = None) -> bool: - """The model asked for one, the person's words did (turn.chart_asked), or the period (naive local start/end) spans 3+ days.""" + """The call asked for one (its `chart`, or turn.chart_asked), or the period (naive local start/end) spans 3+ days.""" long = bool(start and end and (end.date() - start.date()).days >= CHART_MIN_DAYS - 1) return bool(args.get("chart")) or turn.chart_asked or long @@ -21,9 +21,6 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | "per series (Outdoor and Indoor when both were fetched) with its AVERAGE, copied from the series' " "\"average\" field, and its low and high in brackets. Lead with the average: that is what was asked. " "Don't mention or describe the chart.") -LINK_CHART_HINT = ("Your reply is sent as a message just before a chart with the reading as a line and rain as bars behind it, so keep " - "it short: the period, then the finding in one or two lines (how much of the rain fell while the reading " - "was falling, and the correlation), citing the numbers. Don't mention or describe the chart.") STACK_CHART_HINT = ("Your reply is sent as a message just before a chart with these readings on one time axis, so keep it short: the " "period, then one line per reading: temperature and other readings with their high and low (or their " "average if that was asked), rain with its total (\"rain_total_mm\"). Don't mention or describe the chart.") @@ -34,9 +31,3 @@ def wants_chart(args: dict, turn, start: datetime | None = None, end: datetime | "most common direction and how steady it was. Don't mention or describe the chart.") COUNT_CHART_HINT = ("Your reply is sent as a message just before a bar chart of these counts, so keep it to one short line: how many of the days " "matched (matching_days of days_checked) and the period. Don't list the bars or describe the chart.") - -# The argument that says the chart is the whole answer (weather_history, air_quality and the day tools offer it; their handlers ignore -# it): the bot then sends the chart with a caption written in code and asks the model nothing more (bot.Bot._chart_answer) -CHART_ANSWERS_IT = {"type": "boolean", "description": "true only when the question is just to see this chart and its figures: nothing " - "else to answer (\"plot pressure this week\", not \"plot pressure this week: is a " - "storm coming?\"). Then the chart and a ready caption are the whole answer."} diff --git a/lib/compose.py b/lib/compose.py index d6bcb044..7949be5c 100644 --- a/lib/compose.py +++ b/lib/compose.py @@ -1,12 +1,12 @@ -"""Charts across both sources, composed by the model from a fixed list of series and styles. +"""Charts across both sources, composed from a fixed list of series and styles, and the air sensor against rain and the weather (the +engines of lib/service's summary, relate and scan). -The model names what to plot (`plot_chart`: up to four panels, each a series and a style); this module loads the data +A call names what to plot (`plot_chart`: up to four panels, each a series and a style); this module loads the data from the caches, puts it on one time axis and hands the chart to the renderer. The model never supplies numbers or drawing code, so a chart the bot has never drawn before is still made from checked data. Only the cached readings are used for the weather station (nothing is fetched); AirGradient fills any missing days first, as its own tool does.""" import asyncio -import copy import logging from datetime import date, datetime, time, timedelta, tzinfo from statistics import fmean @@ -21,8 +21,8 @@ from .panels import panel_for, same_axis, two_axes from .specs import AIR_SOURCE, ECOWITT_SOURCE, Panel, Shares, stack from .rain import bar_layout, bar_of, rain_bars, rain_slots -from .timeutil import SLOT, day_bounds, now_local, parse_period, period_parameters -from .tools import Tool, Turn, json_result +from .timeutil import SLOT, day_bounds, now_local, parse_period +from .tools import Turn, json_result log = logging.getLogger(__name__) @@ -30,44 +30,9 @@ DEFAULT_DAYS = 30 # Weather station series: name -> (group, field, label, unit); the composer draws the wind as its average speed SERIES = [*WEATHER, *ALL_METRICS] -SERIES_ASKED = [*SERIES, *EXTRA] # what a question that asks for the air sensor's own temperature or humidity is offered +SERIES_ASKED = [*SERIES, *EXTRA] # with the air sensor's own temperature and humidity STYLES = ("line", "bars", "rating") -PLOT_DESCRIPTION = ( - "Plot readings from the weather station and the air-quality sensor together on one time axis, one panel each: " - "'plot the traffic light rating of air quality against rainfall', 'plot PM2.5 and humidity'. Each panel is a series and " - "a style. Styles: 'line' (the reading; long periods are averaged, with the day's range shaded), 'bars' (rain only), " - "'rating' (air-quality series only: the share of time in good, poor and very poor, as traffic-light bars). " - "Bars and ratings are per hour for a few days, per 6 hours up to a month, per day beyond. Rain defaults to bars and " - "everything else to line. Default period: the last 30 days up to yesterday.") -PLOT_PARAMETERS = { - "type": "object", - "properties": { - "panels": {"type": "array", "minItems": 1, "maxItems": MAX_PANELS, "description": "Top to bottom.", - "items": {"type": "object", "properties": {"series": {"type": "string", "enum": SERIES}, - "style": {"type": "string", "enum": list(STYLES)}}, - "required": ["series"]}}, - "two_axes": {"type": "boolean", "description": "Set true to draw the series on ONE panel with a left and a right axis: " - "'on two axes', 'dual axis', 'overlay', 'combine them on one chart'."}, - "invert_second_axis": {"type": "boolean", "description": "With two_axes: the right-hand axis runs top to bottom, so its lines fall as the " - "reading rises ('invert the second Y axis')."}, - **period_parameters(DEFAULT_DAYS), - }, - "required": ["panels"], -} - - -def plot_asked() -> tuple[str, dict]: - """plot_chart as a question about the air sensor's own temperature or humidity is offered it: those two series too, and same_axis.""" - parameters = copy.deepcopy(PLOT_PARAMETERS) - parameters["properties"]["panels"]["items"]["properties"]["series"]["enum"] = SERIES_ASKED - parameters["properties"]["same_axis"] = { - "type": "boolean", "description": "Set true to draw the series as ONE panel on one axis, the lines over each other: " - "'plot airgradient humidity over ecowitt humidity'."} - return (PLOT_DESCRIPTION + " Also air_temperature and air_humidity: the AirGradient sensor's own temperature and humidity (ask for " - "them only by those names: plain temperature and humidity are the weather station's).", parameters) - - SCAN_DAYS = 90 SCAN_MAX_DAYS = 400 # a longer scan is cut to its latest days: its time grows with the period SCAN_AIR = ("pm2_5", "pm10", "co2", "voc_index", "nox_index") @@ -75,37 +40,8 @@ def plot_asked() -> tuple[str, dict]: SCAN_WEATHER = {**{n: (WEATHER[n].group, WEATHER[n].field, WEATHER[n].label.lower(), WEATHER[n].unit) for n in ("temperature", "humidity", "dew_point", "pressure")}, "wind_speed": ("wind", "wind_speed", "wind speed", "km/h"), "wind_gust": ("wind", "wind_gust", "wind gusts", "km/h")} -SCAN_DESCRIPTION = ( - "Which readings go with air quality? Scans every air-quality metric (PM2.5, PM10, CO2, VOC, NOx) against the weather " - "(temperature, humidity, dew point, pressure and its 3-hour change, wind speed, gusts, wind direction, rain), allowing for " - "the daily cycle and for chance, and reports only the relationships that stand out, with a plain verdict. Use it for 'is " - "there a correlation between air quality and other metrics', 'what affects air quality'. For rain alone use air_link. " - "Default period: the last 90 days.") -SCAN_PARAMETERS = { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": ["all", *SCAN_AIR], "description": "One air reading, or all (default)."}, - **period_parameters(SCAN_DAYS), - "chart": {"type": "boolean", "description": "Set true for a chart of the strongest relationship found."}, - }, -} LINK_DAYS = 60 LINK_METRICS = ("pm2_5", "pm10") -LINK_DESCRIPTION = ( - "Does rain go with cleaner air? Reads the air-quality sensor (PM2.5 by default) and the weather station's rain together at " - "30-minute resolution and reports whether the air was cleaner in the hours after rain than before it, its level in wet and " - "dry periods, and wet days against dry days, with a plain verdict. Use it for 'is there a correlation between air quality " - "and rainfall', 'does rain clear the air'. Default period: the last 60 days.") -LINK_PARAMETERS = { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": list(LINK_METRICS), "description": "The air reading. Default pm2_5."}, - **period_parameters(LINK_DAYS), - "chart": {"type": "boolean", "description": "Set true for a chart: the reading (with its rating zones) over rain bars."}, - }, -} - - def _error(text: str) -> str: return json_result({"error": text}) @@ -128,9 +64,6 @@ class Composer: def __init__(self, eco, air): self.eco, self.air, self.tz = eco, air, eco.tz - self.tools = [Tool("plot_chart", PLOT_DESCRIPTION, PLOT_PARAMETERS, self.plot_chart, asked=plot_asked, source=""), - Tool("air_link", LINK_DESCRIPTION, LINK_PARAMETERS, self.air_link, source=""), - Tool("air_scan", SCAN_DESCRIPTION, SCAN_PARAMETERS, self.air_scan, source="")] def period(self, args: dict, default_days: int = DEFAULT_DAYS) -> tuple[date, date] | str: """(first, last) day, or an error text. The last day is at most yesterday: today is still settling.""" @@ -189,7 +122,6 @@ async def plot_chart(self, args: dict, turn: Turn | None = None) -> str: return _error(f"no cached readings of {name} for {first} to {last}") built.append(panel) summary.append(facts) - turn.air_extra_used = turn.air_extra_used or any(name in EXTRA for name, _ in asked) if (args.get("two_axes") or args.get("same_axis")) and any(name in EXTRA for name, _ in asked): for (name, _), panel in zip(asked, built): # the station's readings next to the air sensor's own: say whose each is if name in WEATHER and name != "rain": diff --git a/lib/daytable.py b/lib/daytable.py index 08e002fc..e66a6229 100644 --- a/lib/daytable.py +++ b/lib/daytable.py @@ -7,13 +7,12 @@ import logging import operator -import re from dataclasses import dataclass, field from collections.abc import Callable from datetime import date, datetime, timedelta, tzinfo from statistics import fmean -from .captions import CHART_ANSWERS_IT, COUNT_CHART_HINT +from .captions import COUNT_CHART_HINT from .series import AIR from .specs import Chart, Panel, calendar_bars from .timeutil import day_text, parse_period @@ -36,55 +35,6 @@ def noun(name: str) -> str: return PRETTY.get(base, base.replace("_", " ")) -def parameters(fields: list[str], what: str, extra: dict | None = None) -> dict: - """The tool's JSON schema for these fields (`what` names the unit of a day's figure for the descriptions).""" - return { - "type": "object", - "properties": { - "start_date": {"type": "string", "description": "First day, 'YYYY-MM-DD'. Use the start of the 'on record' range for all time."}, - "end_date": {"type": "string", "description": "Last day, 'YYYY-MM-DD' (today's readings aren't final, so up to yesterday)."}, - "where": {"type": "array", "description": f"Conditions that must ALL hold on the same day, e.g. {what}.", - "items": {"type": "object", "properties": { - "field": {"type": "string", "enum": fields}, - "op": {"type": "string", "enum": list(OPS)}, - "value": {"type": "number"}}, "required": ["field", "op", "value"]}}, - "sort_by": {"type": "string", "description": "Rank matching days by this: a field from the where.field list. Default: the first condition's field."}, - "order": {"type": "string", "enum": ["desc", "asc"], "description": "desc = highest first (default), asc = lowest first."}, - "count_only": {"type": "boolean", "description": "true for \"how many days\": returns just the counts, no list of days (much smaller). Use it whenever the days themselves aren't asked for."}, - "group_by": {"type": "string", "enum": ["month", "year"], "description": "Break the result down per month or year, months with none included. It is drawn as a bar chart."}, - "chart_answers_it": CHART_ANSWERS_IT, - "stat": {"type": "string", "enum": list(STATS), "description": "What each month or year (or the whole period, with no group_by) shows: count (default: matching days), or the max, min, avg or sum of the field `of` over the matching days. E.g. rain total per month: stat sum, of rain, group_by month."}, - "of": {"type": "string", "description": "The field to take max, min, avg or sum of (a field from the where.field list; not needed for count)."}, - "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always counted."}, - **(extra or {}), - }, - "required": ["start_date", "end_date"], - } - - -GROUPING = re.compile(r"\b(?:per|by|each|every)\s+(year|month)\b|\b(yearly|annual\w*)\b|\b(monthly)\b", re.I) - - -def grouping_in(text: str) -> str | None: - """"month" or "year" when the words ask for figures by or per month or year, else None.""" - found = GROUPING.search(text or "") - if not found: - return None - return "month" if (found.group(1) or "").lower() == "month" or found.group(3) else "year" - - -def grouped_as_asked(args: dict, turn) -> dict: - """The arguments with group_by filled in from the person's words when the model left it out ("... by year", "per month"): - a count by year or month is a bar chart, never one overall number.""" - if args.get("group_by") or turn is None or not getattr(turn, "text", ""): - return args - by = grouping_in(turn.text) - if not by: - return args - log.info("group_by %s added: the question asks for figures by %s", by, by) - return {**args, "group_by": by} - - def validate(args: dict, fields: dict[str, str]) -> str | None: """An error message for arguments that can't be used, else None. `fields` maps each field name to its unit.""" where = args.get("where") or [] diff --git a/lib/ecowitt/days.py b/lib/ecowitt/days.py index 8511d9dd..e1da6e9b 100644 --- a/lib/ecowitt/days.py +++ b/lib/ecowitt/days.py @@ -11,16 +11,14 @@ import logging import operator -import re from datetime import date, datetime, tzinfo -from ..daytable import analyse, grouped_as_asked, lists_days, parameters, prepare +from ..daytable import analyse, lists_days, prepare from ..series import WEATHER from ..storage import Storage from ..storage.catalogue import column_of from ..storage.read import Reader -from ..timeutil import day_text, now_local -from ..tools import json_result +from ..timeutil import day_text from .api import daily_run from .calendar import PublicHolidays @@ -50,23 +48,6 @@ FIELD_UNITS = {n: f[3] for n, f in FIELDS.items()} ALWAYS_SHOWN = ("temp_max", "temp_min", "rain") # every listed day shows them; days rank by the first when nothing else is named -PARAMETERS = parameters(list(FIELDS), "rain >= 1 and temp_max > 30", { - "only": {"type": "string", "enum": ["public_holiday", "weekend"], - "description": "ONLY when the person's words say holidays or weekends: look just at public holidays in the owner's local area " - "(the bot knows them: never pick holiday dates yourself) or just Saturdays and Sundays. Days are then counted " - "from those only, so never set it otherwise."}}) -DESCRIPTION = ("Find, rank or count DAYS by the station's readings, checking every day in the period: for questions that " - "compare readings on the same day or count days (\"the hottest day it also rained\", \"how many days over " - "35°C\", \"how many days was UV 9 or more\", \"the wettest day\", \"the windiest cold day\"). Fields: temp_max / temp_min (outdoor °C), " - "rain (mm total for the day; a rainy day is 1 mm or more, above 0 is only a trace), wind_gust (km/h, highest), and a day's " - "highest (_max) or lowest (_min) of every other reading: humidity, pressure, dew_point, feels_like, vpd, " - "indoor_temp, indoor_humidity (_max and _min); wind_speed, solar, uv, rain_rate (_max only), e.g. uv_max >= 9; and _avg, a day's mean (temp_avg, " - "humidity_avg, pressure_avg ...). For \"how many\" use count_only; group_by month or year breaks it down and draws a bar chart. " - "For a total, average, highest or lowest per month or year use stat and of (\"rain per month\": stat sum, of rain; \"hottest day each " - "year\": stat max, of temp_max; \"average humidity per month\": stat avg, of humidity_avg). Returns the total of matching " - "days and the top ones. For a record's value and the time it happened (hottest, coldest, fastest gust), use weather_history instead. For ONE known day, give start_date = end_date = that day and no conditions: it returns that day's figures. Can be limited to local public holidays or weekends (only). Works from cached history, so any period up to the whole record is fast.") - - PARTS = {"high": "hi", "low": "lo", "mean": "mean"} # a figure's kind -> where a day row (storage.read.Days) keeps it COARSER = {"5min": 0, "30min": 1, "1day": 2} @@ -160,18 +141,3 @@ async def find_days(storage: Storage, mac: str, tz: tzinfo, args: dict, now: dat out["note"] = "No cached readings for this period yet (the bot may still be downloading history)." log.info("Days %s to %s: %d checked, %d match, %d exact", first, last, len(checked), len(matches), len(exact_days)) return out - - -HOLIDAY_WORDS = re.compile(r"\b(holidays?|weekends?|saturdays?|sundays?)\b", re.I) - - -async def days_tool(storage: Storage, mac: str, tz: tzinfo, args: dict, turn=None) -> str: - if args.get("only") and turn is not None and turn.text and not HOLIDAY_WORDS.search(turn.text): - # the model added a holiday or weekend filter nobody asked for: it would count only those days (and, with holidays, - # only the years the calendar knows), so it is dropped - log.warning("Ignored only=%s: the question doesn't mention holidays or weekends (%s)", args["only"], turn.text[:60]) - args = {k: v for k, v in args.items() if k != "only"} - args = grouped_as_asked(args, turn) - now = now_local(tz) - result = await find_days(storage, mac, tz, args, now, turn) # (one read of the day rows; the rest is quick enough to stay here) - return json_result(result) diff --git a/lib/ecowitt/link.py b/lib/ecowitt/link.py index 27dea082..bbe10f2f 100644 --- a/lib/ecowitt/link.py +++ b/lib/ecowitt/link.py @@ -1,4 +1,4 @@ -"""weather_link: does rain come with a change in another reading (pressure by default)? Both series are read together +"""Does rain come with a change in another reading (pressure by default)? Both series are read together from the 30-minute readings held, so it is about WHEN the rain fell, not what a day's extremes were. Nothing here calls Ecowitt: it works from what the archive holds. @@ -7,21 +7,17 @@ falling, steady or rising; the reading's average level in wet and dry slots; a correlation between the change before and the rain after; and the biggest rain spells with the change that preceded each.""" -import asyncio import logging -from datetime import date, datetime, time, tzinfo +from datetime import date, datetime, tzinfo from ..analysis.pairs import analyse -from ..captions import LINK_CHART_HINT, wants_chart from ..lines import build_line, shaded_up_to, slot_readings from ..rain import rain_bars, rain_slots from ..panels import panel_for from ..series import WEATHER from ..specs import Chart, Line, stack -from ..storage import Storage from ..storage.read import Reader -from ..timeutil import day_bounds, day_text, local_date, now_local, parse_period, period_parameters -from ..tools import json_result +from ..timeutil import day_bounds, day_text, local_date, parse_period from .reads import slot_values_on log = logging.getLogger(__name__) @@ -29,23 +25,6 @@ DEFAULT_DAYS = 90 DRIVERS = {"pressure": 1.0, "humidity": 5.0, "wind": 5.0} # a reading (series) -> the change over 3 hours that counts as falling or rising -PARAMETERS = { - "type": "object", - "properties": { - **period_parameters(DEFAULT_DAYS), - "driver": {"type": "string", "enum": list(DRIVERS), - "description": "The reading to relate to rain. Default pressure (relative)."}, - "chart": {"type": "boolean", "description": "Set true for a chart: the reading as a line, rain as bars behind it."}, - }, -} -DESCRIPTION = ("Does rain come WITH a change in pressure (or humidity or wind)? Reads both together at 30-minute " - "resolution from the cache and reports how much rain fell while the reading was falling, steady or " - "rising over the previous 3 hours, the reading's level in wet and dry periods, a correlation, and the " - "biggest rain spells with the change before each. Use it for 'is there a correlation between pressure and " - "rainfall', 'did the rain come with the pressure drop' and 'plot pressure against rainfall'. Up to the " - "whole record; never averaged to days.") - - def reading_slots(r: Reader, mac: str, name: str, start: int, end: int) -> tuple[dict, dict, dict]: """(values, lows, highs) per 30-minute slot of a reading (series), as every chart of it shades them: the band is the row's (Ecowitt's own lows and highs, widened by its 5-minute readings and the live readings the bot and Home Assistant saw). A reading shaded up to @@ -114,11 +93,3 @@ def link(read, mac: str, tz: tzinfo, args: dict, now: datetime) -> tuple[dict, C out["days_with_data"] = len({local_date(t, tz) for t in rain}) spec = chart_spec(driver, rain, tz, first, last, name, lows, highs) return out, spec, first, last - - -async def link_tool(storage: Storage, mac: str, tz: tzinfo, args: dict, turn) -> str: - out, spec, first, last = await asyncio.to_thread(link, storage.read_now, mac, tz, args, now_local(tz)) - if spec and wants_chart(args, turn, datetime.combine(first, time()), datetime.combine(last, time())): - turn.charts.append(spec) - out["chart"] = LINK_CHART_HINT - return json_result(out) diff --git a/lib/ecowitt/query.py b/lib/ecowitt/query.py index ba830c08..f58fbab8 100644 --- a/lib/ecowitt/query.py +++ b/lib/ecowitt/query.py @@ -13,7 +13,6 @@ from ..captions import AVERAGE_CHART_HINT, CHART_HINT, STACK_CHART_HINT, DIRECTION_CHART_HINT, wants_chart from ..lines import DAY, Plotted, Sample, build_line, how_drawn, shaded_up_to, time_mean -from ..daytable import grouping_in from ..rain import rain_bars, rain_slots from ..timeutil import at_hour, day_bounds, day_text, local_date, now_local, parse_local, SLOT from ..storage.catalogue import text @@ -476,8 +475,7 @@ def _rain_bars(self, held: Held) -> Bars: if day not in days and self.start.date() <= day <= self.end.date(): rain[day_bounds(day, self.tz)[0] + 12 * 3600] = mm self.rain_from_daily = True - by = None if self.by_day else grouping_in(self.turn.text) - return rain_bars(rain, self.tz, self.start.date(), self.end.date(), until=hi, by=by, since=lo) + return rain_bars(rain, self.tz, self.start.date(), self.end.date(), until=hi, since=lo) def _stack_spec(self, names: list[str]) -> Chart | None: """The readings asked for, one panel each on a shared time axis (rain behind the first line); None if fewer than diff --git a/lib/ecowitt/source.py b/lib/ecowitt/source.py index 6bb2bfd2..8dff8d09 100644 --- a/lib/ecowitt/source.py +++ b/lib/ecowitt/source.py @@ -1,6 +1,6 @@ """The Ecowitt weather station as a data source, peer of AirGradient: -start() finds the station, tools are what the model can call, warm()/poke() keep recent -readings ready, readings() feeds the alert monitors.""" +start() finds the station, warm()/poke() keep recent readings ready, readings() feeds the alert monitors, and the service's tools +(lib/service) read its file and its live reading.""" import asyncio import logging @@ -10,79 +10,27 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError -from ..captions import CHART_ANSWERS_IT from ..config import Config from ..lines import RANGE_KEEP_DAYS from ..sources import Source -from ..specs import ECOWITT_SOURCE -from ..timeutil import local_epoch, naive_local, when -from ..tools import Tool, Turn, json_result +from ..timeutil import local_epoch, naive_local from ..warm import FAST_REFRESH_SECONDS, Warmer, safely from .api import FINE_CYCLES, EcowittAPI, GROUPS, unit_text from .calendar import PublicHolidays -from .link import DESCRIPTION as LINK_DESCRIPTION, PARAMETERS as LINK_PARAMETERS, link_tool -from .days import DESCRIPTION as DAYS_DESCRIPTION, PARAMETERS as DAYS_PARAMETERS, days_tool -from .glance import glance from .fetch import Fetcher, Recent from .fallback import FallbackAPI, newest from .hass_api import HomeAssistantAPI from .homeassistant import HomeAssistant from .live import BUCKET, readings_in -from ..series import READING_GROUPS, WEATHER, find +from ..series import READING_GROUPS from ..storage import Storage from ..storage.catalogue import AIR from ..storage.write import MIN_READINGS -from .query import HistoryQuery, KEEP_HOURS, chart_field, stack_names +from .query import KEEP_HOURS from .reads import newest_minute_on log = logging.getLogger(__name__) -DEFAULT_GROUPS = "outdoor,indoor" - -def parse_groups(value, default: str = DEFAULT_GROUPS) -> list[str]: - """'outdoor, indoor' or ['outdoor', 'indoor'] -> ['outdoor', 'indoor'] (plain group names only). A reading named instead of - its group ("humidity", "dew_point", "rain") becomes its group; a name Ecowitt has no such group for is dropped, since one - bad name fails the whole request.""" - parts = value if isinstance(value, list) else str(value or default).split(",") - named = (p.split(".")[0].strip().lower() for p in parts if p.strip()) - groups = (g if g in GROUPS else (r.group if (r := find(g)) else None) for g in named) - return list(dict.fromkeys(g for g in groups if g)) or default.split(",") - -HISTORY_PARAMS = { - "type": "object", - "properties": { - "start_date": {"type": "string", "description": "Start, 'YYYY-MM-DD HH:MM:SS' local time."}, - "end_date": {"type": "string", "description": "End, 'YYYY-MM-DD HH:MM:SS' local time (today is fine: up to now)."}, - "groups": {"type": "string", "description": "Comma-separated group names, e.g. 'outdoor,indoor'. Add 'rainfall', " - "'wind' or 'pressure' only if needed. Plain group names, not dotted fields."}, - "chart_fields": {"type": "array", "items": {"type": "string", "enum": list(WEATHER)}, - "description": "To plot SEVERAL readings together ('plot temperature and rain'): which, in order, " - "one panel each on a shared time axis. The groups they need are fetched for you."}, - "two_axes": {"type": "boolean", "description": "Set true to draw the chart_fields as ONE panel with a scale each " - "(left and right axis) when the question says 'on two axes', 'dual axis' or 'overlay'."}, - "average": {"type": "boolean", "description": "Set true only when the question asks for an average or mean: adds the " - "period's average (and per day or month). Highs and lows are the default."}, - "chart_field": {"type": "string", "description": "What the chart should plot when the question is about something other " - "than temperature: the reading, e.g. 'humidity', 'pressure', 'wind', 'dew_point', 'solar' or 'uv' " - "(a wind chart shows the average speed shaded up to the gusts). " - "Omit for temperature."}, - "chart": {"type": "boolean", "description": "Set true to send a chart with the answer: for trends over several " - "days or longer, or when a graph/chart is asked for."}, - "chart_answers_it": CHART_ANSWERS_IT, - "include_derived": {"type": "array", "items": {"type": "string", "enum": ["feels_like", "app_temp", "dew_point", "vpd"]}, - "description": "Only when the question asks about feels-like, apparent temperature, dew point or " - "VPD: which of them to include. Otherwise omit (they are left out by default)."}, - }, - "required": ["start_date", "end_date"], -} -HISTORY_DESCRIPTION = ("History from the owner's Ecowitt weather station: each day's low/high and the overall extremes " - "with times, for any range up to 4 years. Resolution and units are handled automatically.") -REALTIME_PARAMS = { - "type": "object", - "properties": {"groups": {"type": "string", "description": "Comma-separated group names, e.g. 'outdoor,indoor'."}}, -} -REALTIME_DESCRIPTION = "Current readings from the owner's Ecowitt weather station." - LIVE_GROUPS = list(READING_GROUPS) # what the once-a-minute live reading asks for: everything "weather now" and the report show HA_IMPORT_SECONDS = 900 # how often Home Assistant's readings are folded into the 5-minute ranges ... HA_RECENT_SECONDS = 3 * 3600 # ... the last few hours each time (the whole RANGE_KEEP_DAYS the first time) @@ -167,10 +115,6 @@ def __init__(self, cfg: Config, transport=None, ha_transport=None, storage: Stor self.created: datetime | None = None self.latitude: float | None = None # the station's own location (the forecast uses it unless one is configured) self.longitude: float | None = None - self.tools = [Tool("weather_now", REALTIME_DESCRIPTION, REALTIME_PARAMS, self._realtime), - Tool("weather_history", HISTORY_DESCRIPTION, HISTORY_PARAMS, self._history, source=ECOWITT_SOURCE), - Tool("weather_days", DAYS_DESCRIPTION, DAYS_PARAMETERS, self._days, source=ECOWITT_SOURCE), - Tool("weather_link", LINK_DESCRIPTION, LINK_PARAMETERS, self._link, source=ECOWITT_SOURCE)] async def start(self): devices = await self.api.devices() @@ -212,48 +156,10 @@ def archive_pace(self) -> float | None: None for the archive's own.""" return 0.0 if isinstance(self.api, HomeAssistantAPI) else None - def describe(self) -> str: - created = f", created {self.created:%Y-%m-%d %H:%M}" if self.created else "" - return f"Ecowitt weather station '{self.station_name}'{created} (people say \"ecowitt\" or \"weather\")" - def fetcher(self, groups: list[str], urgent: bool = False) -> Fetcher: """urgent: for a question (its requests go before the background ones).""" return Fetcher(self.api, self.storage, self.fetches, self.mac, groups, self.tz, urgent, self.has_minutes) - # ---------- tools ---------- - async def _history(self, args: dict, turn: Turn | None = None) -> str: - turn = turn or Turn() - groups = parse_groups(args.get("groups")) - groups += [g for n in stack_names(args, turn) if (g := WEATHER[n].group) not in groups] # what "plot temperature and rain" needs - if (r := find(chart_field(args, turn) or "")) and r.group not in groups: # ... and what a chart of one reading needs - groups.append(r.group) - return await HistoryQuery(self.fetcher(groups, urgent=not turn.ahead), args, turn).run() - - async def _days(self, args: dict, turn: Turn | None = None) -> str: - return await days_tool(self.storage, self.mac, self.tz, args, turn) - - async def _link(self, args: dict, turn: Turn | None = None) -> str: - return await link_tool(self.storage, self.mac, self.tz, args, turn or Turn()) - - async def _realtime(self, args: dict, turn: Turn | None = None) -> str: - groups = parse_groups(args.get("groups")) - data = await self._live_data(groups) - out, newest, emoji = {}, 0, {} - for grp, fields in data.items(): - for name, obj in (fields.items() if isinstance(fields, dict) else ()): - if isinstance(obj, dict) and "value" in obj: - out.setdefault(grp, {})[name] = f"{obj['value']} {obj.get('unit', '')}".strip() - try: - if tag := glance(grp, name, float(obj["value"])): - emoji[f"{grp}.{name}"] = tag - except (TypeError, ValueError): - pass - try: - newest = max(newest, int(obj.get("time") or 0)) - except (TypeError, ValueError): - pass - return json_result({"time": when(newest, self.tz) if newest else None, **out, **({"emoji": emoji} if emoji else {})}) - async def _live_data(self, groups: list[str], max_age: float = LIVE_FRESH_SECONDS, urgent: bool = True) -> dict: """The real_time data for these groups: the kept reading when it is under `max_age` old (a minute and a half for a question) and asked for them, or when Home Assistant's poll has just confirmed it is the newest; else a request of its own, ahead of the background diff --git a/lib/forecast/source.py b/lib/forecast/source.py index 8ed36ce1..5ccc4b72 100644 --- a/lib/forecast/source.py +++ b/lib/forecast/source.py @@ -12,8 +12,6 @@ from ..config import Config from ..snapshots import Snapshots from ..sources import Source -from ..timeutil import when -from ..tools import Tool, Turn, json_result from ..warm import Warmer, in_sync_hours log = logging.getLogger(__name__) @@ -27,13 +25,6 @@ FORECAST_REFRESH_SECONDS = 15 * 60 FRESH_SECONDS = 10 * 60 # a question reuses a forecast this young -DESCRIPTION = ("The weather forecast for the owner's location: today and the days ahead, " - "each with a summary, the lowest and highest temperature and the chance of at least 1 mm of rain. Use it for forecast " - "questions ('what's tomorrow like', 'will it rain this week'). days = how many days from today (default 7, " - "at most 7: the whole week; pass 1 for 'today' and 2 for 'tomorrow'). The result's \"lines\" are ready-made, emoji included: copy them as they are, and put the result's " - "\"place\" in parentheses after the forecast heading, e.g. (Melbourne).") -PARAMETERS = {"type": "object", "properties": {"days": {"type": "integer", "description": "Days from today (default 7, at most 7)."}}} - SOURCE = "Open-Meteo" WMO = {0: "☀️ Clear.", 1: "🌤️ Mostly clear.", 2: "⛅ Partly cloudy.", 3: "☁️ Overcast.", 45: "🌫️ Fog.", 48: "🌫️ Fog.", 51: "🌧️ Light drizzle.", 53: "🌧️ Drizzle.", 55: "🌧️ Heavy drizzle.", 61: "🌧️ Light rain.", 63: "🌧️ Rain.", 65: "🌧️ Heavy rain.", 71: "🌨️ Snow.", 73: "🌨️ Snow.", @@ -88,7 +79,6 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra self.store = Snapshots(cfg.storage_path) self._load() self.warmer = Warmer(self.warm, FORECAST_REFRESH_SECONDS) - self.tools = [Tool("weather_forecast", DESCRIPTION, PARAMETERS, self.handle)] async def start(self): if not self.location: @@ -99,9 +89,6 @@ async def start(self): except Exception as e: log.warning("Forecast not readable yet: %s", e) - def describe(self) -> str: - return "Weather forecast for the owner's location (Open-Meteo) (people say \"forecast\")" - def wants(self, text: str) -> bool: """Only forecast questions start a refresh; the report always uses what is cached.""" return bool(re.search(r"\bforecast\w*|\btomorrow\b|\bthis week\b", text, re.I)) @@ -185,21 +172,3 @@ def upcoming(self, count: int = 2) -> list[dict]: def lines(self, count: int = 2) -> list[str]: today = self.now().date() return [f"{day_label(d['date'], today)}: {describe_day(d)}" for d in self.upcoming(count)] - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - if self.days is None and not args.get("cached"): # the report ("cached") never fetches - try: - await self.warm(True) - except Exception as e: - log.warning("Forecast not readable: %s", e) - try: - count = max(1, min(7, int(args.get("days") or 7))) - except (TypeError, ValueError): - count = 7 - lines = self.lines(count) - if not lines: - return json_result({"error": "No forecast is available right now."}) - if turn: - turn.forecast_shown.extend(self.upcoming(count)) # remembered for the chat once the answer is sent - stamped = {"time": when(int(self.fetched_at), self.tz)} if self.fetched_at else {} # when it was last fetched - return json_result({"lines": lines, "place": self.place, "source": SOURCE, **stamped}) diff --git a/lib/history.py b/lib/history.py index 6695bdca..c3af61b1 100644 --- a/lib/history.py +++ b/lib/history.py @@ -1,7 +1,7 @@ -"""The `readings` tool: one reading's stored values at a fixed interval, each with its time, read straight from the bot's file (lib/storage). +"""One reading's stored values at a fixed interval, each with its time, read straight from the bot's file (lib/storage): the engine of the +service's `readings` tool (lib/service/readings.py), and the readings the service knows (Metric, station_metrics, air_metrics). It answers "humidity each hour for the last 5 hours", "PM2.5 every 30 minutes this morning" and other requests for a table of values. -weather_history gives a period's highs, lows, averages and charts; this gives the readings themselves. Every interval is offered for every reading. - An interval a sensor stores is read as it is: Ecowitt's 5min, 30min and 4hour, Home Assistant's and the air sensor's minutes, and the @@ -18,9 +18,7 @@ """ import logging -import time as clock from bisect import bisect_left, bisect_right -from collections.abc import Callable from datetime import date, datetime, time, timedelta, tzinfo from typing import NamedTuple @@ -32,8 +30,7 @@ from .storage.catalogue import BY_NAME, KINDS, OTHER, RAIN_COUNTERS, Column, column_of, kind_of, text from .storage.read import FINE, Reader from .storage.schema import q -from .timeutil import clock_text, day_text, local_date, local_epoch, parse_local, to_local, when -from .tools import Tool, Turn, json_result +from .timeutil import clock_text, day_text, local_date, local_epoch, to_local, when log = logging.getLogger(__name__) @@ -116,33 +113,6 @@ def air_metrics(extra: bool = False) -> list[Metric]: return [Metric(AIR_SENSOR, n, AIR_SENSOR, BY_NAME[AIR_SENSOR][n], AIR_STORED[n][1]) for n in names] -def parameters(names: list[str]) -> dict: - return { - "type": "object", - "properties": { - "metric": {"type": "string", "enum": names, - "description": "The sensor and reading, e.g. outdoor.humidity, indoor.temperature, pressure.relative, " - "wind.wind_gust, rainfall.rain (mm that fell in each interval), air.pm2_5. One per call: " - "outdoor and indoor are two calls, made together."}, - "start": {"type": "string", "description": "Start, 'YYYY-MM-DD HH:MM' local time."}, - "end": {"type": "string", "description": "End, 'YYYY-MM-DD HH:MM' local time. Default: now."}, - "interval": {"type": "string", "enum": list(INTERVALS), - "description": "One row per interval, a block of local time (1hour runs from :00 to :00; 4hour follows the station's " - "own 4-hour records, whose times say where they start). 1min goes back 10 days."}, - }, - "required": ["metric", "start", "interval"], - } - - -DESCRIPTION = ( - "The stored readings of ONE metric at a fixed interval, a row per interval with its time: for values at set times or per interval " - "(\"humidity each hour for the last 5 hours\", \"PM2.5 every 30 minutes this morning\", \"rain each hour today\", a table of " - "values; for one moment such as 3pm, a few minutes either side at 5min). Each row: the interval's average with its lowest and highest (rain: the mm that fell in it; gusts: the " - f"highest). At most {MAX_ROWS} rows: pick an interval that fits (5min for a few hours, 1hour for up to 12 days, 4hour for up to 7 " - "weeks, 1day for up to 300 days). For a period's highs and lows, records, averages or a chart use weather_history or air_quality.") -PARAMETERS = parameters([m.name for m in [*station_metrics(), *air_metrics()]]) # the tool as offered before any file is read (the evals) - - def interval_starts(start: int, end: int, width: int, tz: tzinfo) -> list[int]: """The starts of the intervals of `width` seconds that hold [start, end]: blocks of local time from midnight, so an hour runs from :00 whatever the zone's offset, and a day from midnight; across a daylight-saving change one is an hour longer or shorter. Four hours are @@ -341,101 +311,4 @@ def read_days(r: Reader, m: Metric, sensor: int, first: date, last: date, tz: tz "mean": "the day's average, with its lowest and highest and when they happened"} -class History: - """The `readings` tool over the weather station's and the air sensor's stored readings (either may be missing).""" - - def __init__(self, eco=None, air=None, sent: dict[str, dict[str, str]] | None = None, now: Callable[[], float] = clock.time): - """eco, air: the sources (Ecowitt, AirGradient), started. sent: the station's fields as the file has them ({group: {field: unit}}; - History.open reads them). now: the clock (a test's).""" - self.eco, self.air, self.now = eco, air, now - self.storage = eco.storage if eco else air.store.storage - self.tz = eco.tz if eco else air.tz - station = station_metrics(sent) if eco else [] - self.metrics = {m.name: m for m in [*station, *(air_metrics(extra=True) if air else [])]} - offered = [m.name for m in [*station, *(air_metrics() if air else [])]] - asked = [m.name for m in [*station, *(air_metrics(extra=True) if air else [])]] - self.tools = [Tool("readings", DESCRIPTION, parameters(offered), self.handle, - asked=(lambda: (DESCRIPTION, parameters(asked))) if air else None)] - - @classmethod - async def open(cls, eco=None, air=None) -> "History": - """The tool, with the readings the station has sent read from the file.""" - return cls(eco, air, await station_fields(eco) if eco else None) - - def find(self, name: str) -> Metric | None: - """The metric a name means: its own name, else a reading's ("humidity", "uv", "pm2_5", "rain") on the sensor that has it. A sensor - named (indoor, air) is kept: "air.humidity" is the air sensor's own, never the outdoor humidity; "indoor.vpd" is none.""" - name = name.strip().lower() - if name in self.metrics: - return self.metrics[name] - prefix, _, bare = name.rpartition(".") - if prefix == AIR_SENSOR and (m := self.metrics.get(f"{AIR_SENSOR}.{AIR_SENSOR}_{bare}")): - return m - reading = WEATHER.get(bare) or next((r for r in WEATHER.values() if r.field == bare), None) - m = (reading and self.metrics.get(f"{reading.group}.{RAIN if reading.field == 'daily' else reading.field}") - or self.metrics.get(f"{AIR_SENSOR}.{bare}") or self.metrics.get(f"outdoor.{bare}")) - return None if m and prefix in ("indoor", AIR_SENSOR) and m.sensor != prefix else m - - def _sensor(self, m: Metric) -> int | None: - if m.air: - s = self.air.store.sensor if self.air else None - else: - s = self.storage.sensors.find(self.eco.mac, m.sensor) if self.eco else None - return s.id if s else None - - def _time(self, value, default: int) -> int: - """A start or end as sent ("2026-11-09 01:00", with seconds, a "T", or an offset such as "Z", which is moved into local time).""" - if value in (None, ""): - return default - text = str(value).strip() - try: - local = parse_local(text, self.tz) - except ValueError: # trailing words ("2026-11-09 01:00 AEDT"): the time alone - local = parse_local(text.replace("T", " ")[:19], self.tz) - return local_epoch(local, self.tz) - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - m = self.find(str(args.get("metric") or "")) - if m is None: - return json_result({"error": f"unknown metric {args.get('metric')!r}", "metrics": list(self.metrics)}) - interval = str(args.get("interval") or "").strip().lower() - interval = ALIASES.get(interval, interval) - if interval not in INTERVALS: - return json_result({"error": f"unknown interval {args.get('interval')!r}", "intervals": list(INTERVALS)}) - now = int(self.now()) - try: - start, end = self._time(args.get("start"), None), min(self._time(args.get("end"), now), now) - except (TypeError, ValueError): - return json_result({"error": "start and end are 'YYYY-MM-DD HH:MM', local time"}) - if start is None or start >= end: - return json_result({"error": "start must be before end (and before now)"}) - by_day = interval == "1day" and m.how != "last" # (a compass point has no day figures: the last reading of each day) - n = row_count(start, end, interval, self.tz) - too_many = n > (MAX_ROWS if by_day else MAX_ROWS + 1) # (an interval's count is exact only once listed: the first starts before `start`) - marks = [] if too_many or by_day else interval_starts(start, end, INTERVALS[interval], self.tz) - if too_many or len(marks) > MAX_ROWS: - fits = finest_fit(start, end, self.tz) - return json_result({"error": "too many rows", "rows": max(n, len(marks)), "max_rows": MAX_ROWS, "fits": fits, - "note": f"Ask again with interval {fits}." if fits else - "Too long even for days: split the period, or use weather_history or weather_days."}) - out = {"metric": m.name, "unit": m.unit, "interval": interval, "value_is": (DAY_VALUE_IS if by_day else VALUE_IS)[m.how]} - sensor = self._sensor(m) - if sensor is None: - return json_result({**out, "rows": [], "note": "Nothing is stored for this sensor yet."}) - if by_day: - first, last = local_date(start, self.tz), local_date(end, self.tz) - out |= await self.storage.read(read_days, m, sensor, first, last, self.tz) - partial = last == local_date(now, self.tz) - else: - out |= await self.storage.read(read_intervals, m, sensor, interval, marks, end, now, self.tz) - partial = marks[-1] + INTERVALS[interval] > now - if partial: - out["note_last"] = "The last row is still filling: it runs up to now." - if not any(row[1] is not None for row in out["rows"]): - out["note"] = (f"No readings at this interval for this period: ask again with interval {out['fits']}." if out.get("fits") else - "No readings are stored for this period at this interval: say so; never fill the gap.") - return json_result(out) - - -__all__ = ["DESCRIPTION", "History", "INTERVALS", "MAX_ROWS", "PARAMETERS", "air_metrics", "interval_starts", "parameters", "station_fields", - "station_metrics"] +__all__ = ["INTERVALS", "MAX_ROWS", "air_metrics", "interval_starts", "read_days", "read_intervals", "station_fields", "station_metrics"] diff --git a/lib/intent.py b/lib/intent.py index 67f76d9c..1f8ea3c1 100644 --- a/lib/intent.py +++ b/lib/intent.py @@ -1,29 +1,27 @@ -"""What a message is asking for, decided with patterns rather than the model. - - - how much the model should think (only predictions and "describe it" questions get reasoning); - - whether fresh data must be fetched first (weather / air questions); - - the fast path: simple "period + highs/lows", chart and "air quality now" questions become a - tool call built here, so the model's first round trip is skipped and it is only invoked once - the data is in, to word the answer. Anything not clearly matched returns None and takes the - normal path, so strictness is the point. +"""What the bot decides about a message with patterns rather than the model (docs/mcp-service.md 4): + + - how much the model should think (only predictions, analysis and "describe it" questions get reasoning); + - the few shortcuts the bot answers in code, each a fixed call to a service tool: the report, the gauges, "weather now", and a + named reading's chart and a period ("humidity chart 7d", "chart rain this month", "humidity 7d", the keyboard's and the alerts' + sentences: `chart_call`). Anything not clearly matched goes to the model, so strictness is the point. + +Nothing here reaches a tool except a shortcut's own call: the words are passed on as they are (the readings and the period), and +the service reads them. """ import logging import re from collections.abc import Collection -from dataclasses import dataclass, field -from datetime import date, datetime, timedelta +from dataclasses import dataclass +from datetime import datetime, timedelta, tzinfo -from .logs import BUGS -from .daytable import GROUPING, grouping_in -from .series import AIR as AIR_TABLE, INDOOR_READINGS, PRESSURE_WORDS, READING_GROUPS, SPECIFIC, WEATHER as WEATHER_READINGS -from .service import names as service_names +from .series import AIR as AIR_TABLE log = logging.getLogger(__name__) I = re.IGNORECASE -# ---------- reasoning and fetching ---------- +# ---------- reasoning ---------- EFFORT_DEFAULT, EFFORT_DESCRIBE, EFFORT_THINK = "none", "low", "medium" EFFORT_STEPS = ("none", "low", "medium", "high") @@ -33,33 +31,11 @@ def lower_effort(effort: str) -> str | None: i = EFFORT_STEPS.index(effort) if effort in EFFORT_STEPS else 0 return EFFORT_STEPS[i - 1] if i else None -# The words that name each reading, shared by every pattern below: the series table's, and a breeze is wind too -_TEMP = WEATHER_READINGS["temperature"].words -_WIND = rf"{WEATHER_READINGS['wind'].words}|breez\w*" -# Which temperature words make a message a weather question that must fetch ("only that it's cold" is chat): "temp", "temperature", -# "how hot/cold ...", and the superlatives that rank days ("hottest weekends"). _TEMP (all the words) still names the reading. -_TEMP_ASK = r"temp\w*|how (?:hot|cold|warm|cool|freezing)|(?:hott|cold|warm|cool)est" -_PRESSURE = PRESSURE_WORDS + # The two devices by name: "ecowitt" is the weather, "ag" / "airgradient" / "air gradient" the air quality _ECOWITT = r"ecowitt" _AG = r"air ?gradient|ag" -AIR_METRICS = [(m.words, name) for name, m in AIR_TABLE.items()] # words -> metric; checked in order, so PM10 wins over PM1 -_AIR_METRIC = "|".join(words for words, _ in AIR_METRICS) # the words that name an air reading, for every pattern below -_OTHER_THAN_AIR = rf"temp\w*|rain\w*|wind\w*|humid\w*|hot|cold|warm|pressure|weather|{_ECOWITT}" # a question that is not (only) about the air -# The words of every reading but temperature and feels-like, which name their reading more broadly than a question asks for it -# ("cool, thanks", "feeling better"): those two ask with _TEMP_ASK and "feels" instead -_READING_ASK = "|".join(r.words for name, r in WEATHER_READINGS.items() if name not in ("temperature", "feels_like")) - -# Messages about the weather or air must fetch fresh data; anything else (thanks, chat) needn't -WEATHER = re.compile( - rf"\b(weather|{_ECOWITT}|{_AG}|{_TEMP_ASK}|{_READING_ASK}|frost\w*|pollen|hay ?fever|asthma|" - rf"rain\w*|showers?|drizzle|storms?|thunder\w*|hail|snow|fog\w*|cloud\w*|sun\w*|uv|solar|" - rf"{_WIND}|humid\w*|dew|{_PRESSURE}|forecast\w*|umbrella|" - r"highs?|lows?|max\w*|min\w*|records?|extremes?|average|chart\w*|graph\w*|plot\w*|trend\w*|" - r"indoors?|outdoors?|inside|outside|conditions|feels?|today|tonight|tomorrow|yesterday|" - rf"week|month|year|air|aqi|{_AIR_METRIC}|smok\w*|pollut\w*|stuffy)\b|°|" - r"\b\d{1,2}(st|nd|rd|th)?\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*|" - r"\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*\s+\d{1,2}\b|\b\d{1,2}/\d{1,2}\b", I) +_AIR_METRIC = "|".join(m.words for m in AIR_TABLE.values()) # the words that name an air reading # Describing a day or playing along with a hypothetical benefits from a little thinking DESCRIBE = re.compile( @@ -72,21 +48,18 @@ def lower_effort(effort: str) -> str | None: r"tonight|tomorrow|later|soon|coming|next (few )?(hour|hours)|this (afternoon|evening)|" r"should i|chance of|likely|expect\w*|predict\w*|outlook)\b", I) - # Combining readings across days or conditions ("the hottest day that also rained", "how many days ...") ANALYSIS = re.compile( r"\b(also|both|same day|at the same time|coincid\w*|combination|how many days|how often|" r"(days?|times?|when) (when|that|where|with|it)|(that|where|when) (it )?(also|and)|" r"(hottest|coldest|wettest|driest|windiest|warmest|coolest)\b.*\b(that|where|when|but|and)\b)", I) - # Is one reading tied to another ("is there a correlation between pressure and rain"): the answer is a judgement LINK = re.compile( r"\b(correlat\w*|(link|links|linked|connection|connected|relation|relationship|relationships|relate|related|relates)\b" r".*\b(between|to|with)\b|(between|with)\b.*\b(link|connection|relation\w*)|cross[- ]?referenc\w*|cross[- ]?check\w*|" r"(does|do|did|is|are)\b.*\b(affect\w*|influence\w*|predict\w*|cause\w*)\b.*\b(rain|pressure|humidity|wind|temperature)\w*)\b", I) - # Asking the model to think: "think about it", "try to work out why", "reason it through", "predict", "estimate", "grind", "whirl" THINK = re.compile(r"\b(think\w*|try|trying|reason\w*|predict\w*|estimat\w*|grind\w*|whirl\w*)\b", I) @@ -100,6 +73,7 @@ def reasoning_effort(text: str) -> str: return next((effort for effort, patterns in EFFORT_RULES if any(p.search(text) for p in patterns)), EFFORT_DEFAULT) +# ---------- the report, the gauges, weather now ---------- def _only(words: str, lead: str = "") -> str: """A pattern for a message that is just these words (optionally with please, a lead-in and punctuation).""" return rf"^\s*(please\s+)?{lead}({words})(\s+please)?\s*[?.!]*\s*$" @@ -107,6 +81,9 @@ def _only(words: str, lead: str = "") -> str: _ASK = r"((give me|show me|show|get|what's|whats)\s+)?(the\s+)?" # the usual lead-in: "show me the ...", "what's the ..." +# Any of these means the question names a period: the report, the gauges and "weather now" are the readings now +TIME_WORDS = re.compile(r"\b(hours?|days?|weeks?|months?|years?|quarter|fortnight|decade|since|between|until|ago|ytd|" + r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(19|20)\d\d)\b", I) # (a month and year: "oct 2025") # "status", "report": the whole current picture from both devices (a period word or a subject makes it something else) REPORT = re.compile(_only(r"status|report|sitrep|overview|summary|everything|what you'?ve got", @@ -125,39 +102,7 @@ def wants_dashboard(text: str) -> bool: return bool(DASHBOARD.search(text)) and not TIME_WORDS.search(text) -def report_calls(sources: Collection[str]) -> list[tuple[str, dict]]: - """What the full report needs from these sources (by name), fetched together before the model sees the question.""" - calls = {"Ecowitt": ("weather_now", {"groups": NOW_GROUPS}), "AirGradient": ("air_quality", {}), - "Pollen": ("pollen_asthma", {"cached": True}), "Forecast": ("weather_forecast", {"days": 3, "cached": True})} - return [call for name, call in calls.items() if name in sources] - - -# Pollen and thunderstorm asthma (the Pollen source) -POLLEN_WORDS = re.compile(r"\b(pollen|hay ?fever|thunderstorm asthma|asthma)\b", I) -POLLEN_NOW = re.compile(_only(r"pollen( count| level| forecast| today| now)?|hay ?fever|(thunderstorm )?asthma( risk)?", - _ASK), I) - - -def mentions_pollen(text: str) -> bool: - return bool(POLLEN_WORDS.search(text)) - - -POLLEN_FILLER = frozenset("pollen hay fever hayfever asthma thunderstorm count counts level levels risk forecast today bad high like much " - "dangerous okay ok safe".split()) - - -def pollen_ask(text: str) -> bool: - """Is this only a plain question about the pollen or thunderstorm asthma ("is the pollen bad today", "how's the hay fever")?""" - return mentions_pollen(text) and _only_words(text, POLLEN_FILLER.__contains__) - - -def _only_words(text: str, fits) -> bool: - """Is every word of the text filler (FILLER: what, is, the, now ...) or one `fits` (a word -> bool) takes?""" - return all(word in FILLER or fits(word) for word in re.findall(r"[\w'’.]+", text.lower())) - - # "weather", "weather now", "current weather", "ecowitt": every reading the station has right now (the weather half of the report) -NOW_GROUPS = ",".join(READING_GROUPS) WEATHER_NOW = re.compile(_only(rf"(weather|{_ECOWITT}|conditions)(\s+(now|right now|currently|at the moment))?|(current|latest)\s+(weather|conditions)", _ASK), I) @@ -166,731 +111,127 @@ def wants_weather_now(text: str) -> bool: return bool(WEATHER_NOW.search(text)) and not TIME_WORDS.search(text) -# Questions about the bot itself ("what metrics do you have", "list our sources"): answered from what it knows, no fetch -ABOUT_THE_BOT = re.compile( - r"\b(what|which|list|show)\b.*\b(metrics?|sensors?|sources?|devices?)\b|" - rf"\bwhat (can|do) you (do|measure|track|have|know|tell)\b|\bwhat can (i|we) ask\b|\bwhat (does|do) ({_ECOWITT}|{_AG}) (measure|track|have|report|tell)\b|" - + _only(r"metrics?|sensors?|sources?|devices?", r"((our|the|my|available|all)\s+)*"), I) - - -def about_the_bot(text: str) -> bool: - return bool(ABOUT_THE_BOT.search(text)) and not TIME_WORDS.search(text) - - -# Asking the bot to DO something ("add an alert if winds reach 100 km/h") is not a request for readings -COMMAND = re.compile(r"^\s*(please\s+)?(add|set( up)?|create|remind|schedule|turn (on|off)|enable|disable|mute|unmute|subscribe)\b", I) - - -# Asking for the bot's view ("what do you think of weather in general"): a conversation, not a lookup, unless it names a time or a reading now -OPINION = re.compile(r"\b(what do you think|your (view|opinion|thoughts?)|philosoph\w*|do you (like|prefer|love|hate|enjoy))\b", I) -RIGHT_NOW = re.compile(r"\b(today|tonight|tomorrow|yesterday|now|currently|current|right now|outside|forecast\w*|this (morning|afternoon|evening|week))\b", I) - - -def is_opinion(text: str) -> bool: - return bool(OPINION.search(text)) and not RIGHT_NOW.search(text) and not TIME_WORDS.search(text) - - -def needs_data(text: str) -> bool: - """Must the model fetch before answering? Weather and air words say yes, unless it is an instruction or a question about the bot - or its opinion: those are not forced to call a tool.""" - return bool(WEATHER.search(text)) and not COMMAND.search(text) and not about_the_bot(text) and not is_opinion(text) - - -# ---------- periods ---------- -def period_ranges(today: date) -> dict[str, tuple[date, date]]: - """Named periods. The prompt's date list and the fast path both use these.""" - week_start = today - timedelta(days=today.weekday()) # Monday - month_start = today.replace(day=1) - prev_month_end = month_start - timedelta(days=1) - return { - "today": (today, today), - "yesterday": (today - timedelta(days=1), today - timedelta(days=1)), - "last 7 days": (today - timedelta(days=6), today), - "current calendar week": (week_start, today), - "last week": (week_start - timedelta(days=7), week_start - timedelta(days=1)), - "this month": (month_start, today), - "last month": (prev_month_end.replace(day=1), prev_month_end), - "this year": (today.replace(month=1, day=1), today), - "last year": (date(today.year - 1, 1, 1), date(today.year - 1, 12, 31)), - "past month": (today - timedelta(days=29), today), - "past year": (today - timedelta(days=364), today), - "on record": (today - timedelta(days=1459), today), # what Ecowitt keeps (also safe on 29 Feb) - } - - -# Phrase -> period name. Numbered periods ("4 months", "24h", "last 7 days") are parsed separately. -PERIOD_PHRASES = [ - # "the last year" / "in the last year" = rolling; bare "last year" = previous calendar year - (r"(on record|all[- ]time|of all time|ever recorded|ever|(the )?(full|whole|entire|complete|all( the)?) (history|record|data))", "on record"), - (r"(the )?past year|the last year", "past year"), - (r"(the )?past month|the last month", "past month"), - (r"(the )?past week|the last week|this week", "last 7 days"), - (r"(? tuple[datetime, datetime]: - """Start and end of a named period. The rolling "last 24 hours" ends now; others cover whole days.""" - if name == "last 24 hours": - return default_span(now)[1:] - first, last = period_ranges(now.date())[name] - return datetime.combine(first, datetime.min.time()), datetime.combine(last, datetime.max.time()).replace(microsecond=0) - - -MAX_PERIOD_DAYS = 3650 # ten years: well past the four Ecowitt keeps, which the tools trim to what exists - - -def default_span(now: datetime) -> tuple[str, datetime, datetime]: - """The period of a chart that names none: the last 24 hours.""" - return numbered_span("24", "h", now) - - -def numbered_span(count: str, unit: str, now: datetime) -> tuple[str, datetime, datetime] | None: - """"4 months", "24h", "2 weeks": a rolling period ending now. One day means the last 24 hours; - longer ones cover whole days up to today (a month is 30 days, a year 365, as in the named periods).""" - n = int(count[:6]) if count.isdigit() else NUMBER_WORDS[count.lower()] # 6 digits at most: nothing sane is longer - u = unit.lower() - if n == 0: - return None - hours = n if u[0] == "h" else 24 if u[0] == "d" and n == 1 else 0 - days = hours / 24 if hours else n if u[0] == "d" else 7 * n if u[0] == "w" else 365 * n if u[0] == "y" else round(n * 365 / 12) - if days > MAX_PERIOD_DAYS: # beyond what any sensor has: the model can explain, dates would be nonsense - return None - if hours: - return f"last {hours} hours", now - timedelta(hours=hours), now - start = datetime.combine(now.date() - timedelta(days=days - 1), datetime.min.time()) - label = {"d": "days", "w": "weeks", "y": "years", "m": "months"}[u[0]] - return f"last {n} {label[:-1] if n == 1 else label}", start, datetime.combine(now.date(), datetime.max.time()).replace(microsecond=0) - - -_MONTH_NAMES = "jan feb mar apr may jun jul aug sep oct nov dec".split() -_MONTH_YEAR = r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+((?:19|20)\d\d)" -# "oct 2025 to oct 2026", "from March 2025 until June 2025", "between jan 2026 and mar 2026", "oct 2025": whole calendar months -MONTHS_SPAN = re.compile(rf"\b(?:(?:from|between)\s+)?{_MONTH_YEAR}(?:\s*(?:to|until|till|through|and|-|–)\s*{_MONTH_YEAR})?\b", I) - - -def months_span(m: re.Match, now: datetime) -> tuple[str, datetime, datetime] | None: - """The calendar months a MONTHS_SPAN match names, from the first day of the first to the last day of the last (today at most); - None when it starts after today or ends before it starts.""" - first = date(int(m[2]), _MONTH_NAMES.index(m[1][:3].lower()) + 1, 1) - last = date(int(m[4]), _MONTH_NAMES.index(m[3][:3].lower()) + 1, 1) if m[3] else first - last = min((last.replace(day=28) + timedelta(days=4)).replace(day=1) - timedelta(days=1), now.date()) - if first > now.date() or last < first: - return None - name = f"{first:%b %Y}" + (f" - {last:%b %Y}" if (first.year, first.month) != (last.year, last.month) else "") - return name, datetime.combine(first, datetime.min.time()), datetime.combine(last, datetime.max.time()).replace(microsecond=0) - - -HISTORY = re.compile(r"\bhistory\b", I) # with no other period named: the whole record - - -def _periods(text: str, now: datetime) -> dict[tuple[datetime, datetime], tuple[str, str]]: - """{(start, end): (the words said, the period's name)} for every distinct period the text names.""" - found: dict = {} - for m in MONTHS_SPAN.finditer(text): - if months := months_span(m, now): - found.setdefault(months[1:], (m.group(0), months[0])) - for phrase, name in PERIOD_PHRASES: - if m := re.search(rf"\b({phrase})\b", text, I): - found.setdefault(span(name, now), (m.group(0), name)) - for m in NUMBERED_PERIOD.finditer(text): - if numbered := numbered_span(m.group(1), m.group(2), now): - found.setdefault(numbered[1:], (m.group(0), numbered[0])) - if not found and (said := HISTORY.search(text)): # "co2 history": all of it - found[span("on record", now)] = (said.group(0), "on record") - if not found and (bare := BARE_PERIOD.search(text)): # "weather week", "aq month": as if "this ..." - name = BARE_PERIODS[bare.group(1).lower()] - found[span(name, now)] = (bare.group(0), name) - return found - - -def spans_in(text: str, now: datetime) -> list[tuple[str, datetime, datetime]]: - """Every distinct period the text names, as (name, start, end).""" - return [(name, *window) for window, (_, name) in _periods(text, now).items()] - - -DEFAULT_CHART_DAYS = 1 # a chart with no period named is the last day - - -def period_days(text: str, now: datetime) -> int: - """How many days the period a question names covers (a day when it names none).""" - spans = spans_in(text, now) - if not spans: - return DEFAULT_CHART_DAYS - _, start, end = spans[0] - return max(1, round((end - start).total_seconds() / 86400)) - - -def _has_days(text: str, days: int, now: datetime | None = None) -> bool: - """Does the text name a period of at least this many days?""" - now = now or datetime.now() - return bool(spans_in(text, now)) and period_days(text, now) >= days - - -def without_period(text: str, now: datetime) -> str: - """The question with its period taken out: "temperature chart 30d" -> "temperature chart".""" - for said, _ in _periods(text, now).values(): - text = re.sub(rf"(?:\b(?:for|over|in|during|the|past)\s+)*\b{re.escape(said)}\b", "", text, flags=I) - return " ".join(text.split()) - - -def with_period(text: str, days: int, now: datetime) -> str: - """The question with its period swapped for the last `days` days: "temperature chart 30d" -> "temperature chart 90d"; a question - that names no period gets one added.""" - return f"{without_period(text, now)} {days}d" - - -def period_hints(text: str, now: datetime) -> list[str]: - """One line per period the person's words name, with its exact dates, for the model: "3m" = the last 3 months: - 2026-07-01 00:00:00 to 2026-09-30 23:59:59. The model otherwise guesses short forms (3m has been read as 3 days).""" - return [f'"{said}" = {name}: {start:%Y-%m-%d %H:%M:%S} to {end:%Y-%m-%d %H:%M:%S}' - for (start, end), (said, name) in _periods(text, now).items()] - - -# ---------- weather fast path ---------- -_HILO = r"hottest|coldest|warmest|coolest|highest|lowest|highs?|lows?|max(imum)?|min(imum)?|extremes?" -# A highs/lows summary: naming the temperature asks for its range ("temps this week") -EXTREMES = re.compile(rf"\b({_HILO}|temperatures?|temps?)\b", I) -# A reading's highest or lowest, in so many words ("peak humidity", "strongest gust") -HILO = re.compile(rf"\b({_HILO}|peak|strongest|fastest)\b", I) -GRAPH = re.compile(r"\b(graph\w*|chart\w*|plot\w*|trend\w*|visuali[sz]\w*)\b", I) -# What no weather fast path answers: a comparison, a reason, a count, a look ahead or the reading right now (a period is the question) -_NOT_PLAIN = r"compare\w*|vs|versus|than|why|how many|days (above|below|over|under)|will|going to|now|right now|current\w*" -NOT_PLAIN = re.compile(rf"\b({_NOT_PLAIN})\b", I) -# The highs/lows summary is of the temperature alone: another reading, the air, an average or anything ahead goes the normal way -# (or another fast path) -NOT_HILO = re.compile(rf"\b({_NOT_PLAIN}|rain\w*|pressure|humid\w*|uv|solar|lightning|{_AIR_METRIC}|pm2|air|air quality|aqi?|smok\w*|pollut\w*|{_AG}|" - r"average|mean|median|feels?|dew|forecast\w*|tomorrow|tonight|later)\b", I) -WIND = re.compile(rf"\b({_WIND})\b", I) -# What a chart request with no period must name to default to the last day ("chart it" refers back instead) -WEATHER_SUBJECT = re.compile(rf"\b(weather|{_ECOWITT}|{_TEMP}|highs?|lows?|indoors?|outdoors?|inside|outside|station)\b", I) -WEATHER_WORD = re.compile(rf"\b(weather|{_ECOWITT}|conditions)\b", I) -# A period named on its own ("weather week", "aq month") is the rolling week, month or year ending today, not the calendar -# one (on the 1st, "month" must not be just today) -BARE_PERIODS = {"week": "last 7 days", "month": "past month", "year": "past year"} -BARE_PERIOD = re.compile(r"\b(week|month|year)\b", I) -INDOOR = re.compile(r"\b(indoors?|inside)\b", I) -OUTDOOR = re.compile(r"\b(outdoors?|outside)\b", I) -FMT = "%Y-%m-%d %H:%M:%S" -AVERAGE = re.compile(r"\b(averages?|avg|mean)\b", I) -# "all metrics", "everything", "aq all week" (every reading, a week), but not the period "all time" nor "every day" or "each month" -# How many of a unit, before it: "every 30 minutes", "every ten minutes", "every half an hour", "every couple of hours", "every other hour" -_HOW_MANY = (r"(?:\d+\s*|(?:a\s+)?few\s+|half[\s-]+(?:an?\s+)?|quarter[\s-]+(?:of\s+)?(?:an?\s+)?|other\s+|(?:a\s+)?couple(?:\s+of)?\s+|" - r"(?:one|two|three|four|five|six|ten|twelve|fifteen|twenty|thirty|forty|sixty)(?:[\s-]+five)?\s+)") -ALL = re.compile(rf"\b(all(?![\s-]+time\b)|everything|(?:every|each)(?!\s+{_HOW_MANY}?(?:days?|nights?|weeks?|months?|years?|hours?|hrs?|" - r"min(?:ute)?s?|times?)\b))\b", I) -# Values at an interval ("each hour", "every 30 minutes", "hourly", "in 15 minute steps"): the readings tool, through the model, never -# a whole period's highs and lows. A speed or a rate ("miles per hour", "mm per hour") is a unit, not an interval: UNIT_PER takes it out first. -INTERVAL = re.compile(rf"\b(?:each|every)\s+{_HOW_MANY}?(?:hours?|hrs?|min(?:ute)?s?)\b|\bper\s+(?:hour|minute)\b|\btwice\s+an\s+hour\b|" - r"\b(?:half[\s-]+)?hourly\b|\bhour[\s-]+by[\s-]+hour\b|" - r"\b\d+[\s-]*(?:min(?:ute)?s?|hours?|hrs?)\s+(?:intervals?|steps?|increments?|resolution)\b", I) -UNIT_PER = re.compile(r"(?:\b(?:kms?|kilomet(?:re|er)s?|mi|miles?|mm|millimet(?:re|er)s?|inch(?:es)?|metres?|meters?|m|ft|feet|knots?|kmh|kph|" - r"mph)|\d(?:km|mm|m))\s+per\s+(?:hour|minute)\b|\bkm/h\s+per\s+(?:hour|minute)\b", I) - - -def asks_interval(text: str) -> bool: - """Does the question want values at an interval ("humidity each hour", "pm2.5 every ten minutes")? A chart is drawn in code as before.""" - return bool(INTERVAL.search(UNIT_PER.sub(" ", text))) and not GRAPH.search(text) - - -PER_DAY = re.compile(r"\b(each|every|per|by)\s+day|daily|day[- ]by[- ]day|which days|list|breakdown|one by one", I) - - -def _named(text: str) -> dict[str, int]: - """The readings a question names, with where. "dew point temperature" names the dew point, not also the temperature.""" - found = {name: m.start() for name, r in WEATHER_READINGS.items() if (m := re.search(rf"\b({r.words})\b", text, I))} - if "temperature" in found and any(name in found for name in SPECIFIC): - del found["temperature"] - return found - - -# "on two axes", "dual axis", "2 axes", "secondary axis", "overlay": two readings on one panel, each with a scale of its own -TWO_AXES = re.compile(r"\b(?:(?:two|2|dual|twin|double|secondary|second)[- ](?:y[- ]?)?ax[ie]s|overla(?:y(?:ed|ing|s)?|id))\b", I) - - -AG_NAMED = re.compile(rf"\b({_AG})\b", I) -AIR_EXTRA_WORDS = re.compile(r"\b(temp\w*|humid\w*)\b", I) - - -def wants_air_extra(text: str) -> bool: - """The air sensor's own temperature or humidity, named as the AirGradient's ("plot airgradient humidity over ecowitt humidity"): only - then are the tools offered those series. Temperature and humidity without the sensor named are the weather station's.""" - return bool(AG_NAMED.search(text) and AIR_EXTRA_WORDS.search(text)) - - -def chart_fields(text: str) -> list[str]: - """The readings named in the text, in order, when it names two or more ("plot temperature and rain"); else [].""" - found = _named(text) - if wants_chart_all(text): # "weather all week", "chart all 90d", "weather chart 90d": every reading, a panel each - indoors = _sides(text) == ["indoor"] # the indoor sensor only has these - return [n for n in service_names.in_all() if not indoors or n in INDOOR_READINGS] # the service's order and settings; naming one still works - return sorted(found, key=found.get) if len(found) >= 2 else [] - - -def wants_chart_all(text: str) -> bool: - """"weather all week", "chart all 90d", "weather chart 90d": every reading, a panel each (the picture says it all: no caption). - A chart that names no reading is of all of them, not of temperature.""" - named = len(_named(text)) - if named < 2 and ALL.search(text) and WEATHER_WORD.search(text): - return True - asked = GRAPH.search(text) or WEATHER_WORD.search(text) and _has_days(text, 2) # "weather 30d" is a chart too - return named == 0 and bool(asked) and not mentions_air(text) and not _judgement(text) - - -def chart_field(text: str) -> str | None: - """The one reading a question is about, if it isn't temperature ("lowest and highest humidity"); None when it - is about temperature, several readings, or none in particular.""" - found = list(_named(text)) - return WEATHER_READINGS[found[0]].field if len(found) == 1 and found[0] != "temperature" else None - - -# "rain chart 7d": a rain chart whose caption is just the least and most rain -RAIN_CHART = re.compile(r"^\s*rain\s+(chart|graph|plot)\b[^,&+]*$", I) - - -def wants_rain_caption(text: str) -> bool: - return bool(RAIN_CHART.search(text)) and not re.search(r"\band\b", text, I) - - -JUDGEMENT = (FORECAST, LINK, THINK, ANALYSIS, DESCRIBE) # questions that want the model's thinking, not just a chart +# The report's calls: the readings now (both devices), the pollen and the forecast's next 3 days (what the report has always shown) +REPORT_CALLS = {"current": ("current", {}), "pollen": ("pollen", {}), "forecast": ("forecast", {"period": "next 3 days"})} +WEATHER_NOW_CALL = ("current", {}) -def _judgement(text: str) -> bool: - return any(p.search(text) for p in JUDGEMENT) - - -def _sides(text: str) -> list[str]: - indoor, outdoor = bool(INDOOR.search(text)), bool(OUTDOOR.search(text)) - return ["indoor"] if indoor and not outdoor else ["outdoor"] if outdoor and not indoor else ["outdoor", "indoor"] - - -def _groups(text: str, names: list[str]) -> list[str]: - """The Ecowitt groups for these readings. Temperature and humidity come from both sensors unless one side is named; the - rest of what the indoor sensor measures (dew point, feels like) from the indoor one only when it is named.""" - groups = list(dict.fromkeys(WEATHER_READINGS[n].group for n in names)) - if "outdoor" in groups and ({"temperature", "humidity"} & set(names) or INDOOR.search(text) and set(INDOOR_READINGS) & set(names)): - groups = [g for g in groups if g != "outdoor"] + _sides(text) - return list(dict.fromkeys(groups)) - - -def bare_chart_ask(text: str, now: datetime) -> bool: - """Nothing but readings (or "weather") and a period: "humidity 7d", "weather 30d". Anything with a time range is a chart.""" - if not _has_days(text, 2, now) or not (_named(text) or WEATHER_WORD.search(text)): - return False # a day or less ("temperature today") is a figure to read, not a chart - rest = text - for said, _ in _periods(text, now).values(): - rest = re.sub(rf"\b{re.escape(said)}\b", " ", rest, flags=I) - patterns = [re.compile(rf"({r.words}|weather|{_ECOWITT}|conditions|indoors?|outdoors?)", I) for r in WEATHER_READINGS.values()] - return _only_words(rest, lambda word: any(p.fullmatch(word) for p in patterns)) - - -AVERAGE_READINGS = ("temperature", "humidity", "pressure", "wind", "dew_point", "feels_like", "vpd", "solar", "uv") # a rain total has no average - - -def _simple_weather(text: str, now: datetime) -> tuple[str, tuple[str, datetime, datetime], list[str]] | None: - """(kind, (period name, start, end), Ecowitt groups) for a weather question answered without the model, else None. The kinds: - "chart", a plain chart of named readings ("rain chart 7d", "plot temperature and humidity"); "average", a plain average, highest - or lowest of named readings ("average temp last week", "highest humidity yesterday"); "extremes", a highs/lows summary of the - temperature ("this week's high and low", "weather week", "indoor high yesterday"). A comparison, a forecast or a question that - wants thinking is the model's; so is one naming no period or several ("this week vs last week"), unless a chart's default (the - last day) applies.""" - if NOT_PLAIN.search(text): - return None - graph, plain, spans = bool(GRAPH.search(text)), not mentions_air(text) and not _judgement(text), spans_in(text, now) - if plain and (graph or bare_chart_ask(text, now)) and (fields := chart_fields(text) or list(_named(text))): - kind, groups, default = "chart", _groups(text, fields), not TIME_WORDS.search(text) - elif plain and (AVERAGE.search(text) or HILO.search(text)) and (names := list(_named(text))) and set(names) <= set(AVERAGE_READINGS): - kind, groups, default = "average", _groups(text, names), False - # "weather " is a summary request too, but "weather today" also wants current conditions; wind only as a plain chart - # ("wind direction plot 3m"), and then it is just wind - elif (not (NOT_HILO.search(text) or "wind" in _named(text) and not graph) - and (EXTREMES.search(text) or graph or WEATHER_WORD.search(text) and spans and {n for n, _, _ in spans} != {"today"})): - kind, groups = "extremes", ["wind"] if WIND.search(text) else _sides(text) - default = graph and WEATHER_SUBJECT.search(text) and not TIME_WORDS.search(text) - else: - return None - if not spans and default: - spans = [default_span(now)] # "chart weather": the last day - return (kind, spans[0], groups) if len(spans) == 1 else None +def report_calls(sources: Collection[str]) -> list[tuple[str, dict]]: + """The calls the report is written from, for these sources (by name).""" + return [*([REPORT_CALLS["current"]] if {"Ecowitt", "AirGradient"} & set(sources) else []), + *([REPORT_CALLS["pollen"]] if "Pollen" in sources else []), + *([REPORT_CALLS["forecast"]] if "Forecast" in sources else [])] -# ---------- air-quality fast path ---------- -# "how's the air?", "what's the AQI", "report my airgradient aq". History, comparisons and mixed -# weather questions go the normal way. +# ---------- which source a question is about (each source's wants(): fetch its newest readings while the question is answered) ---------- +POLLEN_WORDS = re.compile(r"\b(pollen|hay ?fever|thunderstorm asthma|asthma)\b", I) AIR = re.compile(rf"\b(air|aqi|aq|{_AIR_METRIC}|smok\w*|pollut\w*|particulates?|particles?|{_AG})\b", I) AIR_QUALITY = re.compile(r"\bair quality\b", I) -# What no air fast path answers: a comparison, a reason, a look ahead or another reading; the current reading also needs no past -# (period words, the past tense), no chart and no figure -_AIR_NOT = rf"compare\w*|vs|versus|than|why|forecast\w*|tomorrow|will|{_OTHER_THAN_AIR}" -AIR_CHART_NOT = re.compile(rf"\b({_AIR_NOT})\b", I) -AIR_NOT_NOW = re.compile( - rf"\b({_AIR_NOT}|yesterday|overnight|last|past|week|month|year|since|earlier|this morning|was|were|been|trend\w*|" - r"graph\w*|chart\w*|plot\w*|tonight|later|average|highest|lowest|peak|max\w*|min\w*|record\w*)\b", I) - - -def mentions_air(text: str) -> bool: - return bool(AIR.search(text) or AIR_QUALITY.search(text)) - - -def air_period(text: str, now: datetime) -> tuple[str, datetime, datetime] | None: - """(period name, start, end) for a plain air-quality chart request, else None. Any air question - with a period ("aq 1d", "air quality this week") is a chart; a graph word alone means the last - 24 hours.""" - if not mentions_air(text) or AIR_CHART_NOT.search(text): - return None - spans = spans_in(text, now) - if not spans and GRAPH.search(text) and not TIME_WORDS.search(text): - spans = [default_span(now)] - return spans[0] if len(spans) == 1 else None - - -PARTICULATES = re.compile(r"\b(particulates?|particles?|particulate matter)\b", I) -def air_named(text: str) -> list[str]: - """The air readings the text names ("pm10", "co2"); all of them for "all"; none if it only says air.""" - metrics = [m for _, m in AIR_METRICS] if ALL.search(text) else ["pm2_5", "pm10", "pm1"] if PARTICULATES.search(text) else [] - for pattern, metric in AIR_METRICS: - if re.search(rf"\b({pattern})", text, I) and metric not in metrics: - metrics.append(metric) - return metrics - - -def air_metrics(text: str) -> list[str]: - return air_named(text) or ["pm2_5"] - +def mentions_pollen(text: str) -> bool: + return bool(POLLEN_WORDS.search(text)) -# ---------- dispatch ---------- -# A particular date, weekday or time of day: the fast path only knows whole periods, so these go to the model -_MONTHS = r"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\w*" -SPECIFIC_MOMENT = re.compile( - rf"\b\d{{1,2}}(st|nd|rd|th)?\s+(of\s+)?{_MONTHS}|\b{_MONTHS}\s+\d{{1,2}}\b|\b\d{{1,2}}/\d{{1,2}}\b|" - r"\b\d{1,2}(:\d{2})?\s?(am|pm)\b|\b\d{1,2}:\d{2}\b|\b(noon|midnight|morning|afternoon|evening|overnight|tonight)\b|" - r"\b(mon|tues?|wed(nes)?|thu(rs?)?|fri|sat(ur)?|sun)(day)?\b", I) -# Plain lookups, answered in code from the tool's own result (no model): what is said is nothing but the reading asked for -FILLER = frozenset("what whats what's how hows how's is are it its it's the a an of tell me give show please like reading level speed " - "now currently current right at moment outside outdoors outdoor indoors indoor inside out there any we point".split()) -FORECAST_PLAIN = re.compile(_only(r"(weather\s+)?forecast(\s+(for\s+)?(the\s+)?(this\s+|next\s+)?(week|7 days|seven days|coming days))?|" - r"(the\s+)?(7|seven)[- ]day (weather )?forecast|(the\s+)?week ahead", - _ASK), I) +def mentions_air(text: str) -> bool: + return bool(AIR.search(text) or AIR_QUALITY.search(text)) -def reading_now(text: str) -> list[str] | None: - """The readings named when the text is only a plain question about them right now ("how hot is it", "is it raining", "uv"), else None.""" - if (GRAPH.search(text) or TIME_WORDS.search(text) or SPECIFIC_MOMENT.search(text) or mentions_air(text) - or _judgement(text) or not (names := list(_named(text))) or len(names) > 2): - return None - patterns = [re.compile(rf"({WEATHER_READINGS[n].words}|indoors?|outdoors?)", I) for n in names] - return names if _only_words(text, lambda word: any(p.fullmatch(word) for p in patterns)) else None - - -# Counting, ranking or totalling over periods ("count days over PM2.5 of 90 per year", "how many times", "rain per month"): the model -# picks the days tool, never a plain chart of the period -COUNTING = re.compile(r"\b(count\w*|how many|how often|number of|days? (over|above|below|under|with|when|that|where)|" - r"(per|by|each|every) (year|month)|monthly|yearly|annual\w*|worst|rank\w*|top \d+)\b", I) - - -# "days over UVI 10 by year", "count days over PM2.5 of 90 per year", "how many days was UV 9 or more": one reading against one limit, -# counted in code with weather_days or air_days (the model is not asked, so the answer is always the same bar chart or count) -OR_MORE = re.compile(r"\bor (?:more|higher|above|greater|over)\b", I) -OR_LESS = re.compile(r"\bor (?:less|lower|below|under)\b", I) -AT_LEAST = re.compile(r"\b(?:at least|reach\w*|hit|hits)\b", I) -ABOVE = re.compile(r"\b(?:over|above|more than|greater than|higher than|exceed\w*)\b", I) -BELOW = re.compile(r"\b(?:under|below|less than|lower than|fewer than|at most)\b", I) -def _figures(name: str, stem: str) -> tuple[dict[str, str], str]: - """A reading's daily fields by stat (temp_max, temp_min, temp_avg); none for its lowest when it has no low worth telling.""" - return {"max": f"{stem}_max", **({"min": f"{stem}_min"} if WEATHER_READINGS[name].low else {}), "avg": f"{stem}_avg"}, "avg" - - -# A reading's weather_days field for each stat a question asks of it ("max" its highest, "min" its lowest, "avg" its average, -# "sum" its total), and the stat when it names none. Without a "min" it has no lowest to ask for. -DAILY = { - **{name: _figures(name, stem) for name, stem in (("temperature", "temp"), ("humidity", "humidity"), ("pressure", "pressure"), - ("dew_point", "dew_point"), ("feels_like", "feels_like"), ("vpd", "vpd"), - ("solar", "solar"))}, - "uv": ({"max": "uv_max", "min": "uv_max", "avg": "uv_max"}, "max"), # a UV index is its day's high, whatever is asked of it - "wind": ({"max": "wind_gust", "avg": "wind_speed_avg"}, "avg"), # its highest is a gust - "rain": ({"max": "rain", "min": "rain", "sum": "rain"}, "sum"), # a day's rain is its total -} -HOLIDAYISH = re.compile(r"\b(holidays?|weekends?|saturdays?|sundays?)\b", I) - - -def _limits(rest: str) -> list[str]: - """The numbers in the text that aren't a year or part of a period: "UV over 9 for 3 months in 2024" -> ["9"].""" - return re.findall(r"(? tuple[str, dict[str, str]] | None: - """(name, the start_date and end_date arguments) of what a count or a figure per period covers: the period named, a calendar year - ("in 2024": up to now, if it is this one), else everything on record; None when the text names more than one.""" - spans, years = spans_in(rest, now), set(re.findall(r"\b((?:19|20)\d\d)\b", rest)) - if len(spans) + len(years) > 1: - return None - if years: - year = int(years.pop()) - name, start, end = str(year), datetime(year, 1, 1), min(datetime(year, 12, 31, 23, 59, 59), now) - else: - name, start, end = spans[0] if spans else ("on record", *span("on record", now)) - return name, {"start_date": start.strftime("%Y-%m-%d"), "end_date": end.strftime("%Y-%m-%d")} - - -_NOT_COUNTED = (FORECAST, LINK, THINK, DESCRIBE, HOLIDAYISH) # a look ahead, a judgement or particular days: the model's - - -def _daily_reading(text: str, sources: Collection[str]) -> tuple[str, str, dict[str, str], str] | None: - """(tool, reading, its daily fields by stat, the stat when none is named) for the one reading a days question names: an air - reading goes to air_days (it needs the AirGradient), a weather one to weather_days (the Ecowitt); None when it names none, - several, "all", or a reading without daily figures.""" - if mentions_air(text): - metrics = air_named(text) - if "AirGradient" not in sources or len(metrics) != 1 or ALL.search(text): - return None - return "air_days", metrics[0], {stat: f"{metrics[0]}_{stat}" for stat in ("max", "min", "avg")}, "avg" - names = list(_named(text)) - if "Ecowitt" not in sources or len(names) != 1 or names[0] not in DAILY: - return None - return "weather_days", names[0], *DAILY[names[0]] +# ---------- a named reading's chart and a period ---------- +CHART_WORDS = ("chart", "charts", "graph", "plot") +# The keyboard's and the alerts' sentences whose readings aren't the service's words (lib/templates.py, lib/alerts/pictures.py): +# their readings, as the service's words +SENTENCE_READINGS = {"air quality all metrics": ["air"], "particulates": ["pm2.5", "pm10", "pm1"]} +BARE_MIN = timedelta(days=1) # " " with no chart word is a chart only over more than a day ("humidity 7d"; not + # "rain today": a figure to read) +APOSTROPHES = str.maketrans("’‘", "''") # a phone's typographic apostrophes ("what’s"), read as the plain one every pattern uses -def count_days_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool, arguments, label) when the text asks how many days one reading was over or under one limit (optionally per year or month), - else None and the model decides.""" - if (not re.search(r"\bdays?\b|\btimes\b", text, I) or any(p.search(text) for p in _NOT_COUNTED) - or re.search(r"\b(and|also|both|but)\b", text, I)): - return None - below, above = bool(BELOW.search(text) or OR_LESS.search(text)), bool(ABOVE.search(text) or OR_MORE.search(text) or AT_LEAST.search(text)) - if below == above: # neither, or both: not a plain comparison - return None - op = ">=" if OR_MORE.search(text) or AT_LEAST.search(text) else "<=" if OR_LESS.search(text) else "<" if below else ">" - rest = GROUPING.sub(" ", text) - if len(numbers := _limits(rest)) != 1 or not (reading := _daily_reading(text, sources)) or not (period := _whole_period(rest, now)): - return None - tool, name, fields, _ = reading - field = fields.get("min", fields["max"]) if below else fields["max"] # under a limit: its lowest, if it has one - if name == "uv" and op == ">": # a UV index is quoted in whole numbers: "over 10" means the days that read 10 - op = ">=" - name_, dates = period - args = {"where": [{"field": field, "op": op, "value": float(numbers[0])}], "count_only": True, **dates} - if by := grouping_in(text): - args["group_by"] = by - return tool, args, f"days count, {name_}" - - -# "rain by month for 2 years", "average temperature per year", "highest PM2.5 by month": one reading, a figure for each month or year, worked -# out in code (weather_days or air_days with stat, of and group_by): one bar for each month or year, the same figure a text line would give -HIGHER = re.compile(r"\b(hottest|highest|max\w*|peak\w*|wettest|windiest|warmest|worst|strongest|biggest)\b", I) -LOWER = re.compile(r"\b(coldest|lowest|min\w*|driest|coolest|calmest|smallest)\b", I) - - -def period_figures_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool, arguments, label) when the text asks for one reading's figure by or per month or year, else None (the model decides).""" - if (not (by := grouping_in(text)) or any(p.search(text) for p in (*_NOT_COUNTED, ABOVE, BELOW, OR_MORE, OR_LESS, AT_LEAST)) - or re.search(r"\b(and|also|both|but|days|times)\b", text, I)): - return None - rest = GROUPING.sub(" ", text) - high, low = bool(HIGHER.search(text)), bool(LOWER.search(text)) - if (_limits(rest) or high and low # a limit or another number, or both ways: not a plain figure per period - or not (reading := _daily_reading(text, sources)) or not (period := _whole_period(rest, now))): +def _readings(words: list[str], catalogue) -> list[str] | None: + """The readings these words name, as the person said them (each one the service's catalogue reads), else None.""" + said = " ".join(words) + from .service.names import UnknownReading + parts = list(SENTENCE_READINGS[said]) if said in SENTENCE_READINGS else [p.strip() for p in re.split(r",|&|\band\b", said)] + if not all(parts): return None - tool, _, fields, plain = reading - stat = "max" if high else "min" if low else plain - if stat not in fields: # a lowest of a reading that has none (wind, solar) + try: + return parts if all(catalogue.resolve(p, default=None) for p in parts) else None + except UnknownReading: return None - name_, dates = period - return tool, {"stat": stat, "of": fields[stat], "count_only": True, "group_by": by, **dates}, f"figures by {by}, {name_}" -def fast_call(text: str, now: datetime, sources: Collection[str]) -> tuple[str, dict, str] | None: - """(tool name, arguments, what it is) for a question the bot can fetch for without the model, from these sources (by name).""" - if asks_interval(text): # "each hour", "highest hourly rain each month": an interval's figures, never a day's or a period's - return None - if (counted := count_days_call(text, now, sources)) or (counted := period_figures_call(text, now, sources)): - return counted - ecowitt, air, pollen, forecast = ("Ecowitt" in sources, "AirGradient" in sources, "Pollen" in sources, "Forecast" in sources) - if SPECIFIC_MOMENT.search(text) or COUNTING.search(text): # "high on 5 Jan this year", "at 3pm today": a whole period would be the wrong data +def _period(words: list[str], now: datetime, tz: tzinfo, bare: bool) -> str | None: + """These words as a period the service reads (summary's, not whole days), passed on as they are; None when it can't read them (or, + bare: when they are a day or less).""" + from .periods_text import PeriodError, read_period + said = " ".join(words) + if not said: return None - if air and (period := air_period(text, now)): - name, start, end = period - return "air_quality", {"chart": True, "metrics": air_metrics(text), - "start_date": start.strftime(FMT), "end_date": end.strftime(FMT)}, f"air quality chart, {name}" - if air and mentions_air(text) and not AIR_NOT_NOW.search(text) and not TIME_WORDS.search(text): - return "air_quality", {}, "air quality now" - if pollen and (POLLEN_NOW.search(text) and not TIME_WORDS.search(text) or pollen_ask(text)): - return "pollen_asthma", {}, "pollen and thunderstorm asthma" - if ecowitt and wants_weather_now(text): - return "weather_now", {"groups": NOW_GROUPS}, "weather now" - if forecast and FORECAST_PLAIN.search(text): - return "weather_forecast", {"days": 7}, "forecast" - if ecowitt and reading_now(text): - return "weather_now", {"groups": NOW_GROUPS}, "weather reading now" - if ecowitt and (simple := _simple_weather(text, now)): - kind, (name, start, end), groups = simple - # a chart when one is asked for, over 3+ days or an hours-long window; a day or two of highs and lows is figures - chart = kind == "chart" or (end - start).days >= 2 or name.endswith("hours") or bool(GRAPH.search(text)) - average = {"average": True} if kind == "average" and AVERAGE.search(text) else {} - return "weather_history", {"groups": ",".join(groups), **average, "chart": chart, "start_date": start.strftime(FMT), - "end_date": end.strftime(FMT)}, f"weather {'chart' if kind == 'chart' else 'history'}, {name}" + try: + read = read_period(said, None, None, now=now, tz=tz, default=said) + except (PeriodError, ValueError): + return None + return said if not bare or read.end - read.start > BARE_MIN else None + + +def chart_call(text: str, now: datetime, tz: tzinfo, catalogue=None) -> tuple[str, dict] | None: + """The service call of a message that is only a named reading's chart and a period: " chart ", "chart + " or " " (over more than a day): summary {readings: the words, period: the words, chart: true}; None + for anything else (a question beside it, an average, two axes, no period: the model's). `catalogue`: the service's readings (default: + every reading it knows).""" + if catalogue is None: + from .service.names import CATALOGUE as catalogue + said = text.translate(APOSTROPHES).strip().rstrip("?.!").split() # (the period goes on as it was said, case and all) + words = [w.lower() for w in said] + chart = [i for i, w in enumerate(words) if w in CHART_WORDS] + if len(chart) > 1: + return None + if chart and chart[0] == 0: # "chart " + splits = [(words[1:i], said[i:]) for i in range(2, len(words))] + elif chart: # " chart " + splits = [(words[:chart[0]], said[chart[0] + 1:])] + else: # " " + splits = [(words[:i], said[i:]) for i in range(1, len(words))] + for named, period_words in splits: + bare = not chart and " ".join(named) not in SENTENCE_READINGS # ("Air quality all metrics 1d": a button's chart) + if (readings := _readings(named, catalogue)) and (period := _period(period_words, now, tz, bare)): + return "summary", {"readings": readings, "period": period, "chart": True} return None -# ---------- what the model needs for a question: guidance for the prompt, tools for the call ---------- -DAYS_WORDS = re.compile(r"\b(days?|how many|how often|most|least|ranks?|ranking|top|worst|best|holidays?|weekends?|" - r"hottest|coldest|wettest|driest|windiest|warmest|coolest|compare\w*|versus|vs|yesterday)\b", I) -OUTLOOK_WORDS = re.compile(r"\b(rain\w*|umbrella|showers?|wet|storms?|later|soon|going to|will|about to)\b", I) -WIND_WORDS = re.compile(rf"\b({_WIND}|direction)\b", I) -BOT_WORDS = re.compile(r"\b(can|could|do|does|are|will)\s+(you|the bot)\b|\b(alerts?|notify|notification\w*|support\w*|capabilit\w*|able to|add|set up|remind)\b", I) -COMPARE = re.compile(r"\b(against|versus|vs|compare\w*|affect\w*|influence\w*|correlat\w*|relat\w*|link\w*|cause\w*)\b", I) - - -def topics_in(said: str) -> set[str]: - """The guidance topics one message touches: air, air_extra (the air sensor's own temperature or humidity), days, link, outlook, wind, - describe, bot.""" - return {name for name, hit in ( - ("air", mentions_air(said)), ("air_extra", wants_air_extra(said)), - ("days", bool(DAYS_WORDS.search(said) or ANALYSIS.search(said) or SPECIFIC_MOMENT.search(said))), - ("link", bool(LINK.search(said)) or bool(COMPARE.search(said)) and bool(OUTLOOK_WORDS.search(said))), - ("outlook", bool(FORECAST.search(said)) or bool(OUTLOOK_WORDS.search(said))), - ("wind", bool(WIND_WORDS.search(said))), ("describe", bool(DESCRIBE.search(said))), - ("bot", bool(BOT_WORDS.search(said)) or about_the_bot(said) or bool(COMMAND.search(said))), - ) if hit} - - -def topics(text: str, before: list[str] = ()) -> set[str]: - """What guidance and tools the question needs beyond the basics, from its words and the messages just before it (a follow-up - like "and indoors?" is about what came before). Generous on purpose: a topic that isn't needed costs a few tokens, one that - is missing costs the answer.""" - found: set[str] = set() - for said in (*before, text): - found |= topics_in(said) - return found - - -# The topic a tool call is evidence of: a chat that is being answered with these is still on the topic -TOOL_TOPICS = {"weather_days": "days", "air_days": "days", "weather_link": "link", "air_link": "link", "air_scan": "link", - "weather_forecast": "outlook", "air_quality": "air"} - - -# "will it rain?", "do I need an umbrella?", "rain later?": the model reasons from the station, and the forecast (if on) comes with it -RAIN_AHEAD = re.compile(r"\b(umbrella|chance of rain|(will|going to|gonna|likely to|expect\w*)\b.*\brain\w*|" - r"rain\w*\b.*\b(later|soon|tonight|tomorrow|this (afternoon|evening)|coming|next)\b)", I) -WEEK_AHEAD = re.compile(r"\b(week|days|weekend|next \w+day)\b", I) - - -def model_prefetch(text: str, now: datetime, sources: Collection[str]) -> list[tuple[str, dict]]: - """What the model would fetch first for these questions, fetched here instead (so it answers in one call, not two): for rain - ahead, the current reading, the last 3 hours and the forecast (cached); for a described today or yesterday, that day's readings.""" - calls: list[tuple[str, dict]] = [] - ecowitt = "Ecowitt" in sources - if RAIN_AHEAD.search(text): - if ecowitt: - groups = "outdoor,pressure,rainfall,rainfall_piezo,wind" - calls += [("weather_now", {"groups": groups}), - ("weather_history", {"groups": groups, "start_date": (now - timedelta(hours=3)).strftime(FMT), "end_date": now.strftime(FMT)})] - if "Forecast" in sources: - calls.append(("weather_forecast", {"days": 7 if WEEK_AHEAD.search(text) else 3, "cached": True})) - elif ecowitt and DESCRIBE.search(text) and not SPECIFIC_MOMENT.search(text): - spans = spans_in(text, now) - if len(spans) == 1 and spans[0][0] in ("yesterday", "today", "last 24 hours"): - _, start, end = spans[0] - calls.append(("weather_history", {"groups": "outdoor,indoor,rainfall,wind", "start_date": start.strftime(FMT), "end_date": end.strftime(FMT)})) - return calls - - - +# ---------- one message ---------- @dataclass class Intent: """Everything decided about one message before the model sees it.""" effort: str = EFFORT_DEFAULT - needs_data: bool = False # the model must call a tool first - about_the_bot: bool = False # answered without tools - report: bool = False # "status": the full report + report: bool = False # "status": the report, written in code dashboard: bool = False # "dashboard": the station's gauges, one picture - hints: list[str] = field(default_factory=list) # what the period words in the message mean - fast: tuple[str, dict, str] | None = None # (tool, arguments, what it is): fetched here, before the model - chart_asked: bool = False # "plot" means a chart, whatever the model calls - chart_field: str | None = None # humidity questions get a humidity chart - chart_fields: list[str] = field(default_factory=list) # "temperature and rain": one chart, a panel each - two_axes: bool = False # "uvi and solar on two axes": the two share one panel, a scale each - air_extra: bool = False # "airgradient humidity": the air sensor's own temperature and humidity are offered to the model - average_asked: bool = False - more: list[tuple[str, dict]] = field(default_factory=list) # the rest of the report's calls (fast is the first) - weather_now: bool = False # "weather now": every reading the station has, in the report's layout - rain_caption: bool = False # "rain chart 7d": the caption is just the least and most rain - chart_in_code: bool = False # a chart asked for plainly: fetched and captioned in code, no model - readings: list[str] = field(default_factory=list) # the readings the words name - per_day: bool = False # figures day by day were asked for - extra: list[tuple[str, dict]] = field(default_factory=list) # fetched with the model's first step (the forecast, for "will it rain?") - lookup: str = "" # "reading", "air", "days", "extremes", "pollen", "forecast" or "about": answered in code, no model - lookup_arg: list[str] = field(default_factory=list) # the readings named ("reading", "air"; none: all) - sides: list[str] = field(default_factory=list) # "indoor", "outdoor" or both, for a reading + weather_now: bool = False # "weather now": every reading the station has now, written in code + chart: tuple[str, dict] | None = None # a named reading's chart and a period: the service call that draws it @property - def tool_choice(self) -> str: - """What the model's first step may do with the tools (see Agent.run): none about the bot itself, a fetch it must make - when the answer needs data, else its own choice.""" - return "none" if self.about_the_bot else "required" if self.needs_data else "auto" - - -PLAIN_LOOKUPS = {"pollen_asthma": "pollen", "weather_days": "days", "air_days": "days", "weather_forecast": "forecast"} # whatever the words - - -def plain_lookup(text: str, fast: tuple | None) -> tuple[str, list[str]]: - """(kind, readings named) for a question answered in code from one tool result, else ("", []). The tools in PLAIN_LOOKUPS always - are; a weather or air reading only when the words ask for nothing more.""" - if about_the_bot(text): - return "about", [] - if not fast: - return "", [] - tool, args = fast[0], fast[1] - if tool in PLAIN_LOOKUPS: - return PLAIN_LOOKUPS[tool], [] - if _judgement(text): - return "", [] - if tool == "weather_history" and not args.get("chart"): - return "extremes", list(_named(text)) - if tool == "weather_now" and (names := reading_now(text)): - return "reading", names - if tool == "air_quality" and not args and len(text.split()) <= 6: - return "air", air_named(text) - return "", [] + def shortcut(self) -> bool: + """Is it answered in code (no model)?""" + return bool(self.report or self.dashboard or self.weather_now or self.chart) -APOSTROPHES = str.maketrans("’‘", "''") # a phone's typographic apostrophes ("what’s"), read as the plain one every pattern uses - - -def read(text: str, now: datetime, sources: Collection[str] = ("Ecowitt", "AirGradient")) -> Intent: +def read(text: str, now: datetime, sources: Collection[str] = ("Ecowitt", "AirGradient"), tz: tzinfo | None = None, + catalogue=None) -> Intent: """The decisions made in code for this message, given the sources the bot has (by name: "Ecowitt", "AirGradient", "Pollen", - "Forecast"). A shortcut that fails is dropped: the model handles the question.""" + "Forecast"), at `now` (aware, or naive on the station's clock `tz`), over the service's catalogue (default: every reading).""" text = text.translate(APOSTROPHES) ecowitt = "Ecowitt" in sources - report = wants_report(text) - calls = report_calls(sources) if report else [] + tz = tz or now.tzinfo + report = wants_report(text) and bool(report_calls(sources)) + shortcut = report or (ecowitt and (wants_dashboard(text) or wants_weather_now(text))) try: - fast = (*calls[0], "report") if calls else fast_call(text, now, sources) + chart = None if shortcut or tz is None or not ({"Ecowitt", "AirGradient"} & set(sources)) else chart_call(text, now, tz, catalogue) except Exception as e: - log.error("Fast path failed (%s: %s); using the normal path", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - fast = None - in_code = bool(fast and fast[0] in ("weather_history", "air_quality") and fast[1].get("chart") - and not _judgement(text)) - rain_caption = ecowitt and wants_rain_caption(text) - lookup, named = plain_lookup(text, fast) if not (report or in_code) else ("", []) - return Intent(effort=reasoning_effort(text), needs_data=needs_data(text), about_the_bot=about_the_bot(text), report=report, - hints=period_hints(text, now), fast=fast, chart_asked=bool(GRAPH.search(text)), chart_field=chart_field(text), - chart_fields=chart_fields(text), two_axes=bool(TWO_AXES.search(text)) and len(chart_fields(text)) == 2, air_extra=wants_air_extra(text), average_asked=bool(AVERAGE.search(text)), more=calls[1:], - weather_now=ecowitt and wants_weather_now(text), dashboard=ecowitt and wants_dashboard(text), rain_caption=rain_caption, chart_in_code=in_code, - readings=list(_named(text)), per_day=bool(PER_DAY.search(text)), - extra=model_prefetch(text, now, sources) if not fast else [], lookup=lookup, lookup_arg=named, sides=_sides(text)) + log.error("Couldn't read %r as a chart (%s: %s); the model takes it", text, type(e).__name__, e) + chart = None + return Intent(effort=reasoning_effort(text), report=report, dashboard=ecowitt and wants_dashboard(text), + weather_now=ecowitt and wants_weather_now(text) and not report, chart=chart) + + +__all__ = ["EFFORT_DEFAULT", "Intent", "chart_call", "lower_effort", "mentions_air", "mentions_pollen", "read", "reasoning_effort", + "report_calls", "wants_dashboard", "wants_report", "wants_weather_now"] diff --git a/lib/llm.py b/lib/llm.py index b156d4ed..06d013ae 100644 --- a/lib/llm.py +++ b/lib/llm.py @@ -78,22 +78,18 @@ async def _stream(self, kwargs: dict, on_text) -> tuple[str, list[dict], object] on_text(content) return content, [calls[i] for i in sorted(calls)], usage - async def run(self, messages: list[dict], system_prompt: str, effort: str, *, - first_call: tuple[str, dict] | list[tuple[str, dict]] | None = None, tool_choice: str = "required", + async def run(self, messages: list[dict], system_prompt: str, effort: str, *, tool_choice: str = "auto", turn: Turn | None = None, on_text=None, on_heavy=None, finish=None) -> str: """Runs the tool loop, appending assistant/tool turns to `messages` in place. The prompt is passed per question (not stored) so concurrent chats can't clash. - first_call (tool name, args), or a list of them, is what the bot already worked out (the fast path): the calls run - straight away, together, and the model is only invoked once the data is in. tool_choice is what the model's first - step may do with the tools: "required" makes it fetch fresh data first (weather questions), "auto" lets it just - reply (chat), "none" gives it no tools at all (a question about the bot itself). Every later step is "auto". - on_text(text so far) is called as each answer streams in (private chats show it as a draft). + tool_choice is what the model's first step may do with the tools ("auto": its own choice; every later step is "auto", the + last forced answer "none"). on_text(text so far) is called as each answer streams in (private chats show it as a draft). on_heavy(tokens) is called once, before the model is sent a lot of data: when the tool results of a question pass WARN_TOKENS (twice a 500-point query), so the chat can be told first. The work carries on; nothing waits for a reply. - finish(calls, results) is asked after each step of the model's own tool calls (never after first_call): text from it is - the reply, and the turn ends there with no further model call (the bot's chart that answers the question by itself).""" + finish(calls, results) is asked after each step of the model's tool calls: text from it is the reply, and the turn ends there + with no further model call (a complete result, docs/mcp-service.md 3.7).""" cache: dict = {} # identical tool calls within one question are only made once async def call(name: str, args: str) -> str: @@ -127,22 +123,14 @@ async def run_calls(calls: list[dict]) -> list[str]: messages.extend({"role": "tool", "tool_call_id": c["id"], "content": r} for c, r in zip(calls, results)) return results - first_step = 0 try: - if first_call: - fast = [{"id": f"fast_{i}", "name": n, "arguments": json.dumps(a)} - for i, (n, a) in enumerate(first_call if isinstance(first_call, list) else [first_call], 1)] - messages.append({"role": "assistant", "content": "", "tool_calls": [_tool_call(c) for c in fast]}) - await run_calls(fast) - await heavy_check() - first_step = 1 # data is in; the model just answers (and may still call tools) - for step in range(first_step, MAX_STEPS + 1): + for step in range(MAX_STEPS + 1): final = step == MAX_STEPS # out of steps: force an answer from what we have kwargs = {"model": self.model, "messages": [{"role": "system", "content": system_prompt}, *messages], "extra_body": {"reasoning": {"effort": effort}}} # OpenRouter's setting for every model that reasons: none / low / medium / high if self.tools.schemas: # every tool, every time: the same list keeps the provider's cached prompt valid - kwargs["tools"] = self.tools.schemas_for(turn) + kwargs["tools"] = self.tools.schemas kwargs["tool_choice"] = "none" if final or tool_choice == "none" else tool_choice if step == 0 else "auto" if final: log.warning("Tool step limit (%d) reached - asking for a final answer", MAX_STEPS) @@ -158,7 +146,7 @@ async def run_calls(calls: list[dict]) -> list[str]: return content.strip() or "Sorry, I couldn't get an answer together - try a narrower question." results = await run_calls(tool_calls) if finish and (reply := finish(tool_calls, results)): - log.info("The turn ended on a chart that answers the question (%s): no LLM %d", + log.info("The turn ended on a complete result (%s): no LLM %d", ", ".join(c["name"] for c in tool_calls), step + 2) messages.append({"role": "assistant", "content": reply}) return reply diff --git a/lib/model_tools.py b/lib/model_tools.py new file mode 100644 index 00000000..53be5e5a --- /dev/null +++ b/lib/model_tools.py @@ -0,0 +1,43 @@ +"""The service's ten tools (lib/service) as the bot offers them to its model (docs/mcp-service.md 4): each by its own name, description +and parameters, as they are. The bot draws the charts itself, so it asks for them as drawn (request `_meta` `chart_points: "drawn"`) +and keeps each whole result on the question's Turn (`Turn.results`: for drawing, the period buttons, the complete result that ends the +turn, the forecast days shown; a call that gave no JSON object leaves None); the model is sent the result less the charts' data (`for_model`): each chart as its title and period, +with `chart_note`, `caption`, `reply` and `complete` as they are.""" + +import json + +from .service.common import AS_DRAWN +from .tools import Tool, Tools, Turn, json_result + + +def for_model(out: dict) -> dict: + """A result as the model is sent it: `charts` as [{title, period}] (the bot draws them), everything else as it is.""" + if not isinstance(out.get("charts"), list): + return out + return {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} + + +def tool(service_tool) -> Tool: + """One ServiceTool as the model is offered it: run with the question's metadata, charts as drawn; the whole result kept on the + Turn, the model sent for_model of it.""" + async def handle(args: dict, turn: Turn) -> str: + slot = len(turn.results) # (taken before the call: the calls of a step run together, and keep the order they were made in) + turn.results.append(None) + text = await service_tool.call(args, {**turn.meta, "chart_points": AS_DRAWN}) + try: + out = json.loads(text) + except ValueError: + return text + if not isinstance(out, dict): + return text + turn.results[slot] = (service_tool.name, args, out) + return json_result(for_model(out)) + return Tool(service_tool.name, service_tool.description, service_tool.parameters, handle) + + +def tools(service) -> Tools: + """The service's tools (a lib.service.Service, or any list of ServiceTools), in its order, as the model is offered them.""" + return Tools([tool(t) for t in service]) + + +__all__ = ["for_model", "tool", "tools"] diff --git a/lib/periods.py b/lib/periods.py index 851271de..f6fae87a 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -4,10 +4,8 @@ each with its label ("7d", "7D"). Its buttons are those periods, the chart's own shaded (the blue of an alert toggle that is on), and none when it lists none (but a 🔄, "pd:reload", that draws it again when its period runs to now); a button's data is the period ("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one replays the call with that period -(Bot.on_period_button); what drew each chart is remembered for that (Charted). - -A chart the model drew through the old tools whose call has no service equivalent keeps the old buttons, 1D / 7D / 1M / 3M / 1Y (1, -7, 30, 90 and 365 days, "pd:7"), which ask its question again with that period.""" +(Bot.on_period_button); what drew each chart is remembered for that (Charted). A chart remembered by its question (sent before every +chart carried its drawn_by) answers that it is out of date.""" import json import time @@ -21,8 +19,6 @@ from . import charts from .buttons import button -NAMES = {1: "1D", 7: "7D", 30: "1M", 90: "3M", 365: "1Y"} # each period, in days, and what its button says (a question asked again) -PERIODS = tuple(NAMES) PREFIX = "pd:" REMEMBERED = 300 # charts whose call is kept, newest first to stay WHOLE_DAY_TOOLS = ("days", "relate", "scan") # the tools that read a period as whole days, up to yesterday @@ -30,20 +26,6 @@ RELOAD = "reload" # the 🔄 under a chart with no periods to offer whose period runs to now: its call replayed as it is ("pd:reload") -def keyboard(current: int | None = None) -> InlineKeyboardMarkup: - """The old row of period buttons, for a question asked again; the one for the chart's own period (`current`, in days) is shaded.""" - return InlineKeyboardMarkup([[button(NAMES[days], f"{PREFIX}{days}", KeyboardButtonStyle.PRIMARY if days == current else None) - for days in PERIODS]]) - - -def days_in(data: str | None) -> int | None: - """The period an old button's callback data asks for ("pd:7"), if it is one of ours.""" - if not data or not data.startswith(PREFIX): - return None - days = data.removeprefix(PREFIX) - return int(days) if days.isdigit() and int(days) in PERIODS else None - - def period_in(data: str | None) -> str | None: """The period a button under a service's chart asks for ("pd:7d" -> "7d").""" return data.removeprefix(PREFIX) if data and data.startswith(PREFIX) and data != PREFIX else None diff --git a/lib/pollen/source.py b/lib/pollen/source.py index fa71983f..a32ba1b7 100644 --- a/lib/pollen/source.py +++ b/lib/pollen/source.py @@ -15,8 +15,7 @@ from ..config import Config from ..snapshots import Snapshots from ..sources import Source -from ..timeutil import day_text, local_date, when -from ..tools import Tool, Turn, json_result +from ..timeutil import day_text, local_date from ..warm import Warmer, in_sync_hours from .parse import DISTRICTS, LEVEL_EMOJI, parse_melbourne_pollen @@ -28,11 +27,6 @@ SEASON_MONTHS = (10, 11, 12) # grass pollen and the thunderstorm asthma forecast run October to December: nothing else is fetched, shown or alerted OFF_SEASON = "Pollen and thunderstorm asthma forecasts only run from October to December." -DESCRIPTION = ("Melbourne's grass pollen level today and the thunderstorm asthma risk (Low, Moderate, High or Extreme), from " - "melbournepollen.com.au. Use it for pollen, hay fever and thunderstorm asthma questions. Takes no arguments. " - "The result's \"lines\" are ready-made, emoji included: copy them as they are.") -PARAMETERS = {"type": "object", "properties": {}} - def _district(name: str) -> str: """The site's name for this district, whatever its case. One the site doesn't have is warned about: no level can be found for it.""" @@ -56,7 +50,6 @@ def __init__(self, cfg: Config, transport=None): self.store = Snapshots(cfg.storage_path) self._load() self.warmer = Warmer(self.warm, POLLEN_REFRESH_SECONDS) - self.tools = [Tool("pollen_asthma", DESCRIPTION, PARAMETERS, self.handle)] async def start(self): if not self.in_season(): @@ -68,9 +61,6 @@ async def start(self): except Exception as e: # the site may just be briefly unreachable log.warning("Pollen not readable yet: %s", e) - def describe(self) -> str: - return "Melbourne pollen forecast and thunderstorm asthma risk (melbournepollen.com.au) (people say \"pollen\" or \"hay fever\")" - def wants(self, text: str) -> bool: """Only pollen questions start a refresh; the report always uses what is cached.""" return intent.mentions_pollen(text) @@ -146,25 +136,3 @@ def lines(self) -> list[str]: if a := cur["asthma"]: out.append(f"Thunderstorm asthma forecast: {a['emoji']} {a['level']}") return out - - async def handle(self, args: dict, turn: Turn | None = None) -> str: - if not self.in_season(): - return json_result({"error": OFF_SEASON}) - if self.page is None and not args.get("cached"): # the report ("cached") never fetches - try: - await self.warm(True) - except Exception as e: - log.warning("Pollen not readable: %s", e) - lines = self.lines() - if not lines: - return json_result({"error": "No pollen levels are available right now."}) - cur = self.current() - out = {"lines": lines, "place": self.place, "source": "melbournepollen.com.au (grass pollen from pollen-trap data; asthma risk from the " - "Victorian Department of Health and BOM, 1 Oct - 31 Dec)"} - if cur["fetched_at"]: - out["time"] = when(int(cur["fetched_at"]), self.tz) # when the page was last fetched - if cur["asthma"] and cur["asthma"]["updated"]: - out["asthma_updated"] = cur["asthma"]["updated"] - if not cur["asthma"]: # in season the page always has one: it may have changed - out["asthma_note"] = "The page had no thunderstorm asthma level for this district when it was last read." - return json_result(out) diff --git a/lib/prompt.py b/lib/prompt.py index 9ab9eafa..65700c14 100644 --- a/lib/prompt.py +++ b/lib/prompt.py @@ -1,242 +1,40 @@ -"""The system prompt. Everything the model would otherwise have to work out (dates, devices, -units, wording of times) is decided in code and handed over ready-made.""" +"""The bot's system prompt (docs/mcp-service.md 4): its persona, a friendly Telegram bot, then the server's instructions +(lib/service/instructions.py) and the date and time now. Everything about the tools and the data is in their descriptions and results +(3.2): nothing here is about which tool to call or how to read what comes back.""" -from collections.abc import Collection from datetime import datetime -from .airgradient.metrics import ALL_METRICS, CHART_UNITS, LABELS -from .alerts.forecast import TEMP_CHANGE_C -from .alerts.menu import TYPES -from .alerts.weather import GUST_ALERT_KMH -from .ecowitt.glance import UVI_ALERT -from .intent import period_ranges -from .series import WEATHER -from .timeutil import day_text - -WEATHER_NAMES = list(WEATHER) -NEVER_AVAILABLE = ["lightning", "soil or extra sensor channels", "indoor air quality", "other stations or places"] -WITHOUT = {"Pollen": "pollen and thunderstorm asthma", "Forecast": "forecasts (only a short read of the pressure trend)"} # what a source that is off leaves out -# Each alert type as the prompt describes it, with its own threshold; told only when the source that sends it is on (alerts.menu.TYPES) -ALERT_WORDS = {"rain": "rain starting or stopping", "gusts": f"wind gusts over {GUST_ALERT_KMH} km/h", - "uv": f"UV index of {UVI_ALERT} or more", "temps": "indoor/outdoor temperature crossing", - "particulates": "air-quality mask alerts", "pollen_and_asthma": "pollen or thunderstorm asthma risk reaching High", - "forecast": f"a forecast it sent being revised (rain, or max temperature over {TEMP_CHANGE_C:g} degrees)"} - -PROMPT = """\ -You are a friendly weather bot on Telegram. -People ask about the owner's personal weather station and air-quality sensor: current conditions and historical data. Always fetch data with your tools; never guess or invent readings. If data is missing, say so briefly. - -DATA SOURCES (already discovered - no lookup needed) -{sources} -People name the devices too: "ecowitt" means the weather station, exactly like "weather" (the weather_* tools); "ag", "airgradient" and "air gradient" mean the air-quality sensor, exactly like "aq" and "air quality" (the air_quality tool). -{capabilities} -TIME PERIODS -- A day runs from midnight to midnight local time. Weeks start on Monday. -- "This week" (especially in past tense) means the last 7 days: today plus the previous 6 days. -- "This month"/"this year" are month-to-date/year-to-date. -- Short forms: 24h or 1d = the last 24 hours, 1w = the last 7 days, 1m = one month, 3m = three months, 6m = six months, 1y = one year (a number then h, d, w, m or y is a length of time, never a date). Rolling periods end now. -- With "the" ("the last year", "in the last year", "over the last month", "the last week") or "past" ("past year"), or a number ("last 12 months", "last 30 days"), it's a rolling period ending today: past year / past month / last 7 days. -- Bare "last week/month/year" ("hottest last year") is the previous full calendar week (Monday to Sunday), month or year. -- The exact ranges, and the time now, are listed under RIGHT NOW at the end (use them, don't recalculate). -- A period that includes today runs up to now; include today's data. -- "On record", "ever" or "all time" means all available data: the "on record" range under RIGHT NOW, or from the station's creation time above if that is later. Never shorten it to this year. -- State the date range you used in a few words, e.g. "Sun 20 - Sat 26 Sep". - -HOW TO FETCH WEATHER DATA (be fast: ONE round of tool calls, in parallel if more than one, then answer) -- If a tool returns an error, a note saying it can't do something, or no data, read it and correct the call once (the note usually says how) rather than answering from nothing. Never invent readings to fill a gap. -- Always fetch fresh data for every question, even if the same or a similar question was answered earlier in this conversation. Never reuse numbers, times or dates from earlier messages or earlier tool results. A follow-up about what was just answered ("give me the timestamp", "in ISO format", "and the lowest?") is fetched again at once, for the same reading and period: never ask whether to. -- For any past period (highs/lows, records, daily summaries, "this week" etc.): make ONE weather_history call covering the whole period, start_date = first day 00:00:00, end_date = last day 23:59:59 (today is included up to now). Any length up to 4 years is fine: the bot handles resolution, request limits and units. Don't split it yourself and don't add weather_now calls. -- For a reading's values at set times or per interval ("each hour", "every 30 minutes", "hourly", a table of values, or what it was at one time such as 3pm: a few minutes either side at 5min), use readings, not weather_history (unless a chart or graph is asked for: that is weather_history or air_quality with chart=true): one call per metric, made together (outdoor and indoor humidity are two), with the interval asked for (each hour = 1hour) and start and end in local time. Give a "•" line per row with its time, and say which rows are missing; never fill a gap. If it answers "too many rows", call it again with the interval in "fits". -- Prefer one or two calls. Never split a period into many weather_history calls when weather_days or one weather_history call can answer it; the bot warns the chat by itself when a question pulls in a lot of data. -- To plot several readings together ("plot temperature and rain", "humidity and wind"), set chart_fields to them, in order (temperature, humidity, pressure, wind, rain, dew_point, feels_like, vpd, solar, uv): one chart, a panel each, on one time axis. Never say it can't combine them. When the person says "on two axes", "dual axis" or "overlay", also set two_axes true: one panel, each reading with a scale of its own, left and right (plot_chart takes two_axes too, for readings from both sensors). -- A chart plots temperature unless told otherwise: for a question about humidity, pressure, wind or another reading, set chart_field to it (a reading name such as "humidity", "dew_point", "solar" or "uv" is fine). -- Set chart=true on the history call whenever the period is 3 days or longer (the bot draws one anyway), or a graph or chart is asked for. Your reply then becomes the chart's caption: keep it short: the period, then one line each for Outdoor and Indoor with its high and low (or its average, if that is what was asked), with times and dated days as usual, no other lists. For a chart of several readings, one short line per reading. The whole reply must stay under 900 characters (Telegram's limit for a chart's caption is 1024; a longer one is cut). Never write about the chart itself (e.g. "Chart sent..."). -- With any chart, set the tool's source argument to where its data came from: the site, tool or URL ("Ecowitt weather station", "AirGradient sensor", "ecowitt.net"). It is written small under the chart; never repeat it in your reply. -- Feels-like, apparent temperature, dew point and VPD are left out of history results unless you ask for them with include_derived (only when the question is about them; a chart of one of them brings it in by itself). -- groups takes plain group names, comma-separated, e.g. "outdoor,indoor" (add "rainfall" or "wind" only if needed). Never use dotted names like "outdoor.temp". -- The result has, per series (e.g. "outdoor.temperature"): low and high for the whole period, each with ready-made "_when" wording and a "_date" (plus the raw "_time"), and a "daily" (up to 31 days) or "monthly" breakdown. For periods of up to about a year, each month in "monthly" also has its own low/high "_when" and "_date" (when the bot has the detailed data cached; otherwise, and for longer periods, monthly figures are values only - see "monthly_note"). Read the answer straight from those fields. -- If the question names several months ("June, July, August") or asks about "each month", answer each month separately (its low and/or high, with when and date) rather than one figure for the whole period. -- If the result has a "warning" or "missing", say briefly that some data couldn't be fetched. -- State only what the result shows. weather_history has no day-by-day figures over about a month, and each series is separate, so it can't say what one reading (e.g. rain) was on a day picked by another. Never guess or say "no rain was recorded" without seeing it. -- Use weather_now only for current conditions. Its "emoji" holds ready-made emojis, only for readings that are notable right now: put each right before that reading's own value, copied exactly. a reading with no entry gets NO emoji, and never add one of your own to current readings. -- Never repeat an identical call. Timestamps in results are already local time. - -HIGHS AND LOWS -- Say when each high or low happened by copying its "_when" text exactly as given ("at 7:05am", "around 3:30pm", or a window), then "on", the day's emoji and its "_date": "28.3°C around 3:30pm on ☀️ Fri 9 Jan 2026". Never change "at" to "around" or the reverse. -- If "_date" is empty, the "_when" text is a window spanning two days: give it as is, with no emoji and no single date. -- If a high or low has a note saying it came from averaged data, add a short caveat that the real value may have been more extreme (not needed for averages). -- Default to highs and lows. Give averages only when asked ("average", "mean"): set average=true on the history call, then use the series' "average" for the period (and "avg" per day or month), each the average over its time (a part day counts for its hours). Never work an average out from lows and highs. - -LABELS -- For temperature and humidity, give both Indoor and Outdoor (fetch groups "outdoor,indoor"), unless the question asks about only one of them. Wind, rain, pressure, solar radiation and UV exist only outdoors: just give those. -- Call readings simply "Indoor" and "Outdoor". Don't mention sensor models, console names or the station name. - -UNITS -- Always Celsius for temperature (convert if a sensor reports Fahrenheit). Never show Fahrenheit, not even in brackets. Metric for everything else: mm rain, km/h wind, hPa pressure, kPa vapour pressure deficit, W/m² solar radiation. - -WEATHER EMOJIS (required) -- Whenever you name a specific day, including today, put an emoji for that day's outdoor weather immediately before it (day-by-day lists and single mentions such as the day of a high or low). Infer it from that day's figures ("daily", or temp_max, temp_min, rain and wind_gust): ☀️ sunny, 🌤️ mostly sunny, ⛅ partly cloudy, ☁️ overcast, 🌦️ light showers, 🌧️ rain, ⛈️ storms, 💨 windy, 🥵 very hot, 🥶 very cold, 🌫️ foggy. Use only these. With no figures for the day, leave the emoji out rather than guess. +PERSONA = """\ +You are a friendly weather bot on Telegram, for the owner's home weather station and air-quality sensor. TONE - Friendly and a little playful. Match the person's tone: if they're joking, play along briefly while still answering. -- Imagination is for the description, never the data: every number, time and date must come from tool results. +- Imagination is for the description, never the data: every number, time and date comes from the tools' results. Never guess or invent a reading, and never say something was or wasn't recorded without seeing it. If data is missing, say so briefly. STYLE -- A message that replies to an earlier one, or follows on from your last answer ("the lowest day", "that day", "and indoors?"), is about that answer: keep its subject (e.g. pressure, not temperature) and use the dates it gave. Never switch to a different reading because the words fit it too. -- Only talk about the weather when the message asks about it. Compliments, thanks, jokes and chat get a short, natural reply, with no weather data and no tool calls. +- A message that replies to an earlier one, or follows on from your last answer ("the lowest day", "that day", "and indoors?"), is about that answer: keep its subject (e.g. pressure, not temperature) and the dates it gave. Never switch to a different reading because the words fit it too. +- Only talk about the weather when the message asks about it. Compliments, thanks, jokes and chat get a short, natural reply, with no weather data. - In group chats, messages are prefixed with the sender's name. Never start your reply with a name or "Name:" prefix. -- Be concise. Plain text only: no markdown headers, tables or bold. Use "•" bullet lists for data answers (highs and lows, lists of days); descriptive and chatty answers are prose. - -EXAMPLE -Q: what was this week's high and low for indoor and outdoor? -A: Mon 3 - Sun 9 Aug (including today so far): -Outdoor -• High: 19.4°C at 2:35pm on 🌤️ Thu 6 Aug -• Low: -1.2°C at 6:10am on 🥶 Mon 3 Aug -Indoor -• High: 22.1°C at 3:55pm on 🌤️ Thu 6 Aug -• Low: 11.5°C at 7:20am on 🥶 Mon 3 Aug -(Example values are made up. Always use real tool data.) +- Be concise. Plain text only: no markdown headers, tables or bold. Use "•" bullet lists for data answers (highs and lows, lists of days, rows of readings); descriptive and chatty answers are prose. +- "What was it like", "describe" or "imagine" questions get a short, vivid picture of the day in 2-4 sentences of plain prose, built only from the real readings, then the key numbers in one short line. +- Emoji: put the ones the results give (a day's look, a reading's, a rating's) beside what they belong to, copied as given. Never add your own to a day or a reading. +- Call the sides simply "Indoor" and "Outdoor". Don't mention sensor models, console names or the station's name. +- When a result has a chart, the bot sends the chart with your reply as its caption: keep it short (the period, then one short line per reading), under 900 characters (Telegram cuts a caption at 1024), and never write about the chart itself ("Chart sent...", "see the chart above"). +- Don't mention a dashboard or chart link: the bot adds a small live-chart link under air-quality answers itself. +- About the bot itself: alerts are sent to chats by themselves, each with buttons to subscribe or unsubscribe by type, and /alerts opens the same settings; /usage lists what it can do; in a private chat the buttons under the message box ask the common questions. """ -# What the model is told only when the question needs it. Everything above is the same on every call, so the model provider -# can cache it; these follow it, then the date and time. -BLOCKS = { - "air_extra": """AIRGRADIENT'S OWN TEMPERATURE AND HUMIDITY -- The person named the AirGradient sensor's own temperature or humidity. They are the series air_temperature and air_humidity (plot_chart series, or metrics of air_quality), not the weather station's temperature and humidity. -- To put them against the station's ("plot airgradient humidity over ecowitt outdoor humidity"): plot_chart with series air_humidity and humidity and same_axis true (the same unit: one axis, the lines over each other). For readings in different units use two_axes true; for two pairs (humidity from each sensor, and temperature from each) list all four and set two_axes true: each unit gets an axis. Keep the caption short: the period, then one line per series with its low, high and average. -""", - "air": """AIR QUALITY -- For air quality (AQI, PM2.5, PM10, CO2, VOC, smoke, "is the air OK"), use the air_quality tool (the owner's AirGradient outdoor sensor): no dates for now, start_date/end_date for how it was over a period (up to about a year). -- Use the weather station for temperature and humidity; use the air-quality sensor only for air quality. -- Don't mention a dashboard or chart link: the bot adds a small "live chart" link itself. -- For air-quality graphs ("graph PM2.5 this week", "chart the air quality"), call air_quality with chart=true, the period's start_date/end_date (none for the last 24 hours) and the metrics asked about (default PM2.5; "all" means all six). Keep the caption short: the period, then one line per metric with its peak and rating (a practical tip only when something isn't good). -- VOC and NOx are relative indexes, not health measurements: 100 (VOC) and 1 (NOx) are the sensor's recent average and baseline. Well above that means something changed nearby (e.g. smoke, solvents, traffic); say so plainly, without calling it healthy or unhealthy. -- Put each metric's ready-made rating ("\U0001f7e2 good", "\U0001f7e1 poor" or "\U0001f534 very poor") next to it, copied exactly: e.g. "• PM2.5: 0.0 µg/m³ \U0001f7e2 good (AQI 0)". For history, use high_rating and average_rating. A current rating is held at the better level until two readings in a row agree (a "rating_note" says so): use the ready-made rating and never add a warning of your own about a single high value. Add a short practical tip when anything isn't good. -""", - "days": """DAYS (ranking, comparing and counting days) -- For questions that rank, compare or count DAYS ("the hottest day it also rained", "how many days over 35°C", "the wettest day", "the windiest cold day", "days below 5°C with wind"), use weather_days instead of weather_history, in ONE call. It checks every day in the period. weather_days has a day's highest or lowest of every reading the station has (temp_max, humidity_max, pressure_min, uv_max, solar_max, wind_gust, rain ...), so "how many days was UV 9 or more" is one call: where uv_max >= 9, count_only true (group_by month or year adds a count for each and the bot draws them as a bar chart: your reply is then its one-line caption, the matching days out of those checked and the period, never a list of the bars). A total, average, highest or lowest of a reading per month or year ("rain per month", "hottest day each year", "average humidity per year") is also one call: stat (sum, avg, max, min) and of (a field such as rain, temp_max, humidity_avg) with group_by, drawn as a bar chart the same way. With no period named ("per year", "how many times"), use the whole record (the "on record" range). Set only (public_holiday, weekend) only when the person's words say holidays or weekends; it limits the count to those days. For air quality use air_days, which has the same arguments over pm1, pm2_5, pm10, co2, voc_index and nox_index (pm2_5_max, co2_avg ...). - - A RECORD (the highest, lowest, hottest, coldest or fastest reading over a period or ever) with when it happened is weather_history, not weather_days: it gives the value and its exact time. - - Put each requirement in "where" and say what to rank by: sort_by (e.g. temp_max for "hottest") and order. Ask for a few days (limit 3-5). Use the "on record" range for all time. - - For public holidays ("hottest public holidays"), set only="public_holiday": the bot knows the local ones and names each in "holiday". Never pick holiday dates yourself; give each day's holiday name with its figures. - - For the figures of one known day ("did it rain on Sat 5 Sep"), set start_date = end_date = that day and no "where". To describe a day ("what was it like", "what kind of weather was June 11"), use weather_history for that day. Never search a wider period and infer from a day's absence. - - A rainy or wet day means rain of 1 mm or more (rain >= 1), unless the person says "any rain" or "a trace" (then rain > 0). - - Answer with the top day: its date (with the weather emoji) and figures (temp_max, temp_min, rain, wind_gust), the rain amount if it is small. - - Give the count in plain words, e.g. "It rained on 507 of 1,454 days" (matching_days of days_checked), never "507 such days". - - If the result has "trace_rain_days", add the first as a short footnote, e.g. "(A hotter day, 41.6°C on Sun 4 Feb 2024, had only 0.3 mm of rain.)". - - If a day you name is marked "daily", or the period reaches back before "exact_from", add the short caveat from "note_daily". -""", - "link": """CORRELATION -- To ask whether rain comes WITH a change in pressure (or humidity or wind) - "is there a correlation between pressure and rainfall", "did the rain come with the pressure drop", "plot pressure against rainfall" - use weather_link in ONE call (default period: the last 90 days). It reads both together at 30 minutes; open with its `verdict` (a plain yes, no or weak), then give the evidence from its `findings` - the ratios for moving vs steady, the level in rain, and the rain events with the biggest one (the most checkable evidence) - and say it used 30-minute readings, never monthly figures. Never conclude 'no link' from the correlation alone; it is weak by design. -""", - "outlook": """RAIN AND SHORT-TERM OUTLOOK ("will it rain?", "do I need an umbrella?", "what's it doing later?") -- The current reading (weather_now) and the last 3 hours (weather_history), groups "outdoor,pressure,rainfall,rainfall_piezo,wind", are normally - already in the conversation: use them. Fetch them in ONE step, in parallel, only if they are missing. -- Pressure tendency (relative pressure, last 3 hours): falling if the high came before the low, rising if the low came first. Change = high minus low. - Falling more than 3 hPa: unsettled, rain likely soon. Falling 1-3 hPa: rain possible. Steady (under 1 hPa) or rising: rain unlikely. -- Pressure level: under 1005 hPa is unsettled; over 1020 hPa is settled. -- Moisture: humidity 90% or more, or temperature within 2°C of dew point, makes rain more likely. -- Recent rain: a rain rate above 0 now, or rain in the last hour, means showers are likely to continue for a while. -- Wind picking up alongside falling pressure strengthens a rain call. -- Answer with one of: unlikely / possible / likely, then a short reason citing one or two readings (e.g. "pressure down 2.4 hPa in 3 hours, humidity 91%"). Only look a few hours ahead. -- When a weather_forecast result is in the conversation (or the tool is available), give it too: its ready-made lines for the days asked about (copied as they are, emoji included), after your own read of the station. If it disagrees with the station read, say so plainly. Keep the station read short and say it is a read of the station data; the forecast is Open-Meteo's. Don't list every reading. -""", - "wind": """WIND DIRECTION -- Wind direction has no low or high (it is circular: 350° and 10° are 20° apart). For "wind.wind_direction" the result gives "most_common" (with its share of the time), "then", "average_direction", "steadiness" and, for up to 31 days, a "daily" dominant direction. Answer from those with compass names, e.g. "mostly NE (34% of the time), then E; fairly steady". Never give degrees as a range, or say the wind swung "from 2° to 349°". Add any "note", "note_period" or "calm" briefly. -""", - "describe": """DESCRIBING A DAY -For today or yesterday the day's readings are normally already in the conversation; fetch only if missing. -- For "what was it like", "what would it have been like", "describe" or "imagine" questions, paint a short, vivid picture of the day in 2-4 sentences of plain prose, built only from the real readings (e.g. when the rain came, how cold it got, how windy), then give the key numbers in one short line. No bullet list for these. -""", -} - - -DATE_LABELS = [ # period name -> label in the prompt - ("yesterday", "Yesterday"), - ("last 7 days", 'Last 7 days / the last week / "this week"'), ("current calendar week", "Current calendar week"), - ("last week", "Last week"), ("this month", "This month"), ("last month", "Last month"), - ("this year", "This year"), ("last year", "Last year"), ("past month", "Past month / the last month / last 30 days"), - ("past year", "Past year / the last year / last 12 months"), ("on record", "On record (Ecowitt keeps 4 years)"), -] - +def now_line(now: datetime, zone: str | None = None) -> str: + """"Now: Tuesday 10 November 2026, 14:05 (Australia/Melbourne time).": the date, time and zone the model is told.""" + zone = zone or getattr(now.tzinfo, "key", None) or (now.tzname() if now.tzinfo else None) + return f"Now: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M}" + (f" ({zone} time)." if zone else ".") -def date_ranges(now: datetime) -> str: - """Pre-computed date ranges so the model never does calendar maths (same definitions as - the fast path).""" - fmt = day_text - periods = period_ranges(now.date()) - lines = [f" Today: {fmt(now)} (00:00 to now)"] - for name, label in DATE_LABELS: - first, last = periods[name] - lines.append(f" {label}: {fmt(first)}" if first == last else f" {label}: {fmt(first)} to {fmt(last)}") - return "\n".join(lines) - -def capabilities(have: Collection[str], brief: bool = False) -> str: - """What the bot can and can't do with the sources it has (by name), for questions about the bot itself ("what metrics do you - have?") and so the model knows what is possible before it says something can't be done. Built from the code's own lists.""" - missing = ", ".join([*NEVER_AVAILABLE, *(what for name, what in WITHOUT.items() if name not in have)]) - if brief: # most questions: only the limits, so it never promises what it can't do - return (f"\nLIMITS: not available: {missing}. Custom alerts (\"tell me when winds reach 100\") can't be added: say so. " - "A chart series or style the tools don't offer can't be drawn: say so.\n") - lines = ["\nWHAT THIS BOT CAN AND CAN'T DO (answer questions about the bot from this, with no tool call)"] - if "Ecowitt" in have: - lines.append("- Weather station: outdoor and indoor temperature and humidity, dew point, feels-like, vapour pressure deficit, " - "pressure, wind speed, gust and direction, rain (daily total and rate), solar radiation and UV index. History " - "back to when it was installed: 5-minute detail for the last 90 days, 30-minute for a year, then daily.") - if "AirGradient" in have: - lines.append("- Air quality (outdoor AirGradient): " + ", ".join(f"{LABELS[m]} ({CHART_UNITS[m] or 'index'})" for m in ALL_METRICS) - + ", each with a traffic-light rating. History about a year.") - lines.append("- Tools: weather_now (current), weather_history (highs, lows, averages, charts), weather_days (find, rank and " - "count days, holidays, weekends), weather_link (does rain come with a pressure, humidity or wind change), " - "air_quality, readings (any reading's values at an interval, from a minute to a day, each with its time).") - if "Ecowitt" in have and "AirGradient" in have: - lines.append("- Across both devices: plot_chart draws readings from both on one chart, up to 4 panels (series: " - + ", ".join([*WEATHER, *ALL_METRICS]) + "; styles: line, bars for rain, " - "rating = the traffic-light share of time, air series only), air_link answers whether rain goes with " - "cleaner air, and air_scan scans every air metric against every weather reading for what goes with what. " - "Use them for \"plot X against Y\", \"does rain affect air quality\" and \"is there a correlation between air " - "quality and other metrics\"; a series or style not listed can't be plotted: say so.") - if "Pollen" in have: - lines.append("- Pollen: Melbourne's grass pollen level and the thunderstorm asthma risk (Low, Moderate, High, Extreme), tool pollen_asthma. " - "Both forecasts only run from October to December: outside those months the tool says so.") - if "Forecast" in have: - lines.append("- Forecast: today and the days ahead from Open-Meteo (summary, temperatures, chance of at least 1 mm of rain), tool weather_forecast.") - lines.append("- Charts: any one reading, or several readings together on one time axis, one panel each (" + ", ".join(WEATHER_NAMES) - + "; \"weather all week\" draws every reading); wind as average speed with gusts beside a compass rose of directions; " - "air quality with ratings.") - if alerts := ", ".join(words for kind, words in ALERT_WORDS.items() if TYPES[kind][1] in have): - lines.append(f"- Alerts, sent to chats automatically: {alerts}. Each alert has buttons to subscribe or unsubscribe by type, and " - "/alerts opens the same settings. Custom alerts (\"tell me when winds reach 100\", another limit) can't be added: say so.") - lines.append(f"- Not available: {missing}.") - return "\n".join(lines) + "\n" - - -RAIN_CAPTION_SECTION = """ -THIS IS A RAIN CHART: its caption is ONLY the least and the most rain in the period (daily totals, mm, with the dated days). -Nothing else: no averages, no other readings, no outlook. -""" +def build(now: datetime, instructions: str = "") -> str: + """The system prompt: the persona, the server's instructions (instructions.instructions(ctx)), then the date and time now (last: the + model provider caches a prompt's start).""" + return "\n\n".join(part for part in (PERSONA.rstrip(), instructions.strip(), now_line(now)) if part) + "\n" -def build(now: datetime, sources: dict[str, str], hints: list[str] = (), about_bot: bool = False, rain_caption: bool = False, - topics: set[str] | None = None) -> str: - """The system prompt for the bot's sources ({name: its line for the prompt, Source.describe()}). `topics` (see intent.topics) - picks the guidance the question needs; None puts all of it in.""" - # Most stable first: the model provider caches a prompt's start, so what changes (the topics, the date, then the time) goes last - everything = topics is None - text = PROMPT.format(sources="\n".join(f"- {s}" for s in sources.values()) or "(none)", - capabilities=capabilities(sources, brief=not (everything or about_bot or "bot" in topics))) - text += "".join(f"\n{block}" for name, block in BLOCKS.items() if everything or name in topics) - text += f"\nRIGHT NOW (exact ranges, then the time)\n{date_ranges(now)}\nIt is now {now.strftime('%A %d %B %Y, %H:%M %Z')}.\n" - if rain_caption: - text += RAIN_CAPTION_SECTION - if about_bot: - text += ("\nTHIS QUESTION IS ABOUT THE BOT ITSELF: answer from WHAT THIS BOT CAN AND CAN'T DO above, with no tool call. Keep it " - "to the METRICS, as a few simple bullet points (\u2022, one short line each, 7 at most, no intro or closing sentence, no " - "sub-bullets), grouped: indoor and outdoor together, PM1, PM2.5 and PM10 together. No dates, and don't say \"available " - "now\"; mention history only if asked. Leave out tools, charts and alerts unless the question asks about them.\n") - if hints: # decided in code, for this question only - text += ("\nTHE PERSON'S WORDS NAME THESE PERIODS (use exactly these start_date/end_date values; do not " - "reinterpret them):\n" + "\n".join(f"- {h}" for h in hints) + "\n") - return text +__all__ = ["PERSONA", "build", "now_line"] diff --git a/lib/report.py b/lib/report.py index 60bbb098..c4110e12 100644 --- a/lib/report.py +++ b/lib/report.py @@ -1,27 +1,10 @@ -"""What the model path still needs written in code from the old tools' results, until the model gets the service's tools (docs/ -mcp-service.md 6, step 3): the caption of a chart that answers the question by itself (the bot's chart_answers_it finish on -weather_history, air_quality and the day tools), and the bold names of the report's headings. Everything the bot answers without the -model is the service's own words now (lib/service: current's lines, summary's caption and text, days' answer, the forecast's and the -pollen's text). Each tool result is JSON; one that failed or is missing gives nothing.""" +"""The bold names of the report's headings (the service's current, pollen and forecast write the report's text: lib/service).""" -import json import re from telegram import MessageEntity -from .ecowitt.api import unit_text from .entities import utf16_len -from .series import AIR, find -from .timeutil import clock_text, day_text, to_local - - -def _load(result: str | None) -> dict | None: - """The tool's JSON, or None when it is missing, an error message or says it has nothing.""" - try: - data = json.loads(result or "") - except ValueError: - return None - return data if isinstance(data, dict) and "error" not in data else None # ---------- the report's headings (the service's current, pollen and forecast write them) ---------- @@ -32,116 +15,3 @@ def _load(result: str | None) -> dict | None: def heading_entities(text: str) -> list[MessageEntity]: """Bold entities over the name of each heading line in `text` (not over its brackets).""" return [MessageEntity(MessageEntity.BOLD, utf16_len(text[:m.start()]), utf16_len(m.group(1))) for m in HEADING_LINE.finditer(text)] - - -# ---------- a days lookup ---------- -def _days(data: dict) -> str | None: - """"137 of 1,454 days with UV index ≥ 10 (period)", or a total, average, highest or lowest over the period: the chart (if any) - carries the breakdown.""" - if "matching_days" not in data: - return None - if data.get("stat") and data.get("value") is not None: - unit = unit_text(data["stat"].get("unit")) or "" - return f"{data['stat']['what']}: {data['value']:g} {unit}".rstrip() + f" over {data['days_checked']:,} days ({_period(data)})." - what = f" with {data['condition']}" if data.get("condition") else "" - note = " Older days use averages, so a count near the limit may fall slightly short." if data.get("note_averaged") else "" - return f"{data['matching_days']:,} of {data['days_checked']:,} days{what} ({_period(data)}).{note}" - - -def lookup(kind: str, result: str | None, names: list[str] = (), sides: list[str] = (), today=None) -> str | None: - """A day tool's result in words (`kind` "days"): the count, or the figure over the period. None when the result can't be used (the - model then answers). (`names`, `sides` and `today` are the old lookups', kept so its callers read as before.)""" - data = _load(result) - return (_days(data) or None) if data and kind == "days" else None - - -# ---------- chart captions ---------- -def _year(text: str | None) -> str: - """"Tue 29 Sep 2026" -> "Tue 29 Sep".""" - return re.sub(r" 20\d\d\b", "", text or "") - - -def _period(data: dict) -> str: - """"Tue 29 Sep 2026 - Tue 06 Oct 2026" -> "Tue 29 Sep – Tue 06 Oct 2026" (the first year is dropped only when it is the same year).""" - text = data.get("period", "") - years = re.findall(r" (20\d\d)\b", text) - if len(years) == 2 and years[0] == years[1]: - text = re.sub(r" 20\d\d\b(?= - )", "", text) - return text.replace(" - ", " – ") - - -def _at(entry: dict, which: str) -> str: - """"high 24.3 °C, Tue 29 Sep around 3pm" for one record of a series.""" - when = _year(f"{entry.get(f'{which}_date', '')} {entry.get(f'{which}_when', '')}".strip()) - return f"{entry[which]} {unit_text(entry.get('unit')) or ''}".strip() + (f", {when}" if when else "") - - -def _range(label: str, entry: dict, average: bool) -> str: - unit = unit_text(entry.get("unit")) or "" - if average and entry.get("average"): - return f"{label}: average {entry['average']} {unit} (low {entry['low']}, high {entry['high']})".replace(" )", ")") - return f"{label}: low {_at(entry, 'low')} · high {_at(entry, 'high')}" - - -def _rain_line(turn, tz) -> list[str]: - """Least and most rain in a period (the chart's own bars).""" - bars = next((p.bars for c in turn.charts for p in c.panels if p.bars and p.bars.x), None) - if not bars: - return [] - - def day(i: int) -> str: - start = to_local(bars.x[i], tz) - return day_text(start, year=False) + (f" {clock_text(start, whole_hours=True)}" if bars.width < 86400 else "") - lo, hi = min(range(len(bars.y)), key=bars.y.__getitem__), max(range(len(bars.y)), key=bars.y.__getitem__) - per = f" per {bars.per}" if bars.per else "" - return [f"☔ Rain{per}: least {bars.y[lo]:g} mm ({day(lo)}) · most {bars.y[hi]:g} mm ({day(hi)}) · {sum(bars.y):.1f} mm in all"] - - -def _weather_caption(result: dict, turn, tz) -> list[str]: - series = result.get("series") or {} - names = [n for n in dict.fromkeys(turn.chart_fields or [turn.chart_field or "temperature"]) if find(n)] - lines: list[str] = [] - for name in names: - reading = find(name) - keys = [k for k in series if k.split(".", 1)[1] == reading.field] - if reading.field == "daily": # rain: the amounts the chart draws - lines += _rain_line(turn, tz) - continue - for key in keys: - group = key.split(".", 1)[0] - label = reading.label + (f" ({group})" if len(keys) > 1 and group in ("outdoor", "indoor") else "") - if reading.field == "wind_speed": - gust = series.get(f"{group}.wind_gust") or series.get("wind.wind_gust") - lines.append(f"🌬️ Wind: strongest gust {_at(gust, 'high')}" if gust else _range(label, series[key], bool(turn.average_asked))) - else: - lines.append(_range(label, series[key], bool(turn.average_asked))) - if reading.field == "wind_speed" and (d := series.get("wind.wind_direction")): - lines.append(f"🧭 Mostly from the {d['most_common']}" + (f", {d['steadiness']}" if d.get("steadiness") else "")) - return lines - - -def _air_caption(result: dict, args: dict) -> list[str]: - lines = [] - for key, label in ((name, m.label) for name, m in AIR.items()): - entry = result.get(key) - if key not in (args.get("metrics") or ["pm2_5"]) or not isinstance(entry, dict): - continue - unit = unit_text(entry.get("unit")) or "" - rating = entry.get("high_rating") - lines.append(f"• {label}: peak {entry['high']} {unit} ({_year(entry.get('high_time'))})".replace(" )", ")") - + (f" · {rating}" if rating else "") + f" · average {entry['average']}") - return lines - - -def chart_caption(tool: str, args: dict, result: str | None, turn, tz) -> str | None: - """The caption for a chart, from the tool's result: the period, then a line per reading. None when there is nothing to say (the - model then takes the question).""" - data = _load(result) - if not data or not turn.charts: - return None - lines = _air_caption(data, args) if tool == "air_quality" else _weather_caption(data, turn, tz) - if not lines: - return None - notes = (["(Older days are still downloading, so they are left out.)"] if data.get("note_missing") else - ["(Some data couldn't be fetched, so this may be incomplete.)"] if data.get("warning") else []) - return "\n".join([_period(data), *lines, *notes]).strip() diff --git a/lib/service/__init__.py b/lib/service/__init__.py index 4ad63d81..7c61afa6 100644 --- a/lib/service/__init__.py +++ b/lib/service/__init__.py @@ -5,10 +5,10 @@ answers: the period it read, the time of its figures, its charts, and its refusals; - names.py: the readings the service has, one name each (`outdoor.temperature`, `air.pm2_5`), and the words people use for them; - daylook.py: a day's look ("wet", 🌧️) from its figures; - - legacy.py: the bot's old tool calls read as the service's (its own code paths' only way in; deleted whole in step 3). + - instructions.py: the server's instructions, a short summary for a client to pass to its model. `build(ctx)` makes the ten, in 3.3's order, each module's `tools(ctx)` (a tool whose source isn't there is left out), and `Service` -holds them by name. Nothing here is offered to a model yet (the bot's own code paths call them: step 2), and nothing here knows of +holds them by name. The bot offers them to its model (lib/model_tools.py) and its own code paths call them; nothing here knows of Telegram, of the bot's buttons or of who draws a chart. """ diff --git a/lib/service/legacy.py b/lib/service/legacy.py deleted file mode 100644 index 3db44e86..00000000 --- a/lib/service/legacy.py +++ /dev/null @@ -1,198 +0,0 @@ -"""The bot's old tool calls read as the service's (docs/mcp-service.md 6, step 2): one of the twelve tools' calls, with what the bot's -words decided beside it (the Turn: the reading charted, the readings stacked, an average, every day, two axes), as the service tool -that answers it and that tool's arguments. The bot's own code paths (its shortcuts, lookups and keyboard charts, intent.read's -decisions) and the charts the model draws through the twelve go through here, and nowhere else, so step 3, when the model gets the -service's tools and the Turn goes, deletes this module whole. - - - translate(name, args, turn, now, tz): (tool, arguments) of a call, or None when it has no service equivalent here; - - lookup(read): the call behind a plain lookup intent.read answers in code ("how hot is it", "co2", "pollen" ...); - - report(sources): the calls the report is written from; - - periods_of(tool, arguments): the periods a chart of that call is worth drawing over, as its drawn_by would list them. -""" - -from datetime import datetime, timedelta, tzinfo - -from ..daytable import grouped_as_asked -from ..ecowitt.days import HOLIDAY_WORDS -from ..ecowitt.query import chart_field, stack_names -from ..periods_text import PeriodError, read_period -from ..series import INDOOR_READINGS, WEATHER -from .days import MONTH_PERIODS -from .names import BARE -from .summary import DAILY_MEANS, OVER_TIME - -FMT = "%Y-%m-%d %H:%M:%S" -FIELD_NAMES = {r.field: name for name, r in WEATHER.items()} # a field a chart plots -> its reading's name ("relative" -> "pressure") -SIDES = ("outdoor", "indoor") -RELATED = ({"period": "1m", "label": "1M"}, {"period": "3m", "label": "3M"}, {"period": "1y", "label": "1Y"}) - - -def station_readings(names: list[str], sides: list[str]) -> list[str]: - """The service's names of lib/series.py's readings, each on the sides asked (temperature and humidity: outdoor and indoor unless - one is named; dew point and feels like indoor's only when indoor alone is).""" - out: list[str] = [] - for name in names: - if name in ("temperature", "humidity"): - out += [f"{side}.{name}" for side in sides] - elif name in INDOOR_READINGS and sides == ["indoor"]: - out.append(f"indoor.{name}") - elif name in BARE: - out += BARE[name] - return list(dict.fromkeys(out)) - - -def _sides(groups) -> list[str]: - groups = [g.strip() for g in (groups.split(",") if isinstance(groups, str) else groups or [])] - return [s for s in SIDES if s in groups] or list(SIDES) - - -def _when(text: str, fmt: str = FMT) -> datetime | None: - try: - return datetime.strptime(str(text).strip(), fmt) - except ValueError: - try: - return datetime.fromisoformat(str(text).strip()) - except ValueError: - return None - - -def period(start: str | None, end: str | None, words: list[str], now: datetime, tz: tzinfo, whole_days: bool = False) -> dict: - """The period of an old call (its start_date and end_date, the station's clock) as the service takes it: the first of `words` (the - period's name as the question gave it) that the service reads as the same span, else whole days as words ("2026-11-04 to 2026-11-10"), else the times.""" - first, last = _when(start) if start else None, _when(end) if end else None - if first is None: - return {} - open_ended = last is None or last.date() >= now.date() # (to today or later: to now, so a replay moves on with the clock) - if whole_days: - return {"period": f"{first:%Y-%m-%d} to now" if open_ended else f"{first:%Y-%m-%d} to {last:%Y-%m-%d}"} - now = now.replace(tzinfo=None, microsecond=0) - until = min(last, now) if last else now - for said in words: - try: - read = read_period(said, None, None, now=now, tz=tz, default=said) - except PeriodError: - continue - if read.start.replace(tzinfo=None) == first and until <= read.end.replace(tzinfo=None) <= until + timedelta(seconds=1): - return {"period": said} - whole_end = last is None or last >= now or last.strftime("%H:%M:%S") == "23:59:59" - if first.time() == datetime.min.time() and whole_end: # whole days, as words the service can swap for another period - return {"period": f"{first:%Y-%m-%d} to now" if open_ended else f"{first:%Y-%m-%d} to {last:%Y-%m-%d}"} - out = {"start": first.strftime("%Y-%m-%d") if first.time() == datetime.min.time() else first.strftime("%Y-%m-%d %H:%M")} - if last is not None and last < now: - out["end"] = last.strftime("%Y-%m-%d") if last.strftime("%H:%M:%S") == "23:59:59" else \ - (last + timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M") - return out - - -def _words(text: str, now: datetime) -> list[str]: - """The names intent gives the periods the question names (and a chart's default), as candidates for period().""" - from .. import intent # (the bot's own reading of the words: lazy, as the service doesn't need it) - names = [name for name, _, _ in intent.spans_in(text, now)] if text else [] - return [*names, *[n.replace("past ", "the last ") for n in names if n.startswith("past ")], "last 24 hours"] - - -def translate(name: str, args: dict, turn=None, *, now: datetime, tz: tzinfo) -> tuple[str, dict] | None: - """(service tool, arguments) for one of the old tools' calls with its Turn (what the words decided; None: nothing), or None.""" - args = dict(args or {}) - text = getattr(turn, "text", "") or "" - if name == "weather_history": - return "summary", _history(args, turn, now, tz) - if name == "air_quality": - metrics = [m for m in (args.get("metrics") or getattr(turn, "air_named", None) or ["pm2_5"])] - if not (args.get("start_date") or args.get("end_date")): - return "current", {"readings": [f"air.{m}" for m in metrics] if args.get("metrics") else ["air"]} - out = {"readings": [f"air.{m}" for m in metrics], - **period(args.get("start_date"), args.get("end_date"), _words(text, now), now, tz)} - if args.get("chart") is not None: - out["chart"] = bool(args.get("chart")) - return "summary", _flags(out, args) - if name in ("weather_days", "air_days"): - keep = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "chart_answers_it") - if name == "weather_days" and args.get("only") and text and not HOLIDAY_WORDS.search(text): - args.pop("only") # (as the old tool: a holiday or weekend filter nobody asked for is dropped) - args = grouped_as_asked(args, turn) # (and group_by from the words when the model left it out) - out = {k: args[k] for k in keep if args.get(k) not in (None, "", [])} - out.update(period(args.get("start_date"), args.get("end_date") or now.strftime("%Y-%m-%d"), [], now, tz, whole_days=True)) - return "days", out - if name == "weather_now": - return "current", {} - if name == "pollen_asthma": - return "pollen", {} - if name == "weather_forecast": - days = int(args.get("days") or 7) - return "forecast", {"period": "the next 7 days" if days >= 7 else "today" if days == 1 else f"next {days} days"} - return None - - -def _flags(out: dict, args: dict) -> dict: - if args.get("chart_answers_it") is True: - out["chart_answers_it"] = True - return out - - -def _history(args: dict, turn, now: datetime, tz: tzinfo) -> dict: - """weather_history as summary: the readings the chart draws (the words' reading, else the model's; several stacked; else the - temperature), on the sides its groups ask for, over its period, with its chart, average, every day and two axes.""" - turn = turn or _NoTurn() - sides = _sides(args.get("groups")) - stacked = stack_names(args, turn) - field = chart_field(args, turn) - names = stacked or ([FIELD_NAMES.get(field, field)] if field else None) or \ - [n for n in (getattr(turn, "readings", None) or []) if n in WEATHER][:1] or ["temperature"] - out = {"readings": station_readings(names, sides), - **period(args.get("start_date"), args.get("end_date"), _words(turn.text or "", now), now, tz)} - if args.get("chart") is not None or turn.chart_asked: - out["chart"] = bool(args.get("chart")) or bool(turn.chart_asked) - if args.get("average") or turn.average_asked: - out["average"] = True - if turn.per_day: - out["every_day"] = True - if (turn.two_axes or args.get("two_axes")) and len(names) == 2: # (the words', else the model's: as the old tool drew it) - out["layout"] = "two_axes" - return _flags(out, args) - - -class _NoTurn: - text, chart_asked, average_asked, per_day, two_axes, readings, chart_field, chart_fields, air_named = "", False, False, False, False, [], None, [], [] - - -def lookup(read) -> tuple[str, dict] | None: - """The call behind a plain lookup intent.read answers in code (read.lookup: "reading", "air", "days", "extremes", "pollen", - "forecast", "about"), from what the words decided.""" - kind = read.lookup - if kind == "about": - return "about", {} - if kind == "reading": - sides = read.sides or list(SIDES) - words = [f"{sides[0]} {n.replace('_', ' ')}" if n in INDOOR_READINGS and len(sides) == 1 else n.replace("_", " ") - for n in read.lookup_arg] - return "current", {"readings": words} - if kind == "air": - return "current", {"readings": [f"air.{m}" for m in read.lookup_arg] or ["air"]} - return None - - -def report(sources) -> list[tuple[str, dict]]: - """The calls the report is written from, for these sources (by name): the readings now (both devices), the forecast's next 3 days - (what the report has always shown) and the pollen.""" - calls = [("current", {})] if {"Ecowitt", "AirGradient"} & set(sources) else [] - calls += [("pollen", {})] if "Pollen" in sources else [] - calls += [("forecast", {"period": "next 3 days"})] if "Forecast" in sources else [] - return calls - - -def periods_of(tool: str, arguments: dict) -> list[dict]: - """The periods a chart drawn by this call is worth drawing over, as the tool's own drawn_by lists them (summary, days, relate, - scan): for a chart the model drew through the old tools, which has none of its own.""" - if tool == "summary": - if "period" not in arguments: - return [] - return [dict(p) for p in (DAILY_MEANS if arguments.get("average") else OVER_TIME)] - if tool == "days": - return [{"period": p, "label": label} for p, label in MONTH_PERIODS] if arguments.get("group_by") == "month" else [] - if tool in ("relate", "scan"): - return [dict(p) for p in RELATED] - return [] - - -__all__ = ["lookup", "period", "periods_of", "report", "station_readings", "translate"] diff --git a/lib/service/summary.py b/lib/service/summary.py index 997fca08..a1a01b12 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -580,7 +580,7 @@ async def _station(self, call: Call, station: list[Reading], drawn: list[Reading series_names = list(dict.fromkeys(_station_series(r) or r.column for r in every)) turn = Turn(chart_asked=here, chart_field=named[0] if len(named) == 1 else None, chart_fields=named if len(named) > 1 else [], two_axes=here and call.layout == "two_axes", average_asked=call.average, per_day=call.every_day, - readings=series_names, text="", ahead=background) + readings=series_names, ahead=background) start, end = self._span(call) args = {"start_date": start, "end_date": end, "average": call.average, "include_derived": sorted({r.column for r in every if r.column in DERIVED})} diff --git a/lib/sources.py b/lib/sources.py index 7600ffbe..633dbba7 100644 --- a/lib/sources.py +++ b/lib/sources.py @@ -1,4 +1,4 @@ -"""What a data source is to the bot: a name, its tools, a local clock and a Warmer that keeps it fresh; started once, poked +"""What a data source is to the bot: a name, a local clock and a Warmer that keeps it fresh; started once, poked when a question wants it, closed at the end. The bot (bot.py) and the startup (ecobot.py) use nothing else of the four sources: the weather station (lib/ecowitt), the air sensor (lib/airgradient), the pollen page (lib/pollen) and the forecast (lib/forecast).""" @@ -6,16 +6,14 @@ from datetime import datetime, tzinfo from .timeutil import now_local -from .tools import Tool from .warm import Warmer class Source(ABC): - """Each source sets `name`, `tz`, `tools` and `warmer` (a Warmer of its own `warm`). close() closes its `client` and its + """Each source sets `name`, `tz` and `warmer` (a Warmer of its own `warm`). close() closes its `client` and its `store` on disk; the weather station, which has an API client and a history cache instead, closes its own.""" name: str tz: tzinfo - tools: list[Tool] warmer: Warmer summary: str = "" # set by start(): the line that tells what the source is reading and from where (logged by the startup, in order) @@ -28,10 +26,6 @@ async def start(self): """Get ready: find the device, read the first page. A failure that leaves the source of no use raises (the bot then runs without it); one that only means "not yet" is logged, and the next refresh tries again.""" - @abstractmethod - def describe(self) -> str: - """The source in a line for the prompt, with the words people use for it.""" - @abstractmethod def wants(self, text: str) -> bool: """Should a question start refreshing this source?""" diff --git a/lib/timeutil.py b/lib/timeutil.py index cb138daa..286b77d5 100644 --- a/lib/timeutil.py +++ b/lib/timeutil.py @@ -84,11 +84,5 @@ def parse_period(args: dict, today: date, default_days: int) -> tuple[date, date return (first, last) if first <= last else "start_date must be before end_date (today isn't final, so the latest day is yesterday)" -def period_parameters(default_days: int) -> dict: - """The start_date and end_date in a tool's parameters, for a period parse_period reads.""" - return {"start_date": {"type": "string", "description": f"First day, 'YYYY-MM-DD'. Default: {default_days} days before the end."}, - "end_date": {"type": "string", "description": "Last day, 'YYYY-MM-DD' (up to yesterday). Default: yesterday."}} - - SLOT = 1800 # the 30-minute slots both devices are lined up on MIN_DAY_SLOTS = 24 # a day counts for a daily comparison with at least 12 hours of readings diff --git a/lib/tools.py b/lib/tools.py index 3c37e659..ac0845fe 100644 --- a/lib/tools.py +++ b/lib/tools.py @@ -1,54 +1,15 @@ -"""The tools the model can call. Each data source contributes its own.""" +"""The tools the bot's model is offered (lib/service's ten, wrapped by lib/model_tools.py), and the Turn the engines take.""" -import asyncio import json import logging from collections.abc import Awaitable, Callable -from contextvars import ContextVar from dataclasses import dataclass, field from .logs import BUGS, QUOTES -from .specs import CHART_SOURCE, source_text log = logging.getLogger(__name__) MAX_OUTPUT_CHARS = 60000 -SOURCE_PARAMETER = {"type": "string", "description": "With a chart: where its data came from, written small under it. Name the site, " - "tool or URL (e.g. 'Ecowitt weather station', 'AirGradient sensor', 'ecowitt.net'). " - "Leave out to use the device the tool reads."} - - -CALL: ContextVar[tuple[str, dict] | None] = ContextVar("tool_call", default=None) # (tool, arguments) of the call being run - - -class Charts(list): - """Turn.charts: the chart specs, each put down to the call that added it (CALL, read as it is added: the model's calls in one step - run together, so counting charts before and after a call would give one call's chart to another). Its `calls` are in the same order.""" - - def __init__(self, charts=()): - super().__init__(charts) - self.calls = [self._call() for _ in self] - - @staticmethod - def _call() -> tuple: - return CALL.get() or (None, {}) # (a chart added another way has no call) - - def append(self, chart): - super().append(chart) - self.calls.append(self._call()) - - def extend(self, charts): - charts = list(charts) - super().extend(charts) - self.calls += [self._call() for _ in charts] - - def __iadd__(self, charts): - self.extend(charts) - return self - - def insert(self, i, chart): - super().insert(i, chart) - self.calls.insert(i, self._call()) def json_result(out) -> str: @@ -58,37 +19,24 @@ def json_result(out) -> str: @dataclass class Turn: - """What one question carries between the bot and the tools it calls (nothing is shared between questions).""" - charts: list = field(default_factory=Charts) # chart specs the tools add; the bot renders them after the answer - chart_asked: bool = False # the person's words asked for a chart ("plot"), whatever the model sets - chart_field: str | None = None # the one reading the question is about ("humidity"); None: temperature - chart_fields: list[str] = field(default_factory=list) # readings asked to be seen together ("temperature and rain") - two_axes: bool = False # the words ask for two readings on one chart with a scale each ("on two axes") - air_extra: bool = False # the tools offer the air sensor's own temperature and humidity: the words name them, or this chat is still using them - air_extra_used: bool = False # a tool served them for this question - air_named: list[str] = field(default_factory=list) # the air readings the person's words name, else their last messages' ("co2"): a chart's default - topics: set = field(default_factory=set) # the guidance topics this question was given (intent.topics, and the chat's memory of them) - average_asked: bool = False # an average was asked for: the caption leads with it - text: str = "" # what the person said (a tool can check an argument against it) - readings: list[str] = field(default_factory=list) # the readings the words name ("temperature", "rain"): a result can leave out the others - per_day: bool = False # day by day figures were asked for: a long period keeps every day, not only its extremes - result_chars: int = 0 # the size of every tool result so far this question (what the model will be sent) - forecast_shown: list = field(default_factory=list) # the forecast days the answer includes, remembered once it is sent + """What one call carries: the options an engine is driven with (set by the service from its own arguments: lib/service/summary.py, + days.py, relate.py, scan.py) and what it gives back (its charts, its timings); for the bot's model, the request's metadata and the + results it keeps. Nothing is shared between questions.""" + charts: list = field(default_factory=list) # chart specs the engines add + chart_asked: bool = False # draw a chart (the call's `chart`) + chart_field: str | None = None # the one reading drawn; None: temperature + chart_fields: list[str] = field(default_factory=list) # the readings drawn together, a panel each + two_axes: bool = False # two readings on one panel with a scale each + air_named: list[str] = field(default_factory=list) # the air readings a chart of the air sensor draws + average_asked: bool = False # the figures and the chart as averages + readings: list[str] = field(default_factory=list) # the readings asked for: a result leaves out the others + per_day: bool = False # a long period keeps every day, not only its extremes + ahead: bool = False # nobody is waiting (a background request): its fetches wait their turn times: dict = field(default_factory=dict) # seconds spent by step ("data", "draw", "png"), for the reply's timing line in the log - ahead: bool = False # a chart drawn ahead, nobody waiting: its requests wait their turn meta: dict = field(default_factory=dict) # the request's metadata, all a service tool reads (lib/service/common.py: chart_points, # fetch, priority); over MCP, the request's _meta - - @property - def chart_calls(self) -> list: - """(tool, arguments) of the call that drew each chart, in the same order ((None, {}): added outside any call).""" - return getattr(self.charts, "calls", None) or [(None, {})] * len(self.charts) - - @classmethod - def of(cls, read, text: str, **more) -> "Turn": - """The Turn for a question as intent.read read it (`read`): what its words ask of a chart and of the figures.""" - return cls(chart_asked=read.chart_asked, chart_field=read.chart_field, chart_fields=read.chart_fields, two_axes=read.two_axes, air_extra=read.air_extra, - average_asked=read.average_asked, readings=read.readings, per_day=read.per_day, text=text, **more) + results: list = field(default_factory=list) # the bot's model: (tool, arguments, its whole result as data) of each call it made + result_chars: int = 0 # the size of every result the model was sent so far this question @dataclass @@ -96,17 +44,10 @@ class Tool: name: str description: str parameters: dict - handler: Callable[[dict, Turn], Awaitable[str]] # (arguments, the question's Turn); a Turn is optional when called directly - asked: Callable[[], tuple[str, dict]] | None = None # (description, parameters) a question that asks for the air sensor's own - # temperature or humidity is offered instead (Turn.air_extra) - source: str | None = None # the tool draws charts: where their data comes from unless the model says (specs.CHART_SOURCE); - # "" leaves it to the tool. It is then offered a `source` argument (SOURCE_PARAMETER). + handler: Callable[[dict, Turn], Awaitable[str]] # (arguments, the question's Turn) - def schema(self, turn: "Turn | None" = None) -> dict: - description, parameters = self.asked() if turn and turn.air_extra and self.asked else (self.description, self.parameters) - if self.source is not None: - parameters = {**parameters, "properties": {**parameters["properties"], "source": SOURCE_PARAMETER}} - return {"type": "function", "function": {"name": self.name, "description": description, "parameters": parameters}} + def schema(self) -> dict: + return {"type": "function", "function": {"name": self.name, "description": self.description, "parameters": self.parameters}} class Tools: @@ -114,13 +55,6 @@ def __init__(self, tools: list[Tool]): self.by_name = {t.name: t for t in tools} self.schemas = [t.schema() for t in tools] - def schemas_for(self, turn: "Turn | None") -> list[dict]: - """The tool list for this question: every tool, the same list as every other question's (so the provider's cached prompt holds), - except that a question asking for the air sensor's own temperature or humidity is offered them in the tools that can use them.""" - if turn and turn.air_extra and any(t.asked for t in self.by_name.values()): - return [t.schema(turn) for t in self.by_name.values()] - return self.schemas - async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: """Run a tool for the model; failures come back as text the model can explain.""" tool = self.by_name.get(name) @@ -131,26 +65,16 @@ async def call(self, name: str, raw_args: str, turn: Turn | None = None) -> str: except json.JSONDecodeError as e: return f"Error: tool arguments were not valid JSON ({e})" log.debug("Tool call %s %s", name, raw_args, extra=QUOTES) - sourced = CHART_SOURCE.set(source_text(args.get("source") if isinstance(args, dict) else None) or tool.source or "") # the charts this call draws - turn = turn or Turn() - calling = CALL.set((name, args)) # (each call made together runs in a context of its own: llm gathers them) + turn = turn if turn is not None else Turn() try: # no time limit of its own: the question's (bot.TURN_SECONDS) runs from before the call out = await tool.handler(args, turn) except Exception as e: log.error("Tool %s failed: %s: %s", name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) return f"Error calling tool: {e}" - finally: - CHART_SOURCE.reset(sourced) - CALL.reset(calling) out = out or "(no output)" if len(out) > MAX_OUTPUT_CHARS: log.warning("Tool %s output truncated: %d chars", name, len(out)) out = out[:MAX_OUTPUT_CHARS] + "\n...[truncated - request a shorter range]" log.debug("Tool result %s: %s", name, out if len(out) < 90 else f"{len(out)} chars", extra=QUOTES) - if turn: - turn.result_chars += len(out) + turn.result_chars += len(out) return out - - async def call_all(self, calls: list[tuple[str, dict]], turn: Turn | None = None) -> list[str]: - """The bot's own calls (name, arguments), made together; their results in the same order.""" - return await asyncio.gather(*(self.call(name, json.dumps(args), turn) for name, args in calls)) diff --git a/lib/topicmemory.py b/lib/topicmemory.py deleted file mode 100644 index 84fbbb34..00000000 --- a/lib/topicmemory.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Which guidance topics a chat is still on. A follow-up ("and for temperature?") often says nothing that names its topic, so a topic -stays on for a chat while either side keeps naming it or the model keeps using its tools, until RUNS runs in a row go by with none of -that. (The last messages are looked at as well: see Bot.respond.)""" - -RUNS = 2 - - -class TopicMemory: - def __init__(self): - self.idle: dict[str, int] = {} # topic -> runs since it was last named or used; a topic that has gone quiet is dropped - - def active(self) -> set[str]: - return set(self.idle) - - def update(self, offered: set[str], mentioned: set[str]) -> None: - """After a run. `offered`: the topics it was given guidance for; `mentioned`: those named by the person, named in the reply or - used by a tool.""" - for topic in mentioned: - self.idle[topic] = 0 - for topic in offered - mentioned: - if topic in self.idle: - self.idle[topic] += 1 - self.idle = {t: n for t, n in self.idle.items() if n < RUNS} diff --git a/scripts/bench_storage.py b/scripts/bench_storage.py index ba6e1f70..1edd4240 100644 --- a/scripts/bench_storage.py +++ b/scripts/bench_storage.py @@ -19,7 +19,6 @@ import sys import tempfile import time -from datetime import datetime, timedelta from pathlib import Path from zoneinfo import ZoneInfo @@ -28,7 +27,6 @@ from _common import parser # noqa: E402 (also puts the repo on sys.path) from lib.config import Config, data_dir, local_tz # noqa: E402 -from lib.tools import Turn # noqa: E402 FILES = ("ecobot.sqlite",) @@ -112,8 +110,19 @@ def count(r): return storage.read_now(count) -def period(days: float, now: datetime) -> dict: - return {"start_date": f"{now - timedelta(days=days):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}"} +def service(**sources): + """The service's tools over these sources (lib/service), as the bot and the model call them.""" + from lib.service import Service + from lib.service.context import Context + return Service.of(Context(**sources, tz=next(iter(sources.values())).tz)) + + +def asking(tools, name: str, args: dict): + """A request: the service's `name` called with `args`, as the bot asks for its charts (as drawn).""" + return lambda: tools[name].call(args, {"chart_points": "drawn"}) + + +FOUR_YEARS = "last 4 years" async def bench(folder: Path, repeat: int, tz) -> list[tuple[str, float, int]]: @@ -132,20 +141,16 @@ async def bench(folder: Path, repeat: int, tz) -> list[tuple[str, float, int]]: eco.has_minutes = any(n for _, _, n in held) # Home Assistant's minutes, which the bot draws a chart of a few hours from print(f"Ecowitt {eco.mac}: {held[0][1] if held else 0:,} rows of readings, {held[0][2] if held else 0:,} minutes, {Archive(eco).held()} " f"(opened in {opened:.1f} s)") - now = eco.now() - history, days, link = eco.tools[1].handler, eco.tools[2].handler, eco.tools[3].handler - chart = lambda field, d, groups="outdoor": lambda: history({"groups": groups, "chart": True, "chart_field": field, **period(d, now)}, Turn()) - work = [(f"Temperature chart, {label}", chart("temperature", d)) - for label, d in (("3 hours", 0.125), ("1D", 1), ("7D", 7), ("1M", 30), ("3M", 90), ("1Y", 365))] - work += [("Rain chart, 3M", chart("rain", 90, "rainfall")), - ("History of outdoor and indoor, 7 days, no chart", lambda: history({"groups": "outdoor,indoor", **period(7, now)}, Turn())), - ("weather_days: days over 30°C, 4 years", lambda: days({"condition": "temp_max > 30", "count_only": True, - "start_date": f"{now - timedelta(days=1460):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn())), - ("weather_days: rain per month, a year", lambda: days({"stat": "sum", "of": "rain", "group_by": "month", - "start_date": f"{now - timedelta(days=365):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn())), - ("weather_link: pressure and rain, 90 days, chart", lambda: link({"driver": "pressure", "chart": True}, Turn())), + tools = service(eco=eco) + chart = lambda reading, period: asking(tools, "summary", {"readings": [reading], "period": period, "chart": True}) + work = [(f"Temperature chart, {label}", chart("outdoor.temperature", period)) + for label, period in (("3 hours", "last 3 hours"), ("1D", "1d"), ("7D", "7d"), ("1M", "1m"), ("3M", "3m"), ("1Y", "1y"))] + work += [("Rain chart, 3M", chart("rain", "3m")), + ("Summary of outdoor and indoor, 7 days, no chart", asking(tools, "summary", {"period": "7d", "chart": False})), + ("days: days over 30°C, 4 years", asking(tools, "days", {"where": [{"field": "temp_max", "op": ">", "value": 30}], + "count_only": True, "period": FOUR_YEARS})), + ("days: rain per month, a year", asking(tools, "days", {"stat": "sum", "of": "rain", "group_by": "month", "period": "1y"})), + ("relate: pressure and rain, 90 days, chart", asking(tools, "relate", {"reading": "pressure", "chart": True})), ("The alerts' last 3 hours", lambda: eco.recent(3))] for label, run in work: rows.append((label, *await measured(run, repeat, lambda: eco.api.asked))) @@ -168,12 +173,11 @@ def cloud(request): # what the cache lacks is counted, and there is none of it air.tz = tz n = (await air.store.lacking())["all"] print(f"AirGradient {air.loc}: {n:,} readings") - now = datetime.now(tz).replace(tzinfo=None) - work = [(f"Air chart (PM2.5), {label}", lambda d=d: air.handle({"chart": True, "metrics": ["pm2_5"], **period(d, now)}, Turn())) - for label, d in (("1D", 1), ("7D", 7), ("1M", 30))] - work.append(("air_days: days PM2.5 over 25, 4 years", lambda: air.tools[1].handler( - {"condition": "pm2_5_max > 25", "count_only": True, "start_date": f"{now - timedelta(days=1460):%Y-%m-%d}", - "end_date": f"{now:%Y-%m-%d}"}, Turn()))) + tools = service(air=air) + work = [(f"Air chart (PM2.5), {label}", asking(tools, "summary", {"readings": ["pm2.5"], "period": period, "chart": True})) + for label, period in (("1D", "1d"), ("7D", "7d"), ("1M", "1m"))] + work.append(("days: days PM2.5 over 25, 4 years", asking(tools, "days", {"where": [{"field": "pm2_5_max", "op": ">", "value": 25}], + "count_only": True, "period": FOUR_YEARS}))) for label, run in work: rows.append((label, *await measured(run, repeat, lambda: asked[0]))) await air.close() diff --git a/scripts/dump_specs.py b/scripts/dump_specs.py index f4584368..993bef6f 100644 --- a/scripts/dump_specs.py +++ b/scripts/dump_specs.py @@ -1,4 +1,5 @@ -"""Draw the charts the bot would draw, from the bot's file (ecobot.sqlite), and save each chart spec (JSON) and picture (PNG). +"""Draw the charts the bot would draw, from the bot's file (ecobot.sqlite), and save each chart (the service's JSON, as drawn) and +picture (PNG). The charts are the service's tools' (lib/service: summary, relate, scan), each asked as the model or the bot asks it. Strictly offline: no API keys, no network (any request raises), and your file is never touched (it is copied to a temporary folder first). A question the file cannot answer is reported as "not cached" and skipped. @@ -8,7 +9,6 @@ """ import asyncio -import dataclasses import json import logging import sqlite3 @@ -22,12 +22,13 @@ from lib.config import data_dir # noqa: E402 from lib.airgradient import AirGradient # noqa: E402 -from lib.charts import render # noqa: E402 +from lib.charts import render_data # noqa: E402 from lib.compose import Composer # noqa: E402 from lib.config import Config # noqa: E402 from lib.ecowitt import Ecowitt # noqa: E402 from lib.storage import FILE, Storage # noqa: E402 -from lib.tools import Turn # noqa: E402 +from lib.service import Service # noqa: E402 +from lib.service.context import Context # noqa: E402 FMT = "%Y-%m-%d %H:%M:%S" @@ -41,55 +42,49 @@ async def handle_async_request(self, request): raise httpx.ConnectError("offline: dump_specs never uses the network") -def questions(now: datetime) -> list[tuple[str, str, dict, dict]]: - """(name, tool, arguments, what the person's words set on the Turn).""" - # The end of the last day the caches treat as final (a day is final an hour after it ends): a still-settling day would need the network - end = datetime.combine((now - timedelta(hours=25)).date(), datetime.min.time()) + timedelta(days=1) - timedelta(seconds=1) +def questions(now: datetime) -> list[tuple[str, str, dict]]: + """(name, service tool, arguments).""" + # The last day the caches treat as final (a day is final an hour after it ends): a still-settling day would need the network + end = (now - timedelta(hours=25)).date() - def back(days: float) -> dict: - return {"start_date": (end - timedelta(days=days) + timedelta(seconds=1)).strftime(FMT), "end_date": end.strftime(FMT)} + def back(days: int) -> dict: # the whole days to that last final day + return {"start": (end - timedelta(days=days - 1)).isoformat(), "end": end.isoformat()} - def days(n: int) -> dict: # n whole days ending on that last final day, for the tools that take dates - return {"start_date": (end.date() - timedelta(days=n - 1)).strftime("%Y-%m-%d"), "end_date": end.strftime("%Y-%m-%d")} - - eco = lambda name, tool, **a: (name, tool, a, {}) + chart = lambda name, *readings, **a: (name, "summary", {"readings": list(readings), "chart": True, **a}) return [ - eco("eco_temp_1d", "weather_history", chart=True, groups="outdoor", **back(1)), - eco("eco_temp_2d_indoor_outdoor", "weather_history", chart=True, groups="outdoor,indoor", **back(2)), - eco("eco_temp_7d", "weather_history", chart=True, groups="outdoor,indoor", **back(7)), - eco("eco_temp_30d", "weather_history", chart=True, groups="outdoor,indoor", **back(30)), - eco("eco_temp_90d", "weather_history", chart=True, groups="outdoor", **back(90)), - eco("eco_temp_400d", "weather_history", chart=True, groups="outdoor", **back(400)), - eco("eco_humidity_7d", "weather_history", chart=True, groups="outdoor", chart_field="humidity", **back(7)), - eco("eco_pressure_7d", "weather_history", chart=True, groups="pressure", chart_field="relative", **back(7)), - eco("eco_pressure_90d", "weather_history", chart=True, groups="pressure", chart_field="relative", **back(90)), - eco("eco_wind_7d_compass", "weather_history", chart=True, groups="wind", chart_field="wind_gust", **back(7)), - eco("eco_wind_90d_compass", "weather_history", chart=True, groups="wind", chart_field="wind_gust", **back(90)), - eco("eco_temp_30d_average", "weather_history", chart=True, groups="outdoor", average=True, **back(30)), - eco("eco_stack_temp_rain_14d", "weather_history", chart=True, chart_fields=["temperature", "rain"], **back(14)), - eco("eco_stack_temp_hum_pres_14d", "weather_history", chart=True, - chart_fields=["temperature", "humidity", "pressure"], **back(14)), - eco("eco_stack_wind_rain_30d", "weather_history", chart=True, chart_fields=["wind", "rain"], **back(30)), - eco("eco_link_pressure_90d", "weather_link", chart=True, driver="pressure", **days(90)), - eco("eco_link_humidity_30d", "weather_link", chart=True, driver="humidity", **days(30)), - eco("eco_link_wind_400d", "weather_link", chart=True, driver="wind", **days(400)), - ("air_pm25_1d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(1)}, {}), - ("air_pm25_7d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(7)}, {}), - ("air_pm25_30d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(30)}, {}), - ("air_pm25_200d_mixed_resolution", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(200)}, {}), - ("air_pm25_400d", "air_quality", {"chart": True, "metrics": ["pm2_5"], **back(360)}, {}), - ("air_all_7d", "air_quality", {"chart": True, "metrics": ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], **back(7)}, {}), - ("air_all_90d", "air_quality", {"chart": True, "metrics": ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], **back(90)}, {}), - ("air_co2_voc_14d", "air_quality", {"chart": True, "metrics": ["co2", "voc_index"], **back(14)}, {}), - ("air_pm_group_14d", "air_quality", {"chart": True, "metrics": ["pm1", "pm2_5", "pm10"], **back(14)}, {}), - ("plot_pm25_over_rain_30d", "plot_chart", {"panels": [{"series": "pm2_5"}, {"series": "rain"}], **days(30)}, {}), - ("plot_rating_over_rain_30d", "plot_chart", - {"panels": [{"series": "pm2_5", "style": "rating"}, {"series": "rain"}], **days(30)}, {}), - ("plot_temp_pm25_humidity_60d", "plot_chart", - {"panels": [{"series": "temperature"}, {"series": "pm2_5"}, {"series": "humidity"}], **days(60)}, {}), - ("plot_wind_pm10_90d", "plot_chart", {"panels": [{"series": "wind"}, {"series": "pm10"}], **days(90)}, {}), - ("air_link_pm25_60d", "air_link", {"chart": True, **days(60)}, {}), - ("air_scan_90d", "air_scan", {"chart": True, **days(90)}, {}), + chart("eco_temp_1d", "outdoor.temperature", **back(1)), + chart("eco_temp_2d_indoor_outdoor", "temperature", **back(2)), + chart("eco_temp_7d", "temperature", **back(7)), + chart("eco_temp_30d", "temperature", **back(30)), + chart("eco_temp_90d", "outdoor.temperature", **back(90)), + chart("eco_temp_400d", "outdoor.temperature", **back(400)), + chart("eco_humidity_7d", "outdoor.humidity", **back(7)), + chart("eco_pressure_7d", "pressure", **back(7)), + chart("eco_pressure_90d", "pressure", **back(90)), + chart("eco_wind_7d_compass", "wind", **back(7)), + chart("eco_wind_90d_compass", "wind", **back(90)), + chart("eco_temp_30d_average", "outdoor.temperature", average=True, **back(30)), + chart("eco_stack_temp_rain_14d", "temperature", "rain", **back(14)), + chart("eco_stack_temp_hum_pres_14d", "temperature", "humidity", "pressure", **back(14)), + chart("eco_stack_wind_rain_30d", "wind", "rain", **back(30)), + ("eco_link_pressure_90d", "relate", {"reading": "pressure", "chart": True, **back(90)}), + ("eco_link_humidity_30d", "relate", {"reading": "humidity", "chart": True, **back(30)}), + ("eco_link_wind_400d", "relate", {"reading": "wind", "chart": True, **back(400)}), + chart("air_pm25_1d", "pm2.5", **back(1)), + chart("air_pm25_7d", "pm2.5", **back(7)), + chart("air_pm25_30d", "pm2.5", **back(30)), + chart("air_pm25_200d_mixed_resolution", "pm2.5", **back(200)), + chart("air_pm25_400d", "pm2.5", **back(360)), + chart("air_all_7d", "air", **back(7)), + chart("air_all_90d", "air", **back(90)), + chart("air_co2_voc_14d", "co2", "voc", **back(14)), + chart("air_pm_group_14d", "pm1", "pm2.5", "pm10", **back(14)), + chart("plot_pm25_over_rain_30d", "pm2.5", "rain", **back(30)), + chart("plot_rating_over_rain_30d", "pm2.5", "rain", chart_readings=["air.pm2_5:rating", "rain"], **back(30)), + chart("plot_temp_pm25_humidity_60d", "outdoor.temperature", "pm2.5", "outdoor.humidity", **back(60)), + chart("plot_wind_pm10_90d", "wind", "pm10", **back(90)), + ("air_link_pm25_60d", "relate", {"reading": "pm2.5", "chart": True, **back(60)}), + ("air_scan_90d", "scan", {"chart": True, **back(90)}), ] @@ -132,21 +127,17 @@ async def main(): if not (eco or air): storage.close() raise SystemExit(f"{folder / FILE} holds no sensors") - tools = {t.name: t for s in (eco, air) if s for t in s.tools} - if eco and air: - tools.update({t.name: t for t in Composer(eco, air).tools}) + service = Service.of(await Context.open(eco=eco, air=air, composer=Composer(eco, air) if eco and air else None, tz=tz)) now = datetime.now(tz) print(f"as of {now:%Y-%m-%d %H:%M %Z}; held: ecowitt={'yes' if eco else 'NO'} airgradient={'yes' if air else 'NO'}") - for name, tool, tool_args, _ in questions(now): - if tool not in tools: - print(f" skip {name}: no {tool} tool (a cache is missing)") + for name, tool, tool_args in questions(now): + if tool not in service: + print(f" skip {name}: no {tool} tool (a source is missing)") continue - turn = Turn(chart_asked=True, chart_fields=tool_args.get("chart_fields", []), - chart_field=tool_args.get("chart_field"), average_asked=bool(tool_args.get("average"))) before = Offline.calls try: - result = await tools[tool].handler(tool_args, turn) + result = json.loads(await service[tool].call(tool_args, {"chart_points": "drawn", "fetch": False})) except httpx.ConnectError: print(f" cache {name}: not fully cached (it would need the network)") continue @@ -154,17 +145,14 @@ async def main(): print(f" ERROR {name}: {type(e).__name__}: {e}") continue note = f" ({Offline.calls - before} request(s) refused: part of the range is not cached)" if Offline.calls > before else "" - charts = turn.charts + charts = result.pop("charts", None) or [] if not charts: - print(f" none {name}: no chart{note}") + print(f" none {name}: no chart{note}{': ' + str(result['error']) if 'error' in result else ''}") continue - (out / f"{name}.json").write_text(json.dumps([dataclasses.asdict(c) for c in charts], indent=1, default=str)) - for i, spec in enumerate(charts): - (out / f"{name}{'' if i == 0 else f'_{i + 1}'}.png").write_bytes(render(spec, tz)) - try: - (out / f"{name}.result.json").write_text(json.dumps(json.loads(result), indent=1, ensure_ascii=False)) - except (TypeError, ValueError): - pass + (out / f"{name}.json").write_text(json.dumps(charts, indent=1, ensure_ascii=False)) + for i, chart in enumerate(charts): + (out / f"{name}{'' if i == 0 else f'_{i + 1}'}.png").write_bytes(render_data(chart, tz)) + (out / f"{name}.result.json").write_text(json.dumps(result, indent=1, ensure_ascii=False)) print(f" ok {name}: {len(charts)} chart(s){note}") for source in (eco, air): if source: diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index ff119962..f4efd04d 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -1,22 +1,27 @@ -"""Run the saved questions (tests/evals/cases.json). +"""Run the saved questions (tests/evals/cases.json, scored against tests/evals/service_cases.json). -Without --live: only the decisions made in code (fast path, period hints, reasoning effort, chart choices), no key needed. -With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) with recording stand-in -tools, and checks which tool it called and with what. Nothing is fetched. +Without --live: no key needed. The decisions the bot still makes in code (the reasoning effort from the words, and its shortcuts: the +report, the gauges, "weather now", a named reading's chart and a period) are checked over cases.json, and every service expectation +is checked against the tools it names (each one they take). - python scripts/eval_prompts.py # decisions made in code - python scripts/eval_prompts.py --live # and the model +With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) with recording +stand-in tools, and checks which tool it called and with what. Nothing is fetched. The bot's own request is the default: its system +prompt (the persona, the server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them, its reasoning +effort from the words, and a question it answers in code scored by its fixed calls without asking the model. + + python scripts/eval_prompts.py # the decisions made in code, and the service expectations + python scripts/eval_prompts.py --live # and the model, as the bot asks it python scripts/eval_prompts.py --live --effort low # force a reasoning level to see what it fixes python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? -With --service: the same questions against the service's ten tools alone (lib/service; docs/mcp-service.md, step 2), scored against -tests/evals/service_cases.json: the model is offered only their names, descriptions and parameters, with a neutral system line and the -date, time and zone, and none of the bot's prompt, hints or fast path. Without --live it checks the expectations themselves. +With --service: the ten tools alone (docs/mcp-service.md 7): the model is offered only their names, descriptions and parameters, with a +neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; --instructions adds the server's +instructions (lib/service/instructions.py) after the neutral line, as a client that passes them on would. Without --live it checks the +expectations themselves. python scripts/eval_prompts.py --service # every case has a service expectation, each one the tools take python scripts/eval_prompts.py --live --service # and the model, with the ten tools alone - python scripts/eval_prompts.py --live --service --instructions # ... and the server's instructions (lib/service/instructions.py) - # after the neutral line, as a client that passes them on would + python scripts/eval_prompts.py --live --service --instructions """ import asyncio @@ -34,7 +39,7 @@ async def main() -> int: ap.add_argument("--ids", help="comma-separated case ids") ap.add_argument("--repeat", type=int, default=1, help="ask the model this many times per case") ap.add_argument("--effort", choices=["none", "low", "medium"], help="force this reasoning effort for every case") - ap.add_argument("--service", action="store_true", help="the service's ten tools alone, scored against tests/evals/service_cases.json") + ap.add_argument("--service", action="store_true", help="the service's ten tools alone, with a neutral system line") ap.add_argument("--instructions", action="store_true", help="with --service: add the server's instructions to the system line") args = ap.parse_args() if args.instructions and not args.service: @@ -50,28 +55,21 @@ async def main() -> int: sys.exit("--live needs OPENROUTER_API_KEY (and OPENROUTER_BASE_URL, OPENROUTER_MODEL) in the environment") client = AsyncOpenAI(api_key=os.environ["OPENROUTER_API_KEY"], base_url=os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")) model = os.getenv("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") + expectations = evalkit.load_service_cases() if args.service: - failed = await evalkit.run_service(cases, evalkit.load_service_cases(), client, model, repeat=args.repeat, effort=args.effort, + failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, instructions=evalkit.service_instructions() if args.instructions else None) return 1 if failed else 0 - failed = 0 + decided = 0 for case in cases: - problems = evalkit.deterministic(case) - line = "ok" if not problems else "FAIL" - if client and not problems: - passes = 0 - for _ in range(args.repeat): - calls, reply = await evalkit.run_live(case, client, model, args.effort) - why = evalkit.check_calls(calls, case.expect) - passes += not why - problems += [f" run: {w}" for w in why[:3]] if why else [] - line = f"{passes}/{args.repeat}" + ("" if passes == args.repeat else " FAIL") - print(f"{line:>10} {case.id} ({case.ask})") - for p in problems: - print(f" {p}") - failed += bool(problems) - print(f"\n{len(cases) - failed} of {len(cases)} cases pass") - return 1 if failed else 0 + if problems := evalkit.deterministic(case): + decided += 1 + print(f"{'FAIL':>10} {case.id} ({case.ask})") + for p in problems: + print(f" {p}") + print(f"{len(cases) - decided} of {len(cases)} cases: the decisions made in code hold\n") + failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, bot=True) + return 1 if failed or decided else 0 if __name__ == "__main__": diff --git a/scripts/report_inputs.py b/scripts/report_inputs.py index d0a03a46..2b346534 100644 --- a/scripts/report_inputs.py +++ b/scripts/report_inputs.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 -"""Print exactly what the report's fast path fetches (weather_now, air_quality and, if switched on, pollen_asthma and -weather_forecast), as the raw results the bot hands over. Paste the output to whoever is writing the report layout. Needs the -bot's environment, as the other scripts do (load your env file into the shell first; this script never reads it): +"""Print exactly what the report is written from: the service's calls the bot makes for it (current, and, if switched on, pollen and +forecast: lib/intent.report_calls), as the raw results the service gives. Paste the output to whoever is writing the report layout. +Needs the bot's environment, as the other scripts do (load your env file into the shell first; this script never reads it): set -a; . /etc/ecobot.env; set +a python scripts/report_inputs.py @@ -10,14 +10,14 @@ """ import asyncio -import json from _common import parser # noqa: E402 (also puts the repo on sys.path) from ecobot import start_sources # noqa: E402 from lib import intent # noqa: E402 from lib.config import Config # noqa: E402 -from lib.tools import Tools # noqa: E402 +from lib.service import Service # noqa: E402 +from lib.service.context import Context # noqa: E402 async def main(): @@ -25,11 +25,12 @@ async def main(): cfg = Config.from_env() sources, cfg = await start_sources(cfg) try: - tools = Tools([t for s in sources for t in s.tools]) - names = {s.name for s in sources} - for name, args in intent.report_calls(names): - print(f"=== {name} {json.dumps(args)}") - print(await tools.call(name, json.dumps(args))) + by_name = {s.name: s for s in sources} + service = Service.of(await Context.open(eco=by_name.get("Ecowitt"), air=by_name.get("AirGradient"), forecast=by_name.get("Forecast"), + pollen=by_name.get("Pollen"), tz=cfg.tz)) + for name, args in intent.report_calls(by_name): + print(f"=== {name} {args}") + print(await service[name].call(args)) print() finally: for source in sources: diff --git a/scripts/show_request.py b/scripts/show_request.py index 40212466..2961a9f8 100644 --- a/scripts/show_request.py +++ b/scripts/show_request.py @@ -1,34 +1,34 @@ """Show exactly what the bot sends to the model for a question, without calling the model. -Builds the real system prompt and tool definitions, runs the real reasoning/fast-path decisions, and -runs the real tools against the bot's file (no network, no API keys). A recording stand-in plays the -model: its first reply is a tool call you choose with --call (default: the call the model made for -"hottest day where it also rained"), its second is a short answer. Every request the bot would send -is printed in full. +Builds the real system prompt (the bot's persona, the server's instructions and the time) and the service's tools as the model is +offered them (lib/model_tools.py), reads the effort from the words, and runs the service's tools against the bot's file (no network, no +API keys: the weather station is its file alone, so a tool that needs more answers with its error). A recording stand-in plays the +model: its first reply is a tool call you choose with --call (default: the call for "hottest day where it also rained"), its second is a +short answer. Every request the bot would send is printed in full. python scripts/show_request.py "hottest day where it also rained" python scripts/show_request.py --file /path/ecobot.sqlite --call '{"name": ..., "arguments": {...}}' "..." - python scripts/show_request.py --call '{"name": "readings", "arguments": {"metric": "outdoor.humidity", "start": "2026-11-08 20:47", + python scripts/show_request.py --call '{"name": "readings", "arguments": {"reading": "outdoor.humidity", "period": "last 5 hours", "interval": "1hour"}}' "humidity each hour for the last 5 hours" # the readings tool, run on the file """ import asyncio import json import sys -from datetime import datetime, timedelta +from datetime import datetime from pathlib import Path from types import SimpleNamespace as NS from _common import parser # noqa: E402 (also puts the repo on sys.path) from lib.config import data_dir, local_tz # noqa: E402 -from lib import intent, prompt # noqa: E402 -from lib.history import History # noqa: E402 -from lib.airgradient import source as air # noqa: E402 -from lib.ecowitt import days, source as station # noqa: E402 +from lib import intent, model_tools, prompt # noqa: E402 from lib.llm import Agent # noqa: E402 +from lib.service import Service # noqa: E402 +from lib.service.context import Context # noqa: E402 +from lib.service.instructions import instructions # noqa: E402 from lib.storage import FILE, Storage # noqa: E402 -from lib.tools import Tool, Tools # noqa: E402 +from lib.tools import Turn # noqa: E402 class Recorder: @@ -48,10 +48,9 @@ async def create(self, **kwargs): return NS(choices=[NS(message=msg)], usage=None) -def default_call(today): - return {"name": "weather_days", "arguments": { - "start_date": str(today - timedelta(days=1459)), "end_date": str(today - timedelta(days=1)), - "where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "order": "desc", "limit": 3}} +def default_call(): + return {"name": "days", "arguments": {"where": [{"field": "rain", "op": ">=", "value": 1}], "sort_by": "temp_max", "order": "desc", + "limit": 3}} def banner(text): @@ -75,33 +74,22 @@ async def main(): storage.close() sys.exit(f"{args.file} has no station history") - async def days_handler(a): - return await days.days_tool(storage, macs[0], tz, a) - - async def unavailable(a): - return "(not run by this script)" - - air_sensor = next(iter(storage.sensors.all(kind="air")), None) - history = await History.open(NS(storage=storage, mac=macs[0], tz=tz), - NS(store=NS(storage=storage, sensor=lambda: air_sensor), tz=tz) if air_sensor else None) - tools = Tools([Tool("weather_now", station.REALTIME_DESCRIPTION, station.REALTIME_PARAMS, unavailable), - Tool("weather_history", station.HISTORY_DESCRIPTION, station.HISTORY_PARAMS, unavailable), - Tool("weather_days", days.DESCRIPTION, days.PARAMETERS, days_handler), - Tool("air_quality", air.DESCRIPTION, air.PARAMETERS, unavailable), *history.tools]) + station = NS(name="Ecowitt", storage=storage, mac=macs[0], tz=tz, latitude=None) # (the file alone) + ctx = await Context.open(eco=station, tz=tz) + tools = model_tools.tools(Service.of(ctx)) text = args.question - r = intent.read(text, now.replace(tzinfo=None)) - system = prompt.build(now, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor air-quality sensor"}, r.hints) - effort, fast = r.effort, r.fast - call = json.loads(args.call) if args.call else default_call(now.date()) + r = intent.read(text, now, {"Ecowitt"}, tz, ctx.readings()) + system = prompt.build(now, instructions(ctx)) + effort = r.effort + call = json.loads(args.call) if args.call else default_call() client = Recorder([call, "(the model's answer goes here)"]) messages = [{"role": "user", "content": text}] - await Agent(client, "deepseek/deepseek-v4.1-flash-1017", tools).run(messages, system, effort, first_call=([fast[:2], *r.more] if r.more else fast[:2]) if fast else None, - tool_choice=r.tool_choice) + await Agent(client, "deepseek/deepseek-v4.1-flash-1017", tools).run(messages, system, effort, turn=Turn()) banner("DECISIONS MADE IN CODE") - print(f"reasoning effort: {effort} fast path: {fast[2] if fast else 'no (the model chooses the tool)'} " - f"must call a tool first: {r.needs_data}") + print(f"reasoning effort: {effort} answered in code (no model): " + f"{'the report' if r.report else 'the gauges' if r.dashboard else 'weather now' if r.weather_now else r.chart or 'no'}") first = client.requests[0] banner("REQUEST 1: settings") print(json.dumps({k: v for k, v in first.items() if k not in ("messages", "tools")}, indent=2)) diff --git a/tests/evalkit.py b/tests/evalkit.py index 45dc5b15..0b047492 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -1,12 +1,15 @@ -"""Saved questions with the tool calls we expect, so every fix we make for a real report stays fixed. - -tests/evals/cases.json holds the questions (real ones from the logs). Two kinds of check: - - decisions made in code (fast path, period hints, reasoning effort, which readings a chart combines): run by pytest; - - what the model does with them (which tool, which arguments): `python scripts/eval_prompts.py --live`, against the - real model with recording stand-in tools (nothing is fetched). -tests/evals/service_cases.json holds, for the same case ids, what a model offered only the service's ten tools (lib/service) should -call: checked offline by tests/test_service_evals.py, and asked of the model by `python scripts/eval_prompts.py --live --service` -(with `--instructions`, the server's instructions, lib/service/instructions.py, after the neutral system line). +"""Saved questions with what should happen to them, so every fix we make for a real report stays fixed. + +tests/evals/cases.json holds the questions (real ones from the logs) and the decisions the bot still makes in code (docs/mcp-service.md 4): +the reasoning effort from the words, and its few shortcuts (the report, the gauges, "weather now", a named reading's chart and a +period, each a fixed call to a service tool). pytest checks them (`deterministic`). +tests/evals/service_cases.json holds, for the same case ids, what a model offered the service's ten tools (lib/service) should call: +checked offline by tests/test_service_evals.py, and asked of a model by `python scripts/eval_prompts.py --live` three ways: + - the bot's own request (`bot=True`, the default of --live): its system prompt (lib/prompt.py: the persona, the server's + instructions, the date and time), the ten tools as the bot offers them, its reasoning effort from the words; a question the bot + answers in code is not asked of the model, its fixed calls are scored instead; + - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM); + - `--service --instructions`: that, with the server's instructions (lib/service/instructions.py) after the neutral line. """ import json @@ -15,15 +18,11 @@ from datetime import date, datetime from pathlib import Path -from lib import compose, history, intent, prompt -from lib.airgradient import days as air_days, source as air -from lib.ecowitt import days, link, source as station -from lib.forecast import source as forecast -from lib.pollen import source as pollen -from tests.fakes import EVERY_SOURCE +from lib import intent, prompt +from lib.bot import complete_reply from lib.llm import Agent -from lib.specs import AIR_SOURCE, ECOWITT_SOURCE -from lib.tools import Tool, Tools +from lib.tools import Tool, Tools, Turn +from tests.fakes import EVERY_SOURCE CASES = Path(__file__).resolve().parent / "evals" / "cases.json" NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday: dates in the cases are relative to this @@ -67,35 +66,6 @@ def load_cases(path: Path = CASES) -> list[Case]: return [Case(**c) for c in json.loads(path.read_text())] -def tool_names() -> list[str]: - return ["weather_now", "weather_history", "weather_days", "weather_link", "air_quality", "plot_chart", "air_link", "air_scan", - "pollen_asthma", "weather_forecast", "air_days", "readings"] - - -def make_tools(calls: list) -> Tools: - """The real tool definitions with stand-in handlers that record the call.""" - def recorder(name): - async def handler(args, turn=None): - calls.append((name, args)) - return CANNED - return handler - defs = [("weather_now", station.REALTIME_DESCRIPTION, station.REALTIME_PARAMS), - ("weather_history", station.HISTORY_DESCRIPTION, station.HISTORY_PARAMS), - ("weather_days", days.DESCRIPTION, days.PARAMETERS), - ("weather_link", link.DESCRIPTION, link.PARAMETERS), - ("air_quality", air.DESCRIPTION, air.PARAMETERS), - ("plot_chart", compose.PLOT_DESCRIPTION, compose.PLOT_PARAMETERS), - ("air_link", compose.LINK_DESCRIPTION, compose.LINK_PARAMETERS), - ("air_scan", compose.SCAN_DESCRIPTION, compose.SCAN_PARAMETERS), - ("pollen_asthma", pollen.DESCRIPTION, pollen.PARAMETERS), - ("weather_forecast", forecast.DESCRIPTION, forecast.PARAMETERS), - ("air_days", air_days.DESCRIPTION, air_days.PARAMETERS), - ("readings", history.DESCRIPTION, history.PARAMETERS)] - sources = {name: ECOWITT_SOURCE for name in ("weather_history", "weather_days", "weather_link")} | \ - {name: AIR_SOURCE for name in ("air_quality", "air_days")} | {name: "" for name in ("plot_chart", "air_link", "air_scan")} - return Tools([Tool(n, d, p, recorder(n), source=sources.get(n)) for n, d, p in defs]) - - def content(case: Case) -> str: """The user turn exactly as the bot builds it for a private chat.""" return f'(replying to your earlier message: "{case.reply_to}") {case.ask}' if case.reply_to else case.ask @@ -159,54 +129,81 @@ def check_calls(calls: list[tuple[str, dict]], expect: dict) -> list[str]: return fails +DECISIONS = {"effort", "report", "dashboard", "weather_now", "chart"} # what cases.json's `expect` may say + + +def read(case: Case): + """intent.read of the case's question, as the bot reads it at NOW with every source.""" + from zoneinfo import ZoneInfo + from lib.service.names import CATALOGUE + tz = ZoneInfo(NOW_TZ) + return intent.read(case.ask, NOW.replace(tzinfo=tz), EVERY_SOURCE, tz, CATALOGUE) + + def deterministic(case: Case) -> list[str]: - """Failures of the decisions made in code (no model): reasoning effort, fast path, hints, chart choices.""" + """Failures of the decisions made in code (no model): the reasoning effort, and which shortcut answers it, if any (`chart`: the + summary arguments of a named reading's chart and a period, or null: no chart shortcut).""" e, fails = case.expect, [] - text = case.ask - r = intent.read(text, NOW, EVERY_SOURCE) + if extra := set(e) - DECISIONS: + fails.append(f"unknown keys {sorted(extra)}") + r = read(case) if "effort" in e and r.effort != e["effort"]: fails.append(f"effort {r.effort}, expected {e['effort']}") - if "fast" in e: - fast = r.fast - if e["fast"] is None: - if fast: - fails.append(f"took the fast path ({fast[0]}) but should go to the model") - elif not fast: - fails.append("did not take the fast path") - else: - if fast[0] != e["fast"].get("tool"): - fails.append(f"fast path tool {fast[0]}, expected {e['fast'].get('tool')}") - fails += [f"fast path {f}" for f in check_args(fast[1], e["fast"].get("args", {}))] - if "hints" in e: - hints = " | ".join(r.hints) - fails += [f"period hints lack {h!r} (got: {hints or 'none'})" for h in e["hints"] if h not in hints] - for key, got in (("chart_fields", r.chart_fields), ("two_axes", r.two_axes), ("air_extra", r.air_extra), ("chart_field", r.chart_field), ("report", r.report), ("dashboard", r.dashboard), - ("about_the_bot", r.about_the_bot), ("needs_data", r.needs_data), - ("weather_now", r.weather_now), ("rain_caption", r.rain_caption), ("chart_in_code", r.chart_in_code), ("lookup", r.lookup)): - if key in e and got != e[key]: - fails.append(f"{key} {got}, expected {e[key]}") - for name in e.get("tools", []) + e.get("any_tools", []) + e.get("not_tools", []) + ([e["first_tool"]] if "first_tool" in e else []): - if name not in tool_names(): - fails.append(f"unknown tool {name!r} in the case") + for key in ("report", "dashboard", "weather_now"): + if key in e and getattr(r, key) != e[key]: + fails.append(f"{key} {getattr(r, key)}, expected {e[key]}") + if "chart" in e: + got = r.chart[1] if r.chart else None + if got != e["chart"]: + fails.append(f"chart shortcut {got}, expected {e['chart']}") return fails +def shortcut_calls(r) -> list[tuple[str, dict]] | None: + """The service calls the bot makes itself for a question it answers in code (the report, the gauges, weather now, a chart), else + None: the model takes it.""" + from lib import gauge_sheet + if r.report: + return intent.report_calls(EVERY_SOURCE) + if r.dashboard: + return [("current", gauge_sheet.call())] + if r.weather_now: + return [intent.WEATHER_NOW_CALL] + return [r.chart] if r.chart else None + + +# Where the bot's own shortcuts differ from what a model is expected to call, on purpose (docs/mcp-service.md 4): the report's forecast +# is the next 3 days, as it always was; a chart the bot draws itself sends its caption, so it needs no chart_answers_it +SHORTCUT_LEAVES = {"forecast": ("period",), "summary": ("chart_answers_it",)} + + +def shortcut_expectation(expect: dict) -> dict: + """The case's service expectation, as the bot's own shortcut calls are held to it (less SHORTCUT_LEAVES).""" + args = {} + for tool, want in expect.get("args", {}).items(): + drop = SHORTCUT_LEAVES.get(tool, ()) + args[tool] = [{k: v for k, v in w.items() if k not in drop} for w in want] if isinstance(want, list) else \ + {k: v for k, v in want.items() if k not in drop} + return {**expect, "args": args} + + +def bot_system(now: datetime = NOW) -> str: + """The bot's system prompt at `now` (the station's local time): its persona, the server's instructions, the date and time.""" + from zoneinfo import ZoneInfo + return prompt.build(now.replace(tzinfo=ZoneInfo(NOW_TZ)), service_instructions()) + + async def run_live(case: Case, client, model: str, effort: str | None = None) -> tuple[list[tuple[str, dict]], str]: - """Ask the real model; returns the tool calls it made and its final reply.""" - calls: list[tuple[str, dict]] = [] - text = case.ask - r = intent.read(text, NOW, EVERY_SOURCE) - system = prompt.build(NOW, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor air-quality sensor", - "Pollen": "Melbourne pollen forecast and thunderstorm asthma risk (melbournepollen.com.au)", - "Forecast": "Weather forecast for the owner's location (Open-Meteo)"}, - r.hints, r.about_the_bot, r.rain_caption, intent.topics(content(case), [m["content"] for m in case.history if m["role"] == "user"][-2:])) - fast = r.fast + """The bot's own request (docs/mcp-service.md 4): a question it answers in code gives its fixed calls (no model); any other is asked + of the model with the bot's system prompt, the ten tools as it offers them, its reasoning effort from the words, tool_choice auto, + and the turn ended on a complete result as the bot ends it. Returns the calls made and the reply.""" + r = read(case) + if (calls := shortcut_calls(r)) is not None: + return list(calls), "(answered in code)" + calls = [] messages = [*case.history, {"role": "user", "content": content(case)}] - reply = await Agent(client, model, make_tools(calls)).run( - messages, system, effort or r.effort, first_call=[*([fast[:2], *r.more] if fast else []), *r.extra] or None, - tool_choice=r.tool_choice) - if fast or r.extra: - calls[0:0] = [*([(fast[0], fast[1]), *r.more] if fast else []), *r.extra] # the bot ran them itself, before the model + reply = await Agent(client, model, make_service_tools(calls)).run(messages, bot_system(), effort or r.effort, tool_choice="auto", + turn=Turn(), finish=lambda _, results: complete_reply(results)) return calls, reply @@ -488,7 +485,7 @@ def calls_text(calls: list[tuple[str, dict]]) -> str: async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, - effort: str | None = None, instructions: str | None = None, out=print) -> int: + effort: str | None = None, instructions: str | None = None, bot: bool = False, out=print) -> int: """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times with the ten tools alone (and the server's `instructions`, when given) and its calls scored against it (check_calls), as `--live` scores cases.json. Prints a line per case (`out`), with the calls of a run that fails; returns how many cases fail.""" @@ -500,14 +497,21 @@ async def run_service(cases: list[Case], expectations: dict[str, dict], client=N if client and not problems: passes = 0 for _ in range(repeat): - calls, _reply = await run_live_service(case, client, model, effort, instructions) - why = check_calls(calls, expect) + if bot: + calls, _reply = await run_live(case, client, model, effort) + in_code = shortcut_calls(read(case)) is not None + else: + calls, _reply, in_code = *await run_live_service(case, client, model, effort, instructions), False + why = check_calls(calls, shortcut_expectation(expect) if in_code else expect) passes += not why problems += [*(f" run: {w}" for w in why[:3]), f" called: {calls_text(calls)}"] if why else [] - line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + (" code" if bot and in_code else "") out(f"{line:>10} {case.id} ({case.ask})") for p in problems: out(f" {p}") failed += bool(problems) - out(f"\n{len(cases) - failed} of {len(cases)} cases pass (the service's ten tools alone{', with its instructions' if instructions else ''})") + what = "the bot's prompt and the ten tools" if bot else f"the service's ten tools alone{', with its instructions' if instructions else ''}" + if client: + out(f"\nmodel: {model}") + out(f"\n{len(cases) - failed} of {len(cases)} cases pass ({what})") return failed diff --git a/tests/evals/cases.json b/tests/evals/cases.json index 926737ac..3f8f1af1 100644 --- a/tests/evals/cases.json +++ b/tests/evals/cases.json @@ -4,22 +4,7 @@ "ask": "average temp 3m", "note": "3m was read as 3 days", "expect": { - "hints": [ - "\"3m\" = last 3 months: 2026-07-01" - ], - "effort": "none", - "chart_fields": [], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-07-0[1-2]" - }, - "average": true - } - } + "effort": "none" }, "covers": [ "q:average", @@ -31,15 +16,12 @@ "ask": "wind direction plot 3m", "note": "fast path: a plain wind chart request with a short-form period", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "wind", - "chart": true, - "start_date": { - "regex": "^2026-07-01" - } - } + "chart": { + "readings": [ + "wind direction" + ], + "period": "3m", + "chart": true } }, "covers": [ @@ -52,18 +34,7 @@ "ask": "plot temperature and rain", "note": "only temperature was charted", "expect": { - "chart_fields": [ - "temperature", - "rain" - ], - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "rainfall,outdoor,indoor", - "chart": true - } - } + "chart": null }, "covers": [ "c:stack", @@ -76,10 +47,7 @@ "ask": "lowest and highest humidity", "note": "plotted temperature on a humidity question", "expect": { - "chart_field": "humidity", - "tools": [ - "weather_history" - ] + "chart": null }, "covers": [ "m:humidity", @@ -91,13 +59,7 @@ "ask": "Is there a correlation between pressure and rainfall", "note": "answered from monthly extremes", "expect": { - "effort": "medium", - "tools": [ - "weather_link" - ], - "not_tools": [ - "weather_days" - ] + "effort": "medium" }, "covers": [ "q:correlation", @@ -109,9 +71,7 @@ "id": "pressure-vs-rain-graph", "ask": "plot a graph of pressure against rainfall", "expect": { - "tools": [ - "weather_link" - ] + "chart": null }, "covers": [ "c:link", @@ -123,20 +83,7 @@ "id": "public-holidays", "ask": "hottest public holidays", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "only": "public_holiday", - "sort_by": { - "any_of": [ - "temp_max", - null - ] - } - } - } + "chart": null }, "covers": [ "q:rank-days", @@ -147,21 +94,7 @@ "id": "hottest-day-that-rained", "ask": "what was the hottest day that also rained", "expect": { - "effort": "low", - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "temp_max", - "order": { - "any_of": [ - "desc", - null - ] - } - } - } + "effort": "low" }, "covers": [ "q:rank-days", @@ -173,16 +106,7 @@ "id": "wind-direction-week", "ask": "most common wind direction this week", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "groups": { - "regex": "wind" - } - } - } + "chart": null }, "covers": [ "m:wind-direction" @@ -192,10 +116,7 @@ "id": "will-it-rain", "ask": "will it rain later?", "expect": { - "effort": "low", - "tools": [ - "weather_now" - ] + "effort": "low" }, "covers": [ "q:forecast", @@ -206,9 +127,7 @@ "id": "air-now", "ask": "how's the air?", "expect": { - "fast": { - "tool": "air_quality" - } + "chart": null }, "covers": [ "q:current", @@ -219,14 +138,12 @@ "id": "weather-week", "ask": "weather week", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-09-23" - } - } + "chart": { + "readings": [ + "weather" + ], + "period": "week", + "chart": true } }, "covers": [ @@ -238,14 +155,7 @@ "id": "hello", "ask": "thanks, that's great", "expect": { - "fast": null, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "chart": null }, "covers": [ "q:chat" @@ -255,15 +165,7 @@ "id": "chart-pm10-week", "ask": "chart PM10 from the past week", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true, - "metrics": [ - "pm10" - ] - } - } + "chart": null }, "covers": [ "c:air-single", @@ -275,14 +177,12 @@ "ask": "weather 4 months", "note": "4 months was read as the last 7 days", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-05-31" - } - } + "chart": { + "readings": [ + "weather" + ], + "period": "4 months", + "chart": true } }, "covers": [ @@ -295,13 +195,7 @@ "id": "chart-indoors", "ask": "chart the past week indoors", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "indoor", - "chart": true - } - } + "chart": null }, "covers": [ "c:line", @@ -313,17 +207,13 @@ "ask": "pressure week", "note": "a bare 'pressure week' is a chart of the pressure group, sent with no model call", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "pressure", - "chart": true - } - }, - "chart_field": "relative", - "hints": [ - "\"week\" = last 7 days" - ] + "chart": { + "readings": [ + "pressure" + ], + "period": "week", + "chart": true + } }, "covers": [ "m:pressure", @@ -335,19 +225,13 @@ "ask": "wind 3m", "note": "wind 3m was read as 3 days; a bare reading and period is a chart", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "groups": "wind", - "chart": true, - "start_date": { - "regex": "^2026-07-0[1-2]" - } - } - }, - "hints": [ - "\"3m\" = last 3 months: 2026-07-01" - ] + "chart": { + "readings": [ + "wind" + ], + "period": "3m", + "chart": true + } }, "covers": [ "m:wind-speed", @@ -358,20 +242,7 @@ "id": "hottest-weekends", "ask": "hottest weekends", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "only": "weekend", - "sort_by": { - "any_of": [ - "temp_max", - null - ] - } - } - } + "chart": null }, "covers": [ "q:rank-days" @@ -381,17 +252,7 @@ "id": "windiest-day-on-record", "ask": "Windiest day on record", "expect": { - "hints": [ - "\"on record\" = on record" - ], - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "wind_gust" - } - } + "chart": null }, "covers": [ "q:rank-days", @@ -403,17 +264,7 @@ "id": "rainy-days-in-september", "ask": "list rainy days in september", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "start_date": "2026-09-01", - "where": { - "regex": "rain" - } - } - } + "chart": null }, "covers": [ "q:rank-days", @@ -425,23 +276,7 @@ "ask": "give me the outdoor high between 11am Fri 10 Nov 2023 and 11am Sat 11 Nov 2023", "note": "a particular window, not a whole period", "expect": { - "fast": null, - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2023-11-10 11:00" - }, - "end_date": { - "regex": "^2023-11-11 11:00" - }, - "groups": { - "regex": "outdoor" - } - } - } + "chart": null }, "covers": [ "q:known-day", @@ -452,16 +287,7 @@ "id": "weather-on-june-11", "ask": "what kind of weather was June 11", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-06-11" - } - } - } + "chart": null }, "covers": [ "q:describe-day" @@ -471,17 +297,7 @@ "id": "what-it-would-have-been-like", "ask": "what would it have been like if we were alive on Mon 10 Aug", "expect": { - "effort": "low", - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-08-10" - } - } - } + "effort": "low" }, "covers": [ "q:describe-day" @@ -492,14 +308,7 @@ "ask": "add an alert for if winds reach 100 km hour", "note": "a request to change the bot, not for readings: it was forced to fetch the weather", "expect": { - "needs_data": false, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "chart": null }, "covers": [ "q:command" @@ -509,15 +318,7 @@ "id": "metrics-bare", "ask": "metrics", "expect": { - "needs_data": false, - "about_the_bot": true, - "not_tools": [ - "weather_now", - "weather_history", - "weather_days", - "weather_link", - "air_quality" - ] + "chart": null }, "covers": [ "q:about-the-bot" @@ -527,16 +328,7 @@ "id": "most-rain-days-jja", "ask": "Days with most rain in June, July, August 2026", "expect": { - "tools": [ - "weather_days" - ], - "args": { - "weather_days": { - "sort_by": "rain", - "start_date": "2026-06-01", - "end_date": "2026-08-31" - } - } + "chart": null }, "covers": [ "q:rank-days", @@ -547,10 +339,7 @@ "id": "fastest-gust", "ask": "fastest gust recorded", "expect": { - "any_tools": [ - "weather_history", - "weather_days" - ] + "chart": null }, "covers": [ "q:record", @@ -561,12 +350,7 @@ "id": "chart-all-airgradient-week", "ask": "chart all airgradient past week", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } - } + "chart": null }, "covers": [ "c:air-panels", @@ -578,24 +362,7 @@ "ask": "did it rain on Sat 5 Sep", "note": "one known day: its figures, not a search of the month", "expect": { - "any_tools": [ - "weather_days", - "weather_history" - ], - "args": { - "weather_days": { - "start_date": "2026-09-05", - "end_date": "2026-09-05" - }, - "weather_history": { - "start_date": { - "regex": "^2026-09-05" - }, - "end_date": { - "regex": "^2026-09-05" - } - } - } + "chart": null }, "covers": [ "q:known-day", @@ -617,16 +384,7 @@ ], "note": "a pushback: fetch again, don't defend or agree from memory", "expect": { - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2026-09-23" - } - } - } + "chart": null }, "covers": [ "q:correction" @@ -646,19 +404,7 @@ } ], "expect": { - "hints": [ - "\"all time\" = on record" - ], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "start_date": { - "regex": "^2022-10" - } - } - } + "chart": null }, "covers": [ "q:follow-up" @@ -669,20 +415,7 @@ "ask": "win direction 3 months", "note": "a typo: the model path handles it", "expect": { - "fast": null, - "hints": [ - "\"3 months\" = last 3 months: 2026-07-01" - ], - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "groups": { - "regex": "wind" - } - } - } + "chart": null }, "covers": [ "m:wind-direction" @@ -692,14 +425,7 @@ "id": "hottest-coldest-this-month", "ask": "hottest/coldest day this month", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "start_date": { - "regex": "^2026-09-01" - } - } - } + "chart": null }, "covers": [ "q:summary", @@ -710,14 +436,7 @@ "id": "high-low-all-time", "ask": "high and low all time", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "start_date": { - "regex": "^2022-10" - } - } - } + "chart": null }, "covers": [ "q:record", @@ -739,9 +458,7 @@ ], "note": "the resolution is chosen automatically and extremes are refined to 5-minute windows: fetch again and say so", "expect": { - "tools": [ - "weather_history" - ] + "chart": null }, "covers": [ "q:detail-level", @@ -755,16 +472,7 @@ "note": "only the weather station was fetched; the older answer listed everything from both devices", "expect": { "report": true, - "tools": [ - "weather_now", - "air_quality" - ], - "fast": { - "tool": "weather_now", - "args": { - "groups": "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - } - } + "chart": null }, "covers": [ "q:report" @@ -775,8 +483,8 @@ "ask": "dashboard", "note": "the station's gauges, drawn in code with no model; it used to mean the report", "expect": { - "dashboard": true, - "report": false + "report": false, + "dashboard": true }, "covers": [ "q:dashboard" @@ -798,10 +506,7 @@ "note": "AirGradient and Ecowitt are separate tools: needs the cross-source link", "expect": { "effort": "medium", - "fast": null, - "tools": [ - "air_link" - ] + "chart": null }, "covers": [ "q:cross-source", @@ -814,10 +519,7 @@ "ask": "plot the traffic light rating of air quality against rainfall for the last 30 days", "note": "a new kind of chart: the rating over rain", "expect": { - "fast": null, - "tools": [ - "plot_chart" - ] + "chart": null }, "covers": [ "c:rating-strip", @@ -830,13 +532,7 @@ "note": "needs a scan of every pair, not one lookup", "expect": { "effort": "medium", - "fast": null, - "tools": [ - "air_scan" - ], - "not_tools": [ - "air_link" - ] + "chart": null }, "covers": [ "q:scan", @@ -848,14 +544,12 @@ "ask": "ecowitt week", "note": "ecowitt is a synonym of weather", "expect": { - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "start_date": { - "regex": "^2026-09-23" - } - } + "chart": { + "readings": [ + "ecowitt" + ], + "period": "week", + "chart": true } }, "covers": [ @@ -868,11 +562,12 @@ "ask": "ag 7d", "note": "ag is a synonym of air quality", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } + "chart": { + "readings": [ + "ag" + ], + "period": "7d", + "chart": true } }, "covers": [ @@ -885,10 +580,7 @@ "ask": "air gradient", "note": "air gradient is a synonym of air quality", "expect": { - "fast": { - "tool": "air_quality", - "args": {} - } + "chart": null }, "covers": [ "q:current", @@ -900,15 +592,7 @@ "ask": "ecowitt all week", "note": "every reading stacked (solar third, wind last), except UV, feels like and VPD (unless configured)", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "chart": null }, "covers": [ "q:summary", @@ -920,11 +604,7 @@ "ask": "sitrep", "note": "sitrep is a synonym of status: the full current report", "expect": { - "report": true, - "tools": [ - "weather_now", - "air_quality" - ] + "report": true }, "covers": [ "q:report" @@ -935,10 +615,7 @@ "ask": "think: hottest day this week", "note": "asking to think gives medium reasoning to a lookup; the hottest day of a period with when it was is weather_history (a record), not weather_days", "expect": { - "effort": "medium", - "tools": [ - "weather_history" - ] + "effort": "medium" }, "covers": [ "q:record", @@ -950,15 +627,12 @@ "ask": "Rain chart 7d", "note": "the Rain chart button", "expect": { - "chart_field": "daily", - "rain_caption": true, - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "rainfall", - "chart": true - } + "chart": { + "readings": [ + "rain" + ], + "period": "7d", + "chart": true } }, "covers": [ @@ -971,14 +645,12 @@ "ask": "Humidity chart 7d", "note": "the Humidity chart button", "expect": { - "chart_field": "humidity", - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "outdoor,indoor", - "chart": true - } + "chart": { + "readings": [ + "humidity" + ], + "period": "7d", + "chart": true } }, "covers": [ @@ -991,12 +663,7 @@ "ask": "AQ all week", "note": "the AQ all week button", "expect": { - "fast": { - "tool": "air_quality", - "args": { - "chart": true - } - } + "chart": null }, "covers": [ "c:air-panels", @@ -1008,13 +675,8 @@ "ask": "weather now", "note": "every reading the station has, in the report's layout", "expect": { - "fast": { - "tool": "weather_now", - "args": { - "groups": "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - } - }, - "weather_now": true + "weather_now": true, + "chart": null }, "covers": [ "q:report", @@ -1026,9 +688,7 @@ "ask": "pollen", "note": "pollen and thunderstorm asthma are fetched without the model", "expect": { - "fast": { - "tool": "pollen_asthma" - } + "chart": null }, "covers": [ "q:pollen" @@ -1039,10 +699,7 @@ "ask": "is the pollen bad today?", "note": "a plain pollen question is answered in code", "expect": { - "fast": { - "tool": "pollen_asthma" - }, - "lookup": "pollen" + "chart": null }, "covers": [ "q:pollen" @@ -1053,11 +710,7 @@ "ask": "what's the forecast for tomorrow?", "note": "the forecast tool, not the station's own pressure trend", "expect": { - "fast": null, - "needs_data": true, - "tools": [ - "weather_forecast" - ] + "chart": null }, "covers": [ "q:forecast" @@ -1068,7 +721,6 @@ "ask": "what do you think of weather in general, from a philosophical perspective?", "note": "an opinion, not a lookup: no tool is forced (the model still thinks a little)", "expect": { - "needs_data": false, "effort": "medium" }, "covers": [ @@ -1080,7 +732,7 @@ "ask": "only that it's cold", "note": "a chat reply, not a request: it replaced the bot's answer with the temperatures", "expect": { - "needs_data": false + "chart": null }, "covers": [ "q:chat" @@ -1091,11 +743,7 @@ "ask": "how cold is it", "note": "a plain current-temperature question", "expect": { - "needs_data": true, - "any_tools": [ - "weather_now", - "weather_history" - ] + "chart": null }, "covers": [ "q:current", @@ -1107,7 +755,7 @@ "ask": "ok now what?", "note": "'now' alone is not a weather question", "expect": { - "needs_data": false + "chart": null }, "covers": [ "q:chat" @@ -1118,7 +766,7 @@ "ask": "plot rain this week and will it rain tomorrow", "note": "a forecast question goes to the model", "expect": { - "chart_in_code": false + "chart": null } }, { @@ -1126,7 +774,7 @@ "ask": "graph humidity and say if it relates to rain", "note": "correlation goes to the model", "expect": { - "chart_in_code": false + "chart": null } }, { @@ -1134,13 +782,12 @@ "ask": "pressure graph 30d", "note": "a plain chart of a named reading", "expect": { - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "groups": "pressure", - "chart": true - } + "chart": { + "readings": [ + "pressure" + ], + "period": "30d", + "chart": true } } }, @@ -1149,35 +796,35 @@ "ask": "how hot is it", "note": "a plain reading question", "expect": { - "lookup": "reading" + "chart": null } }, { "id": "lookup-raining", "ask": "is it raining", "expect": { - "lookup": "reading" + "chart": null } }, { "id": "lookup-air", "ask": "how's the air", "expect": { - "lookup": "air" + "chart": null } }, { "id": "lookup-forecast", "ask": "forecast", "expect": { - "lookup": "forecast" + "chart": null } }, { "id": "lookup-about", "ask": "what can you do", "expect": { - "lookup": "about" + "chart": null } }, { @@ -1185,7 +832,7 @@ "ask": "is it too cold to run", "note": "judgement stays with the model", "expect": { - "lookup": "" + "chart": null } }, { @@ -1193,14 +840,14 @@ "ask": "hottest today", "note": "highs and lows of a short period", "expect": { - "lookup": "extremes" + "chart": null } }, { "id": "lookup-hottest-vs", "ask": "is today hotter than yesterday", "expect": { - "lookup": "" + "chart": null } }, { @@ -1208,21 +855,14 @@ "ask": "average temp yesterday", "note": "a plain average is answered in code", "expect": { - "lookup": "extremes", - "fast": { - "tool": "weather_history", - "args": { - "average": true, - "chart": false - } - } + "chart": null } }, { "id": "highest-humidity-yesterday", "ask": "highest humidity yesterday", "expect": { - "lookup": "extremes" + "chart": null } }, { @@ -1230,7 +870,7 @@ "ask": "will the pollen be bad tomorrow", "note": "looking ahead stays with the model", "expect": { - "lookup": "" + "chart": null } }, { @@ -1238,7 +878,7 @@ "ask": "average rain last week", "note": "a rain total has no average: the model explains", "expect": { - "lookup": "" + "chart": null } }, { @@ -1246,13 +886,7 @@ "ask": "how many times was UV 9 or more in the past two years?", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "count_only": true - } - } + "chart": null } }, { @@ -1260,14 +894,7 @@ "ask": "days over UVI 10 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "chart": null } }, { @@ -1275,16 +902,7 @@ "ask": "rain total per month this year", "note": "a total per month is counted in code and drawn as bars", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "sum", - "of": "rain", - "group_by": "month", - "count_only": true - } - } + "chart": null } }, { @@ -1292,16 +910,7 @@ "ask": "hottest day each year", "note": "the highest daily maximum per year is counted in code and drawn as bars", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "max", - "of": "temp_max", - "group_by": "year", - "count_only": true - } - } + "chart": null } }, { @@ -1309,14 +918,7 @@ "ask": "days PM2.5 over 25 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "chart": null } }, { @@ -1324,14 +926,7 @@ "ask": "count days over PM2.5 of 90 per year", "note": "counted in code: one reading against one limit", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "count_only": true, - "group_by": "year" - } - } + "chart": null } }, { @@ -1339,31 +934,14 @@ "ask": "days over UVI 10 by year", "note": "the model once answered with one overall count and no chart; now counted in code, per year, whole record", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "group_by": "year", - "count_only": true, - "where": { - "has": [ - { - "field": "uv_max", - "op": ">=", - "value": 10 - } - ] - } - } - } + "chart": null } }, { "id": "days-two-readings-go-to-the-model", "ask": "days over 35 and also rained", "expect": { - "lookup": "", - "fast": null + "chart": null } }, { @@ -1371,56 +949,28 @@ "ask": "rain by month for 2 years", "note": "the model answered with monthly text under a chart of daily bars: now monthly bars, one per line", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "sum", - "of": "rain", - "group_by": "month", - "start_date": { - "regex": "^2024-(09|10)-" - } - } - } + "chart": null } }, { "id": "avg-temp-per-year", "ask": "average temperature per year", "expect": { - "lookup": "days", - "fast": { - "tool": "weather_days", - "args": { - "stat": "avg", - "of": "temp_avg", - "group_by": "year" - } - } + "chart": null } }, { "id": "highest-pm25-by-month", "ask": "highest PM2.5 by month", "expect": { - "lookup": "days", - "fast": { - "tool": "air_days", - "args": { - "stat": "max", - "of": "pm2_5_max", - "group_by": "month" - } - } + "chart": null } }, { "id": "two-readings-by-month-go-to-the-model", "ask": "pm2.5 and co2 by month", "expect": { - "lookup": "", - "fast": null + "chart": null } }, { @@ -1428,15 +978,13 @@ "ask": "weather chart 90d", "note": "a chart naming no reading is every reading, a panel each", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "chart": { + "readings": [ + "weather" + ], + "period": "90d", + "chart": true + } }, "covers": [ "c:line", @@ -1448,15 +996,13 @@ "ask": "chart all 90d", "note": "a chart naming no reading is every reading, a panel each", "expect": { - "chart_fields": [ - "temperature", - "humidity", - "solar", - "pressure", - "rain", - "dew_point", - "wind" - ] + "chart": { + "readings": [ + "all" + ], + "period": "90d", + "chart": true + } }, "covers": [ "c:line", @@ -1468,19 +1014,7 @@ "ask": "graph combine uvi and solar radiation on two axis", "note": "two readings with different scales on one panel: fast path, drawn in code with the second on a right-hand axis", "expect": { - "chart_fields": [ - "uv", - "solar" - ], - "two_axes": true, - "chart_in_code": true, - "fast": { - "tool": "weather_history", - "args": { - "chart": true, - "groups": "solar_and_uvi" - } - } + "chart": null }, "covers": [ "c:two-axes" @@ -1491,8 +1025,7 @@ "ask": "plot airgradient humidity over ecowitt outdoor humidity", "note": "the air sensor's own humidity is offered to the model only when the AirGradient is named with it; the chart is the model's (plot_chart)", "expect": { - "air_extra": true, - "fast": null + "chart": null }, "covers": [] }, @@ -1501,27 +1034,7 @@ "ask": "What was the humidity each hour for the last 5 hours", "note": "the bot said its tool only gave extremes: the readings tool gives a value per hour", "expect": { - "fast": null, - "hints": [ - "\"5 hours\" = last 5 hours" - ], - "tools": [ - "readings" - ], - "not_tools": [ - "weather_history" - ], - "args": { - "readings": { - "metric": { - "regex": "humidity$" - }, - "interval": "1hour", - "start": { - "regex": "^2026-09-29 (08|09)" - } - } - } + "chart": null }, "covers": [ "q:interval", @@ -1533,21 +1046,7 @@ "ask": "temperature every 30 minutes today", "note": "took the fast path to a highs-and-lows summary of today", "expect": { - "fast": null, - "tools": [ - "readings" - ], - "args": { - "readings": { - "metric": { - "regex": "temperature$" - }, - "interval": "30min", - "start": { - "regex": "^2026-09-29 00:00" - } - } - } + "chart": null }, "covers": [ "q:interval", @@ -1559,15 +1058,12 @@ "ask": "plot pressure since Sunday", "note": "only the chart is asked for: the model says so (chart_answers_it) and the bot sends the chart with its caption written in code, with no second model call. A weekday keeps it off the fast path, so the model decides", "expect": { - "fast": null, - "chart_in_code": false, - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "chart_answers_it": true - } + "chart": { + "readings": [ + "pressure" + ], + "period": "since Sunday", + "chart": true } }, "covers": [ @@ -1580,21 +1076,7 @@ "ask": "plot pressure since Sunday, is a storm coming?", "note": "the chart and something else to answer: the model writes the reply, so chart_answers_it stays unset", "expect": { - "fast": null, - "chart_in_code": false, - "tools": [ - "weather_history" - ], - "args": { - "weather_history": { - "chart_answers_it": { - "any_of": [ - null, - false - ] - } - } - } + "chart": null }, "covers": [ "q:chart-only", diff --git a/tests/old_tools.py b/tests/old_tools.py new file mode 100644 index 00000000..294f277c --- /dev/null +++ b/tests/old_tools.py @@ -0,0 +1,257 @@ +"""The bot's twelve old tools' handlers, as they answered before the model got the service's tools (docs/mcp-service.md 6, step 3), kept +for the tests only: they drive the engines the service wraps the way the old tools did (HistoryQuery, AirGradient.history, find_days, +link, the readings), and they are the oracle the service's words were ported against (with tests/report_words.py). The corrections +from the person's words are gone with step 3. Deleted with the bot (step 6).""" + +import asyncio +import logging +import time as clock +from collections.abc import Callable +from dataclasses import replace +from datetime import datetime, time + +from lib.airgradient.days import find_air_days +from lib.airgradient.metrics import EXTRA +from lib.captions import wants_chart +from lib.ecowitt.api import GROUPS +from lib.ecowitt.days import find_days +from lib.ecowitt.glance import glance +from lib.ecowitt.link import link +from lib.ecowitt.query import HistoryQuery, chart_field, stack_names +from lib.forecast.source import SOURCE +from lib.history import (AIR_SENSOR, ALIASES, DAY_VALUE_IS, INTERVALS, MAX_ROWS, RAIN, VALUE_IS, air_metrics, finest_fit, + interval_starts, read_days, read_intervals, row_count, station_fields, station_metrics) +from lib.pollen.source import OFF_SEASON +from lib.series import READING_GROUPS, WEATHER, find +from lib.timeutil import local_date, local_epoch, now_local, parse_local, when +from lib.tools import Turn, json_result + +log = logging.getLogger(__name__) + +LINK_CHART_HINT = ("Your reply is sent as a message just before a chart with the reading as a line and rain as bars behind it, so keep " + "it short: the period, then the finding in one or two lines (how much of the rain fell while the reading " + "was falling, and the correlation), citing the numbers. Don't mention or describe the chart.") +DEFAULT_GROUPS = "outdoor,indoor" +NOW_GROUPS = ",".join(READING_GROUPS) + + +def parse_groups(value, default: str = DEFAULT_GROUPS) -> list[str]: + """'outdoor, indoor' or ['outdoor', 'indoor'] -> ['outdoor', 'indoor'] (a reading named instead of its group becomes its group).""" + parts = value if isinstance(value, list) else str(value or default).split(",") + named = (p.split(".")[0].strip().lower() for p in parts if p.strip()) + groups = (g if g in GROUPS else (r.group if (r := find(g)) else None) for g in named) + return list(dict.fromkeys(g for g in groups if g)) or default.split(",") + + +# ---------- the weather station's ---------- +async def weather_now(eco, args: dict, turn=None) -> str: + """weather_now: the live reading of these groups, each value with its unit, and the emoji of a notable one.""" + data = await eco._live_data(parse_groups(args.get("groups"))) + out, newest, emoji = {}, 0, {} + for grp, fields in data.items(): + for name, obj in (fields.items() if isinstance(fields, dict) else ()): + if isinstance(obj, dict) and "value" in obj: + out.setdefault(grp, {})[name] = f"{obj['value']} {obj.get('unit', '')}".strip() + try: + if tag := glance(grp, name, float(obj["value"])): + emoji[f"{grp}.{name}"] = tag + except (TypeError, ValueError): + pass + try: + newest = max(newest, int(obj.get("time") or 0)) + except (TypeError, ValueError): + pass + return json_result({"time": when(newest, eco.tz) if newest else None, **out, **({"emoji": emoji} if emoji else {})}) + + +async def weather_history(eco, args: dict, turn: Turn | None = None) -> str: + """weather_history: HistoryQuery over the groups asked for (and those its chart needs).""" + turn = turn or Turn() + groups = parse_groups(args.get("groups")) + groups += [g for n in stack_names(args, turn) if (g := WEATHER[n].group) not in groups] + if (r := find(chart_field(args, turn) or "")) and r.group not in groups: + groups.append(r.group) + return await HistoryQuery(eco.fetcher(groups, urgent=not turn.ahead), args, turn).run() + + +async def weather_days(eco, args: dict, turn=None) -> str: + """weather_days: find_days over the day rows.""" + return json_result(await find_days(eco.storage, eco.mac, eco.tz, args, now_local(eco.tz), turn)) + + +async def weather_link(eco, args: dict, turn: Turn | None = None) -> str: + """weather_link: link() over the 30-minute readings, its chart when asked (or the period is 3 days or more).""" + turn = turn or Turn() + out, spec, first, last = await asyncio.to_thread(link, eco.storage.read_now, eco.mac, eco.tz, args, now_local(eco.tz)) + if spec and wants_chart(args, turn, datetime.combine(first, time()), datetime.combine(last, time())): + turn.charts.append(spec) + out["chart"] = LINK_CHART_HINT + return json_result(out) + + +# ---------- the air sensor's ---------- +async def air_current(air, extras=()) -> dict: + """The latest reading as air_quality gave it.""" + return (await air.latest(extras)).reading + + +async def air_quality(air, args: dict, turn: Turn | None = None) -> str: + """air_quality: the reading now, or a period's summary (and chart).""" + turn = turn or Turn() + try: + chart = wants_chart(args, turn) + if args.get("start_date") or args.get("end_date") or chart: + return json_result(await air.history(args.get("start_date"), args.get("end_date"), chart=chart, metrics=args.get("metrics"), + turn=turn)) + return json_result(await air_current(air, [m for m in args.get("metrics") or [] if m in EXTRA])) + except Exception as e: + log.warning("AirGradient request failed: %s", e) + return f"Error: couldn't read the air-quality sensor ({e})" + + +async def air_days(store, tz, args: dict, turn=None) -> str: + """air_days: find_air_days over the air sensor's day rows (its AirReadings).""" + return json_result(await find_air_days(store, tz, args, now_local(tz), turn)) + + +# ---------- the forecast's and the pollen's ---------- +async def forecast(fc, args: dict, turn=None) -> str: + """weather_forecast: the next days' lines.""" + if fc.days is None and not args.get("cached"): + try: + await fc.warm(True) + except Exception as e: + log.warning("Forecast not readable: %s", e) + try: + count = max(1, min(7, int(args.get("days") or 7))) + except (TypeError, ValueError): + count = 7 + lines = fc.lines(count) + if not lines: + return json_result({"error": "No forecast is available right now."}) + stamped = {"time": when(int(fc.fetched_at), fc.tz)} if fc.fetched_at else {} + return json_result({"lines": lines, "place": fc.place, "source": SOURCE, **stamped}) + + +async def pollen(p, args: dict, turn=None) -> str: + """pollen_asthma: the pollen page's lines.""" + if not p.in_season(): + return json_result({"error": OFF_SEASON}) + if p.page is None and not args.get("cached"): + try: + await p.warm(True) + except Exception as e: + log.warning("Pollen not readable: %s", e) + lines = p.lines() + if not lines: + return json_result({"error": "No pollen levels are available right now."}) + cur = p.current() + out = {"lines": lines, "place": p.place, "source": "melbournepollen.com.au (grass pollen from pollen-trap data; asthma risk from the " + "Victorian Department of Health and BOM, 1 Oct - 31 Dec)"} + if cur["fetched_at"]: + out["time"] = when(int(cur["fetched_at"]), p.tz) + if cur["asthma"] and cur["asthma"]["updated"]: + out["asthma_updated"] = cur["asthma"]["updated"] + if not cur["asthma"]: + out["asthma_note"] = "The page had no thunderstorm asthma level for this district when it was last read." + return json_result(out) + + +def as_drawn(tool: str, args: dict, turn: Turn) -> tuple[dict, Turn]: + """(args, turn) as the old tool read them to draw its chart (what the bot captioned a chart that answered the question from): the + readings charted, air quality's metrics (else PM2.5), an average if asked for.""" + if tool == "air_quality": + return {**args, "metrics": args.get("metrics") or turn.air_named or ["pm2_5"]}, turn + return args, replace(turn, chart_field=chart_field(args, turn), chart_fields=stack_names(args, turn), + average_asked=turn.average_asked or bool(args.get("average"))) + + +# ---------- readings ---------- +class History: + """The old `readings` tool over the weather station's and the air sensor's stored readings (either may be missing).""" + + def __init__(self, eco=None, air=None, sent: dict[str, dict[str, str]] | None = None, now: Callable[[], float] = clock.time): + self.eco, self.air, self.now = eco, air, now + self.storage = eco.storage if eco else air.store.storage + self.tz = eco.tz if eco else air.tz + station = station_metrics(sent) if eco else [] + self.metrics = {m.name: m for m in [*station, *(air_metrics(extra=True) if air else [])]} + + @classmethod + async def open(cls, eco=None, air=None) -> "History": + return cls(eco, air, await station_fields(eco) if eco else None) + + def find(self, name: str): + name = name.strip().lower() + if name in self.metrics: + return self.metrics[name] + prefix, _, bare = name.rpartition(".") + if prefix == AIR_SENSOR and (m := self.metrics.get(f"{AIR_SENSOR}.{AIR_SENSOR}_{bare}")): + return m + reading = WEATHER.get(bare) or next((r for r in WEATHER.values() if r.field == bare), None) + m = (reading and self.metrics.get(f"{reading.group}.{RAIN if reading.field == 'daily' else reading.field}") + or self.metrics.get(f"{AIR_SENSOR}.{bare}") or self.metrics.get(f"outdoor.{bare}")) + return None if m and prefix in ("indoor", AIR_SENSOR) and m.sensor != prefix else m + + def _sensor(self, m) -> int | None: + if m.air: + s = self.air.store.sensor if self.air else None + else: + s = self.storage.sensors.find(self.eco.mac, m.sensor) if self.eco else None + return s.id if s else None + + def _time(self, value, default: int) -> int: + if value in (None, ""): + return default + text = str(value).strip() + try: + local = parse_local(text, self.tz) + except ValueError: + local = parse_local(text.replace("T", " ")[:19], self.tz) + return local_epoch(local, self.tz) + + async def handle(self, args: dict, turn: Turn | None = None) -> str: + m = self.find(str(args.get("metric") or "")) + if m is None: + return json_result({"error": f"unknown metric {args.get('metric')!r}", "metrics": list(self.metrics)}) + interval = str(args.get("interval") or "").strip().lower() + interval = ALIASES.get(interval, interval) + if interval not in INTERVALS: + return json_result({"error": f"unknown interval {args.get('interval')!r}", "intervals": list(INTERVALS)}) + now = int(self.now()) + try: + start, end = self._time(args.get("start"), None), min(self._time(args.get("end"), now), now) + except (TypeError, ValueError): + return json_result({"error": "start and end are 'YYYY-MM-DD HH:MM', local time"}) + if start is None or start >= end: + return json_result({"error": "start must be before end (and before now)"}) + by_day = interval == "1day" and m.how != "last" + n = row_count(start, end, interval, self.tz) + too_many = n > (MAX_ROWS if by_day else MAX_ROWS + 1) + marks = [] if too_many or by_day else interval_starts(start, end, INTERVALS[interval], self.tz) + if too_many or len(marks) > MAX_ROWS: + fits = finest_fit(start, end, self.tz) + return json_result({"error": "too many rows", "rows": max(n, len(marks)), "max_rows": MAX_ROWS, "fits": fits, + "note": f"Ask again with interval {fits}." if fits else + "Too long even for days: split the period, or use weather_history or weather_days."}) + out = {"metric": m.name, "unit": m.unit, "interval": interval, "value_is": (DAY_VALUE_IS if by_day else VALUE_IS)[m.how]} + sensor = self._sensor(m) + if sensor is None: + return json_result({**out, "rows": [], "note": "Nothing is stored for this sensor yet."}) + if by_day: + first, last = local_date(start, self.tz), local_date(end, self.tz) + out |= await self.storage.read(read_days, m, sensor, first, last, self.tz) + partial = last == local_date(now, self.tz) + else: + out |= await self.storage.read(read_intervals, m, sensor, interval, marks, end, now, self.tz) + partial = marks[-1] + INTERVALS[interval] > now + if partial: + out["note_last"] = "The last row is still filling: it runs up to now." + if not any(row[1] is not None for row in out["rows"]): + out["note"] = (f"No readings at this interval for this period: ask again with interval {out['fits']}." if out.get("fits") else + "No readings are stored for this period at this interval: say so; never fill the gap.") + return json_result(out) + + +__all__ = ["History", "NOW_GROUPS", "air_current", "as_drawn", "air_days", "air_quality", "forecast", "parse_groups", "pollen", "weather_days", + "weather_history", "weather_link", "weather_now"] diff --git a/tests/service_switch.json b/tests/service_switch.json index d17634eb..875f990d 100644 --- a/tests/service_switch.json +++ b/tests/service_switch.json @@ -833,8 +833,25 @@ { "panels": [ { - "label": "PM2.5", + "label": "PM1, PM2.5, PM10", "series": [ + [ + "PM1", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 3.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 3.0 + ] + ] + ], [ "PM2.5", "line", @@ -851,66 +868,140 @@ 8.0 ] ] + ], + [ + "PM10", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 8.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 8.0 + ] + ] ] ], "unit": "µg/m³" + }, + { + "label": "CO₂", + "series": [ + [ + "CO₂", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 450.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 450.0 + ] + ] + ] + ], + "unit": "ppm" + }, + { + "label": "VOC index", + "series": [ + [ + "VOC index", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 100.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 100.0 + ] + ] + ] + ], + "unit": "" + }, + { + "label": "NOx index", + "series": [ + [ + "NOx index", + "line", + 159, + [ + [ + "2026-11-04T00:00:00+11:00", + 1.0 + ] + ], + [ + [ + "2026-11-10T14:00:00+11:00", + 1.0 + ] + ] + ] + ], + "unit": "" } ], "period": [ "2026-11-04", "2026-11-10" ], - "sha": "8f50228347701651", + "sha": "5fd0fec2c3317446", "source": "AirGradient sensor", "subtitle": "Wed 4 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", - "title": "PM2.5" + "title": "Air quality" } ], "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Wed 4 Nov 10:00am) · 🟡 poor · average 10.4", + "history": "Wed 4 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Wed 4 Nov 10:00am) · 🟡 poor · average 10.4\n• PM10: peak 8.0 µg/m³ (Wed 4 Nov 12:00am) · 🟢 good · average 8.0\n• PM1: peak 3.0 µg/m³ (Wed 4 Nov 12:00am) · 🟢 good · average 3.0\n• CO₂: peak 450.0 ppm (Wed 4 Nov 12:00am) · 🟢 good · average 450.0\n• VOC index: peak 100.0 relative index (100 = this sensor's recent average) (Wed 4 Nov 12:00am) · 🟢 good · average 100.0\n• NOx index: peak 1.0 relative index (1 = baseline) (Wed 4 Nov 12:00am) · 🟢 good · average 1.0", "sent": [ [ "photo", - "PM2.5, since Wed 4 Nov 2026", + "Air quality\nWed 4 – Tue 10 Nov 2026", [ [ [ "1D", - "pd:1" + "pd:1d" ], [ "7D", - "pd:7" + "pd:7d" ], [ "1M", - "pd:30" + "pd:1m" ], [ "3M", - "pd:90" + "pd:3m" ], [ "1Y", - "pd:365" + "pd:1y" ] ] ] ] ] }, - "air quality now": { - "charts": [], - "gauges": [], - "history": "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", - "sent": [ - [ - "text", - "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", - null - ] - ] - }, "alert gusts": { "charts": [ { @@ -1130,63 +1221,126 @@ "newest": 1794279900, "title": "UV index, since Mon 9 Nov 2026" }, - "average pressure yesterday": { + "dashboard": { "charts": [], - "gauges": [], - "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Pressure: average 1012.1 °C (low 1009.1, high 1015.9)", + "gauges": [ + "2035f1d261cdf408" + ], + "history": "Weather station dashboard, Tue 10 Nov 2026 2:05pm", "sent": [ [ - "text", - "Mon 9 Nov – Mon 9 Nov 2026\n• Pressure: average 1012.1 °C (low 1009.1, high 1015.9)", - null + "photo", + "Weather station dashboard, Tue 10 Nov 2026 2:05pm", + [ + [ + [ + "🔄", + "rp:dashboard" + ] + ] + ] ] ] }, - "average temperature 7d": { + "humidity 7d": { "charts": [ { "panels": [ { - "label": "Temperature", + "label": "Humidity", "series": [ [ "Outdoor", "band", - 6, + 317, [ [ - "2026-11-04T12:00:00+11:00", - 14.103125, - 8.1, - 20.1 + "2026-11-04T00:00:00+11:00", + 80.0, + 80.0, + 82.0 ] ], [ [ - "2026-11-09T12:00:00+11:00", - 14.103125, - 8.1, - 20.1 + "2026-11-10T14:00:00+11:00", + 55.0, + 55.0, + 55.0 ] ] - ], + ] + ], + "unit": "%" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "790cb258a590921b", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Humidity" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", + "sent": [ + [ + "photo", + "Humidity, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "indoor temperature chart 7d": { + "charts": [ + { + "panels": [ + { + "label": "Temperature", + "series": [ [ "Indoor", "band", - 6, + 317, [ [ - "2026-11-04T12:00:00+11:00", - 14.103125, - 8.1, - 20.1 + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 ] ], [ [ - "2026-11-09T12:00:00+11:00", - 14.103125, - 8.1, + "2026-11-10T14:00:00+11:00", + 20.0, + 20.0, 20.1 ] ] @@ -1199,14 +1353,14 @@ "2026-11-04", "2026-11-10" ], - "sha": "0762f22a458eb82c", + "sha": "7fc9b62280a4051f", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", "title": "Temperature" } ], "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): average 14.1 °C (low 8.1, high 20.4)\nTemperature (indoor): average 14.1 °C (low 8.1, high 20.4)", + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature: low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", "sent": [ [ "photo", @@ -1238,50 +1392,50 @@ ] ] }, - "average temperature per month this year": { + "pm2.5 chart 3d": { "charts": [ { "panels": [ { - "label": "Temperature", + "label": "PM2.5", "series": [ [ - "Temperature", - "bars", - 11, + "PM2.5", + "line", + 63, [ [ - "2026-01-01T00:00:00+11:00", - 14.3 + "2026-11-08T00:00:00+11:00", + 6.0 ] ], [ [ - "2026-11-01T00:00:00+11:00", - 14.3 + "2026-11-10T14:00:00+11:00", + 8.0 ] ] ] ], - "unit": "°C" + "unit": "µg/m³" } ], "period": [ - "2026-01-01", - "2026-11-09" + "2026-11-08", + "2026-11-10" ], - "sha": "ea97546802ab0054", - "source": "Ecowitt weather station", - "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 days counted · per month", - "title": "Average temperature" + "sha": "30a44e700edbe879", + "source": "AirGradient sensor", + "subtitle": "Sun 8 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", + "title": "PM2.5" } ], "gauges": [], - "history": "Average temperature: 14.3 °C over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + "history": "Sun 8 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Sun 8 Nov 10:00am) · 🟡 poor · average 10.3", "sent": [ [ "photo", - "Average temperature, Thu 1 Jan – Mon 9 Nov 2026\n\nAverage temperature: 14.3 °C over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", + "PM2.5, since Sun 8 Nov 2026", [ [ [ @@ -1309,1246 +1463,27 @@ ] ] }, - "chart weather": { + "press 1M under Rain chart 1d": { "charts": [ { "panels": [ { - "label": "Temperature", + "label": "Rain", "series": [ [ - "Indoor", - "line", - 289, + "Rain", + "bars", + 119, [ [ - "2026-11-09T14:05:00+11:00", - 19.95 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 20.0 - ] - ] - ], - [ - "Outdoor", - "line", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 19.95 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 20.0 - ] - ] - ] - ], - "unit": "°C" - }, - { - "label": "Humidity", - "series": [ - [ - "Humidity", - "line", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 55.0 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 55.0 - ] - ] - ], - [ - "Rain", - "bars", - 25, - [ - [ - "2026-11-09T14:00:00+11:00", - 0.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 0.0 - ] - ] - ] - ], - "unit": "%" - }, - { - "label": "Solar radiation", - "series": [ - [ - "Solar radiation", - "line", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 848.0 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 848.0 - ] - ] - ] - ], - "unit": "W/m²" - }, - { - "label": "Pressure", - "series": [ - [ - "Pressure", - "line", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 1012.1 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 1007.8 - ] - ] - ] - ], - "unit": "hPa" - }, - { - "label": "Dew point", - "series": [ - [ - "Dew point", - "line", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 19.95 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 20.0 - ] - ] - ] - ], - "unit": "°C" - }, - { - "label": "Wind", - "series": [ - [ - "Wind", - "band", - 289, - [ - [ - "2026-11-09T14:05:00+11:00", - 10.0, - 10.0, - 26.0 - ] - ], - [ - [ - "2026-11-10T14:05:00+11:00", - 10.0, - 10.0, - 29.0 - ] - ] - ] - ], - "unit": "km/h" - } - ], - "period": [ - "2026-11-09", - "2026-11-10" - ], - "sha": "a5e62602517de50d", - "source": "Ecowitt weather station", - "subtitle": "Mon 9 – Tue 10 Nov 2026 · rain per hour · range shaded", - "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" - } - ], - "gauges": [], - "history": "Mon 9 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nTemperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\nHumidity: low 55 %, Mon 9 Nov at 2:05pm · high 85 %, Tue 10 Nov at 2:40am\nSolar radiation: low 0.0 °C, Mon 9 Nov at 7pm · high 880.0 °C, Tue 10 Nov at 12:40pm\nPressure: low 1007.0 °C, Tue 10 Nov at 7:45am · high 1012.1 °C, Mon 9 Nov at 2:05pm\n☔ Rain per hour: least 0 mm (Mon 9 Nov 2pm) · most 0 mm (Mon 9 Nov 2pm) · 0.0 mm in all\nDew point: low 8.2 °C, Tue 10 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n🌬️ Wind: strongest gust 36.0 °C, Mon 9 Nov at 3pm\n🧭 Mostly from the N (100%), steady", - "sent": [ - [ - "photo", - "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 9 – Tue 10 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "co2": { - "charts": [], - "gauges": [], - "history": "• CO₂: 450 ppm 🟢 good", - "sent": [ - [ - "text", - "• CO₂: 450 ppm 🟢 good", - null - ] - ] - }, - "dashboard": { - "charts": [], - "gauges": [ - "2035f1d261cdf408" - ], - "history": "Weather station dashboard, Tue 10 Nov 2026 2:05pm", - "sent": [ - [ - "photo", - "Weather station dashboard, Tue 10 Nov 2026 2:05pm", - [ - [ - [ - "🔄", - "rp:dashboard" - ] - ] - ] - ] - ] - }, - "days with uv over 9 per month this year": { - "charts": [ - { - "panels": [ - { - "label": "Days", - "series": [ - [ - "Days", - "bars", - 11, - [ - [ - "2026-01-01T00:00:00+11:00", - 31.0 - ] - ], - [ - [ - "2026-11-01T00:00:00+11:00", - 9.0 - ] - ] - ] - ], - "unit": "" - } - ], - "period": [ - "2026-01-01", - "2026-11-09" - ], - "sha": "16cbdac19c3806a9", - "source": "Ecowitt weather station", - "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 of 313 days · per month", - "title": "Days with UV index ≥ 9" - } - ], - "gauges": [], - "history": "313 of 313 days with UV index ≥ 9 (Thu 1 Jan – Mon 9 Nov 2026). Older days use averages, so a count near the limit may fall slightly short.", - "sent": [ - [ - "photo", - "Days with UV index ≥ 9, Thu 1 Jan – Mon 9 Nov 2026\n\n313 of 313 days with UV index ≥ 9 (Thu 1 Jan – Mon 9 Nov 2026). Older days use averages, so a count near the limit may fall slightly short.", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "forecast": { - "charts": [], - "gauges": [], - "history": "Forecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm\n• Friday: ⛅ Partly cloudy. 14–19°C, 75% chance of at least 1 mm\n• Saturday: 🌦️ Showers. 15–20°C, 0% chance of at least 1 mm\n• Sunday: ☁️ Overcast. 16–21°C, 75% chance of at least 1 mm\n• Monday: 🌧️ Light rain. 17–22°C, 0% chance of at least 1 mm", - "sent": [ - [ - "text", - "Forecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm\n• Friday: ⛅ Partly cloudy. 14–19°C, 75% chance of at least 1 mm\n• Saturday: 🌦️ Showers. 15–20°C, 0% chance of at least 1 mm\n• Sunday: ☁️ Overcast. 16–21°C, 75% chance of at least 1 mm\n• Monday: 🌧️ Light rain. 17–22°C, 0% chance of at least 1 mm", - null - ] - ] - }, - "high and low today": { - "charts": [], - "gauges": [], - "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", - "sent": [ - [ - "text", - "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", - null - ] - ] - }, - "highest humidity this week": { - "charts": [ - { - "panels": [ - { - "label": "Humidity", - "series": [ - [ - "Outdoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 80.0, - 80.0, - 82.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 55.0, - 55.0, - 55.0 - ] - ] - ] - ], - "unit": "%" - } - ], - "period": [ - "2026-11-04", - "2026-11-10" - ], - "sha": "790cb258a590921b", - "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Humidity" - } - ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", - "sent": [ - [ - "photo", - "Humidity, since Wed 4 Nov 2026\n\nWed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "highest temperature yesterday": { - "charts": [], - "gauges": [], - "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n• Temperature (indoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", - "sent": [ - [ - "text", - "Mon 9 Nov – Mon 9 Nov 2026\n• Temperature (outdoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm\n• Temperature (indoor): low 8.1 °C, Mon 9 Nov at 2:25am · high 20.1 °C, Mon 9 Nov at 2:30pm", - null - ] - ] - }, - "how hot is it": { - "charts": [], - "gauges": [], - "history": "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C\n• Indoor: 🧥 18.3 °C, feels like 18.3 °C", - "sent": [ - [ - "text", - "• Outdoor: 🧥 12.3 °C, feels like 12.3 °C\n• Indoor: 🧥 18.3 °C, feels like 18.3 °C", - null - ] - ] - }, - "how many days was humidity under 60 last month": { - "charts": [], - "gauges": [], - "history": "31 of 31 days with lowest humidity < 60 % (Thu 1 Oct – Sat 31 Oct 2026).", - "sent": [ - [ - "text", - "31 of 31 days with lowest humidity < 60 % (Thu 1 Oct – Sat 31 Oct 2026).", - null - ] - ] - }, - "how many days was pm2.5 over 15 this week": { - "charts": [], - "gauges": [], - "history": "0 of 0 days with PM2.5 > 15 µg/m³ (Wed 4 Nov – Mon 9 Nov 2026).", - "sent": [ - [ - "text", - "0 of 0 days with PM2.5 > 15 µg/m³ (Wed 4 Nov – Mon 9 Nov 2026).", - null - ] - ] - }, - "how many days was the temperature over 18 this year": { - "charts": [], - "gauges": [], - "history": "313 of 313 days with temperature > 18 °C (Thu 1 Jan – Mon 9 Nov 2026).", - "sent": [ - [ - "text", - "313 of 313 days with temperature > 18 °C (Thu 1 Jan – Mon 9 Nov 2026).", - null - ] - ] - }, - "how's the air": { - "charts": [], - "gauges": [], - "history": "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", - "sent": [ - [ - "text", - "• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good", - null - ] - ] - }, - "humidity": { - "charts": [], - "gauges": [], - "history": "• Outdoor: 💦 94 %", - "sent": [ - [ - "text", - "• Outdoor: 💦 94 %", - null - ] - ] - }, - "humidity 7d": { - "charts": [ - { - "panels": [ - { - "label": "Humidity", - "series": [ - [ - "Outdoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 80.0, - 80.0, - 82.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 55.0, - 55.0, - 55.0 - ] - ] - ] - ], - "unit": "%" - } - ], - "period": [ - "2026-11-04", - "2026-11-10" - ], - "sha": "790cb258a590921b", - "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Humidity" - } - ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am", - "sent": [ - [ - "photo", - "Humidity, since Wed 4 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "indoor temperature": { - "charts": [], - "gauges": [], - "history": "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", - "sent": [ - [ - "text", - "• Indoor: 🧥 18.3 °C, feels like 18.3 °C", - null - ] - ] - }, - "indoor temperature chart 7d": { - "charts": [ - { - "panels": [ - { - "label": "Temperature", - "series": [ - [ - "Indoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, - 20.1 - ] - ] - ] - ], - "unit": "°C" - } - ], - "period": [ - "2026-11-04", - "2026-11-10" - ], - "sha": "7fc9b62280a4051f", - "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Temperature" - } - ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature: low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", - "sent": [ - [ - "photo", - "Temperature, since Wed 4 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "is it raining": { - "charts": [], - "gauges": [], - "history": "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)", - "sent": [ - [ - "text", - "• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)", - null - ] - ] - }, - "lowest humidity yesterday": { - "charts": [], - "gauges": [], - "history": "Mon 9 Nov – Mon 9 Nov 2026\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am", - "sent": [ - [ - "text", - "Mon 9 Nov – Mon 9 Nov 2026\n• Humidity: low 55 %, Mon 9 Nov at 1:50pm · high 85 %, Mon 9 Nov at 2:15am", - null - ] - ] - }, - "lowest temperature on record": { - "charts": [ - { - "panels": [ - { - "label": "Temperature", - "series": [ - [ - "Outdoor", - "band", - 1458, - [ - [ - "2022-11-13T11:00:00+11:00", - 17.4, - 8.5, - 20.4 - ] - ], - [ - [ - "2026-11-09T10:00:00+11:00", - 14.103125, - 8.1, - 20.1 - ] - ] - ], - [ - "Indoor", - "band", - 1458, - [ - [ - "2022-11-13T11:00:00+11:00", - 17.4, - 8.5, - 20.4 - ] - ], - [ - [ - "2026-11-09T10:00:00+11:00", - 14.103125, - 8.1, - 20.1 - ] - ] - ] - ], - "unit": "°C" - } - ], - "period": [ - "2022-11-13", - "2026-11-10" - ], - "sha": "8757c1081d06b47b", - "source": "Ecowitt weather station", - "subtitle": "Sun 13 Nov 2022 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", - "title": "Temperature" - } - ], - "gauges": [], - "history": "Sun 13 Nov 2022 – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov\nTemperature (indoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov", - "sent": [ - [ - "photo", - "Temperature, since Sun 13 Nov 2022\n\nSun 13 Nov 2022 – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov\nTemperature (indoor): low 8.1 °C, sometime between 11am Mon 14 Nov and 11am Tue 15 Nov · high 20.4 °C, sometime between 11am Sun 13 Nov and 11am Mon 14 Nov", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "plot uv and solar on two axes 7d": { - "charts": [ - { - "panels": [ - { - "label": "UV index and Solar radiation", - "series": [ - [ - "UV index", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 0.0, - 0.0, - 0.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 10.7, - 10.4, - 10.7 - ] - ] - ], - [ - "Solar radiation (W/m²)", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 0.0, - 0.0, - 0.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 856.0, - 832.0, - 856.0 - ] - ] - ] - ], - "unit": "" - } - ], - "period": [ - "2026-11-04", - "2026-11-10" - ], - "sha": "399d97ba4eef630b", - "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · range shaded", - "title": "UV index and Solar radiation" - } - ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nUV index: low 0 °C, Wed 4 Nov at 12am · high 11 °C, Wed 4 Nov at 12:40pm\nSolar radiation: low 0.0 °C, Wed 4 Nov at 12am · high 880.0 °C, Wed 4 Nov at 12:40pm", - "sent": [ - [ - "photo", - "UV index and Solar radiation, since Wed 4 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "pm2.5 chart 3d": { - "charts": [ - { - "panels": [ - { - "label": "PM2.5", - "series": [ - [ - "PM2.5", - "line", - 63, - [ - [ - "2026-11-08T00:00:00+11:00", - 6.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 8.0 - ] - ] - ] - ], - "unit": "µg/m³" - } - ], - "period": [ - "2026-11-08", - "2026-11-10" - ], - "sha": "30a44e700edbe879", - "source": "AirGradient sensor", - "subtitle": "Sun 8 Nov 2026 - Tue 10 Nov 2026 · AirGradient readings", - "title": "PM2.5" - } - ], - "gauges": [], - "history": "Sun 8 Nov – Tue 10 Nov 2026\n• PM2.5: peak 16.0 µg/m³ (Sun 8 Nov 10:00am) · 🟡 poor · average 10.3", - "sent": [ - [ - "photo", - "PM2.5, since Sun 8 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "pollen": { - "charts": [], - "gauges": [], - "history": "Pollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low", - "sent": [ - [ - "text", - "Pollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low", - null - ] - ] - }, - "press 1M under Rain chart 1d": { - "charts": [ - { - "panels": [ - { - "label": "Rain", - "series": [ - [ - "Rain", - "bars", - 119, - [ - [ - "2026-10-12T00:00:00+11:00", - 0.0 - ] - ], - [ - [ - "2026-11-10T12:00:00+11:00", - 0.0 - ] - ] - ] - ], - "unit": "mm" - } - ], - "period": [ - "2026-10-12", - "2026-11-10" - ], - "sha": "faca6ea0ee20ddf7", - "source": "Ecowitt weather station", - "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours", - "title": "Rain" - } - ], - "edits": [ - [ - "photo", - "Rain, since Mon 12 Oct 2026" - ] - ] - }, - "press 1Y under rain by month this year": { - "charts": [ - { - "panels": [ - { - "label": "Rain", - "series": [ - [ - "Rain", - "bars", - 13, - [ - [ - "2025-11-01T00:00:00+11:00", - 11.5 - ] - ], - [ - [ - "2026-11-01T00:00:00+11:00", - 5.5 - ] - ] - ] - ], - "unit": "mm" - } - ], - "period": [ - "2025-11-11", - "2026-11-09" - ], - "sha": "5712fdfd9c1551e6", - "source": "Ecowitt weather station", - "subtitle": "Tue 11 Nov 2025 – Mon 9 Nov 2026 · 364 days counted · per month", - "title": "Total rain" - } - ], - "edits": [ - [ - "photo", - "Total rain, Tue 11 Nov 2025 – Mon 9 Nov 2026\n\nTotal rain: 248 mm over 364 days (Tue 11 Nov 2025 – Mon 9 Nov 2026)." - ] - ] - }, - "press 7D under Temperature chart 1d": { - "charts": [ - { - "panels": [ - { - "label": "Temperature", - "series": [ - [ - "Outdoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, - 20.1 - ] - ] - ], - [ - "Indoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, - 20.1 - ] - ] - ] - ], - "unit": "°C" - } - ], - "period": [ - "2026-11-04", - "2026-11-10" - ], - "sha": "4b8bc87c49be3cd2", - "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Temperature" - } - ], - "edits": [ - [ - "photo", - "Temperature, since Wed 4 Nov 2026" - ] - ] - }, - "pressure": { - "charts": [], - "gauges": [], - "history": "• Pressure: 🗜️ 1025.0 hPa", - "sent": [ - [ - "text", - "• Pressure: 🗜️ 1025.0 hPa", - null - ] - ] - }, - "pressure chart this month": { - "charts": [ - { - "panels": [ - { - "label": "Pressure", - "series": [ - [ - "Pressure", - "band", - 461, - [ - [ - "2026-11-01T00:00:00+11:00", - 1022.3, - 1022.3, - 1022.4 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 1007.9, - 1007.8, - 1007.9 - ] - ] - ] - ], - "unit": "hPa" - } - ], - "period": [ - "2026-11-01", - "2026-11-10" - ], - "sha": "6e7a1c488d0f5081", - "source": "Ecowitt weather station", - "subtitle": "Sun 1 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Pressure" - } - ], - "gauges": [], - "history": "Sun 1 Nov – Tue 10 Nov 2026\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.5 °C, Sat 7 Nov at 1:45am", - "sent": [ - [ - "photo", - "Pressure, since Sun 1 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "rain by month this year": { - "charts": [ - { - "panels": [ - { - "label": "Rain", - "series": [ - [ - "Rain", - "bars", - 11, - [ - [ - "2026-01-01T00:00:00+11:00", - 17.0 + "2026-10-12T00:00:00+11:00", + 0.0 ] ], [ [ - "2026-11-01T00:00:00+11:00", - 5.5 + "2026-11-10T12:00:00+11:00", + 0.0 ] ] ] @@ -2557,153 +1492,72 @@ } ], "period": [ - "2026-01-01", - "2026-11-09" + "2026-10-12", + "2026-11-10" ], - "sha": "78e9e3e016d11dc1", + "sha": "faca6ea0ee20ddf7", "source": "Ecowitt weather station", - "subtitle": "Thu 1 Jan 2026 – Mon 9 Nov 2026 · 313 days counted · per month", - "title": "Total rain" + "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours", + "title": "Rain" } ], - "gauges": [], - "history": "Total rain: 214.5 mm over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", - "sent": [ + "edits": [ [ "photo", - "Total rain, Thu 1 Jan – Mon 9 Nov 2026\n\nTotal rain: 214.5 mm over 313 days (Thu 1 Jan – Mon 9 Nov 2026).", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] + "Rain, since Mon 12 Oct 2026" ] ] }, - "rain chart 7d": { + "press 1Y under humidity 7d": { "charts": [ { "panels": [ { - "label": "Rain", + "label": "Humidity", "series": [ [ - "Rain", - "bars", - 27, + "Outdoor", + "band", + 364, [ [ - "2026-11-04T00:00:00+11:00", - 0.0 + "2025-11-11T11:00:00+11:00", + 62.0, + 54.0, + 84.0 ] ], [ [ - "2026-11-10T12:00:00+11:00", - 0.0 + "2026-11-09T10:00:00+11:00", + 69.76041666666667, + 55.0, + 85.0 ] ] ] ], - "unit": "mm" + "unit": "%" } ], "period": [ - "2026-11-04", + "2025-11-11", "2026-11-10" ], - "sha": "f692fad2845dea7b", + "sha": "31534a4a0650edb3", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours", - "title": "Rain" + "subtitle": "Tue 11 Nov 2025 – Tue 10 Nov 2026 · daily averages, range shaded · records marked", + "title": "Humidity" } ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", - "sent": [ - [ - "photo", - "Rain, since Wed 4 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] - ] - ] - }, - "status": { - "charts": [], - "gauges": [ - "aa7350dd52231dc7" - ], - "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", - "sent": [ + "edits": [ [ "photo", - "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", - [ - [ - [ - "🔄", - "rp:refresh" - ] - ] - ] - ] - ] - }, - "strongest gust today": { - "charts": [], - "gauges": [], - "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Wind: low 0.0 °C, Tue 10 Nov at 12am · high 10.0 °C, Tue 10 Nov at 6am\n• Wind gust: low 29.0 °C, Tue 10 Nov at 12am · high 29.0 °C, Tue 10 Nov at 12am", - "sent": [ - [ - "text", - "Tue 10 Nov – Tue 10 Nov 2026\n• Wind: low 0.0 °C, Tue 10 Nov at 12am · high 10.0 °C, Tue 10 Nov at 6am\n• Wind gust: low 29.0 °C, Tue 10 Nov at 12am · high 29.0 °C, Tue 10 Nov at 12am", - null + "Humidity, since Tue 11 Nov 2025" ] ] }, - "temperature and rain chart 7d": { + "press 7D under Temperature chart 1d": { "charts": [ { "panels": [ @@ -2711,7 +1565,7 @@ "label": "Temperature", "series": [ [ - "Indoor", + "Outdoor", "band", 317, [ @@ -2732,7 +1586,7 @@ ] ], [ - "Outdoor", + "Indoor", "band", 317, [ @@ -2751,23 +1605,6 @@ 20.1 ] ] - ], - [ - "Rain", - "bars", - 27, - [ - [ - "2026-11-04T00:00:00+11:00", - 0.0 - ] - ], - [ - [ - "2026-11-10T12:00:00+11:00", - 0.0 - ] - ] ] ], "unit": "°C" @@ -2777,114 +1614,67 @@ "2026-11-04", "2026-11-10" ], - "sha": "c71494e2da2cb207", + "sha": "4b8bc87c49be3cd2", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours · range shaded", - "title": "Temperature, Rain" + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" } ], - "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", - "sent": [ + "edits": [ [ "photo", - "Temperature, Rain, since Wed 4 Nov 2026", - [ - [ - [ - "1D", - "pd:1" - ], - [ - "7D", - "pd:7" - ], - [ - "1M", - "pd:30" - ], - [ - "3M", - "pd:90" - ], - [ - "1Y", - "pd:365" - ] - ] - ] + "Temperature, since Wed 4 Nov 2026" ] ] }, - "temperature chart 7d": { + "pressure chart this month": { "charts": [ { "panels": [ { - "label": "Temperature", + "label": "Pressure", "series": [ [ - "Outdoor", - "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, - 20.1 - ] - ] - ], - [ - "Indoor", + "Pressure", "band", - 317, - [ - [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 + 461, + [ + [ + "2026-11-01T00:00:00+11:00", + 1022.3, + 1022.3, + 1022.4 ] ], [ [ "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, - 20.1 + 1007.9, + 1007.8, + 1007.9 ] ] ] ], - "unit": "°C" + "unit": "hPa" } ], "period": [ - "2026-11-04", + "2026-11-01", "2026-11-10" ], - "sha": "4b8bc87c49be3cd2", + "sha": "6e7a1c488d0f5081", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Temperature" + "subtitle": "Sun 1 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Pressure" } ], "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "history": "Sun 1 Nov – Tue 10 Nov 2026\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.5 °C, Sat 7 Nov at 1:45am", "sent": [ [ "photo", - "Temperature, since Wed 4 Nov 2026", + "Pressure, since Sun 1 Nov 2026", [ [ [ @@ -2912,75 +1702,50 @@ ] ] }, - "temperature chart last month": { + "rain chart 7d": { "charts": [ { "panels": [ { - "label": "Temperature", + "label": "Rain", "series": [ [ - "Outdoor", - "band", - 372, - [ - [ - "2026-10-01T01:00:00+10:00", - 9.225, - 8.4, - 9.9 - ] - ], - [ - [ - "2026-11-01T00:00:00+11:00", - 10.899999999999999, - 10.1, - 11.2 - ] - ] - ], - [ - "Indoor", - "band", - 372, + "Rain", + "bars", + 27, [ [ - "2026-10-01T01:00:00+10:00", - 9.225, - 8.4, - 9.9 + "2026-11-04T00:00:00+11:00", + 0.0 ] ], [ [ - "2026-11-01T00:00:00+11:00", - 10.899999999999999, - 10.1, - 11.2 + "2026-11-10T12:00:00+11:00", + 0.0 ] ] ] ], - "unit": "°C" + "unit": "mm" } ], "period": [ - "2026-10-01", - "2026-10-31" + "2026-11-04", + "2026-11-10" ], - "sha": "bb098dff493e9c96", + "sha": "f692fad2845dea7b", "source": "Ecowitt weather station", - "subtitle": "Thu 1 – Sat 31 Oct 2026 · 2-hour averages, range shaded · records marked", - "title": "Temperature" + "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours", + "title": "Rain" } ], "gauges": [], - "history": "Thu 1 Oct – Sat 31 Oct 2026\nTemperature (outdoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm", + "history": "Wed 4 Nov – Tue 10 Nov 2026\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", "sent": [ [ "photo", - "Temperature, Thu 1 – Sat 31 Oct 2026", + "Rain, since Wed 4 Nov 2026", [ [ [ @@ -3008,7 +1773,28 @@ ] ] }, - "temps this week": { + "status": { + "charts": [], + "gauges": [ + "aa7350dd52231dc7" + ], + "history": "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + "sent": [ + [ + "photo", + "Weather station (2:05pm)\n• Outdoor: 🧥 12.3 °C, 💦 94 %\n• Indoor: 🧥 18.3 °C\n• Pressure: 🗜️ 1025.0 hPa\n• Rain today: ☔ 6.3 mm (month total 49.8 mm); 🌧️ raining (1.8 mm/h)\n• Sun: solar radiation 412.5 W/m² (medium), 😎 UV index 6\n• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h\n\nAir quality (2:05pm)\n• PM2.5: 12.0 µg/m³ 🟢 good (AQI 44)\n• PM10: 8.0 µg/m³ 🟢 good\n• PM1: 3.0 µg/m³ 🟢 good\n• CO₂: 450 ppm 🟢 good\n• VOC index: 100 🟢 good\n• NOx index: 1.0 🟢 good\n\nPollen & asthma (Melbourne, 2:05pm)\n• Grass pollen forecast: 🟠 Moderate\n• Thunderstorm asthma forecast: 🟢 Low\n\nForecast (Melbourne, 2:05pm)\n• Today: 🌧️ Rain. 11–16°C, 0% chance of at least 1 mm\n• Wednesday: ☀️ Clear. 12–17°C, 75% chance of at least 1 mm\n• Thursday: ⛈️ Thunderstorm. 13–18°C, 0% chance of at least 1 mm", + [ + [ + [ + "🔄", + "rp:refresh" + ] + ] + ] + ] + ] + }, + "temperature and rain chart 7d": { "charts": [ { "panels": [ @@ -3016,7 +1802,7 @@ "label": "Temperature", "series": [ [ - "Outdoor", + "Indoor", "band", 317, [ @@ -3037,7 +1823,7 @@ ] ], [ - "Indoor", + "Outdoor", "band", 317, [ @@ -3056,6 +1842,23 @@ 20.1 ] ] + ], + [ + "Rain", + "bars", + 27, + [ + [ + "2026-11-04T00:00:00+11:00", + 0.0 + ] + ], + [ + [ + "2026-11-10T12:00:00+11:00", + 0.0 + ] + ] ] ], "unit": "°C" @@ -3065,18 +1868,18 @@ "2026-11-04", "2026-11-10" ], - "sha": "4b8bc87c49be3cd2", + "sha": "c71494e2da2cb207", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", - "title": "Temperature" + "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours · range shaded", + "title": "Temperature, Rain" } ], "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all", "sent": [ [ "photo", - "Temperature, since Wed 4 Nov 2026", + "Temperature, Rain, since Wed 4 Nov 2026", [ [ [ @@ -3104,251 +1907,171 @@ ] ] }, - "temps today": { - "charts": [], - "gauges": [], - "history": "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", - "sent": [ - [ - "text", - "Tue 10 Nov – Tue 10 Nov 2026\n• Temperature (outdoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm\n• Temperature (indoor): low 8.2 °C, Tue 10 Nov at 2:25am · high 20.0 °C, Tue 10 Nov at 1:55pm", - null - ] - ] - }, - "uv": { - "charts": [], - "gauges": [], - "history": "• UV index: 😎 6", - "sent": [ - [ - "text", - "• UV index: 😎 6", - null - ] - ] - }, - "weather 30d": { + "temperature chart 7d": { "charts": [ { "panels": [ { "label": "Temperature", "series": [ - [ - "Indoor", - "band", - 356, - [ - [ - "2026-10-12T00:00:00+11:00", - 9.75, - 9.1, - 10.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 19.733333333333334, - 19.4, - 20.1 - ] - ] - ], [ "Outdoor", "band", - 356, - [ - [ - "2026-10-12T00:00:00+11:00", - 9.75, - 9.1, - 10.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 19.733333333333334, - 19.4, - 20.1 - ] - ] - ] - ], - "unit": "°C" - }, - { - "label": "Humidity", - "series": [ - [ - "Humidity", - "band", - 356, - [ - [ - "2026-10-12T00:00:00+11:00", - 80.5, - 80.0, - 82.0 - ] - ], - [ - [ - "2026-11-10T14:00:00+11:00", - 55.666666666666664, - 55.0, - 56.0 - ] - ] - ], - [ - "Rain", - "bars", - 119, - [ - [ - "2026-10-12T00:00:00+11:00", - 0.0 - ] - ], - [ - [ - "2026-11-10T12:00:00+11:00", - 0.0 - ] - ] - ] - ], - "unit": "%" - }, - { - "label": "Solar radiation", - "series": [ - [ - "Solar radiation", - "band", - 356, + 317, [ [ - "2026-10-12T00:00:00+11:00", - 0.0, - 0.0, - 0.0 + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 ] ], [ [ "2026-11-10T14:00:00+11:00", - 869.3333333333334, - 832.0, - 880.0 + 20.0, + 20.0, + 20.1 ] ] - ] - ], - "unit": "W/m²" - }, - { - "label": "Pressure", - "series": [ + ], [ - "Pressure", + "Indoor", "band", - 356, + 317, [ [ - "2026-10-12T00:00:00+11:00", - 1018.4, - 1018.3, - 1018.4 + "2026-11-04T00:00:00+11:00", + 9.8, + 9.4, + 9.8 ] ], [ [ "2026-11-10T14:00:00+11:00", - 1007.8666666666667, - 1007.8, - 1007.9 + 20.0, + 20.0, + 20.1 ] ] ] ], - "unit": "hPa" - }, + "unit": "°C" + } + ], + "period": [ + "2026-11-04", + "2026-11-10" + ], + "sha": "4b8bc87c49be3cd2", + "source": "Ecowitt weather station", + "subtitle": "Wed 4 – Tue 10 Nov 2026 · 30-minute readings, range shaded · records marked", + "title": "Temperature" + } + ], + "gauges": [], + "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm", + "sent": [ + [ + "photo", + "Temperature, since Wed 4 Nov 2026", + [ + [ + [ + "1D", + "pd:1" + ], + [ + "7D", + "pd:7" + ], + [ + "1M", + "pd:30" + ], + [ + "3M", + "pd:90" + ], + [ + "1Y", + "pd:365" + ] + ] + ] + ] + ] + }, + "temperature chart last month": { + "charts": [ + { + "panels": [ { - "label": "Dew point", + "label": "Temperature", "series": [ [ - "Dew point", + "Outdoor", "band", - 356, + 372, [ [ - "2026-10-12T00:00:00+11:00", - 9.75, - 9.1, - 10.0 + "2026-10-01T01:00:00+10:00", + 9.225, + 8.4, + 9.9 ] ], [ [ - "2026-11-10T14:00:00+11:00", - 19.733333333333334, - 19.4, - 20.1 + "2026-11-01T00:00:00+11:00", + 10.899999999999999, + 10.1, + 11.2 ] ] - ] - ], - "unit": "°C" - }, - { - "label": "Wind", - "series": [ + ], [ - "Wind", + "Indoor", "band", - 356, + 372, [ [ - "2026-10-12T00:00:00+11:00", - 0.0, - 0.0, - 35.0 + "2026-10-01T01:00:00+10:00", + 9.225, + 8.4, + 9.9 ] ], [ [ - "2026-11-10T14:00:00+11:00", - 10.0, - 10.0, - 29.0 + "2026-11-01T00:00:00+11:00", + 10.899999999999999, + 10.1, + 11.2 ] ] ] ], - "unit": "km/h" + "unit": "°C" } ], "period": [ - "2026-10-12", - "2026-11-10" + "2026-10-01", + "2026-10-31" ], - "sha": "b93089b10c508d01", + "sha": "bb098dff493e9c96", "source": "Ecowitt weather station", - "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours · range shaded", - "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" + "subtitle": "Thu 1 – Sat 31 Oct 2026 · 2-hour averages, range shaded · records marked", + "title": "Temperature" } ], "gauges": [], - "history": "Mon 12 Oct – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nHumidity: low 54 %, Mon 12 Oct at 2:20pm · high 85 %, Thu 15 Oct at 2:15am\nSolar radiation: low 0.0 °C, Mon 12 Oct at 12am · high 880.0 °C, Mon 12 Oct at 12:40pm\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.7 °C, Sat 17 Oct at 1:25pm\n☔ Rain per 6 hours: least 0 mm (Mon 12 Oct 12am) · most 5 mm (Thu 15 Oct 12pm) · 21.5 mm in all\nDew point: low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\n🌬️ Wind: strongest gust 48.0 °C, Tue 13 Oct at 3pm\n🧭 Mostly from the N (100%), steady", + "history": "Thu 1 Oct – Sat 31 Oct 2026\nTemperature (outdoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Mon 5 Oct at 2:25am · high 20.4 °C, Sat 3 Oct at 2:30pm", "sent": [ [ "photo", - "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 12 Oct – Tue 10 Nov 2026", + "Temperature, Thu 1 – Sat 31 Oct 2026", [ [ [ @@ -3376,7 +2099,7 @@ ] ] }, - "weather all week": { + "weather 30d": { "charts": [ { "panels": [ @@ -3386,20 +2109,20 @@ [ "Indoor", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 ] ], [ [ "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, + 19.733333333333334, + 19.4, 20.1 ] ] @@ -3407,20 +2130,20 @@ [ "Outdoor", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 ] ], [ [ "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, + 19.733333333333334, + 19.4, 20.1 ] ] @@ -3434,11 +2157,11 @@ [ "Humidity", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", - 80.0, + "2026-10-12T00:00:00+11:00", + 80.5, 80.0, 82.0 ] @@ -3446,19 +2169,19 @@ [ [ "2026-11-10T14:00:00+11:00", + 55.666666666666664, 55.0, - 55.0, - 55.0 + 56.0 ] ] ], [ "Rain", "bars", - 27, + 119, [ [ - "2026-11-04T00:00:00+11:00", + "2026-10-12T00:00:00+11:00", 0.0 ] ], @@ -3478,10 +2201,10 @@ [ "Solar radiation", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", + "2026-10-12T00:00:00+11:00", 0.0, 0.0, 0.0 @@ -3490,9 +2213,9 @@ [ [ "2026-11-10T14:00:00+11:00", - 856.0, + 869.3333333333334, 832.0, - 856.0 + 880.0 ] ] ] @@ -3505,19 +2228,19 @@ [ "Pressure", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", - 1007.4, - 1007.4, - 1007.5 + "2026-10-12T00:00:00+11:00", + 1018.4, + 1018.3, + 1018.4 ] ], [ [ "2026-11-10T14:00:00+11:00", - 1007.9, + 1007.8666666666667, 1007.8, 1007.9 ] @@ -3532,20 +2255,20 @@ [ "Dew point", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", - 9.8, - 9.4, - 9.8 + "2026-10-12T00:00:00+11:00", + 9.75, + 9.1, + 10.0 ] ], [ [ "2026-11-10T14:00:00+11:00", - 20.0, - 20.0, + 19.733333333333334, + 19.4, 20.1 ] ] @@ -3559,13 +2282,13 @@ [ "Wind", "band", - 317, + 356, [ [ - "2026-11-04T00:00:00+11:00", + "2026-10-12T00:00:00+11:00", 0.0, 0.0, - 32.0 + 35.0 ] ], [ @@ -3582,21 +2305,21 @@ } ], "period": [ - "2026-11-04", + "2026-10-12", "2026-11-10" ], - "sha": "89defd08995bd00d", + "sha": "b93089b10c508d01", "source": "Ecowitt weather station", - "subtitle": "Wed 4 – Tue 10 Nov 2026 · rain per 6 hours · range shaded", + "subtitle": "Mon 12 Oct – Tue 10 Nov 2026 · rain per 6 hours · range shaded", "title": "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind" } ], "gauges": [], - "history": "Wed 4 Nov – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nTemperature (indoor): low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\nHumidity: low 54 %, Thu 5 Nov at 2:45pm · high 85 %, Wed 4 Nov at 2:15am\nSolar radiation: low 0.0 °C, Wed 4 Nov at 12am · high 880.0 °C, Wed 4 Nov at 12:40pm\nPressure: low 1006.9 °C, Wed 4 Nov at 6:50am · high 1023.5 °C, Sat 7 Nov at 1:45am\n☔ Rain per 6 hours: least 0 mm (Wed 4 Nov 12am) · most 5 mm (Sun 8 Nov 12pm) · 5.5 mm in all\nDew point: low 8.1 °C, Wed 4 Nov at 2:25am · high 20.4 °C, Sat 7 Nov at 2:30pm\n🌬️ Wind: strongest gust 48.0 °C, Fri 6 Nov at 3pm\n🧭 Mostly from the N (100%), steady", + "history": "Mon 12 Oct – Tue 10 Nov 2026\nTemperature (outdoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nTemperature (indoor): low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\nHumidity: low 54 %, Mon 12 Oct at 2:20pm · high 85 %, Thu 15 Oct at 2:15am\nSolar radiation: low 0.0 °C, Mon 12 Oct at 12am · high 880.0 °C, Mon 12 Oct at 12:40pm\nPressure: low 1006.3 °C, Tue 3 Nov at 7:30pm · high 1023.7 °C, Sat 17 Oct at 1:25pm\n☔ Rain per 6 hours: least 0 mm (Mon 12 Oct 12am) · most 5 mm (Thu 15 Oct 12pm) · 21.5 mm in all\nDew point: low 8.1 °C, Thu 15 Oct at 2:25am · high 20.4 °C, Tue 13 Oct at 2:30pm\n🌬️ Wind: strongest gust 48.0 °C, Tue 13 Oct at 3pm\n🧭 Mostly from the N (100%), steady", "sent": [ [ "photo", - "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nWed 4 – Tue 10 Nov 2026", + "Temperature, Humidity, Solar radiation, Pressure, Rain, Dew point, Wind\nMon 12 Oct – Tue 10 Nov 2026", [ [ [ @@ -3636,30 +2359,6 @@ ] ] }, - "what can you do": { - "charts": [], - "gauges": [], - "history": "• Temperature, humidity (indoor, outdoor)\n• Dew point, vapour pressure deficit, pressure, wind speed\n• Rain, solar radiation, UV index\n• PM1, PM2.5, PM10, CO₂, VOC, NOx\n• Pollen and thunderstorm asthma risk (October to December)\n• Forecast\n• History charts", - "sent": [ - [ - "text", - "• Temperature, humidity (indoor, outdoor)\n• Dew point, vapour pressure deficit, pressure, wind speed\n• Rain, solar radiation, UV index\n• PM1, PM2.5, PM10, CO₂, VOC, NOx\n• Pollen and thunderstorm asthma risk (October to December)\n• Forecast\n• History charts", - null - ] - ] - }, - "wind": { - "charts": [], - "gauges": [], - "history": "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", - "sent": [ - [ - "text", - "• Wind: 14.0 km/h from 131°, gust 🌬️ 31.0 km/h", - null - ] - ] - }, "wind direction plot 3m": { "charts": [ { diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index d3da77ef..ef8ffe92 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -8,6 +8,7 @@ from telegram import CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CallbackQueryHandler +from lib.service.summary import OVER_TIME from lib import periods, report_menu, templates from lib.admins import Admins from lib.alerts import menu @@ -339,6 +340,12 @@ async def test_usage_is_the_help_and_alerts_button(tmp_path, kind): # ---------- every button comes in through one place ---------- +def period_keyboard(current=None): + """The period buttons under a chart of summary's (its drawn_by's periods), `current` shaded.""" + from lib.service.summary import OVER_TIME + return periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}, current) + + def alert_keyboard(opened="alerts"): return menu.keyboard(set(), menu.available_kinds({"Ecowitt"}), opened, set()) @@ -346,7 +353,7 @@ def alert_keyboard(opened="alerts"): async def test_a_stranger_is_refused_on_every_family_of_buttons_and_an_admin_is_let_through(tmp_path): bot, state, tg = make(tmp_path, irrigation=Remote()) state.add_chat(ADMIN, "Rob") - cases = [("al:off:rain:alerts", alert_keyboard()), (f"{periods.PREFIX}7", periods.keyboard(1)), + cases = [("al:off:rain:alerts", alert_keyboard()), (f"{periods.PREFIX}7d", period_keyboard("1d")), ("ir:open:water", irrigation_menu.keyboard(True, True))] for data, markup in cases: press = Press(data, markup, user=STRANGER) @@ -389,8 +396,8 @@ def every_keyboard(bot): for opened in (None, *irrigation_menu.SECTIONS, "bogus"): for paused in (True, False): yield irrigation_menu.keyboard(battery, pause, opened, paused) - for current in (None, *periods.PERIODS): - yield periods.keyboard(current) + for current in (None, *(p["period"] for p in OVER_TIME)): + yield period_keyboard(current) yield report_menu.keyboard() yield report_menu.dashboard_keyboard() @@ -496,7 +503,7 @@ async def test_random_data_never_gets_past_the_entry_point(tmp_path): rng = random.Random(7) spy = Spy() bot, state, tg = make(tmp_path, irrigation=spy) - boards = [alert_keyboard("sub"), irrigation_menu.keyboard(True, True), periods.keyboard(1), report_menu.keyboard()] + boards = [alert_keyboard("sub"), irrigation_menu.keyboard(True, True), period_keyboard("1d"), report_menu.keyboard()] known = {b.callback_data for board_ in boards for row in board_.inline_keyboard for b in row} pieces = ["ir", "al", "pd", "on", "off", "water", "delay", "sw", "batt", "pause", "refresh", "open", "close", "all", "sub", "unsub", "rain", "uv", "24h", "cancel", "5", "30", "99999", "-1", "", " ", "\n", "é", "💧", "*", "%s", "{}", "\\", ";", "$(x)", "None"] diff --git a/tests/test_agent.py b/tests/test_agent.py index 502f42a3..de2f668e 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -34,17 +34,6 @@ async def handler(args, turn=None): return Tools([Tool("weather_now", "d", {"type": "object", "properties": {}}, handler)]), seen -async def test_fast_path_calls_the_model_only_at_the_end(): - t, seen = tools() - client = FakeLLM(["Sunny."]) - agent = llm.Agent(client, "m", t) - msgs = [{"role": "user", "content": "highs today"}] - reply = await agent.run(msgs, "sys", "none", first_call=("weather_now", {"groups": "outdoor"})) - assert reply == "Sunny." and len(client.requests) == 1 and seen == [{"groups": "outdoor"}] - assert client.requests[0]["tool_choice"] == "auto" and client.requests[0]["extra_body"] == {"reasoning": {"effort": "none"}} - assert [m["role"] for m in msgs] == ["user", "assistant", "tool", "assistant"] - - async def test_weather_questions_must_fetch_first_and_reasoning_is_passed_through(): t, seen = tools() client = FakeLLM([[("weather_now", {})], "Rain unlikely."]) @@ -130,79 +119,6 @@ async def reply_text(text, **kw): assert (1, 7) not in bot.chats and bot.chats[(2, None)].history -def test_the_prompt_defines_a_rainy_day_and_how_to_phrase_the_count(): - from datetime import datetime - from lib import prompt - from lib.ecowitt import days - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - assert "rain >= 1" in text and "any rain" in text and "It rained on 507 of 1,454 days" in text - assert "1 mm or more" in days.DESCRIPTION - - -def test_the_prompt_asks_for_a_footnote_about_hotter_trace_days(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - assert "trace_rain_days" in text and "footnote" in text - - -def test_the_day_tool_schema_agrees_with_the_prompt_about_a_rainy_day(): - from lib.ecowitt import days - where = days.PARAMETERS["properties"]["where"]["description"] - assert "rain >= 1" in where and "rain > 0" not in where - - -def test_the_day_tool_rules_are_short_separate_bullets(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt"}) - block = text[text.index("- For questions that rank, compare or count DAYS"):text.index("- To ask whether rain comes WITH")] - bullets = [line for line in block.splitlines() if line.startswith(" - ")] - assert len(bullets) == 9 and all(len(b) < 300 for b in bullets) - for needle in ("sort_by", "rain >= 1", "It rained on 507 of 1,454 days", "trace_rain_days", "note_daily", "on record", "public_holiday", "known day", "RECORD"): - assert sum(needle in b for b in bullets) == 1, needle # each rule lives in exactly one bullet - - -def test_the_system_prompt_carries_the_period_hints_only_when_there_are_some(): - from datetime import datetime - from lib import intent, prompt - now = datetime(2026, 9, 29, 14, 5) - with_hint = prompt.build(now, {"Ecowitt": "Ecowitt"}, intent.period_hints("average temp 3m", now)) - assert "THE PERSON'S WORDS NAME THESE PERIODS" in with_hint and '"3m" = last 3 months: 2026-07-01' in with_hint - assert "THE PERSON'S WORDS NAME" not in prompt.build(now, {"Ecowitt": "Ecowitt"}, intent.period_hints("hello", now)) - - -def test_the_prompt_says_what_the_bot_can_and_cannot_do_for_the_sources_it_has(): - from datetime import datetime - from lib import prompt - now = datetime(2026, 9, 29, 14, 5) - both = prompt.build(now, {"Ecowitt": "Ecowitt weather station", "AirGradient": "AirGradient outdoor sensor"}) - assert "WHAT THIS BOT CAN AND CAN'T DO" in both and "PM2.5 (µg/m³)" in both and "weather_link" in both - assert "Custom alerts" in both and "solar radiation and UV index" in both and "Not available: lightning" in both and "correct the call once" in both - weather_only = prompt.build(now, {"Ecowitt": "Ecowitt weather station"}) - assert "Weather station:" in weather_only and "Air quality (outdoor AirGradient)" not in weather_only - assert "Weather station:" not in prompt.build(now, {"AirGradient": "AirGradient outdoor sensor"}) - - -async def test_a_question_about_the_bot_itself_gets_no_tools_and_the_hint(): - from datetime import datetime - from lib import prompt - t, seen = tools() - client = FakeLLM(["I track temperature, humidity..."]) - reply = await llm.Agent(client, "m", t).run([{"role": "user", "content": "list our metrics"}], "sys", "none", - tool_choice="none") - assert reply.startswith("I track") and client.requests[0]["tool_choice"] == "none" and seen == [] - now = datetime(2026, 9, 29, 14, 5) - assert "ABOUT THE BOT ITSELF" in prompt.build(now, {"Ecowitt": "Ecowitt"}, [], True) and "ABOUT THE BOT ITSELF" not in prompt.build(now, {"Ecowitt": "Ecowitt"}) - - -def test_the_prompt_never_shows_a_temperature_emoji_to_copy_and_says_no_entry_means_no_emoji(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert '"outdoor.temperature": "' not in text and "a reading with no entry gets NO emoji" in text - - def chunk(content=None, calls=None, usage=None): delta = NS(content=content, tool_calls=calls) return NS(choices=[NS(delta=delta)] if (content is not None or calls) else [], usage=usage) @@ -244,77 +160,6 @@ async def test_streamed_answers_give_the_same_result_and_report_the_text_so_far( assert msgs[1]["tool_calls"][0]["function"] == {"name": "weather_now", "arguments": '{"groups": "outdoor"}'} -def test_a_rain_chart_caption_is_only_the_least_and_most_rain(): - from datetime import datetime - from lib import prompt - now = datetime(2026, 9, 29, 14, 5) - text = prompt.build(now, {"Ecowitt": "Ecowitt weather station"}, rain_caption=True) - assert "THIS IS A RAIN CHART" in text and "rain_outlook" not in text - assert "THIS IS A RAIN CHART" not in prompt.build(now, {"Ecowitt": "Ecowitt weather station"}) - - -def test_questions_about_the_bot_are_answered_as_simple_bullet_points(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}, about_bot=True) - assert "simple bullet points" in text and "no sub-bullets" in text and "7 at most" in text and "No dates" in text - - -def test_the_capabilities_mention_the_new_sources_only_when_they_are_on(): - from lib import prompt - base = prompt.capabilities(["Ecowitt"]) - assert "pollen and thunderstorm asthma" in base.split("Not available:")[1] and "forecasts (only a short read" in base - both = prompt.capabilities(["Ecowitt", "Pollen", "Forecast"]) - assert "tool pollen_asthma" in both and "tool weather_forecast" in both and "thunderstorm asthma risk reaching High" in both - assert "pollen" not in both.split("Not available:")[1] and "forecasts" not in both.split("Not available:")[1] - - -async def test_several_fast_calls_run_together_before_the_model(): - seen = [] - - async def handler(args, turn=None): - seen.append(args) - return json.dumps({"ok": True}) - t = Tools([Tool("weather_now", "d", {"type": "object", "properties": {}}, handler), - Tool("air_quality", "d", {"type": "object", "properties": {}}, handler)]) - client = FakeLLM(["The report."]) - msgs = [{"role": "user", "content": "report"}] - reply = await llm.Agent(client, "m", t).run(msgs, "sys", "none", first_call=[("weather_now", {"groups": "outdoor"}), ("air_quality", {})]) - assert reply == "The report." and len(client.requests) == 1 and seen == [{"groups": "outdoor"}, {}] - assert [m["role"] for m in msgs] == ["user", "assistant", "tool", "tool", "assistant"] - assert [tc["id"] for tc in msgs[1]["tool_calls"]] == ["fast_1", "fast_2"] and [m["tool_call_id"] for m in msgs[2:4]] == ["fast_1", "fast_2"] - - - - - -def test_the_capabilities_mention_forecast_revision_alerts_only_with_the_forecast_source(): - from lib import prompt - assert "revised" not in prompt.capabilities(["Ecowitt"]) - assert "a forecast it sent being revised" in prompt.capabilities(["Ecowitt", "Forecast"]) - - -def test_the_capabilities_list_only_the_alerts_the_sources_send_with_their_own_thresholds(): - from lib import prompt - from lib.alerts.weather import GUST_ALERT_KMH - station, air = prompt.capabilities(["Ecowitt"]), prompt.capabilities(["AirGradient"]) - assert f"wind gusts over {GUST_ALERT_KMH} km/h" in station and "mask alerts" not in station - assert "mask alerts" in air and "rain starting" not in air and "Alerts, sent" not in prompt.capabilities([]) - - -def test_the_capabilities_say_pollen_only_runs_october_to_december(): - from lib import prompt - assert "only run from October to December" in prompt.capabilities(["Ecowitt", "Pollen"]) - - -def test_the_prompt_leaves_the_heads_up_to_the_bot_and_points_at_the_count_tool(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert "the bot warns the chat by itself" in text and "\u26a0" not in text and "decline" not in text.lower() - assert "uv_max >= 9" in text and "count_only" in text - - async def test_the_chat_is_warned_once_before_the_model_is_sent_more_than_twice_a_500_point_querys_data(): from lib.llm import CHARS_PER_TOKEN, WARN_TOKENS from lib.tools import Turn @@ -341,13 +186,6 @@ async def tiny(args, turn=None): assert warned == [] -def test_the_prompt_says_to_use_the_whole_record_without_a_period_and_holidays_only_when_asked(): - from datetime import datetime - from lib import prompt - text = prompt.build(datetime(2026, 9, 29, 14, 5), {"Ecowitt": "Ecowitt weather station"}) - assert "use the whole record" in text and "only when the person's words say holidays or weekends" in text - - async def test_the_reasoning_effort_goes_to_openrouter_in_its_own_form(): t, _ = tools() client = FakeLLM([[("weather_now", {})], "Done."]) @@ -372,22 +210,6 @@ def test_older_answers_are_cut_to_their_first_lines_but_the_last_answer_and_ever assert len(llm.shorten_old(one_line)[0]["content"]) <= llm.OLD_ANSWER_CHARS + 2 -async def test_a_question_that_asks_for_the_air_sensors_own_readings_is_sent_the_tools_that_offer_them(): - from lib.tools import Turn - - async def handler(args, turn=None): - return json.dumps({"ok": True}) - base = {"type": "object", "properties": {"series": {"enum": ["humidity"]}}} - wider = {"type": "object", "properties": {"series": {"enum": ["humidity", "air_humidity"]}}} - t = Tools([Tool("plot_chart", "d", base, handler, asked=lambda: ("d+", wider)), Tool("weather_now", "d", {"type": "object", "properties": {}}, handler)]) - plain, asked = FakeLLM(["a"]), FakeLLM(["b"]) - await llm.Agent(plain, "m", t).run([{"role": "user", "content": "x"}], "sys", "none", turn=Turn()) - await llm.Agent(asked, "m", t).run([{"role": "user", "content": "x"}], "sys", "none", turn=Turn(air_extra=True)) - assert plain.requests[0]["tools"] == t.schemas and "air_humidity" not in json.dumps(plain.requests[0]["tools"]) - names = [s["function"]["name"] for s in asked.requests[0]["tools"]] - assert names == ["plot_chart", "weather_now"] and "air_humidity" in json.dumps(asked.requests[0]["tools"]) - - async def test_a_tool_that_fails_answers_the_model_with_the_error_and_only_a_bug_logs_its_traceback(caplog): import logging @@ -403,3 +225,19 @@ async def buggy(args, turn=None): assert await t.call("weather_history", "{}") == "Error calling tool: 'missing'" down, bug = caplog.records assert not down.exc_info and bug.exc_info # a failure is a line; a bug in the code keeps its traceback + + +def test_the_prompt_is_the_persona_then_the_servers_instructions_then_the_time(): + """docs/mcp-service.md 4: the bot adds only its persona (a friendly Telegram bot, plain text, bullets, the caption a photo allows) + to the server's instructions; nothing about the tools, the periods or the data.""" + from datetime import datetime + from zoneinfo import ZoneInfo + from lib import prompt + from lib.service.instructions import INSTRUCTIONS + now = datetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")) + text = prompt.build(now, INSTRUCTIONS) + assert text.startswith("You are a friendly weather bot on Telegram") and INSTRUCTIONS in text + assert text.rstrip().endswith("Now: Tuesday 10 November 2026, 14:05 (Australia/Melbourne time).") + assert "900 characters" in text and "•" in text and "Plain text only" in text + for gone in ("weather_history", "weather_now", "RIGHT NOW", "start_date", "chart_field", "TIME PERIODS", "Fahrenheit"): + assert gone not in text, gone diff --git a/tests/test_airgradient.py b/tests/test_airgradient.py index 5de684fe..b249004b 100644 --- a/tests/test_airgradient.py +++ b/tests/test_airgradient.py @@ -9,6 +9,7 @@ from lib.timeutil import local_date from lib.tools import Turn from tests.fakes import TZ, air_transport, config +from tests import old_tools async def make(tmp_path): @@ -37,7 +38,7 @@ async def test_current_reading_with_ratings(tmp_path): async def no_previous(ts, count): return [] # the fake history's PM2.5 depends on the hour, so the previous reading would too air._previous_rows = no_previous - reading = json.loads(await air.handle({})) + reading = json.loads(await old_tools.air_quality(air, {})) assert reading["pm2_5"]["value"] == 12.0 and reading["pm2_5"]["band"] == "moderate" assert set(reading) == {"sensor", "sensor_type", "time", *METRICS} and reading["pm2_5"]["rating"].endswith("poor") await air.close() @@ -49,7 +50,7 @@ async def test_a_rating_is_the_level_the_last_two_readings_both_reached(tmp_path async def previous(ts, count, before=before): return [{"pm2_5": before}] air._previous_rows = previous - reading = json.loads(await air.handle({})) + reading = json.loads(await old_tools.air_quality(air, {})) assert reading["pm2_5"]["value"] == 12.0 and reading["pm2_5"]["band"] == band assert ("rating_note" in reading["pm2_5"]) is noted await air.close() @@ -59,7 +60,7 @@ async def test_history_summary_and_chart(tmp_path): air, _ = await make(tmp_path) day = datetime.now(TZ).date() - timedelta(days=2) turn = Turn() - out = json.loads(await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59", "chart": True, + out = json.loads(await old_tools.air_quality(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59", "chart": True, "metrics": ["pm2_5", "co2"]}, turn)) assert out["pm2_5"]["high"] >= out["pm2_5"]["low"] and "high_aqi_us" in out["pm2_5"] (chart,) = turn.charts @@ -72,7 +73,7 @@ async def test_a_chart_the_model_names_no_reading_for_is_of_the_one_the_person_a day = datetime.now(TZ).date() - timedelta(days=5) for named, title in (([], "PM2.5"), (["co2"], "CO₂")): # "give me that timestamp", after "CO2 since Sunday": CO2, not PM2.5 turn = Turn(air_named=named) - await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day + timedelta(days=3)} 23:59:59"}, turn) # 3+ days: drawn anyway + await old_tools.air_quality(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day + timedelta(days=3)} 23:59:59"}, turn) # 3+ days: drawn anyway (chart,) = turn.charts assert chart.title == title await air.close() @@ -83,7 +84,7 @@ async def test_finished_days_are_fetched_once(tmp_path): await air.warm(True) n = len(calls) day = datetime.now(TZ).date() - timedelta(days=3) - await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}) + await old_tools.air_quality(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}) assert len(calls) == n # already warmed await air.close() @@ -97,7 +98,7 @@ async def test_warm_summary_and_wants(tmp_path): async def test_history_is_capped_at_14_days(tmp_path): air, _ = await make(tmp_path) - out = json.loads(await air.handle({"start_date": "2026-01-01 00:00:00", "chart": False, "end_date": "2026-03-01 00:00:00"})) + out = json.loads(await old_tools.air_quality(air, {"start_date": "2026-01-01 00:00:00", "chart": False, "end_date": "2026-03-01 00:00:00"})) assert "note_period" in out or out.get("error") is None await air.close() @@ -112,12 +113,12 @@ async def test_finished_days_survive_a_restart_and_need_no_requests(tmp_path): air, calls = await make(tmp_path) day = datetime.now(TZ).date() - timedelta(days=3) args = {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - first = json.loads(await air.handle(args)) + first = json.loads(await old_tools.air_quality(air, args)) assert calls.count("past") == 1 await air.close() dead = httpx.MockTransport(lambda r: httpx.Response(500)) # AirGradient is unreachable now again = AirGradient(config(tmp_path), transport=dead) - assert json.loads(await again.handle(args)) == first + assert json.loads(await old_tools.air_quality(again, args)) == first assert again.requests == 0 await again.close() @@ -132,7 +133,7 @@ async def test_backfill_walks_back_to_the_start_of_the_sensors_data(tmp_path): assert await air.backfill(pace=0, empty_stop=3) == (0, 0, total) # nothing left to fetch assert len(calls) == n # and a long question is now answered entirely from the cache - out = json.loads(await air.handle({"start_date": (datetime.now(TZ) - timedelta(days=9)).strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await old_tools.air_quality(air, {"start_date": (datetime.now(TZ) - timedelta(days=9)).strftime("%Y-%m-%d %H:%M:%S"), "end_date": (datetime.now(TZ) - timedelta(days=2)).strftime("%Y-%m-%d %H:%M:%S")})) assert out["readings"] > 100 and len(calls) == n and "note_missing" not in out await air.close() @@ -167,7 +168,7 @@ async def test_backfill_stops_after_repeated_failures(tmp_path): async def test_missing_days_are_fetched_inline_only_up_to_a_limit(tmp_path, monkeypatch): monkeypatch.setattr(source, "MAX_INLINE_DAYS", 3) air, calls = await make(tmp_path) - out = json.loads(await air.handle({"start_date": (datetime.now(TZ) - timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await old_tools.air_quality(air, {"start_date": (datetime.now(TZ) - timedelta(days=30)).strftime("%Y-%m-%d %H:%M:%S"), "end_date": datetime.now(TZ).strftime("%Y-%m-%d %H:%M:%S")})) assert calls.count("past") <= 3 and "note_missing" in out and out["readings"] > 0 # one window, plus today (and yesterday, in the small hours) await air.close() @@ -222,7 +223,7 @@ async def test_requests_never_ask_for_more_than_ten_days(tmp_path): await air.backfill(pace=0, empty_stop=3) assert 2 <= calls.count("past") <= 10 and longest_request(transport) <= timedelta(days=10) day = datetime.now(TZ) - timedelta(days=200) - out = json.loads(await air.handle({"start_date": day.strftime("%Y-%m-%d %H:%M:%S"), + out = json.loads(await old_tools.air_quality(air, {"start_date": day.strftime("%Y-%m-%d %H:%M:%S"), "end_date": (day + timedelta(days=25)).strftime("%Y-%m-%d %H:%M:%S")})) assert "error" not in out and longest_request(transport) <= timedelta(days=10) # 422s would have failed the answer await air.close() @@ -234,7 +235,7 @@ async def test_no_data_available_is_an_empty_period_not_a_failure(tmp_path): fetched, failed, total = await air.backfill(pace=0, empty_stop=5, empty_before_data=5) assert failed == 0 and fetched >= 5 and total == 5 day = datetime.now(TZ).date() - timedelta(days=3) - out = json.loads(await air.handle({"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"})) + out = json.loads(await old_tools.air_quality(air, {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"})) assert out["note"] == "No readings for this period." and "error" not in out await air.close() @@ -244,10 +245,10 @@ async def test_answers_say_when_old_days_are_hourly_averages(tmp_path): air = AirGradient(config(tmp_path), transport=transport) now = datetime.now(TZ) fmt = "%Y-%m-%d %H:%M:%S" - out = json.loads(await air.handle({"start_date": (now - timedelta(days=9)).strftime(fmt), + out = json.loads(await old_tools.air_quality(air, {"start_date": (now - timedelta(days=9)).strftime(fmt), "end_date": (now - timedelta(days=1)).strftime(fmt)})) assert "hourly averages" in out["note_resolution"] and out["note_resolution"].startswith(("4 ", "5 ", "6 ")) - recent = json.loads(await air.handle({"start_date": (now - timedelta(days=3)).strftime(fmt), + recent = json.loads(await old_tools.air_quality(air, {"start_date": (now - timedelta(days=3)).strftime(fmt), "end_date": (now - timedelta(days=1)).strftime(fmt)})) assert "note_resolution" not in recent await air.close() @@ -294,7 +295,7 @@ async def test_air_charts_too_long_for_the_point_budget_are_bucketed_and_carry_a async def specs(days_back, metrics): turn = Turn() - await air.handle({"start_date": (now - timedelta(days=days_back)).strftime(fmt), "end_date": now.strftime(fmt), + await old_tools.air_quality(air, {"start_date": (now - timedelta(days=days_back)).strftime(fmt), "end_date": now.strftime(fmt), "chart": True, "metrics": metrics}, turn) return turn.charts short = (await specs(3, ["pm2_5"]))[0].panels[0].lines[0] @@ -317,7 +318,7 @@ async def specs(days_back, metrics): async def current_with(tmp_path, latest, earlier, gap=300): - """air.current() when the latest reading is `latest` and today's cache holds `earlier` (a list of values `gap` seconds apart, + """old_tools.air_current(air) when the latest reading is `latest` and today's cache holds `earlier` (a list of values `gap` seconds apart, oldest first, the last one `gap` seconds before the latest).""" from datetime import timezone from tests.fakes import air_row @@ -333,7 +334,7 @@ async def current_row(refresh=False): async def day_rows(day, refresh=False): return cached air._current_row, air._day_rows = current_row, day_rows - out = await air.current() + out = await old_tools.air_current(air) await air.close() return out @@ -410,21 +411,20 @@ async def test_every_air_day_row_is_what_the_glitch_rule_in_python_gives(tmp_pat async def test_air_days_counts_days_by_a_metric_and_draws_the_months_as_bars(tmp_path): - from lib.airgradient.days import air_days_tool from lib.tools import Turn from tests.fakes import TZ store, start = await _air_store(tmp_path) end = datetime.now(TZ).date() - timedelta(days=1) turn = Turn() - out = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), + out = json.loads(await old_tools.air_days(store, TZ, dict(start_date=str(start), end_date=str(end), where=[{"field": "pm2_5_max", "op": ">", "value": 25}], count_only=True, group_by="month"), turn)) assert out["matching_days"] == 4 and out["days_checked"] == 40 and "days" not in out assert sum(out["by_month"].values()) == 4 and turn.charts[0].title == "Days with PM2.5 > 25 µg/m³" - mean = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), stat="avg", of="co2_avg", count_only=True))) + mean = json.loads(await old_tools.air_days(store, TZ, dict(start_date=str(start), end_date=str(end), stat="avg", of="co2_avg", count_only=True))) assert mean["stat"]["what"] == "Average CO₂" and 500 < mean["value"] < 600 # 420 + the mean of 0..287 - worst = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), sort_by="pm2_5_max", limit=2))) + worst = json.loads(await old_tools.air_days(store, TZ, dict(start_date=str(start), end_date=str(end), sort_by="pm2_5_max", limit=2))) assert [r["pm2_5_max"] for r in worst["days"]] == [40.0, 40.0] - bad = json.loads(await air_days_tool(store, TZ, dict(start_date=str(start), end_date=str(end), where=[{"field": "uv_max", "op": ">", "value": 1}]))) + bad = json.loads(await old_tools.air_days(store, TZ, dict(start_date=str(start), end_date=str(end), where=[{"field": "uv_max", "op": ">", "value": 1}]))) assert "unusable condition" in bad["error"] store.close() @@ -494,7 +494,7 @@ async def test_the_latest_reading_comes_with_the_lowest_of_the_last_readings_for air, _ = await make(tmp_path) reading, at, sustained = await air.latest() assert set(sustained) >= {"pm2_5"} and sustained["pm2_5"] <= reading["pm2_5"]["value"] and at.tzinfo is not None - assert json.loads(await air.handle({}, None)) == json.loads(json.dumps(reading)) # the tool gives the reading alone + assert json.loads(await old_tools.air_quality(air, {}, None)) == json.loads(json.dumps(reading)) # the tool gives the reading alone await air.close() @@ -504,7 +504,7 @@ async def test_the_reading_is_rated_alone_when_only_the_history_fails(tmp_path, async def down(day, refresh=False): raise RuntimeError("AirGradient past failed: HTTP 500") air._day_rows = down - reading = json.loads(await air.handle({})) + reading = json.loads(await old_tools.air_quality(air, {})) assert reading["pm2_5"]["value"] == 12.0 and "rating_note" not in reading["pm2_5"] and "rating the latest alone" in caplog.text assert (await air.latest()).sustained["pm2_5"] == 12.0 await air.close() @@ -553,8 +553,8 @@ async def test_a_date_with_an_offset_is_read_and_a_bad_one_is_not_called_a_senso from datetime import timezone as tz_ air, _ = await make(tmp_path) start = (datetime.now(TZ) - timedelta(days=2)).astimezone(tz_.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - out = json.loads(await air.handle({"start_date": start})) - bad = json.loads(await air.handle({"start_date": "yesterday morning"})) + out = json.loads(await old_tools.air_quality(air, {"start_date": start})) + bad = json.loads(await old_tools.air_quality(air, {"start_date": "yesterday morning"})) await air.close() assert "error" not in out and out["readings"] > 0 and bad["error"].startswith("bad date") @@ -573,14 +573,14 @@ async def test_the_sensors_own_temperature_and_humidity_are_kept_but_given_only_ air, _ = await make(tmp_path) day = local_date(datetime.now(TZ).timestamp() - 86400, TZ) span = {"start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - assert "air_humidity" not in json.loads(await air.handle({})) and "air_humidity" not in json.loads(await air.handle(span)) - now = json.loads(await air.handle({"metrics": ["air_humidity", "air_temperature"]})) + assert "air_humidity" not in json.loads(await old_tools.air_quality(air, {})) and "air_humidity" not in json.loads(await old_tools.air_quality(air, span)) + now = json.loads(await old_tools.air_quality(air, {"metrics": ["air_humidity", "air_temperature"]})) assert now["air_humidity"]["unit"] == "%" and now["air_temperature"]["unit"] == "°C" and "rating" not in now["air_humidity"] assert "pm2_5" in now # the air itself is still there - out = json.loads(await air.handle({**span, "metrics": ["air_humidity"]})) + out = json.loads(await old_tools.air_quality(air, {**span, "metrics": ["air_humidity"]})) assert out["air_humidity"]["unit"] == "%" and {"low", "high", "average"} <= set(out["air_humidity"]) and "air_temperature" not in out turn = Turn() - out = json.loads(await air.handle({**span, "chart": True, "metrics": ["air_temperature", "air_humidity"]}, turn)) + out = json.loads(await old_tools.air_quality(air, {**span, "chart": True, "metrics": ["air_temperature", "air_humidity"]}, turn)) assert turn.charts[0].title == "AirGradient temperature and AirGradient humidity" and len(turn.charts[0].panels) == 2 assert [p.unit for p in turn.charts[0].panels] == ["°C", "%"] await air.close() diff --git a/tests/test_alert_menu.py b/tests/test_alert_menu.py index 4f7b460f..3ab6c80b 100644 --- a/tests/test_alert_menu.py +++ b/tests/test_alert_menu.py @@ -569,12 +569,12 @@ def test_every_alert_chart_has_the_key_of_the_call_its_typed_request_is_read_as( from lib.alerts.pictures import CHARTS from lib.periods import call_key charts, images = alert_charts([0.0]) - day = {"period": "last 24 hours", "chart": True} + day = {"period": "1d", "chart": True} assert {kind: charts.call(kind) for kind in CHARTS} == { - "gusts": ("summary", {"readings": ["wind.wind_speed", "wind.wind_direction"], **day}), # "Wind chart 1d", the Wind button's - "uv": ("summary", {"readings": ["solar_and_uvi.uvi"], **day}), - "temps": ("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], **day}), - "particulates": ("summary", {"readings": ["air.pm2_5", "air.pm10", "air.pm1"], **day})} + "gusts": ("summary", {"readings": ["wind"], **day}), # "Wind chart 1d", the Wind button's + "uv": ("summary", {"readings": ["uv"], **day}), + "temps": ("summary", {"readings": ["temperature"], **day}), + "particulates": ("summary", {"readings": ["pm2.5", "pm10", "pm1"], **day})} assert charts.key("gusts") == call_key(*charts.call("gusts")) assert charts.key("rain") is None # an alert without a chart diff --git a/tests/test_alerts.py b/tests/test_alerts.py index ea881e47..d9215c7b 100644 --- a/tests/test_alerts.py +++ b/tests/test_alerts.py @@ -11,6 +11,7 @@ from lib.alerts.weather import WeatherMonitor from lib.entities import with_link from tests.fakes import TZ +from tests import old_tools T0 = int(datetime(2026, 9, 29, 13, 0, tzinfo=TZ).timestamp()) # 1pm Melbourne, a settled day @@ -813,17 +814,14 @@ async def test_the_alert_charts_are_the_typed_one_day_charts_drawn_from_each_sou async def test_the_particulates_chart_draws_pm1_pm25_and_pm10_together(tmp_path): - from lib import intent from lib.airgradient import AirGradient - from lib.timeutil import now_local from lib.tools import Turn from tests.fakes import air_transport, config transport, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) air = AirGradient(config(tmp_path), transport=transport) await air.start() - read = intent.read("Particulates chart 1d", now_local(TZ)) - turn = Turn(chart_asked=read.chart_asked, text="Particulates chart 1d") - await air.handle(read.fast[1], turn) + turn = Turn(chart_asked=True) + await old_tools.air_quality(air, {"chart": True, "metrics": ["pm2_5", "pm10", "pm1"]}, turn) (panel,) = turn.charts[0].panels assert sorted(line.label for line in panel.lines) == ["PM1", "PM10", "PM2.5"] await air.close() diff --git a/tests/test_bench_storage.py b/tests/test_bench_storage.py index b63c8cbf..cd2b62bb 100644 --- a/tests/test_bench_storage.py +++ b/tests/test_bench_storage.py @@ -45,4 +45,4 @@ async def test_the_benchmark_s_own_cache_is_as_old_as_asked_and_its_short_chart_ short = rows["Temperature chart, 3 hours"] assert short[2] == 0 assert rows["Temperature chart, 1D"][2] == 1 # its newest hour is settling - assert "air_days: days PM2.5 over 25, 4 years" in rows + assert "days: days PM2.5 over 25, 4 years" in rows diff --git a/tests/test_bot.py b/tests/test_bot.py index 6383252d..9eecbdf5 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -16,8 +16,8 @@ async def run(self, *a, **k): class AnsweringAgent: - async def run(self, messages, system, effort, *, first_call=None, turn=None, **k): - self.first_call = first_call + async def run(self, messages, system, effort, *, turn=None, **k): + self.system = system return "It is 12 degrees." @@ -62,16 +62,35 @@ async def test_without_a_model_a_question_for_it_is_told_so_and_what_works_still replies = await ask(alert_state, NoModel(), "will it rain tomorrow, do you think?") assert len(replies) == 1 and "needs the AI model" in replies[0] and "/report" in replies[0] and "/air_quality" in replies[0] replies = await ask(alert_state, NoModel(), "what can you do") - assert len(replies) == 1 and "needs the AI model" not in replies[0] # answered in code, as before + assert len(replies) == 1 and "needs the AI model" in replies[0] # the model's: it calls `about` async def test_a_failing_shortcut_falls_back_to_the_model(alert_state, monkeypatch): def boom(*a, **k): raise OverflowError("date value out of range") - monkeypatch.setattr(intent, "fast_call", boom) + monkeypatch.setattr(intent, "chart_call", boom) agent = AnsweringAgent() - assert await ask(alert_state, agent, "weather last 99999 years") == ["It is 12 degrees."] - assert agent.first_call is None + replies = [] + + async def reply_text(body, **kw): + replies.append(body) + + async def send_chat_action(*a, **k): + pass + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None)] + await Bot(NS(tz=TZ), agent, sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "humidity 7d") + assert replies == ["It is 12 degrees."] + + +async def test_the_model_is_sent_the_persona_the_servers_instructions_and_the_time(alert_state): + from lib.prompt import PERSONA + agent = AnsweringAgent() + assert await ask(alert_state, agent, "is it too cold to run?") == ["It is 12 degrees."] + assert agent.system.startswith(PERSONA.rstrip()) and "\n\nThe devices: " in agent.system # (lib/service/instructions.py) + assert agent.system.rstrip().splitlines()[-1].startswith("Now: ") and "RIGHT NOW" not in agent.system def test_a_reply_carries_the_message_it_replies_to_in_private_chats_too(alert_state): @@ -142,7 +161,11 @@ async def ask_private(alert_state, agent, bot, chat_type="private", text="how ho async def reply_text(body, **kw): replies.append(body) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, + + async def reply_photo(photo, caption=None, **kw): + replies.append(caption.split("\n\n", 1)[-1]) + return NS(message_id=5) + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, reply_photo=reply_photo, chat=NS(type=chat_type, title=None), from_user=NS(full_name="Rob"), reply_to_message=None) update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) await Bot(NS(tz=TZ), agent, [], alert_state).respond(update, NS(bot=bot), text) @@ -307,12 +330,8 @@ async def send_chat_action(*a, **k): pass service = chart_service() await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service).respond(update, NS(bot=telegram(send_chat_action)), "Humidity chart 7d") - assert service.calls == [("summary", {"readings": ["outdoor.humidity", "indoor.humidity"], "period": "last 7 days", "chart": True})] + assert service.calls == [("summary", {"readings": ["humidity"], "period": "7d", "chart": True})] # the words, as they are assert sent == ["Humidity"] # the chart's title is its whole caption - sent.clear() - await Bot(NS(tz=TZ), Agent(), sources, alert_state, service=service).respond(update, NS(bot=telegram(send_chat_action)), - "when was humidity highest this week") - assert "high 60 %, Sat 26 Sep" in sent[0] # a record asked for: its figures, with when, go with the chart async def test_a_chart_made_in_code_starts_no_refresh_and_other_questions_do(alert_state, monkeypatch): @@ -402,25 +421,13 @@ async def send_chat_action(*a, **k): return replies, bool(asked) -async def test_a_plain_reading_question_is_answered_in_code_without_the_model(alert_state): - answer = {"lines": {"station": ["• Outdoor: 12.3 °C, feels like 11.0 °C", "• Indoor: 18.3 °C"]}} - replies, asked = await _ask_with(alert_state, answer, "how hot is it") - assert not asked and replies == ["• Outdoor: 12.3 °C, feels like 11.0 °C\n• Indoor: 18.3 °C"] - - -async def test_a_lookup_that_cannot_be_written_falls_back_to_the_model(alert_state): - replies, asked = await _ask_with(alert_state, {"error": "station not answering"}, "how hot is it") +async def test_a_chart_shortcut_the_service_cant_draw_falls_back_to_the_model(alert_state): + replies, asked = await _ask_with(alert_state, {"error": "station not answering"}, "humidity 7d") assert asked and replies == ["from the model"] - replies, asked = await _ask_with(alert_state, {"lines": {"station": ["• not available right now"]}, - "unavailable": {"station": "The weather station isn't answering right now."}}, "how hot is it") + replies, asked = await _ask_with(alert_state, {"text": "no chart"}, "humidity chart 7d") assert asked and replies == ["from the model"] -async def test_about_the_bot_is_answered_in_code_without_the_model(alert_state): - replies, asked = await _ask_with(alert_state, {"lines": ["• Temperature, humidity (indoor, outdoor)", "• History charts"]}, "what can you do") - assert not asked and replies[0].startswith("• Temperature, humidity") - - async def test_typing_starts_before_the_model_is_asked_and_runs_alongside_the_draft(alert_state): seen = {} @@ -434,28 +441,6 @@ async def run(self, *a, **k): assert seen["typing_when_asked"] >= 1 and bot.drafts -async def test_the_forecast_is_fetched_with_the_first_step_of_a_rain_ahead_question(alert_state): - got = [] - - class Agent: - async def run(self, messages, system, effort, first_call=None, **k): - got.append(first_call) - return "Possibly." - sources = [NS(name=n, wants=lambda t: True, poke=lambda: None, describe=lambda n=n: n) for n in ("Ecowitt", "Forecast")] - replies = [] - - async def reply_text(body, **kw): - replies.append(body) - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), "will it rain?") - assert [name for name, _ in got[0]] == ["weather_now", "weather_history", "weather_forecast"] and replies == ["Possibly."] - - async def _message_aged(alert_state, seconds): from datetime import datetime, timedelta, timezone answered = [] @@ -518,19 +503,7 @@ async def send_chat_action(*a, **k): assert replies == ["\u26a0\ufe0f That's pulling in about 24k tokens of data, so it will take a little longer. Working on it...", "The answer."] -async def test_a_days_over_a_limit_question_is_counted_in_code_with_no_model(alert_state): - answer = {"answer": "137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026).", "days_checked": 1454, "matching_days": 137} - replies, asked = await _ask_with(alert_state, answer, "days over UVI 10 by year") - assert not asked and replies == ["137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)."] - - -async def test_rain_by_month_is_worked_out_in_code_with_no_model(alert_state): - answer = {"answer": "Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026).", "value": 1234.5} - replies, asked = await _ask_with(alert_state, answer, "rain by month for 2 years") - assert not asked and replies == ["Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026)."] - - -async def test_the_model_is_asked_with_the_tool_choice_the_message_calls_for(alert_state): +async def test_the_model_chooses_its_own_tools_whatever_the_message(alert_state): seen = [] class Agent: @@ -550,7 +523,7 @@ async def reply_text(body, **kw): async def send_chat_action(*a, **k): pass await Bot(NS(tz=TZ), Agent(), sources, alert_state).respond(update, NS(bot=telegram(send_chat_action)), text) - assert seen == ["required", "auto"] + assert seen == ["auto", "auto"] async def test_weather_all_week_and_a_plain_chart_are_sent_with_just_their_title(alert_state, monkeypatch): @@ -565,7 +538,7 @@ async def reply_photo(photo, caption=None, **kw): sent.append(caption) monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - for text in ("ecowitt all week", "temperature chart 7d"): + for text in ("weather 30d", "temperature chart 7d"): sent.clear() msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) @@ -648,132 +621,19 @@ async def answer(self, *args, **kwargs): await answer_query(Query(BadRequest("Message is not modified"))) -async def test_the_air_sensors_own_readings_stay_offered_in_a_chat_until_two_runs_go_by_without_the_model_using_them(alert_state): - seen = [] - uses = iter([True, True, False, False, False]) # what the model does with the series when it has them: used, used, then not - - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append((turn.air_extra, "AIRGRADIENT'S OWN TEMPERATURE AND HUMIDITY" in system)) - if turn.air_extra and next(uses): - turn.air_extra_used = True # a tool served them - return "ok" - replies = [] - - async def reply_text(body, **kw): - replies.append(body) - - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in ("what is the weather like", "overlay ecowitt humidity with airgradient humidity", "do that again but for temperature", - "and the wind?", "and the rain?", "and the pressure?", "and the uv?"): - await bot.respond(update, context, said) - assert seen == [(False, False), # nothing about the air sensor yet - (True, True), (True, True), # named, used; the follow-up (no AirGradient in it) still offered, used again - (True, True), (True, True), # two runs the model did not use them in ... - (False, False), (False, False)] # ... and they are no longer offered, nor mentioned in the prompt - - -async def test_either_side_naming_the_air_sensors_readings_keeps_them_offered(alert_state): - seen = [] - replies_by_question = {"what is the weather like": "It is mild.", "tell me about airgradient humidity": "The AirGradient humidity is 61%.", - "and tomorrow?": "Sunny.", "and the day after?": "Cloudy.", "what about the wind?": "Calm."} - - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append(turn.air_extra) - return replies_by_question[messages[-1]["content"]] - sent = [] - - async def reply_text(body, **kw): - sent.append(body) - - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in replies_by_question: - await bot.respond(update, context, said) - # the person's words named it (offered) and the reply did too (still offered for the next two runs); then they stop - assert seen == [False, True, True, True, False] - - -async def test_the_air_sensors_own_readings_are_offered_to_a_follow_up_when_the_last_messages_named_them_whatever_the_count(alert_state): - seen = [] - - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append(turn.air_extra) - return "ok" - sent = [] - - async def reply_text(body, **kw): - sent.append(body) - - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - for earlier in ( - [{"role": "user", "content": "plot airgradient humidity"}, {"role": "assistant", "content": "Done."}], # the person named it - [{"role": "user", "content": "plot humidity"}, {"role": "assistant", "content": "Here is AirGradient humidity over Ecowitt."}], # the reply did - [{"role": "user", "content": "plot humidity"}, {"role": "assistant", "content": "Done."}]): # neither did - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - bot.chats[bot._key(msg)].history = list(earlier) # a chat whose count has run out: only the messages are left - await bot.respond(update, context, "do that again but for temperature") - assert seen == [True, True, False] - +class ChartingAgent(StreamingAgent): + """The model's first step drew a chart (a result with `charts` kept on the Turn); then it streams its answer.""" -async def test_every_guidance_topic_stays_on_in_a_chat_while_either_side_names_it_or_its_tools_are_used_then_goes_after_two_quiet_runs(alert_state): - seen = [] - script = {"how many days was uv over 9": ("ok", "weather_days"), # the person names days, and its tool is used - "and for solar": ("ok", None), "thanks": ("ok", None), "right": ("ok", None), - "tell me something": ("The pressure is steady and the wind was strong.", None), # the reply names wind - "and the pressure": ("ok", None), "and humidity": ("ok", None), "fine": ("ok", None), "good": ("ok", None)} - - class Capturing: - async def run(self, messages, system, effort, *, turn=None, **k): - seen.append((messages[-1]["content"], sorted(turn.topics & {"days", "wind"}))) - reply, tool = script[messages[-1]["content"]] - if tool: - messages.append({"role": "assistant", "content": None, "tool_calls": [{"function": {"name": tool}}]}) - return reply - sent = [] - - async def reply_text(body, **kw): - sent.append(body) - - async def send_chat_action(*a, **k): - pass - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - context = NS(bot=telegram(send_chat_action)) - bot = Bot(NS(tz=TZ), Capturing(), [], alert_state) - for said in script: - await bot.respond(update, context, said) - got = dict(seen) - assert got["how many days was uv over 9"] == ["days"] - assert got["and for solar"] == ["days"] and got["thanks"] == ["days"] # no word of it, but its tool was just used - assert got["right"] == [] # two quiet runs: gone - assert got["and the pressure"] == ["wind"] # the reply to the question before named the wind - assert got["and humidity"] == ["wind"] and got["fine"] == [] and got["good"] == [] # and that goes too, after two quiet runs + async def run(self, messages, system, effort, *, turn=None, **k): + turn.results.append(("summary", {"readings": ["humidity"]}, {"caption": "c", "charts": [{"title": "Humidity"}]})) + return await super().run(messages, system, effort, turn=turn, **k) async def test_an_answer_that_comes_with_a_chart_is_not_streamed_into_the_draft(alert_state, monkeypatch): monkeypatch.setattr("lib.bot.DRAFT_MIN_GAP", 0.01) + monkeypatch.setattr("lib.bot.Bot._draw", lambda self, chart, times=None: (b"png", "Humidity", 0)) bot = DraftBot() - assert await ask_private(alert_state, StreamingAgent(), bot, text="plot humidity for a week") == ["It is 12 degrees."] + assert await ask_private(alert_state, ChartingAgent(), bot, text="plot humidity for a week") == ["It is 12 degrees."] assert bot.drafts and all(t is None for _, t in bot.drafts) # only "Thinking...": no text to be followed by a picture and a second message bot = DraftBot() await ask_private(alert_state, StreamingAgent(), bot, text="how hot is it") @@ -787,18 +647,69 @@ def chart_service(caption="Fri 25 Sep – Thu 1 Oct 2026\nHumidity: low 50 %, Fr return StandInService(summary=lambda args, meta: {"caption": caption, "charts": [chart_data(title)]}) -def test_a_chart_the_model_drew_over_a_period_the_service_cant_word_keeps_its_old_buttons(alert_state): - """Until step 3, every chart the model draws has period buttons: one whose call the service lists no periods for (the last 48 hours as - times) gets no drawn_by, so its question is asked again on a press, as before.""" - from lib.tools import CALL +async def test_a_chart_kept_by_its_question_from_before_the_swap_is_out_of_date(alert_state): + """Before step 3 a chart the model drew through a call the service had no equivalent of was remembered by its question; its buttons + are out of date now.""" from tests.fakes import StandInService bot = Bot(NS(tz=TZ), None, [], alert_state, service=StandInService()) - now = datetime(2026, 11, 10, 14, 5) - turn = Turn(text="how warm was it") - for start in ("2026-11-09 14:05:00", "2026-11-08 14:05:00"): - called = CALL.set(("weather_history", {"start_date": start, "end_date": "2026-11-10 14:05:00", "chart": True})) - turn.charts.append("chart") - CALL.reset(called) - day = bot._model_drawn_by(turn, 0, now) - assert day["tool"] == "summary" and day["arguments"]["period"] == "last 24 hours" and day["periods"] - assert bot._model_drawn_by(turn, 1, now) is None + bot.charted.remember(1, 7, "how warm was it") + answers = [] + + async def answer(text=None, **k): + answers.append(text) + query = NS(data="pd:7", message=NS(chat_id=1, message_id=7), answer=answer) + await bot.on_period_button(NS(callback_query=query), None) + assert answers == ["That chart is out of date, please ask again"] + + +async def test_the_models_charts_are_drawn_with_their_buttons_and_the_model_is_sent_their_titles_alone(alert_state, monkeypatch): + """The model's call drew a chart: the model sees its title and period (no points); the bot draws it from the whole result, with + the period buttons its drawn_by lists, and keeps the call behind them.""" + import json + from lib import model_tools + from lib.llm import Agent + from tests.fakes import chart_data + drawn_by = {"tool": "summary", "arguments": {"readings": ["humidity"], "period": "7d", "chart": True}, + "periods": [{"period": "1d", "label": "1D"}, {"period": "7d", "label": "7D"}]} + chart = {**chart_data("Humidity"), "drawn_by": drawn_by} + + class Summary: + name, description, parameters = "summary", "Summary.", {"type": "object", "properties": {}} + + async def call(self, args, meta): + assert meta["chart_points"] == "drawn" + return json.dumps({"caption": "c", "charts": [chart], "chart_note": "note"}) + seen, sent = [], [] + + class Model: + """A model that calls summary, then answers.""" + def __init__(self): + self.chat = self + + async def create(self, **kw): + seen.append(kw["messages"][-1]) + if len(seen) == 1: + call = NS(id="1", function=NS(name="summary", arguments="{}")) + return NS(choices=[NS(message=NS(content="", tool_calls=[call]))], usage=None) + return NS(choices=[NS(message=NS(content="Humid all week.", tool_calls=None))], usage=None) + + client = NS(chat=NS(completions=Model())) + monkeypatch.setattr("lib.bot.Bot._draw", lambda self, c, times=None: (b"png", c["title"], 0)) + + async def reply_photo(photo, caption=None, reply_markup=None, **kw): + sent.append((caption, reply_markup)) + return NS(message_id=9) + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, + chat=NS(type="group", title="g"), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + + async def send_chat_action(*a, **k): + pass + bot = Bot(NS(tz=TZ), Agent(client, "m", model_tools.tools([Summary()])), [], alert_state) + await bot.respond(update, NS(bot=telegram(send_chat_action)), "how humid was it this week?") + told = json.loads(seen[-1]["content"]) + assert told["charts"] == [{"title": "Humidity", "period": chart["period"]}] and told["chart_note"] == "note" + (caption, markup), = sent + assert caption.startswith("Humidity") and "Humid all week." in caption + assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d"] + assert bot.charted.get(1, 9)["drawn_by"] == drawn_by diff --git a/tests/test_chart_answers.py b/tests/test_chart_answers.py index e7c5290c..369cb305 100644 --- a/tests/test_chart_answers.py +++ b/tests/test_chart_answers.py @@ -1,191 +1,86 @@ -"""A question that is only a chart: the model sets chart_answers_it, the chart's caption is written in code and the model is asked -nothing more (docs/mcp-service.md 3.7). A real Agent over a scripted model and stand-in tools, through the bot's own model call.""" +"""A question that is only a chart: the model sets chart_answers_it, the service's result comes complete (its chart and its `reply`), +and the turn ends with that reply: the model is asked nothing more (docs/mcp-service.md 3.7). A real Agent over a scripted model and +stand-in service tools (offered as the bot offers them, lib/model_tools.py), through the bot's own model call.""" import json import logging from datetime import datetime from types import SimpleNamespace as NS -from lib import intent, llm +from lib import intent, llm, model_tools from lib.bot import Bot -from lib.specs import Chart, Line, Panel -from lib.tools import Tool, Tools, Turn -from tests.fakes import TZ +from lib.tools import Turn +from tests.fakes import TZ, chart_data from tests.test_agent import FakeLLM NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday ONLY_A_CHART = "plot pressure since Sunday" -PERIOD = "Sun 27 Sep 2026 - Tue 29 Sep 2026" -PRESSURE = {"period": PERIOD, "series": {"pressure.relative": { - "unit": "hPa", "low": "1004.2", "low_when": "at 4am", "low_date": "Mon 28 Sep 2026", - "high": "1021.7", "high_when": "at 10pm", "high_date": "Sun 27 Sep 2026"}}, "chart": "(the chart hint)"} -CAPTION = ("Sun 27 Sep – Tue 29 Sep 2026\n" - "Pressure: low 1004.2 hPa, Mon 28 Sep at 4am · high 1021.7 hPa, Sun 27 Sep at 10pm") -ASKED = {"start_date": "2026-09-27 00:00:00", "end_date": "2026-09-29 14:05:00", "groups": "pressure", "chart": True, - "chart_field": "pressure"} -EMPTY = {"type": "object", "properties": {}} +REPLY = "Sun 27 Sep – Tue 29 Sep 2026\nPressure: low 1004.2 hPa, Mon 28 Sep at 4am · high 1021.7 hPa, Sun 27 Sep at 10pm" +COMPLETE = {"period": {"text": "Sun 27 – Tue 29 Sep 2026"}, "caption": REPLY, "charts": [chart_data("Pressure")], "reply": REPLY, + "complete": True} +ASKED = {"readings": ["pressure"], "period": "since Sunday", "chart": True, "chart_answers_it": True} -def chart(title: str = "Pressure") -> Chart: - return Chart(title, "", [Panel(title, "", [Line(title, [1, 2], [1.0, 2.0])])]) +class StandIn: + """A service tool that answers `result` (a dict, or an exception it raises) and keeps the arguments it was sent.""" + def __init__(self, name: str = "summary", result=COMPLETE): + self.name, self.description, self.parameters, self.result, self.seen = name, "d", {"type": "object", "properties": {}}, result, [] -def stand_in(name: str = "weather_history", result: dict | str = PRESSURE, draws: bool = True): - """The tool as a stand-in: it draws its chart (when `draws`) and answers `result`. Returns (the tool, the arguments it was given).""" - seen = [] + async def call(self, args, meta): + self.seen.append(args) + if isinstance(self.result, Exception): + raise self.result + return json.dumps(self.result, ensure_ascii=False) - async def handler(args, turn=None): - seen.append(args) - if isinstance(result, Exception): - raise result - if draws: - turn.charts.append(chart()) - return result if isinstance(result, str) else json.dumps(result) - return Tool(name, "d", EMPTY, handler), seen - -async def ask(alert_state, script, tools, text=ONLY_A_CHART, turn=None): +async def ask(alert_state, script, tools, text=ONLY_A_CHART): """`text` through the bot's model call with a scripted model: (reply, the model's requests, the turn, the conversation).""" client = FakeLLM(script) - bot = Bot(NS(tz=TZ), llm.Agent(client, "m", Tools(tools)), [], alert_state) + bot = Bot(NS(tz=TZ), llm.Agent(client, "m", model_tools.tools(tools)), [], alert_state) read = intent.read(text, NOW) - turn = turn or Turn.of(read, text) + turn = Turn() working = [{"role": "user", "content": text}] reply = await bot._ask_model(working, "sys", read, turn, None) return reply, client.requests, turn, working -def test_the_tools_whose_chart_can_be_the_answer_offer_the_flag_and_say_when_to_set_it(): - from lib.airgradient import days as air_days, source as air - from lib.ecowitt import days, source as station - for parameters in (station.HISTORY_PARAMS, air.PARAMETERS, air.asked()[1], days.PARAMETERS, air_days.PARAMETERS): - flag = parameters["properties"]["chart_answers_it"] - assert flag["type"] == "boolean" and "nothing else to answer" in flag["description"] and "is a storm coming?" in flag["description"] - - -async def test_a_chart_that_answers_the_question_is_the_reply_written_in_code_and_the_model_is_asked_once(alert_state, caplog): - tool, seen = stand_in() - assert intent.read(ONLY_A_CHART, NOW).fast is None # the model takes it, not a shortcut +async def test_a_complete_result_is_the_reply_and_the_model_is_asked_once(alert_state, caplog): + tool = StandIn() + assert intent.read(ONLY_A_CHART, NOW).chart is None # the model takes it, not a shortcut with caplog.at_level(logging.INFO, logger="lib.llm"): - reply, requests, turn, working = await ask(alert_state, [[("weather_history", {**ASKED, "chart_answers_it": True})], - "the model's own caption"], [tool]) - assert reply == CAPTION and len(requests) == 1 and len(turn.charts) == 1 and len(seen) == 1 - assert working[-1] == {"role": "assistant", "content": CAPTION} # the conversation keeps it as the answer - assert any("ended on a chart that answers the question (weather_history): no LLM 2" in r.getMessage() for r in caplog.records) - - -async def test_without_the_flag_the_model_writes_the_answer_as_before(alert_state): - tool, _ = stand_in() - reply, requests, turn, _ = await ask(alert_state, [[("weather_history", ASKED)], "The model's answer."], [tool]) - assert reply == "The model's answer." and len(requests) == 2 and len(turn.charts) == 1 - reply, requests, _, _ = await ask(alert_state, [[("weather_history", {**ASKED, "chart_answers_it": False})], "Again."], [tool]) - assert reply == "Again." and len(requests) == 2 - - -async def test_the_flag_with_no_chart_or_a_failed_call_leaves_the_answer_to_the_model(alert_state): - flagged = [("weather_history", {**ASKED, "chart_answers_it": True})] - for result, draws in (({k: v for k, v in PRESSURE.items() if k != "chart"}, False), # no chart drawn - ({"error": "bad date"}, False), # the tool said no - (RuntimeError("Ecowitt is down"), False), # the tool failed - ({"period": PERIOD, "series": {}, "chart": "(hint)"}, True)): # a chart, but nothing to caption it with - tool, _ = stand_in(result=result, draws=draws) - reply, requests, _, _ = await ask(alert_state, [flagged, "The model's answer."], [tool]) + reply, requests, turn, working = await ask(alert_state, [[("summary", ASKED)], "the model's own caption"], [tool]) + assert reply == REPLY and len(requests) == 1 and len(tool.seen) == 1 + assert turn.results[0][2]["charts"] == COMPLETE["charts"] # the whole result kept, for drawing + assert working[-1] == {"role": "assistant", "content": REPLY} # the conversation keeps it as the answer + assert any("ended on a complete result (summary): no LLM 2" in r.getMessage() for r in caplog.records) + + +async def test_a_result_that_isnt_complete_leaves_the_answer_to_the_model(alert_state): + for result in ({k: v for k, v in COMPLETE.items() if k not in ("reply", "complete")}, # no chart_answers_it, or a note to word + {**COMPLETE, "charts": []}, # complete, but no chart + {"error": "That period isn't one of the forms."}, # refused + RuntimeError("Ecowitt is down")): # failed + reply, requests, _, _ = await ask(alert_state, [[("summary", ASKED)], "The model's answer."], [StandIn(result=result)]) assert reply == "The model's answer." and len(requests) == 2, result -async def test_a_note_the_caption_would_leave_out_leaves_the_answer_to_the_model(alert_state): - flagged = [("weather_history", {**ASKED, "chart_answers_it": True})] - for note in ({"monthly_note": "Monthly figures for long periods come from daily data"}, {"note_resolution": "hourly averages"}): - tool, _ = stand_in(result={**PRESSURE, **note}) - reply, requests, _, _ = await ask(alert_state, [flagged, "The model's answer."], [tool]) - assert reply == "The model's answer." and len(requests) == 2, note - tool, _ = stand_in(result={**PRESSURE, "note_missing": "older days are downloading"}) # a note the caption writes itself - reply, requests, _, _ = await ask(alert_state, [flagged, "unused"], [tool]) - assert len(requests) == 1 and "still downloading" in reply - - -async def test_a_step_with_any_call_that_is_not_a_chart_answering_the_question_goes_back_to_the_model(alert_state): - history, _ = stand_in() - now, _ = stand_in("weather_now", result={"outdoor": {"temperature": "12 ℃"}}, draws=False) - flagged = ("weather_history", {**ASKED, "chart_answers_it": True}) - for step in ([flagged, ("weather_history", ASKED | {"groups": "outdoor"})], # one of the two calls didn't set it - [flagged, ("weather_now", {"chart_answers_it": True})]): # a tool whose answer is not a chart - reply, requests, _, _ = await ask(alert_state, [step, "The model's answer."], [history, now]) - assert reply == "The model's answer." and len(requests) == 2 - - -async def test_several_charts_that_answer_the_question_are_captioned_in_the_order_called(alert_state): - pressure, _ = stand_in() - air = {"period": PERIOD, "pm2_5": {"unit": "µg/m³", "high": 34.2, "high_time": "Mon 28 Sep 2026 3:00pm", "high_rating": "🟠 Poor", - "average": 8.1, "low": 1.0, "low_time": "x"}, "chart": "(hint)"} - quality, _ = stand_in("air_quality", result=air) - script = [[("weather_history", {**ASKED, "chart_answers_it": True}), - ("air_quality", {"start_date": ASKED["start_date"], "end_date": ASKED["end_date"], "metrics": ["pm2_5"], "chart": True, - "chart_answers_it": True})], "unused"] - reply, requests, turn, _ = await ask(alert_state, script, [pressure, quality], text="plot pressure and pm2.5 since Sunday") - assert len(requests) == 1 and len(turn.charts) == 2 - assert reply == CAPTION + "\n\nSun 27 Sep – Tue 29 Sep 2026\n• PM2.5: peak 34.2 µg/m³ (Mon 28 Sep 3:00pm) · 🟠 Poor · average 8.1" - - -async def test_a_day_tools_chart_is_captioned_with_the_days_answer(alert_state): - counted = {"period": "Sat 01 Aug 2026 - Mon 28 Sep 2026", "days_checked": 59, "matching_days": 17, "condition": "rain ≥ 1 mm", - "by_month": {"2026-08": 9, "2026-09": 8}, "chart": "(hint)"} - days, _ = stand_in("weather_days", result=counted) - script = [[("weather_days", {"start_date": "2026-08-01", "end_date": "2026-09-28", "where": [{"field": "rain", "op": ">=", "value": 1}], - "count_only": True, "group_by": "month", "chart_answers_it": True})], "unused"] - reply, requests, _, _ = await ask(alert_state, script, [days], text="chart the rainy days each month since August") - assert reply == "17 of 59 days with rain ≥ 1 mm (Sat 01 Aug – Mon 28 Sep 2026)." and len(requests) == 1 - - -async def test_the_caption_speaks_of_the_readings_the_chart_shows_when_only_the_model_named_them(alert_state): - both = {"period": PERIOD, "chart": "(hint)", "series": { - "outdoor.temperature": {"unit": "℃", "low": "8.1", "high": "24.3"}, "outdoor.humidity": {"unit": "%", "low": "41", "high": "93"}}} - tool, _ = stand_in(result=both) - asked = {**ASKED, "groups": "outdoor", "chart_field": "humidity", "chart_answers_it": True} - reply, _, _, _ = await ask(alert_state, [[("weather_history", asked)], "unused"], [tool], turn=Turn(chart_asked=True)) - assert reply.splitlines()[1].startswith("Humidity: low 41 %") and "Temperature" not in reply - air = {"period": PERIOD, "chart": "(hint)", "pm2_5": {"unit": "µg/m³", "high": 9, "high_time": "x", "average": 3}, - "co2": {"unit": "ppm", "high": 812, "high_time": "Mon 28 Sep 2026 7:00am", "average": 455}} - tool, _ = stand_in("air_quality", result=air) - flagged = {"start_date": ASKED["start_date"], "end_date": ASKED["end_date"], "chart": True, "chart_answers_it": True} - reply, _, _, _ = await ask(alert_state, [[("air_quality", flagged)], "unused"], [tool], text="graph the air since Sunday", - turn=Turn(chart_asked=True, air_named=["co2"])) # no metrics: the tool charts the reading talked about - assert reply.splitlines()[1:] == ["• CO₂: peak 812 ppm (Mon 28 Sep 7:00am) · average 455"] - - -async def test_the_bots_own_first_call_never_ends_the_turn(): - tool, seen = stand_in() - finished = [] - - def finish(calls, results): - finished.append(calls) - return "ended in code" - client = FakeLLM(["The model's answer."]) - reply = await llm.Agent(client, "m", Tools([tool])).run( - [{"role": "user", "content": "q"}], "sys", "none", first_call=("weather_history", {**ASKED, "chart_answers_it": True}), - turn=Turn(), finish=finish) - assert reply == "The model's answer." and len(client.requests) == 1 and finished == [] and len(seen) == 1 - - -async def test_the_whole_answer_goes_out_with_its_chart(alert_state, monkeypatch): - from lib import bot as botmod - from tests.test_bot import telegram - tool, _ = stand_in() - client = FakeLLM([[("weather_history", {**ASKED, "chart_answers_it": True})], "unused"]) - sent = [] - - async def reply_photo(photo, caption=None, **kw): - sent.append(caption) - return NS(message_id=7) - - async def send_chat_action(*a, **k): - pass - monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") - sources = [NS(name="Ecowitt", wants=lambda t: True, poke=lambda: None, describe=lambda: "Ecowitt")] - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_photo=reply_photo, - chat=NS(type="supergroup", title="g"), from_user=NS(full_name="Rob"), reply_to_message=None) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - bot = Bot(NS(tz=TZ), llm.Agent(client, "m", Tools([tool])), sources, alert_state) - await bot.respond(update, NS(bot=telegram(send_chat_action)), ONLY_A_CHART) - assert sent == ["Pressure\n\n" + CAPTION] and len(client.requests) == 1 - assert bot.chats[(1, None)].history[-1] == {"role": "assistant", "content": CAPTION} +async def test_a_step_with_any_result_that_isnt_complete_goes_back_to_the_model(alert_state): + complete, plain = StandIn(), StandIn("current", {"lines": {"station": ["• Outdoor: 12 °C"]}}) + reply, requests, _, _ = await ask(alert_state, [[("summary", ASKED), ("current", {})], "The model's answer."], [complete, plain]) + assert reply == "The model's answer." and len(requests) == 2 + + +async def test_several_complete_results_are_the_reply_in_the_order_called(alert_state): + other = {**COMPLETE, "reply": "PM2.5: peak 34.2 µg/m³"} + days = StandIn("days", other) + reply, requests, _, _ = await ask(alert_state, [[("summary", ASKED), ("days", {"group_by": "month", "chart_answers_it": True})], "x"], + [StandIn(), days]) + assert reply == f"{REPLY}\n\nPM2.5: peak 34.2 µg/m³" and len(requests) == 1 + + +async def test_the_model_is_sent_the_result_less_the_charts_data(alert_state): + _, requests, _, _ = await ask(alert_state, [[("summary", {**ASKED, "chart_answers_it": False})], "Low on Monday."], + [StandIn(result={k: v for k, v in COMPLETE.items() if k not in ("reply", "complete")})]) + told = json.loads(requests[1]["messages"][-1]["content"]) + assert told["charts"] == [{"title": "Pressure", "period": COMPLETE["charts"][0]["period"]}] and told["caption"] == REPLY diff --git a/tests/test_chart_source.py b/tests/test_chart_source.py index 977591e1..8a57be22 100644 --- a/tests/test_chart_source.py +++ b/tests/test_chart_source.py @@ -18,30 +18,6 @@ async def handler(args, turn): return handler -def test_only_chart_tools_offer_a_source_argument(): - tools = Tools([Tool("plain", "", {"type": "object", "properties": {}}, drawer()), - Tool("charts", "", {"type": "object", "properties": {"chart": {"type": "boolean"}}}, drawer(), source="Station")]) - params = {s["function"]["name"]: s["function"]["parameters"]["properties"] for s in tools.schemas} - assert "source" not in params["plain"] and set(params["charts"]) == {"chart", "source"} - - -async def test_the_models_source_wins_else_the_tools_own(): - tools = Tools([Tool("charts", "", {"type": "object", "properties": {}}, drawer(), source="Ecowitt weather station")]) - turn = Turn() - await tools.call("charts", json.dumps({"source": " ecowitt.net\n"}), turn) - await tools.call("charts", "{}", turn) - assert [c.source for c in turn.charts] == ["ecowitt.net", "Ecowitt weather station"] - assert CHART_SOURCE.get() == "" # nothing left behind for the next chart - - -async def test_calls_made_together_keep_their_own_sources(): - tools = Tools([Tool("slow", "", {"type": "object", "properties": {}}, drawer(0.05), source="Ecowitt weather station"), - Tool("fast", "", {"type": "object", "properties": {}}, drawer(0.0), source="AirGradient sensor")]) - turn = Turn() - await tools.call_all([("slow", {}), ("fast", {})], turn) - assert [c.source for c in turn.charts] == ["AirGradient sensor", "Ecowitt weather station"] - - def test_a_long_source_is_cut_to_one_line(): text = source_text("https://example.com/" + "x" * 100) assert len(text) == SOURCE_CHARS and text.endswith("…") and source_text(None) == "" diff --git a/tests/test_compose.py b/tests/test_compose.py index 6e5178f0..48790381 100644 --- a/tests/test_compose.py +++ b/tests/test_compose.py @@ -37,14 +37,6 @@ async def plot(comp, **args): return out, turn.charts -async def test_the_composer_offers_the_chart_tool_and_the_two_air_tools(tmp_path, archived_cache): - comp, eco = await composer(tmp_path, archived_cache) - assert [t.name for t in comp.tools] == ["plot_chart", "air_link", "air_scan"] - schema = comp.tools[0].parameters["properties"]["panels"] - assert schema["maxItems"] == MAX_PANELS and schema["items"]["properties"]["series"]["enum"] == SERIES - await eco.close() - - async def test_a_reading_with_its_zones_over_rain_is_one_stacked_chart(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) out, specs = await plot(comp, panels=[{"series": "pm2_5"}, {"series": "rain"}]) @@ -210,19 +202,6 @@ async def test_the_air_sensors_own_temperature_goes_over_the_stations_on_one_axi await eco.close() -async def test_the_tools_offer_the_air_sensors_own_temperature_and_humidity_only_to_a_question_that_asks(tmp_path, archived_cache): - from lib.tools import Tools - comp, eco = await composer(tmp_path, archived_cache) - tools = Tools(comp.tools) - plain = tools.schemas_for(Turn()) - assert plain is tools.schemas and "air_humidity" not in json.dumps(plain) and "same_axis" not in json.dumps(plain) - asked = {s["function"]["name"]: s["function"] for s in tools.schemas_for(Turn(air_extra=True))} - series = asked["plot_chart"]["parameters"]["properties"]["panels"]["items"]["properties"]["series"]["enum"] - assert series == [*SERIES, "air_temperature", "air_humidity"] and "same_axis" in asked["plot_chart"]["parameters"]["properties"] - assert [s["function"]["name"] for s in tools.schemas_for(Turn(air_extra=True))] == [s["function"]["name"] for s in plain] # the same tools, in order - await eco.close() - - async def test_a_composed_air_series_takes_its_range_from_the_readings_the_bot_recorded(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) air = StubAir(days=2) diff --git a/tests/test_contract.py b/tests/test_contract.py index c23973c9..bef0dc62 100644 --- a/tests/test_contract.py +++ b/tests/test_contract.py @@ -9,30 +9,6 @@ -async def test_every_tool_result_keeps_its_shape(tmp_path, archived_cache): - eco, _ = await archived_station(tmp_path, archived_cache) - today = datetime.now(eco.tz).date() - day = lambda n: f"{today - timedelta(days=n)} 00:00:00" - span = {"start_date": day(9), "end_date": f"{today - timedelta(days=2)} 23:59:59"} - call = lambda i, args: eco.tools[i].handler(args) - now = json.loads(await call(0, {"groups": "outdoor,indoor,pressure,wind,rainfall"})) - assert set(now) == {"time", "outdoor", "emoji"} - history = json.loads(await call(1, {"groups": "outdoor", **span})) - assert set(history) - {"chart"} == {"period", "series"} # "chart": a hint that appears when one was drawn - assert set(history["series"]["outdoor.temperature"]) == { - "unit", "low", "low_time", "low_when", "low_date", "high", "high_time", "high_when", "high_date", "daily"} - wind = json.loads(await call(1, {"groups": "wind", **span})) - assert set(wind["series"]) == {"wind.wind_direction", "wind.wind_gust", "wind.wind_speed"} - assert set(wind["series"]["wind.wind_direction"]) == {"unit", "most_common", "average_direction", "steadiness", "readings", "calm", "daily"} - days = json.loads(await call(2, {"start_date": day(30), "end_date": f"{today - timedelta(days=2)} 23:59:59", "sort_by": "temp_max"})) - assert set(days) == {"period", "days_checked", "matching_days", "units", "days"} - assert set(days["days"][0]) == {"date", "temp_max", "temp_min", "rain", "source"} - link = json.loads(await call(3, {"start_date": str(today - timedelta(days=20)), "end_date": str(today - timedelta(days=2))})) - assert set(link) - {"chart"} == {"period", "driver", "resolution", "how_to_read", "slots", "rain_mm", "wet_slots", "verdict", "findings", - "by_change_before", "average_level", "correlation_change_vs_rain_next_3h", "rain_events", "days_with_data"} - await eco.close() - - async def test_the_cross_source_tools_keep_their_shape(tmp_path, archived_cache): comp, eco = await composer(tmp_path, archived_cache) turn = Turn() diff --git a/tests/test_days.py b/tests/test_days.py index 54ade5b9..bfaa6c7b 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -8,6 +8,7 @@ from lib.ecowitt import Ecowitt from tests.fakes import TZ, archived_station, config, ecowitt_transport, rain_day, temp +from tests import old_tools def local_day(d): @@ -32,7 +33,7 @@ async def station(tmp_path, archived_cache): async def ask(eco, **args): - return json.loads(await eco.tools[2].handler(args)) + return json.loads(await old_tools.weather_days(eco, args)) def dates(eco, first_ago, last_ago): @@ -287,7 +288,7 @@ async def test_counts_per_month_or_year_are_drawn_as_a_bar_chart_with_a_title_th first, last = dates(eco, 70, 1) where = [{"field": "temp_max", "op": ">=", "value": 0}] turn = Turn() - out = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=where, count_only=True, group_by="month"), turn)) + out = json.loads(await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), where=where, count_only=True, group_by="month"), turn)) assert len(turn.charts) == 1 and "chart" in out and "message" in out["chart"] chart = turn.charts[0] bars = chart.panels[0].bars @@ -297,7 +298,7 @@ async def test_counts_per_month_or_year_are_drawn_as_a_bar_chart_with_a_title_th from lib.charts import render assert render(chart, eco.tz)[:4] == b"\x89PNG" plain = Turn() # no group_by: a count, no chart - await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=where, count_only=True), plain) + await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), where=where, count_only=True), plain) assert plain.charts == [] @@ -315,69 +316,33 @@ async def test_a_total_highest_or_average_per_month_is_a_bar_chart_of_those_figu rain[f"{d:%Y-%m}"] += truth(d)[1] top[f"{d:%Y-%m}"] = max(top.get(f"{d:%Y-%m}", -1e9), truth(d)[0]) turn = Turn() - out = json.loads(await eco.tools[2].handler({**args, "stat": "sum", "of": "rain"}, turn)) + out = json.loads(await old_tools.weather_days(eco, {**args, "stat": "sum", "of": "rain"}, turn)) assert out["stat"]["what"] == "Total rain" and out["stat"]["unit"] == "mm" and "days" not in out assert {k: v for k, v in out["by_month"].items()} == {k: round(v, 1) for k, v in sorted(rain.items())} bars = turn.charts[0].panels[0].bars assert turn.charts[0].title == "Total rain" and bars.unit == "mm" and bars.per == "month" and bars.y == list(out["by_month"].values()) - hottest = json.loads(await eco.tools[2].handler({**args, "stat": "max", "of": "temp_max"}, Turn())) + hottest = json.loads(await old_tools.weather_days(eco, {**args, "stat": "max", "of": "temp_max"}, Turn())) assert hottest["stat"]["what"] == "Highest temperature" and hottest["by_month"] == {k: round(v, 1) for k, v in sorted(top.items())} - mean = json.loads(await eco.tools[2].handler({**args, "stat": "avg", "of": "temp_avg"}, Turn())) + mean = json.loads(await old_tools.weather_days(eco, {**args, "stat": "avg", "of": "temp_avg"}, Turn())) assert mean["stat"]["what"] == "Average temperature" and all(v is not None for v in mean["by_month"].values()) - overall = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), stat="max", of="temp_max", count_only=True), Turn())) + overall = json.loads(await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), stat="max", of="temp_max", count_only=True), Turn())) assert overall["value"] == round(max(top.values()), 1) and "by_month" not in overall - bad = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), stat="max"), Turn())) + bad = json.loads(await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), stat="max"), Turn())) assert "needs `of`" in bad["error"] -async def test_a_holiday_filter_the_person_never_asked_for_is_dropped_but_a_requested_one_is_kept(station): - from lib.tools import Turn - eco, _ = station - first, last = dates(eco, 60, 1) - args = dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], count_only=True) - plain = json.loads(await eco.tools[2].handler(args, Turn(text="days over 0 degrees"))) - strayed = json.loads(await eco.tools[2].handler({**args, "only": "weekend"}, Turn(text="days over 0 degrees"))) - assert strayed["days_checked"] == plain["days_checked"] > 40 # the weekend filter was dropped: every day counted - asked = json.loads(await eco.tools[2].handler({**args, "only": "weekend"}, Turn(text="how many weekend days over 0 degrees"))) - assert 0 < asked["days_checked"] < 20 # kept: only Saturdays and Sundays - direct = json.loads(await eco.tools[2].handler({**args, "only": "weekend"})) # no question to check against (a direct call) - assert direct["days_checked"] == asked["days_checked"] - - async def test_a_chart_of_holiday_or_weekend_days_says_so_in_its_subtitle(station): from lib.tools import Turn eco, _ = station first, last = dates(eco, 60, 1) - turn = Turn(text="how many weekend days over 0 degrees per month") - await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], + turn = Turn() + await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], count_only=True, group_by="month", only="weekend"), turn) assert turn.charts[0].subtitle.endswith("weekends only · per month") or "weekends only" in turn.charts[0].subtitle -async def test_group_by_is_added_from_the_question_when_the_model_leaves_it_out(station): - from lib.tools import Turn - eco, _ = station - first, last = dates(eco, 60, 1) - args = dict(start_date=str(first), end_date=str(last), where=[{"field": "temp_max", "op": ">", "value": 0}], count_only=True) - turn = Turn(text="days over 0 degrees by month") - out = json.loads(await eco.tools[2].handler(args, turn)) - assert "by_month" in out and len(turn.charts) == 1 # the model said nothing about months; the words did - plain = Turn(text="how many days over 0 degrees") - assert "by_month" not in json.loads(await eco.tools[2].handler(args, plain)) and plain.charts == [] - - -def test_the_field_list_is_in_the_tool_schema_once_and_a_wrong_sort_or_of_field_is_still_caught(): - from lib.ecowitt import days - props = days.PARAMETERS["properties"] - assert "enum" in props["where"]["items"]["properties"]["field"] and "enum" not in props["sort_by"] and "enum" not in props["of"] - from lib.daytable import validate - units = days.FIELD_UNITS - assert "sort_by must be one of" in validate({"sort_by": "nonsense"}, units) and "needs `of`" in validate({"stat": "sum", "of": "nonsense"}, units) - assert "of must be one of" in validate({"stat": "count", "of": "nonsense"}, units) # a count needs no `of`, but a wrong one is caught - - async def test_a_wrong_of_with_a_plain_count_is_an_error_not_a_crash(station): eco, _ = station first, last = dates(eco, 10, 1) @@ -385,16 +350,6 @@ async def test_a_wrong_of_with_a_plain_count_is_an_error_not_a_crash(station): assert "of must be one of" in out["error"] -def test_the_description_names_every_field_and_which_have_a_lowest(): - """The model learns the fields from the description. A reading whose lowest says nothing (0 every night or calm hour) has no _min.""" - import re - from lib.ecowitt import days - both, max_only = (re.search(rf"(\w+(?:, \w+)*) \(_max {kind}\)", days.DESCRIPTION)[1].split(", ") for kind in ("and _min", "only")) - assert all(f"{n}_max" in days.FIELDS and f"{n}_min" in days.FIELDS for n in both) - assert all(f"{n}_max" in days.FIELDS and f"{n}_min" not in days.FIELDS for n in max_only) - assert {n.removesuffix("_max").removesuffix("_min").removesuffix("_avg") for n in days.FIELDS} == {"temp", "rain", "wind_gust", *both, *max_only} - - async def test_a_figure_per_month_with_no_matching_day_promises_no_chart(station): """Highest temperature per month on days over 99°: every month is None, so there is no bar to draw and the model must not be told a chart is attached.""" @@ -402,6 +357,6 @@ async def test_a_figure_per_month_with_no_matching_day_promises_no_chart(station eco, _ = station first, last = dates(eco, 70, 1) turn = Turn() - out = json.loads(await eco.tools[2].handler(dict(start_date=str(first), end_date=str(last), count_only=True, group_by="month", + out = json.loads(await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), count_only=True, group_by="month", stat="max", of="temp_max", where=[{"field": "temp_max", "op": ">", "value": 99}]), turn)) assert out["by_month"] and all(v is None for v in out["by_month"].values()) and "chart" not in out and turn.charts == [] diff --git a/tests/test_ecowitt.py b/tests/test_ecowitt.py index 23fee53d..2447bb41 100644 --- a/tests/test_ecowitt.py +++ b/tests/test_ecowitt.py @@ -4,11 +4,12 @@ import pytest -from lib import intent from lib.tools import Turn from lib.ecowitt import Ecowitt from lib.ecowitt import api as ecowitt_api from tests.fakes import MAC, FakeEcowitt, archived_station, config, ecowitt_transport +from tests import old_tools +from lib.service.names import in_all @pytest.fixture @@ -23,7 +24,7 @@ async def station(tmp_path): async def test_finds_the_station(station): eco, _ = station assert eco.mac == MAC and eco.station_name == "Fairleigh" and eco.longitude == 145.0 - assert "Fairleigh" in eco.describe() and "created" in eco.describe() + assert eco.created is not None async def test_a_station_that_gives_no_longitude_has_none_not_melbournes(tmp_path): @@ -103,7 +104,7 @@ async def test_requests_use_metric_unit_ids(station): async def test_realtime_is_compact_and_local(station): eco, _ = station - out = json.loads(await eco.tools[0].handler({"groups": "outdoor"})) + out = json.loads(await old_tools.weather_now(eco, {"groups": "outdoor"})) assert out["outdoor"]["temperature"] == "12.3 ℃" and out["time"] @@ -111,7 +112,7 @@ async def test_history_gives_extremes_with_times_and_days(station): eco, fake = station today = datetime.now(eco.tz).date() start, end = today - timedelta(days=3), today - timedelta(days=1) - result = json.loads(await eco.tools[1].handler( + result = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{start} 00:00:00", "end_date": f"{end} 23:59:59"})) s = result["series"]["outdoor.temperature"] assert set(s) >= {"low", "high", "low_when", "high_when", "low_date", "high_date", "daily"} @@ -129,7 +130,7 @@ async def test_every_record_has_its_days_time_and_a_tie_goes_to_the_first_day(tm eco, _ = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() start, end = today - timedelta(days=13), today - timedelta(days=2) - out = json.loads(await eco.tools[1].handler({"groups": "outdoor,indoor,pressure,wind,solar_and_uvi", "start_date": f"{start} 00:00:00", + out = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor,indoor,pressure,wind,solar_and_uvi", "start_date": f"{start} 00:00:00", "end_date": f"{end} 23:59:59"})) records = [s for s in out["series"].values() if "low_when" in s] assert len(records) >= 6 and all(s[f"{w}_when"].startswith("at ") for s in records for w in ("low", "high")) @@ -146,16 +147,16 @@ async def test_second_question_is_served_from_the_cache(station): today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=4)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} - first = await eco.tools[1].handler(args) + first = await old_tools.weather_history(eco, args) fake.calls.clear() - assert await eco.tools[1].handler(args) == first + assert await old_tools.weather_history(eco, args) == first assert fake.calls == [] async def test_long_range_uses_daily_data_and_monthly_figures(station): eco, fake = station today = datetime.now(eco.tz).date() - result = json.loads(await eco.tools[1].handler( + result = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today} 00:00:00"})) s = result["series"]["outdoor.temperature"] assert "monthly" in s and "daily" not in s and result["monthly_note"] @@ -175,8 +176,8 @@ async def with_dew(*a, **k): eco.api.history = with_dew day = datetime.now(eco.tz).date() - timedelta(days=2) args = {"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"} - assert "outdoor.dew_point" not in json.loads(await eco.tools[1].handler(args))["series"] - assert "outdoor.dew_point" in json.loads(await eco.tools[1].handler({**args, "include_derived": ["dew_point"]}))["series"] + assert "outdoor.dew_point" not in json.loads(await old_tools.weather_history(eco, args))["series"] + assert "outdoor.dew_point" in json.loads(await old_tools.weather_history(eco, {**args, "include_derived": ["dew_point"]}))["series"] await eco.close() @@ -184,14 +185,14 @@ async def test_chart_request_adds_a_spec(station): eco, _ = station day = datetime.now(eco.tz).date() - timedelta(days=2) turn = Turn() - out = json.loads(await eco.tools[1].handler( + out = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor,indoor", "chart": True, "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, turn)) assert "chart" in out and len(turn.charts[0].panels) == 1 and {s.label for s in turn.charts[0].panels[0].lines} == {"Outdoor", "Indoor"} async def test_bad_dates_are_reported(station): eco, _ = station - assert (await eco.tools[1].handler({"start_date": "nonsense", "end_date": "x"})).startswith("Error: bad date") + assert (await old_tools.weather_history(eco, {"start_date": "nonsense", "end_date": "x"})).startswith("Error: bad date") async def test_warm_then_question_needs_no_new_requests_for_the_tail(station): @@ -243,11 +244,11 @@ async def watch(path, urgent=False, **params): assert marked and not any(marked) marked.clear() today = eco.now().date() - await eco.tools[1].handler({"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=20)} 00:00:00", + await old_tools.weather_history(eco, {"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=20)} 00:00:00", "end_date": f"{today - timedelta(days=10)} 23:59:59"}, Turn()) assert marked and all(marked) # the question's own, and its wind rose's marked.clear() - await eco.tools[1].handler({"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=40)} 00:00:00", + await old_tools.weather_history(eco, {"groups": "outdoor,wind", "start_date": f"{today - timedelta(days=40)} 00:00:00", "end_date": f"{today - timedelta(days=30)} 23:59:59"}, Turn(ahead=True)) assert marked and not any(marked) # a chart drawn ahead: nobody is waiting for it @@ -279,7 +280,7 @@ async def test_archive_caches_every_cycle_so_long_questions_need_no_requests_and fake.calls.clear() today = datetime.now(eco.tz).date() for days in (5, 12, 23): # up to all of the fake station's 25 days - out = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", + out = await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}) assert "Error" not in out[:20], out[:200] assert fake.calls == [] # nothing was fetched while answering @@ -329,14 +330,14 @@ async def test_year_long_questions_get_dated_monthly_figures_once_the_history_is def monthly(out): return json.loads(out)["series"]["outdoor.temperature"]["monthly"] - before = monthly(await eco.tools[1].handler(args)) # nothing cached: daily figures, values only + before = monthly(await old_tools.weather_history(eco, args)) # nothing cached: daily figures, values only assert all("low_when" not in m for m in before.values()) await eco.close() (tmp_path / "archived").mkdir() eco, fake = await archived_station(tmp_path / "archived", archived_cache) # the whole history archived turn = Turn() - out = await eco.tools[1].handler({**args, "chart": True}, turn) + out = await old_tools.weather_history(eco, {**args, "chart": True}, turn) spec = turn.charts[0] after = monthly(out) assert len(after) >= 6 and all({"low_when", "low_date", "high_when", "high_date"} <= set(m) for m in after.values()) @@ -531,7 +532,7 @@ async def test_a_failed_history_request_tells_the_model_and_the_log_no_key(tmp_p eco = Ecowitt(config(tmp_path, ecowitt_api_key="SECRET-API", ecowitt_app_key="SECRET-APP"), transport=transport) await eco.start() day = datetime.now(eco.tz).date() - timedelta(days=3) - out = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, Turn()) + out = await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{day} 00:00:00", "end_date": f"{day} 23:59:59"}, Turn()) await eco.close() assert "HTTP 502" in out and "SECRET" not in out and "SECRET" not in caplog.text @@ -619,7 +620,7 @@ def test_direction_summary_of_a_variable_wind_and_averaged_data(): async def test_history_reports_direction_by_compass_point_not_a_range(tmp_path, archived_cache): eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{today - timedelta(days=7)} 00:00:00", + out = json.loads(await old_tools.weather_history(eco, {"groups": "wind", "start_date": f"{today - timedelta(days=7)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"})) direction = out["series"]["wind.wind_direction"] assert direction["most_common"].startswith("N ") and "low" not in direction and "high" not in direction @@ -627,7 +628,7 @@ async def test_history_reports_direction_by_compass_point_not_a_range(tmp_path, assert 20 <= int(direction["calm"].split("%")[0]) <= 30 # midnight to 6am had no wind: about a quarter assert len(direction["daily"]) == 6 and all(v.startswith("N ") for v in direction["daily"].values()) assert "high" in out["series"]["wind.wind_gust"] # speeds are unchanged - again = json.loads(await eco.tools[1].handler({"groups": "wind", "chart": True, "include_derived": [], # a chart of direction alone + again = json.loads(await old_tools.weather_history(eco, {"groups": "wind", "chart": True, "include_derived": [], # a chart of direction alone "start_date": f"{today - timedelta(days=3)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}, Turn())) assert "wind.wind_direction" in again["series"] @@ -646,7 +647,7 @@ def recorded(self, groups): # the wind rose's own fetcher, whose reads are cou monkeypatch.setattr(query.Fetcher, "sibling", recorded) today = eco.now().date() turn = Turn(chart_field="wind") - out = json.loads(await eco.tools[1].handler({"groups": "wind", "chart": True, "chart_field": "wind", + out = json.loads(await old_tools.weather_history(eco, {"groups": "wind", "chart": True, "chart_field": "wind", "start_date": f"{today - timedelta(days=30)} 00:00:00"}, turn)) assert out["series"]["wind.wind_direction"] and turn.charts[0].compass assert len(made) == 1 and made[0].ranges <= 2 # the archived days and today in one read (two in the first hours of the local day, while yesterday's last readings are not yet settled), not one for each of 31 days @@ -663,7 +664,7 @@ async def test_the_wind_chart_carries_the_compass_beside_the_speed_line(tmp_path args = {"groups": "wind", "chart": True, "start_date": f"{today - timedelta(days=6)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} turn = Turn() - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await old_tools.weather_history(eco, args, turn)) specs = turn.charts assert len(specs) == 1 and specs[0].compass and "compass" in out["chart"] # one image: speed line and compass spec = specs[0] @@ -695,7 +696,7 @@ async def test_a_chart_asked_for_in_the_persons_words_is_drawn_even_if_the_model long = {**short, "start_date": f"{today - timedelta(days=5)} 00:00:00"} # four days: always a chart for args, asked, expected in ((short, False, 0), (short, True, 1), (long, False, 1)): # one wind chart: line and compass turn = Turn(chart_asked=asked) - await eco.tools[1].handler(args, turn) + await old_tools.weather_history(eco, args, turn) assert len(turn.charts) == expected await eco.close() @@ -709,7 +710,7 @@ async def test_the_chart_plots_the_field_the_question_is_about(tmp_path): "end_date": f"{today - timedelta(days=2)} 23:59:59"} async def chart_of(asked_field=None, **extra): turn = Turn(chart_field=asked_field) # asked_field: from the person's words - await eco.tools[1].handler({**base, **extra}, turn) + await old_tools.weather_history(eco, {**base, **extra}, turn) return turn.charts[0] assert (await chart_of()).title == "Temperature" # the default assert (await chart_of(chart_field="wind_gust", groups="wind")).title == "Wind" @@ -726,7 +727,7 @@ async def test_a_chart_is_bucketed_to_the_point_budget_and_every_period_carries_ async def spec_for(days_back): turn = Turn() - await eco.tools[1].handler({"groups": "outdoor", "chart": True, + await old_tools.weather_history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=days_back)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) return turn.charts[0] @@ -749,7 +750,7 @@ async def test_a_multi_year_chart_uses_cached_30_minute_data_for_the_newest_year eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() turn = Turn() - await eco.tools[1].handler({"groups": "outdoor", "chart": True, + await old_tools.weather_history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=540)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 00:00:00"}, turn) # settled: no request in the small hours spec = turn.charts[0] @@ -769,7 +770,7 @@ async def test_the_wind_chart_is_the_average_speed_shaded_up_to_the_gusts(tmp_pa async def wind_chart(days, **extra): turn = Turn() - await eco.tools[1].handler({"groups": "wind", "chart": True, "chart_field": "wind_gust", + await old_tools.weather_history(eco, {"groups": "wind", "chart": True, "chart_field": "wind_gust", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59", **extra}, turn) return turn.charts[0] @@ -806,7 +807,7 @@ async def test_a_5_minute_temperature_line_is_lightly_smoothed_and_its_records_s async def chart(): turn = Turn() - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await old_tools.weather_history(eco, args, turn)) return out, turn.charts[0] out, smooth = await chart() monkeypatch.setattr(history, "SMOOTH_SERIES", set()) @@ -832,7 +833,7 @@ async def spy(self): eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 00:00:00"} - await eco.tools[1].handler(args) + await old_tools.weather_history(eco, args) assert set(seen) == {"30min"} and fake.calls == [] # held: no daily records, no requests await eco.close() @@ -841,15 +842,15 @@ async def test_averages_come_with_the_answer(tmp_path, archived_cache): eco, _ = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() span = {"groups": "outdoor", "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"} - plain = json.loads(await eco.tools[1].handler(span)) + plain = json.loads(await old_tools.weather_history(eco, span)) assert "average" not in plain["series"]["outdoor.temperature"] # highs and lows are the default - week = json.loads(await eco.tools[1].handler({**span, "average": True})) + week = json.loads(await old_tools.weather_history(eco, {**span, "average": True})) temp = week["series"]["outdoor.temperature"] days = list(temp["daily"].values()) assert float(temp["average"]) == pytest.approx(sum(float(d["avg"]) for d in days) / len(days), abs=0.1) assert float(temp["low"]) <= float(temp["average"]) <= float(temp["high"]) assert all(float(d["low"]) <= float(d["avg"]) <= float(d["high"]) and "_sum" not in d for d in days) - year = json.loads(await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", + year = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=200)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59", "average": True})) months = year["series"]["outdoor.temperature"]["monthly"] assert all("avg" in m and "_sum" not in m for m in months.values()) and "average" in year["series"]["outdoor.temperature"] @@ -865,7 +866,7 @@ async def test_an_average_question_gets_a_caption_that_leads_with_the_average_an hints = {} for asked in (False, True): turn = Turn(average_asked=asked) - out = json.loads(await eco.tools[1].handler(args, turn)) + out = json.loads(await old_tools.weather_history(eco, args, turn)) spec = turn.charts[0] hints[asked] = out["chart"] assert ("average" in out["series"]["outdoor.temperature"]) is asked # highs and lows by default @@ -882,7 +883,7 @@ async def test_asking_for_an_average_uses_daily_points_even_for_a_short_period(t subtitles = {} for asked in (False, True): turn = Turn(average_asked=asked) - await eco.tools[1].handler(args, turn) + await old_tools.weather_history(eco, args, turn) subtitles[asked] = turn.charts[0].subtitle assert "daily averages" not in subtitles[False] and "daily averages" in subtitles[True] and "range shaded" in subtitles[True] await eco.close() @@ -898,7 +899,7 @@ async def test_resolution_follows_the_length_of_the_period(tmp_path): eco = Ecowitt(config(tmp_path / str(days)), transport=transport) await eco.start() today = datetime.now(eco.tz).date() - await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", + await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=days)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"}) calls = [c for c in fake.calls if c.get("path") == "history"] seen[days] = {c["cycle_type"]: sum(1 for x in calls if x["cycle_type"] == c["cycle_type"]) for c in calls} @@ -1006,16 +1007,16 @@ async def test_weather_link_reads_the_cache_only_and_charts_rain_under_the_readi eco, fake = await archived_station(tmp_path, archived_cache) today = datetime.now(eco.tz).date() turn = Turn() - out = json.loads(await eco.tools[3].handler({"start_date": f"{today - timedelta(days=20)}", + out = json.loads(await old_tools.weather_link(eco, {"start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, turn)) specs = turn.charts assert fake.calls == [] and out["resolution"].startswith("30-minute") and out["slots"] > 500 assert set(out["by_change_before"]) == {"falling", "steady", "rising"} and "chart" in out assert len(specs) == 1 and specs[0].title == "Pressure, Rain" and specs[0].panels[0].bars.width == 6 * 3600 assert render(specs[0], eco.tz)[:4] == b"\x89PNG" - assert "error" in json.loads(await eco.tools[3].handler({"driver": "nonsense"})) + assert "error" in json.loads(await old_tools.weather_link(eco, {"driver": "nonsense"})) wind = Turn() # shaded as plot_chart shades it: up to the gusts (48 km/h at most) - await eco.tools[3].handler({"driver": "wind", "start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, wind) + await old_tools.weather_link(eco, {"driver": "wind", "start_date": f"{today - timedelta(days=20)}", "end_date": f"{today - timedelta(days=2)}"}, wind) line = wind.charts[0].panels[0].lines[0] assert line.records["high"][1] == max(line.high) == 48.0 await eco.close() @@ -1125,7 +1126,7 @@ async def test_weather_link_says_which_series_is_missing(tmp_path, driver, serie eco = Ecowitt(config(tmp_path), transport=transport) # nothing cached at all await eco.start() today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[3].handler({"start_date": str(today - timedelta(days=9)), "end_date": str(today - timedelta(days=2)), + out = json.loads(await old_tools.weather_link(eco, {"start_date": str(today - timedelta(days=9)), "end_date": str(today - timedelta(days=2)), **({"driver": driver} if driver else {})})) assert f"{series} or rainfall (rainfall.daily)" in out["note"] and "chart" not in out assert f"falling = {falling} or more" in out["how_to_read"] # the change that counts, in the reading's unit @@ -1141,7 +1142,7 @@ async def test_any_readings_can_be_plotted_together_one_panel_each(tmp_path, arc async def ask_chart(asked_stack=(), **extra): turn = Turn(chart_fields=list(asked_stack)) # asked_stack: from the person's words - out = json.loads(await eco.tools[1].handler({**args, **extra}, turn)) + out = json.loads(await old_tools.weather_history(eco, {**args, **extra}, turn)) return out, turn.charts out, specs = await ask_chart(chart_fields=["temperature", "rain"]) # the model's choice; rain's group is added for it assert len(specs) == 1 and specs[0].title == "Temperature, Rain" and [p.label for p in specs[0].panels] == ["Temperature"] @@ -1186,7 +1187,7 @@ async def test_weather_now_carries_the_emoji_next_to_the_readings(tmp_path): transport, _ = ecowitt_transport() eco = Ecowitt(config(tmp_path), transport=transport) await eco.start() - out = json.loads(await eco.tools[0].handler({"groups": "outdoor"})) + out = json.loads(await old_tools.weather_now(eco, {"groups": "outdoor"})) assert out["emoji"] == {"outdoor.temperature": "🧥"} # the fake station reports 12.3 degrees await eco.close() @@ -1197,7 +1198,7 @@ async def test_rain_on_its_own_is_drawn_as_daily_columns_not_as_the_running_coun await eco.start() today = datetime.now(eco.tz).date() turn = Turn() - out = json.loads(await eco.tools[1].handler({"groups": "rainfall", "chart": True, + out = json.loads(await old_tools.weather_history(eco, {"groups": "rainfall", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn)) (chart,) = turn.charts @@ -1212,7 +1213,7 @@ async def test_a_dew_point_chart_plots_the_dew_point_and_never_quietly_a_tempera await eco.start() today = datetime.now(eco.tz).date() turn = Turn(chart_field="dew_point") - out = json.loads(await eco.tools[1].handler({"groups": "outdoor", "chart": True, + out = json.loads(await old_tools.weather_history(eco, {"groups": "outdoor", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn)) assert turn.charts and turn.charts[0].title == "Dew point" and "outdoor.dew_point" in out["series"] @@ -1224,8 +1225,8 @@ async def test_weather_all_week_is_a_stack_of_every_reading_the_station_has(tmp_ eco = Ecowitt(config(tmp_path), transport=transport) await eco.start() today = datetime.now(eco.tz).date() - turn = Turn(chart_asked=True, chart_fields=intent.chart_fields("weather all week")) - await eco.tools[1].handler({"groups": "outdoor,indoor", "chart": True, "start_date": f"{today - timedelta(days=7)} 00:00:00", + turn = Turn(chart_asked=True, chart_fields=list(in_all())) + await old_tools.weather_history(eco, {"groups": "outdoor,indoor", "chart": True, "start_date": f"{today - timedelta(days=7)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) assert len(turn.charts) == 1 # one image: no separate wind chart with the compass chart = turn.charts[0] @@ -1233,14 +1234,6 @@ async def test_weather_all_week_is_a_stack_of_every_reading_the_station_has(tmp_ await eco.close() -def test_a_reading_named_as_a_group_becomes_its_group_and_an_unknown_name_is_dropped(): - from lib.ecowitt.source import parse_groups - assert parse_groups("pressure,humidity") == ["pressure", "outdoor"] - assert parse_groups("rain, dew_point, wind, outdoor") == ["rainfall", "outdoor", "wind"] - assert parse_groups("outdoor.temperature,bogus") == ["outdoor"] and parse_groups("bogus") == ["outdoor", "indoor"] - assert parse_groups(["indoor", "rainfall_piezo"]) == ["indoor", "rainfall_piezo"] - - async def test_a_job_stops_asking_once_ecowitt_has_refused_twice(tmp_path): from lib.ecowitt.api import EcowittError from tests.fakes import fetcher_on, storage_with @@ -1268,7 +1261,7 @@ async def test_each_weather_chart_carries_its_reading_so_it_is_drawn_in_that_rea today = datetime.now(eco.tz).date() for field, reading in (("wind_gust", "wind"), ("dew_point", "dew_point"), ("relative", "pressure")): turn = Turn(chart_field=field) - await eco.tools[1].handler({"groups": "outdoor,wind,pressure", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", + await old_tools.weather_history(eco, {"groups": "outdoor,wind,pressure", "chart": True, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) panel = turn.charts[0].panels[0] assert panel.reading == reading and _colour(panel.lines[0], 0, panel.reading) == READING_COLOURS[reading] @@ -1283,7 +1276,7 @@ async def test_a_chart_field_may_be_a_readings_name_or_its_field_however_it_is_w for said, title in (("pressure", "Pressure"), ("relative", "Pressure"), ("dew_point", "Dew point"), ("Dew Point", "Dew point"), ("wind gust", "Wind")): turn = Turn() # the reading's group is added for it - await eco.tools[1].handler({"groups": "outdoor", "chart": True, "chart_field": said, + await old_tools.weather_history(eco, {"groups": "outdoor", "chart": True, "chart_field": said, "start_date": f"{today - timedelta(days=9)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"}, turn) assert turn.charts and turn.charts[0].title == title, said await eco.close() @@ -1379,18 +1372,18 @@ async def test_weather_now_is_served_from_the_minute_old_live_reading_and_asks_a eco, fake = station real_time = lambda: [c for c in fake.calls if c.get("path") == "real_time"] groups = "outdoor,indoor,pressure,wind,rainfall,solar_and_uvi" - out = json.loads(await eco.tools[0].handler({"groups": groups})) + out = json.loads(await old_tools.weather_now(eco, {"groups": groups})) assert len(real_time()) == 1 # nothing cached yet: a request of its own await eco.live_rain() # the keep-warm's minute check takes every group assert real_time()[-1]["call_back"] == groups and len(real_time()) == 2 - cached = json.loads(await eco.tools[0].handler({"groups": groups})) + cached = json.loads(await old_tools.weather_now(eco, {"groups": groups})) assert len(real_time()) == 2 and cached["outdoor"] == out["outdoor"] # no request: the report is instant - json.loads(await eco.tools[0].handler({"groups": "outdoor"})) + json.loads(await old_tools.weather_now(eco, {"groups": "outdoor"})) assert len(real_time()) == 2 # a subset of those groups too - json.loads(await eco.tools[0].handler({"groups": "rainfall_piezo"})) + json.loads(await old_tools.weather_now(eco, {"groups": "rainfall_piezo"})) assert len(real_time()) == 3 # a group it doesn't hold: asks eco._live = (time.time() - 100, eco._live[1]) # older than 90 s: asks - json.loads(await eco.tools[0].handler({"groups": groups})) + json.loads(await old_tools.weather_now(eco, {"groups": groups})) assert len(real_time()) == 4 @@ -1398,8 +1391,8 @@ async def test_a_two_week_result_keeps_only_the_days_of_the_records_unless_every eco, _ = station today = datetime.now(eco.tz).date() args = {"groups": "outdoor", "start_date": f"{today - timedelta(days=13)} 00:00:00", "end_date": f"{today - timedelta(days=1)} 23:59:59"} - short = json.loads(await eco.tools[1].handler(args, Turn()))["series"]["outdoor.temperature"] - full = json.loads(await eco.tools[1].handler(args, Turn(per_day=True)))["series"]["outdoor.temperature"] + short = json.loads(await old_tools.weather_history(eco, args, Turn()))["series"]["outdoor.temperature"] + full = json.loads(await old_tools.weather_history(eco, args, Turn(per_day=True)))["series"]["outdoor.temperature"] assert len(full["daily"]) == 13 and 1 <= len(short["daily"]) <= 2 assert short["high"] == full["high"] and set(short["daily"]) <= set(full["daily"]) @@ -1437,9 +1430,6 @@ async def test_rain_older_than_the_30_minute_readings_is_drawn_from_the_daily_re held = storage.read_now(history_on, f.mac, ["rainfall"], [], f.epoch(q.start), f.epoch(q.end), False, [], True) daily = q._rain_bars(held) assert q.rain_from_daily and len(daily.x) >= 59 and round(sum(daily.y), 1) == 120.0 and daily.per == "day" - q.turn = Turn(text="rain by month for 2 months") - monthly = q._rain_bars(held) - assert monthly.per == "month" and monthly.values and round(sum(monthly.y), 1) == 120.0 and len(monthly.x) in (2, 3) storage.close() @@ -1456,7 +1446,7 @@ def _history(p): with caplog.at_level(logging.INFO): await eco.start() today = datetime.now(eco.tz).date() - reply = await eco.tools[1].handler({"groups": "outdoor", "start_date": f"{today - timedelta(days=1)} 00:00:00", + reply = await old_tools.weather_history(eco, {"groups": "outdoor", "start_date": f"{today - timedelta(days=1)} 00:00:00", "end_date": f"{today} 23:59:59"}) assert reply.startswith("Error: no history data returned") text = caplog.text @@ -1474,21 +1464,22 @@ def test_the_live_summary_gives_rain_first_then_a_few_readings_and_skips_what_is async def test_a_single_reading_chart_is_labelled_with_the_reading_not_its_group(tmp_path, archived_cache): - from lib import intent from lib.timeutil import now_local from tests.fakes import archived_station eco, _ = await archived_station(tmp_path, archived_cache) - async def lines(text): - read = intent.read(text, now_local(eco.tz)) - turn = Turn(chart_asked=read.chart_asked, chart_field=read.chart_field, chart_fields=read.chart_fields, text=text) - await eco.tools[1].handler(read.fast[1], turn) + async def lines(groups, field): + now = now_local(eco.tz) + turn = Turn(chart_asked=True, chart_field=field) + await old_tools.weather_history(eco, {"groups": groups, "chart": True, "chart_field": field, + "start_date": f"{now - timedelta(hours=24):%Y-%m-%d %H:%M:%S}", + "end_date": f"{now:%Y-%m-%d %H:%M:%S}"}, turn) (panel,) = turn.charts[0].panels return [line.label for line in panel.lines] - assert await lines("UV chart 1d") == ["UV index"] # not "Solar and uvi" - assert await lines("Solar radiation chart 1d") == ["Solar radiation"] - assert sorted(await lines("Temperature chart 1d")) == ["Indoor", "Outdoor"] # these two tell the lines apart, so they keep their names - assert await lines("Wind chart 1d") == ["Wind"] + assert await lines("solar_and_uvi", "uv") == ["UV index"] # not "Solar and uvi" + assert await lines("solar_and_uvi", "solar") == ["Solar radiation"] + assert sorted(await lines("outdoor,indoor", "temperature")) == ["Indoor", "Outdoor"] # these two tell the lines apart, so they keep their names + assert await lines("wind", "wind") == ["Wind"] await eco.close() @@ -1531,7 +1522,7 @@ def _history(self, p): eco = Ecowitt(cfg, transport=httpx.MockTransport(Retaining())) await eco.start() last = datetime.now(eco.tz).date() - timedelta(days=200) - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{last - timedelta(days=6)} 00:00:00", + out = json.loads(await old_tools.weather_history(eco, {"groups": "wind", "start_date": f"{last - timedelta(days=6)} 00:00:00", "end_date": f"{last} 23:59:59"})) await eco.close() assert len(out["series"]["wind.wind_direction"]["daily"]) == 7 @@ -1548,7 +1539,7 @@ def with_a_failure(self, *args): self.wind = SimpleNamespace(errors=["5min 16 Oct 2026 - 16 Oct 2026: HTTP 502"], seconds=0.0) monkeypatch.setattr(query.HistoryQuery, "_summarise_direction", with_a_failure) today = datetime.now(eco.tz).date() - out = json.loads(await eco.tools[1].handler({"groups": "wind", "start_date": f"{today - timedelta(days=3)} 00:00:00", + out = json.loads(await old_tools.weather_history(eco, {"groups": "wind", "start_date": f"{today - timedelta(days=3)} 00:00:00", "end_date": f"{today - timedelta(days=2)} 23:59:59"})) await eco.close() assert "HTTP 502" in " ".join(out.get("missing", [])) and "warning" in out diff --git a/tests/test_evals.py b/tests/test_evals.py index 0fa45048..c77459f5 100644 --- a/tests/test_evals.py +++ b/tests/test_evals.py @@ -28,18 +28,32 @@ def test_every_kind_of_question_metric_and_chart_has_a_saved_case(): def test_the_call_checker_reports_what_is_wrong(): - expect = {"tools": ["weather_days"], "first_tool": "weather_days", - "args": {"weather_days": {"start_date": "2026-09-05", "where": {"absent": True}, "sort_by": {"any_of": ["temp_max"]}}}} - good = [("weather_days", {"start_date": "2026-09-05", "sort_by": "temp_max"})] + expect = {"tools": ["days"], "first_tool": "days", + "args": {"days": {"period": "this month", "where": {"absent": True}, "sort_by": {"any_of": ["temp_max"]}}}} + good = [("days", {"period": "this month", "sort_by": "temp_max"})] assert evalkit.check_calls(good, expect) == [] - bad = [("weather_history", {}), ("weather_days", {"start_date": "2026-09-01", "where": [{"field": "rain"}], "sort_by": "rain"})] + bad = [("summary", {}), ("days", {"period": "last month", "where": [{"field": "rain"}], "sort_by": "rain"})] fails = " | ".join(evalkit.check_calls(bad, expect)) - assert "first tool" in fails and "start_date" in fails and "where" in fails and "sort_by" in fails - assert evalkit.check_calls([], {"tools": ["weather_link"]}) == ["did not call weather_link (called: nothing)"] - assert evalkit.check_calls([("weather_now", {})], {"not_tools": ["weather_now"]}) == ["should not have called weather_now"] + assert "first tool" in fails and "period" in fails and "where" in fails and "sort_by" in fails + assert evalkit.check_calls([], {"tools": ["relate"]}) == ["did not call relate (called: nothing)"] + assert evalkit.check_calls([("current", {})], {"not_tools": ["current"]}) == ["should not have called current"] assert evalkit.check_args({"g": ["a", "b"]}, {"g": {"has": ["a"]}}) == [] and evalkit.check_args({"g": "x"}, {"g": {"regex": "^y"}}) -def test_the_real_tool_definitions_are_what_the_live_run_offers(): - tools = evalkit.make_tools([]) - assert set(tools.by_name) == set(evalkit.tool_names()) +async def test_the_bots_live_run_is_its_own_request_and_its_shortcuts_ask_no_model(): + """--live asks the model as the bot does (its prompt: the persona, the server's instructions, the time; the ten tools; its effort); + a question it answers in code gives its fixed calls, and the model isn't asked.""" + from tests.test_agent import FakeLLM + from tests.test_service_evals import case + client = FakeLLM([[("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})], "Done."]) + calls, reply = await evalkit.run_live(case("3m-average"), client, "m") + assert calls == [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})] and reply == "Done." + first = client.requests[0] + assert first["messages"][0] == {"role": "system", "content": evalkit.bot_system()} + assert first["messages"][0]["content"].startswith("You are a friendly weather bot on Telegram") and first["tool_choice"] == "auto" + assert [t["function"]["name"] for t in first["tools"]] == evalkit.service_tool_names() + assert first["extra_body"]["reasoning"]["effort"] == evalkit.read(case("3m-average")).effort + assert await evalkit.run_live(case("report"), None, "m") == ( + [("current", {}), ("pollen", {}), ("forecast", {"period": "next 3 days"})], "(answered in code)") + calls, _ = await evalkit.run_live(case("button-rain-chart"), None, "m") + assert calls == [("summary", {"readings": ["rain"], "period": "7d", "chart": True})] diff --git a/tests/test_forecast.py b/tests/test_forecast.py index 00719770..0d0626b6 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -7,6 +7,7 @@ from lib.forecast import Forecast from lib.forecast.source import WMO, day_label, describe_day, temps from tests.fakes import TZ, config +from tests import old_tools def ensemble_body(per_day): @@ -82,7 +83,7 @@ async def test_today_and_the_next_days_come_from_open_meteo_by_local_date(tmp_pa today = datetime.now(TZ).date() assert forecast.lines() == ["Today: 🌧️ Rain. 11–16°C, 50% chance of at least 1 mm", f"{today + timedelta(days=1):%A}: ☀️ Clear. 12–20°C, 0% chance of at least 1 mm"] - out = json.loads(await forecast.handle({"days": 3})) + out = json.loads(await old_tools.forecast(forecast, {"days": 3})) assert len(out["lines"]) == 3 and out["lines"][2] == f"{today + timedelta(days=2):%A}: ⛈️ Thunderstorm. 9–14°C, 75% chance of at least 1 mm" assert out["place"] == "Melbourne" and out["source"] == "Open-Meteo" and "Tomorrow" not in " ".join(out["lines"]) assert "tag" not in out and {c for c in calls if isinstance(c, str)} == {"api.open-meteo.com", "ensemble-api.open-meteo.com"} @@ -92,8 +93,8 @@ async def test_today_and_the_next_days_come_from_open_meteo_by_local_date(tmp_pa async def test_the_place_is_the_configured_name(tmp_path): forecast, _ = make(tmp_path, place="Geelong") await forecast.start() - assert json.loads(await forecast.handle({}))["place"] == "Geelong" - assert json.loads(await forecast.handle({}))["time"] # when it was fetched, for the report's heading + assert json.loads(await old_tools.forecast(forecast, {}))["place"] == "Geelong" + assert json.loads(await old_tools.forecast(forecast, {}))["time"] # when it was fetched, for the report's heading await forecast.close() @@ -126,10 +127,10 @@ async def test_the_station_location_is_used_when_none_is_configured_and_without_ async def test_a_direct_forecast_question_shows_the_whole_week_unless_fewer_days_are_asked_for(tmp_path): forecast, _ = make(tmp_path) await forecast.start() - assert len(json.loads(await forecast.handle({}))["lines"]) == 3 # every day Open-Meteo gave (the test data has three) - assert len(json.loads(await forecast.handle({"days": 2}))["lines"]) == 2 - assert len(json.loads(await forecast.handle({"days": "nonsense"}))["lines"]) == 3 - assert len(json.loads(await forecast.handle({"days": 30}))["lines"]) == 3 + assert len(json.loads(await old_tools.forecast(forecast, {}))["lines"]) == 3 # every day Open-Meteo gave (the test data has three) + assert len(json.loads(await old_tools.forecast(forecast, {"days": 2}))["lines"]) == 2 + assert len(json.loads(await old_tools.forecast(forecast, {"days": "nonsense"}))["lines"]) == 3 + assert len(json.loads(await old_tools.forecast(forecast, {"days": 30}))["lines"]) == 3 await forecast.close() diff --git a/tests/test_forecast_alert.py b/tests/test_forecast_alert.py index 9a934a57..844177bd 100644 --- a/tests/test_forecast_alert.py +++ b/tests/test_forecast_alert.py @@ -7,6 +7,7 @@ from lib.tools import Turn from tests.fakes import TZ, config from tests.test_forecast import make +from tests import old_tools TODAY = date(2026, 10, 3) @@ -127,18 +128,24 @@ async def test_what_was_sent_survives_a_restart_and_is_not_repeated(tmp_path): assert len(bot.sent) == 1 # the new baseline was saved too -async def test_the_forecast_tool_notes_the_days_it_gave_for_the_chat_and_a_failure_notes_none(tmp_path): +async def forecast_result(forecast, period="next 2 days") -> dict: + """What the service's forecast answers the model.""" + from lib.service import Service + from lib.service.context import Context + return json.loads(await Service.of(Context(forecast=forecast, tz=TZ))["forecast"].call({"period": period})) + + +async def test_the_forecast_days_a_result_shows_are_noted_for_the_chat_and_a_failure_notes_none(tmp_path): + from types import SimpleNamespace as NS + from lib.bot import Bot forecast, _ = make(tmp_path) await forecast.start() - turn = Turn() - await forecast.handle({"days": 2}, turn) - assert [d["date"] for d in turn.forecast_shown] == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] - assert turn.forecast_shown[0]["max_c"] == 16 and turn.forecast_shown[0]["rain_chance_pct"] == 40 - empty = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, None) - empty.days, turn = [], Turn() - assert "error" in json.loads(await empty.handle({"cached": True}, turn)) and turn.forecast_shown == [] + bot = Bot(NS(tz=TZ), None, [forecast], AlertState(tmp_path / "s.json")) + shown = bot._shown_forecast(await forecast_result(forecast)) + assert [d["date"] for d in shown] == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] + assert shown[0]["max_c"] == 16 and shown[0]["rain_chance_pct"] == 40 + assert bot._shown_forecast({"error": "No forecast is available right now."}) == [] and bot._shown_forecast(None) == [] await forecast.close() - await empty.close() async def test_a_delivered_answer_records_the_forecast_for_its_chat_and_an_undelivered_one_does_not(tmp_path): @@ -153,10 +160,10 @@ async def test_a_delivered_answer_records_the_forecast_for_its_chat_and_an_undel class Agent: tools = None - async def run(self, messages, system, effort, first_call=None, turn=None, **k): - await forecast.handle({"days": 2}, turn) + async def run(self, messages, system, effort, turn=None, **k): + turn.results.append(("forecast", {"period": "next 2 days"}, await forecast_result(forecast))) # (as lib/model_tools.py keeps it) return "Today: showers" - bot = Bot(NS(tz=TZ), Agent(), [], state) + bot = Bot(NS(tz=TZ), Agent(), [forecast], state) def update(fail): async def reply_text(body, **kw): diff --git a/tests/test_history.py b/tests/test_history.py index 317c996e..443e7bd6 100644 --- a/tests/test_history.py +++ b/tests/test_history.py @@ -6,7 +6,8 @@ import pytest -from lib.history import MAX_ROWS, History, finest_fit, interval_starts +from lib.history import MAX_ROWS, finest_fit, interval_starts +from tests.old_tools import History from lib.storage import Storage from lib.storage.catalogue import CLOUD from lib.timeutil import local_epoch, when @@ -59,17 +60,16 @@ async def ask(history: History, **args) -> dict: return json.loads(await history.handle(args, Turn())) -def offered(history: History, turn: Turn | None = None) -> list[str]: - return history.tools[0].schema(turn)["function"]["parameters"]["properties"]["metric"]["enum"] +def offered(history: History) -> list[str]: + return list(history.metrics) def test_each_sensor_offers_what_it_has_sent_and_rain_as_the_mm_that_fell(storage): names = offered(tool(storage)) assert {"outdoor.temperature", "outdoor.humidity", "indoor.temperature", "indoor.app_temp", "wind.wind_gust", "rainfall.rain", "rainfall.rain_rate", "air.pm2_5", "air.co2"} <= set(names) - assert not {"outdoor.dew_point", "indoor.humidity", "rainfall.event", "rainfall.daily", "air.air_temperature"} & set(names) - assert {"rainfall_piezo.rain", "solar_and_uvi.uvi"} <= set(names) # (groups with nothing recorded yet offer their whole kind) - assert "air.air_temperature" in offered(tool(storage), Turn(air_extra=True)) # the air sensor's own: only when the words name it + assert not {"outdoor.dew_point", "indoor.humidity", "rainfall.event", "rainfall.daily"} & set(names) + assert {"rainfall_piezo.rain", "solar_and_uvi.uvi", "air.air_temperature"} <= set(names) # (groups with nothing recorded yet: their whole kind) assert [n for n in offered(tool(storage, eco=False)) if not n.startswith("air.")] == [] assert [n for n in offered(tool(storage, air=False)) if n.startswith("air.")] == [] diff --git a/tests/test_intent.py b/tests/test_intent.py index 49c2fb27..a25b8255 100644 --- a/tests/test_intent.py +++ b/tests/test_intent.py @@ -1,14 +1,23 @@ -from datetime import datetime, timedelta +"""intent: the reasoning effort from the words, and the few shortcuts the bot answers in code (docs/mcp-service.md 4): the report, +the gauges, "weather now" and a named reading's chart and a period, each a fixed call to a service tool. Everything else is the +model's.""" -from lib import intent -from lib.service import names as service_names +from datetime import datetime +from zoneinfo import ZoneInfo + +import pytest + +from lib import intent, templates +from lib.alerts import pictures +from lib.service.names import Catalogue from tests.fakes import EVERY_SOURCE -NOW = datetime(2026, 9, 29, 14, 5) # a Tuesday +TZ = ZoneInfo("Australia/Melbourne") +NOW = datetime(2026, 9, 29, 14, 5, tzinfo=TZ) # a Tuesday -def call(text, sources=("Ecowitt", "AirGradient")): - return intent.fast_call(text, NOW, sources) +def chart(text, catalogue=None): + return intent.chart_call(text, NOW, TZ, catalogue) def test_only_looking_ahead_and_descriptions_reason_a_little(): @@ -28,169 +37,6 @@ def test_asking_to_think_try_or_reason_gives_medium_reasoning_to_any_question(): assert intent.reasoning_effort(text) == "none", text -def test_chat_needs_no_data(): - assert not intent.needs_data("thanks, that's great") - assert intent.needs_data("how hot is it") - - -def test_every_reading_named_needs_its_data_but_chat_words_like_cool_or_feeling_do_not(): - for asked in ("vpd now", "what's the uvi", "dewpoint 90d", "solar radiation today", "ultraviolet", "precipitation this week"): - assert intent.needs_data(asked), asked - for chat in ("cool, thanks", "feeling better now", "that's apparent"): - assert not intent.needs_data(chat), chat - - -def test_highs_and_lows_go_fast(): - name, args, _ = call("what was this week's high and low?") - assert name == "weather_history" - assert args == {"groups": "outdoor,indoor", "chart": True, "start_date": "2026-09-23 00:00:00", - "end_date": "2026-09-29 23:59:59"} - - -def test_single_day_has_no_chart_and_respects_indoor(): - _, args, _ = call("indoor high yesterday") - assert args["groups"] == "indoor" and args["chart"] is False - assert args["start_date"] == "2026-09-28 00:00:00" - - -def test_last_24_hours_is_rolling(): - _, args, _ = call("graph the temperature last 24 hours") - assert args["start_date"] == "2026-09-28 14:05:00" and args["end_date"] == "2026-09-29 14:05:00" - - -def test_anything_else_takes_the_normal_path(): - assert call("will it rain tomorrow?") is None - assert call("compare this week and last week highs") is None - assert call("highest wind this week")[1]["groups"] == "wind" # a plain highs question is answered in code - assert call("hello") is None - - -def test_air_now_and_air_chart(): - assert call("how's the air?")[:2] == ("air_quality", {}) - name, args, _ = call("graph PM2.5 and CO2 this week") - assert name == "air_quality" and args["chart"] and args["metrics"] == ["pm2_5", "co2"] - assert args["start_date"] == "2026-09-23 00:00:00" - assert call("chart the air quality")[1]["metrics"] == ["pm2_5"] - assert call("air quality yesterday")[1]["start_date"] == "2026-09-28 00:00:00" - - -def test_sources_are_optional(): - assert call("how's the air?", ["Ecowitt"]) is None - assert call("this week's highs", ["AirGradient"]) is None - - -def test_weather_plus_a_period_is_a_summary_request(): - for text in ("weather week", "weather this week", "weather yesterday", "what was the weather last month"): - assert call(text) and call(text)[0] == "weather_history", text - assert call("weather week")[1]["start_date"] == "2026-09-23 00:00:00" and call("weather week")[1]["chart"] - assert call("hottest day of the month")[1]["start_date"] == "2026-08-31 00:00:00" # the rolling month, not the calendar one - - -def test_weather_now_and_open_questions_still_go_to_the_model(): - for text in ("weather today", "how's the weather now", "weather tomorrow", "weather this week vs last week", - "will the weather be nice this week"): - assert call(text) is None, text - - -def test_weather_now_fetches_every_reading_the_station_has_and_asks_for_the_reports_layout(): - for text in ("weather", "weather now", "Weather Now", "current weather", "ecowitt", "ecowitt now", "show me the weather now please"): - name, args, label = call(text) - assert (name, label) == ("weather_now", "weather now") and args == {"groups": intent.NOW_GROUPS}, text - assert intent.read(text, NOW).weather_now - assert not intent.read("weather last 7 days", NOW).weather_now and not intent.read("report", NOW).weather_now - assert not intent.read("weather now", NOW, ["AirGradient"]).weather_now - - -def test_24_hour_weather_charts_over_a_rolling_window(): - for text in ("weather 24h", "weather 1d", "weather last 24 hours", "weather 1 day"): - name, args, label = call(text) - assert name == "weather_history" and args["chart"] is True, text - assert args["start_date"] == "2026-09-28 14:05:00" and args["end_date"] == "2026-09-29 14:05:00" - assert call("weather yesterday")[1]["chart"] is False - - -def test_air_chart_over_the_last_24_hours_works(): - for text in ("chart pm2.5 last 24 hours", "graph the air quality 24h", "chart co2 1d"): - name, args, _ = call(text) - assert name == "air_quality" and args["start_date"] == "2026-09-28 14:05:00", text - - -def test_aq_with_a_period_charts(): - cases = {"aq 24h": "2026-09-28 14:05:00", "aq 1d": "2026-09-28 14:05:00", "aq 1 month": "2026-08-31 00:00:00", - "aq 1w": "2026-09-23 00:00:00", "air quality 1 year": "2025-09-30 00:00:00"} - for text, start in cases.items(): - name, args, _ = call(text) - assert name == "air_quality" and args["chart"] and args["start_date"] == start, text - assert call("aq")[:2] == ("air_quality", {}) # no period: the current reading - assert call("aq now")[:2] == ("air_quality", {}) - assert call("why was the aq bad yesterday") is None # a question, not a chart request - assert call("aq this week vs last week") is None - - -def test_more_ways_to_name_a_period_for_weather(): - assert call("weather 1 month")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 1y")[1]["start_date"] == "2025-09-30 00:00:00" - assert call("weather 7d")[1]["start_date"] == "2026-09-23 00:00:00" - - -def test_numbered_periods_are_read_not_guessed(): - text = "use 30 minute day to plot 4 months of weather" # was answered with the last 7 days - name, args, label = call(text) - assert name == "weather_history" and args["chart"] and label.endswith("last 4 months") - assert args["start_date"] == "2026-05-31 00:00:00" and args["end_date"] == "2026-09-29 23:59:59" - assert call("plot weather for four months")[1]["start_date"] == "2026-05-31 00:00:00" - assert call("weather 2 weeks")[1]["start_date"] == "2026-09-16 00:00:00" - assert call("weather 12h")[1]["start_date"] == "2026-09-29 02:05:00" and call("weather 12h")[1]["chart"] - assert call("chart the temperature over 3 days")[1]["start_date"] == "2026-09-27 00:00:00" - assert call("aq 3 days")[1]["start_date"] == "2026-09-27 00:00:00" - - -def test_a_period_we_cant_read_goes_to_the_model_not_to_a_default(): - for text in ("plot the weather over the last few months", "chart weather since march", "plot temperature this decade", - "graph the weather 3 days ago", "chart weather 3 months vs 6 months"): - assert call(text) is None, text - assert call("chart weather")[1]["start_date"] == "2026-09-28 14:05:00" # nothing period-like: the last 24 hours - assert call("chart the air quality")[1]["start_date"] == "2026-09-28 14:05:00" - assert call("chart the air quality over the last few days") is None - - -def test_a_plain_wind_chart_takes_the_fast_path_with_the_period_read(): - name, args, _ = call("wind direction plot 3m") - assert name == "weather_history" and args["groups"] == "wind" and args["chart"] is True - assert args["start_date"] == "2026-07-01 00:00:00" and args["end_date"] == "2026-09-29 23:59:59" - assert call("graph the wind this week")[1]["groups"] == "wind" - for text in ("plot wind vs temperature 3m", "will the wind chart change", "why was the wind strong 3m"): - assert call(text) is None, text - - -def test_1m_means_one_month(): - assert call("weather 1m")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 1mo")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("aq 1m")[1]["start_date"] == "2026-08-31 00:00:00" - assert call("weather 3m")[1]["start_date"] == "2026-07-01 00:00:00" - # "30 minute" is not "30 months" - assert call("use 30 minute data to plot 4 months of weather")[1]["start_date"] == "2026-05-31 00:00:00" - - -def test_a_bare_week_month_or_year_charts_for_air_quality_too(): - for text, start in (("aq week", "2026-09-23 00:00:00"), ("air quality month", "2026-08-31 00:00:00"), - ("aq year", "2025-09-30 00:00:00"), ("pm2.5 week", "2026-09-23 00:00:00")): - name, args, label = call(text) - assert name == "air_quality" and args["chart"] and args["start_date"] == start, text - assert call("aq")[:2] == ("air_quality", {}) # no period at all: the current reading - - -def test_air_quality_chart_or_current_reading(): - """A period (however written) charts; the bare words give the current reading as text.""" - for text in ("aq week", "aq 1w", "air quality 1d", "aq 1d", "air quality week", "air qual week", "air qual 1d", - "aq 24h", "aq 1m", "pm2.5 1d"): - name, args, label = call(text) - assert name == "air_quality" and args["chart"] is True, text - for text in ("aq", "air qual", "air quality", "air", "aqi", "aq now", "how's the air", "pm2.5"): - assert call(text)[:2] == ("air_quality", {}), text - assert call("aq 1w")[2] == "air quality chart, last 1 week" - - def test_how_one_reading_relates_to_another_gets_medium_thinking(): for text in ("Is there a correlation between pressure and rainfall", "is there a link between humidity and rain", "cross-reference pressure with rain", "cross reference wind and rain", "what's the connection between wind and temperature", @@ -213,434 +59,77 @@ def test_analysis_across_days_or_readings_gets_low_thinking(): assert intent.reasoning_effort("what was yesterday like?") == "low" -def test_absurd_periods_go_to_the_model_instead_of_crashing(): - from datetime import date - for text in ("weather last 99999 years", "chart weather 2000 years", "aq 99999999999999999999 days", - "weather 999999 hours", "aq 500000 weeks", "weather 12345678 months"): - assert call(text) is None, text # no exception, no nonsense dates - assert call("weather 4 years")[1]["start_date"] == "2022-10-01 00:00:00" # a sane long period still works - assert call("weather 8760 hours")[1]["chart"] - # "on record" is safe on 29 February, when the year four earlier had none - ranges = intent.period_ranges(date(2104, 2, 29)) # 2100 was not a leap year: the old code raised here - assert ranges["on record"] == (date(2104, 2, 29) - timedelta(days=1459), date(2104, 2, 29)) - - -def test_an_air_question_with_a_time_we_cant_read_is_not_answered_with_the_current_reading(): - for text in ("air quality since march", "aq the last few days", "how was the air 3 days ago", "aq these days"): - assert call(text) is None, text - for text in ("aq", "air quality", "aq now", "how's the air"): - assert call(text)[:2] == ("air_quality", {}), text - - -def test_a_particular_date_or_time_goes_to_the_model_not_a_whole_period(): - for text in ("what was the high on 5 Jan this year", "temperature at 3pm today", "hottest day in Jan 12 to Jan 20", - "weather on monday this week", "high at 15:30 yesterday", "how hot was it on 3/2 this month", - "aq on sunday this week", "air quality this morning", "graph the temperature yesterday afternoon", - "what was the low on the 5th of March this year", "weather tonight this week"): - assert call(text) is None, text - # whole periods, however they are written, still take the fast path - for text in ("weather this week", "weather 1m", "aq 24h", "aq week", "hottest day this month", "weather 3 months", - "high and low this year", "chart the temperature last 7 days", "weather 12h", "how sunny was last month"): - assert call(text) is not None or text == "how sunny was last month", text - - -def test_a_question_about_one_reading_charts_that_reading(): - assert intent.chart_field("lowest and highest humidity") == "humidity" - assert intent.chart_field("plot pressure this week") == "relative" - assert intent.chart_field("highest wind gust this year") == "wind_speed" # the mean, shaded up to the gusts - for text in ("hottest day this year", "humidity and temperature this week", "wind and rain", "weather week", "how hot was it"): - assert intent.chart_field(text) is None, text - - -def test_average_questions_are_recognised(): - for text in ("average temp 3m", "what was the mean humidity", "avg wind this week"): - assert intent.AVERAGE.search(text), text - assert not intent.AVERAGE.search("hottest day this year") - - -def test_the_model_is_told_the_exact_dates_of_any_period_the_words_name(): - hints = intent.period_hints("average temp 3m", NOW) - assert hints == ['"3m" = last 3 months: 2026-07-01 00:00:00 to 2026-09-29 23:59:59'] # never 3 days - assert intent.period_hints("wind direction 1y", NOW)[0].startswith('"1y" = last 1 year: 2025-09-30') - assert intent.period_hints("humidity 24h", NOW) == ['"24h" = last 24 hours: 2026-09-28 14:05:00 to 2026-09-29 14:05:00'] - assert len(intent.period_hints("compare this week and last week highs", NOW)) == 2 - assert any("last 2 weeks" in h for h in intent.period_hints("weather 2 weeks", NOW)) - assert intent.period_hints("hello", NOW) == [] and intent.period_hints("use 30 minute data", NOW) == [] - - -def test_readings_named_together_are_charted_together(): - assert intent.chart_fields("plot temperature and rain") == ["temperature", "rain"] - assert intent.chart_fields("graph rain, pressure and humidity for 3m") == ["rain", "pressure", "humidity"] - assert intent.chart_fields("wind vs temp this week") == ["wind", "temperature"] - for text in ("plot the temperature", "will it rain", "hottest day this year", "hello"): - assert intent.chart_fields(text) == [], text - - -def test_a_bare_period_is_hinted_and_a_command_to_the_bot_is_not_a_request_for_readings(): - assert intent.period_hints("humidity week", NOW) == ['"week" = last 7 days: 2026-09-23 00:00:00 to 2026-09-29 23:59:59'] - assert intent.period_hints("weather this week", NOW)[0].startswith('"this week"') # a named period wins - for text in ("add an alert for if winds reach 100 km hour", "please set up a rain alert", "mute the alerts"): - assert not intent.needs_data(text), text - for text in ("will the wind reach 100 km/h", "what was the addition of rain", "how windy is it"): - assert intent.needs_data(text), text - - -def test_questions_about_the_bot_are_recognised_and_readings_questions_are_not(): - for text in ("list our metrics from both sources", "what metrics do you have?", "which sensors do you use", "what can you do", - "what do you measure", "what can I ask", "metrics", "our metrics?", "Available sensors", "sources please"): - assert intent.about_the_bot(text) and not intent.needs_data(text), text - for text in ("rain metrics for Tuesday", "metrics last week", "what was the hottest day", "list rainy days in september", "what's the temperature", "show the past week", - "what was the pressure last month", "how's the air?"): - assert not intent.about_the_bot(text), text +def test_one_reasoning_step_down_for_asking_again_after_a_timeout(): + assert [intent.lower_effort(e) for e in ("high", "medium", "low", "none", "odd")] == ["medium", "low", "none", None, None] def test_a_bare_status_or_report_asks_for_everything_and_nothing_else_does(): for text in ("status", "report", "Report please", "give me the full report", "current report", "show what you've got", "overview", "everything?", "what's the status", "sitrep", "SITREP please", "give me the sitrep"): assert intent.wants_report(text), text + assert intent.read(text, NOW, EVERY_SOURCE).report for text in ("weather report for Tuesday", "report the humidity", "status of the rain alert", "report last week", "sitrep last week", "hello", "how's the air?"): assert not intent.wants_report(text), text -def test_dew_point_feels_like_and_vpd_are_charted_readings_that_outrank_temperature(): - assert intent.chart_field("dew point 90d") == intent.chart_field("dew piont 90d") == intent.chart_field("dewpoint 90d") == "dew_point" - assert intent.chart_field("feels like temperature last month") == "feels_like" - assert intent.chart_field("graph the vpd this week") == "vpd" - assert intent.chart_fields("plot dew point and humidity") == ["dew_point", "humidity"] - assert intent.chart_field("how hot was it") is None - - -def test_weather_all_week_leaves_out_uv_feels_like_and_vpd_unless_configured(monkeypatch): - every = ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "wind"] # solar third, wind last; no UV (same shape as solar), feels like or VPD - assert intent.chart_fields("weather all week") == every - monkeypatch.setattr(service_names, "FEELS_LIKE_IN_ALL", True) - monkeypatch.setattr(service_names, "VPD_IN_ALL", True) - assert intent.chart_fields("weather all week") == ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "wind"] - monkeypatch.setattr(service_names, "FEELS_LIKE_IN_ALL", False) - monkeypatch.setattr(service_names, "VPD_IN_ALL", False) - assert intent.chart_fields("plot feels like and humidity") in (["humidity", "feels_like"], ["feels_like", "humidity"]) # named: still charted - assert intent.chart_fields("plot solar and uv") == ["solar", "uv"] and intent.chart_fields("plot vpd and humidity") != [] - assert intent.chart_field("feels 90d") == intent.chart_field("feel 90d") == intent.chart_field("feels-like 90d") == "feels_like" +def test_the_reports_calls_are_the_readings_now_the_pollen_and_the_next_three_days(): + assert intent.report_calls(EVERY_SOURCE) == [("current", {}), ("pollen", {}), ("forecast", {"period": "next 3 days"})] + assert intent.report_calls(["AirGradient"]) == [("current", {})] + assert not intent.read("report", NOW, []).report # nothing to report from: the model's + assert not intent.read("report for last week", NOW, EVERY_SOURCE).report -def test_solar_radiation_and_uv_are_charted_readings_and_a_weekday_is_not_solar(): - assert intent.chart_field("solar 30d") == "solar" and intent.chart_field("uv 7d") == "uvi" == intent.chart_field("uvi last week") - assert intent.chart_field("sun 5 jan") is None and intent.chart_field("how hot was sunday") is None - - -def test_sun_and_uvi_is_two_stacked_readings_but_a_sunday_or_a_dated_sun_is_not_solar(): - assert intent.chart_fields("sun + uvi one month") == ["solar", "uv"] - assert intent.chart_field("sun 5 jan") is None and intent.chart_field("was it hot on sunday") is None - - -def test_a_readings_band_field_still_names_it_and_only_plain_readings_derive_a_range(): - from lib.series import derives_range, field_of, find_name - assert find_name("wind_gust") == find_name("wind_speed") == find_name("wind") == "wind" and field_of("wind_gust") == "wind_speed" - assert derives_range("dew_point") and derives_range("solar") and not derives_range("wind_speed") and not derives_range("wind_direction") - - -def test_ecowitt_means_the_weather_and_ag_or_airgradient_means_the_air_quality(): - assert call("ecowitt week")[0] == "weather_history" and call("ecowitt week") == call("weather week") and call("ecowitt week")[1]["chart"] - for text in ("ag 7d", "airgradient 7d", "air gradient 7d", "AG 7d"): - name, args, _ = call(text) - assert name == "air_quality" and args["chart"] is True and args["metrics"] == ["pm2_5"], text - assert call("ag now")[0] == "air_quality" and call("air gradient")[0] == "air_quality" and not call("ag now")[1] - assert call("ag and ecowitt 7d") is None # both devices: the model decides - assert intent.chart_fields("ecowitt all week") == intent.chart_fields("weather all week") and intent.chart_fields("ecowitt all week") - assert intent.air_metrics("ag all week") == ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"] or len(intent.air_metrics("ag all week")) == 6 - assert intent.needs_data("ecowitt") and intent.needs_data("ag") and intent.about_the_bot("what does ecowitt measure") and intent.about_the_bot("what does ag measure") - assert not intent.needs_data("that was a nice sag in the road") and not intent.needs_data("thanks") - - -def test_the_report_fetches_everything_in_code_before_the_model_sees_it(): - r = intent.read("report", NOW, EVERY_SOURCE) - assert r.report and r.fast == ("weather_now", {"groups": intent.NOW_GROUPS}, "report") - assert r.more == [("air_quality", {}), ("pollen_asthma", {"cached": True}), ("weather_forecast", {"days": 3, "cached": True})] - plain = intent.read("sitrep", NOW) - assert [plain.fast[0], *(t for t, _ in plain.more)] == ["weather_now", "air_quality"] - only_air = intent.read("status", NOW, ["AirGradient"]) - assert only_air.fast[0] == "air_quality" and only_air.more == [] - assert intent.read("report", NOW, []).fast is None - assert not intent.read("report for last week", NOW).report - - -def test_one_reasoning_step_down_for_asking_again_after_a_timeout(): - assert [intent.lower_effort(e) for e in ("high", "medium", "low", "none", "odd")] == ["medium", "low", "none", None, None] - - -def test_asking_for_the_bots_view_is_not_forced_to_fetch_but_a_view_of_the_weather_today_is(): - philosophical = "what do you think of weather in general, from a philosophical perspective?" - assert intent.is_opinion(philosophical) and not intent.needs_data(philosophical) - assert intent.reasoning_effort(philosophical) == "medium" # "think": still given a little thought - for text in ("what do you think of the weather today?", "what do you think about tomorrow's rain", "do you like the rain now", - "what do you think of the weather over the last 3 days", "weather", "how hot is it", "what do you think the forecast says"): - assert intent.needs_data(text), text - - -def test_only_temp_temperature_how_hot_or_cold_and_hottest_style_questions_force_a_fetch(): - for text in ("only that it's cold", "it's so hot in here", "nice and warm", "warm regards", "cool", "freezing", "degrees"): - assert not intent.needs_data(text), text - for text in ("temp", "temps this week", "what's the temperature", "how cold is it", "how hot will it get", "how's the weather", - "hottest weekends", "coldest day last month", "is it cold outside"): - assert intent.needs_data(text), text - assert intent.read("only that it's cold", NOW).needs_data is False - - -def test_now_alone_is_not_a_weather_question_but_naming_a_reading_with_it_is(): - for text in ("now", "ok now what?", "what now", "do it now", "right now", "currently", "current", "what's happening now"): - r = intent.read(text, NOW) - assert not r.needs_data and not r.weather_now and r.fast is None, text - for text in ("weather now", "is it raining now", "what's the temperature now", "current weather", "how windy is it right now"): - assert intent.needs_data(text), text - - -import pytest as _pytest - - -@_pytest.mark.parametrize("text, kind, named", [ - ("how hot is it", "reading", ["temperature"]), ("is it raining", "reading", ["rain"]), ("uv", "reading", ["uv"]), - ("what's the pressure", "reading", ["pressure"]), ("dew point", "reading", ["dew_point"]), - ("how's the air", "air", []), ("pm10", "air", ["pm10"]), ("forecast", "forecast", []), ("7 day forecast", "forecast", []), - ("pollen", "pollen", []), ("what can you do", "about", []), - ("is it too cold to run", "", []), ("is the air ok for a run", "", []), ("will it rain", "", []), ("forecast tomorrow", "", []), - ("temperature today", "extremes", ["temperature"]), ("is it hotter than yesterday", "", []), ("why is it so humid", "", []), -]) -def test_plain_lookups_are_answered_in_code_and_everything_else_is_left_to_the_model(text, kind, named): - read = intent.read(text, datetime(2026, 10, 2, 12), EVERY_SOURCE) - assert (read.lookup, read.lookup_arg) == (kind, named) - - -@_pytest.mark.parametrize("text, before, has, lacks", [ - ("hottest day that also rained", [], {"days"}, {"air", "link"}), - ("did it rain on Sat 5 Sep", [], {"days"}, {"air"}), - ("is there a correlation between pressure and rainfall", [], {"link"}, {"air"}), - ("is the air ok for a run", [], {"air"}, {"days", "link"}), - ("plot air quality against rainfall", [], {"air"}, set()), - ("will it rain later", [], {"outlook"}, {"air"}), - ("most common wind direction", [], {"wind"}, {"air"}), - ("describe what it was like on Monday", [], {"describe"}, set()), - ("add an alert when winds reach 100", [], {"bot"}, set()), - ("how cold is it", [], set(), {"bot", "days", "air", "link"}), - ("and indoors?", ["what was the hottest day this month"], {"days"}, set()), # a follow-up keeps the topics of what came before - ("thanks, that's great", [], set(), {"air", "days", "link", "outlook", "wind", "bot"}), -]) -def test_topics_pick_the_guidance_and_tools_a_question_needs(text, before, has, lacks): - found = intent.topics(text, before) - assert has <= found and not (lacks & found) - - - -@_pytest.mark.parametrize("text, days", [("will it rain?", 3), ("do I need an umbrella", 3), ("is it going to rain tomorrow", 3), - ("will it rain this week", 7), ("rain later?", 3)]) -def test_a_question_about_rain_ahead_has_the_reading_the_last_3_hours_and_the_forecast_fetched_for_the_model(text, days): - now = datetime(2026, 10, 3, 12) - read = intent.read(text, now, ["Ecowitt", "AirGradient", "Forecast"]) - groups = "outdoor,pressure,rainfall,rainfall_piezo,wind" - assert read.fast is None and read.extra == [ - ("weather_now", {"groups": groups}), - ("weather_history", {"groups": groups, "start_date": "2026-10-03 09:00:00", "end_date": "2026-10-03 12:00:00"}), - ("weather_forecast", {"days": days, "cached": True})] - no_forecast = intent.read(text, now).extra - assert [c[0] for c in no_forecast] == ["weather_now", "weather_history"] # forecast off: just the station - assert intent.read(text, now, ["AirGradient", "Forecast"]).extra == [("weather_forecast", {"days": days, "cached": True})] # no station - - -@_pytest.mark.parametrize("text, name, day", [("what was yesterday like?", "yesterday", "2026-10-02"), ("describe today", "today", "2026-10-03")]) -def test_describing_today_or_yesterday_has_that_days_readings_fetched_for_the_model(text, name, day): - read = intent.read(text, datetime(2026, 10, 3, 12)) - (tool, args), = read.extra - assert tool == "weather_history" and args["groups"] == "outdoor,indoor,rainfall,wind" and args["start_date"].startswith(day) - - -@_pytest.mark.parametrize("text", ["what was it like on Mon 10 Aug", "what was it like at 3pm today", "how hot was yesterday", "describe last week"]) -def test_a_named_date_a_moment_a_longer_period_or_a_plain_question_has_nothing_fetched_ahead(text): - assert intent.read(text, datetime(2026, 10, 3, 12), ["Ecowitt", "AirGradient", "Forecast"]).extra == [] - - -@_pytest.mark.parametrize("text", ["how much rain fell today", "how much rain this week", "did it rain yesterday", "forecast", "rain chart 7d"]) -def test_questions_about_rain_so_far_do_not_fetch_the_forecast(text): - assert intent.read(text, datetime(2026, 10, 3, 12), ["Ecowitt", "AirGradient", "Forecast"]).extra == [] - - -@_pytest.mark.parametrize("text", ["how many times did it rain this year", - "worst air quality day per month", "days over 35 and also rained", "days over UVI 10 on weekends"]) -def test_counting_and_totalling_questions_are_never_turned_into_a_plain_chart(text): - read = intent.read(text, datetime(2026, 10, 3, 12), EVERY_SOURCE) - assert read.fast is None and not read.chart_in_code and read.lookup == "" - - -@_pytest.mark.parametrize("text, tool, field, op, value, group", [ - ("days over UVI 10 by year", "weather_days", "uv_max", ">=", 10, "year"), - ("count days over PM2.5 of 90 per year", "air_days", "pm2_5_max", ">", 90, "year"), - ("how many days was UV 9 or more", "weather_days", "uv_max", ">=", 9, None), - ("days over 30 degrees per month this year", "weather_days", "temp_max", ">", 30, "month"), - ("how many days under 5 degrees", "weather_days", "temp_min", "<", 5, None), - ("days with rain over 5 mm", "weather_days", "rain", ">", 5, None), - ("how many days did the wind exceed 60 km/h", "weather_days", "wind_gust", ">", 60, None), - ("count the days humidity was below 30 per month", "weather_days", "humidity_min", "<", 30, "month"), - ("how many days was PM2.5 over 25 in 2024", "air_days", "pm2_5_max", ">", 25, None), -]) -def test_one_reading_against_one_limit_is_counted_in_code(text, tool, field, op, value, group): - read = intent.read(text, datetime(2026, 10, 3, 12)) - name, args, _ = read.fast - assert read.lookup == "days" and name == tool and args["count_only"] is True and args.get("group_by") == group - assert args["where"] == [{"field": field, "op": op, "value": float(value)}] - - -def test_the_period_is_the_whole_record_unless_one_is_named(): - now = datetime(2026, 10, 3, 12) - whole = intent.read("days over UVI 10 by year", now).fast[1] - assert whole["start_date"] == "2022-10-05" and whole["end_date"] == "2026-10-03" - named = intent.read("days over UVI 10 by month this year", now).fast[1] - assert named["start_date"] == "2026-01-01" and named["group_by"] == "month" - year = intent.read("how many days was PM2.5 over 25 in 2024", now).fast[1] - assert year["start_date"] == "2024-01-01" and year["end_date"] == "2024-12-31" - - -@_pytest.mark.parametrize("text, tool, stat, of, group", [ - ("rain by month for 2 years", "weather_days", "sum", "rain", "month"), - ("average temperature per year", "weather_days", "avg", "temp_avg", "year"), - ("hottest day each year", "weather_days", "max", "temp_max", "year"), - ("coldest night per month this year", "weather_days", "min", "temp_min", "month"), - ("humidity by month this year", "weather_days", "avg", "humidity_avg", "month"), - ("uv by month", "weather_days", "max", "uv_max", "month"), - ("windiest day per month", "weather_days", "max", "wind_gust", "month"), - ("highest PM2.5 by month", "air_days", "max", "pm2_5_max", "month"), - ("average co2 per year", "air_days", "avg", "co2_avg", "year"), -]) -def test_one_reading_by_month_or_year_is_a_figure_per_period_worked_out_in_code(text, tool, stat, of, group): - read = intent.read(text, datetime(2026, 10, 3, 12)) - name, args, _ = read.fast - assert read.lookup == "days" and (name, args["stat"], args["of"], args["group_by"]) == (tool, stat, of, group) and args["count_only"] is True - - -@_pytest.mark.parametrize("text", ["pm2.5 and co2 by month", "rain by month on weekends", "air quality by month", "will it rain by month", - "days over 30 degrees and rain per month", "rain days per month"]) -def test_anything_beyond_one_reading_by_month_or_year_is_left_to_the_model(text): - read = intent.read(text, datetime(2026, 10, 3, 12)) - assert read.lookup == "" and (read.fast is None or read.fast[0] not in ("weather_days", "air_days")) - - -def test_weather_all_week_is_every_reading_and_a_named_chart_is_not(): - assert intent.wants_chart_all("weather all week") and intent.wants_chart_all("ecowitt all week") - assert not intent.wants_chart_all("plot temperature and rain") and not intent.wants_chart_all("temperature chart 7d") - - -@_pytest.mark.parametrize("ask", ["weather chart 90d", "chart all 90d", "chart 90d", "chart"]) -def test_a_chart_that_names_no_reading_is_every_reading_not_temperature(ask): - read = intent.read(ask, NOW) - assert intent.wants_chart_all(ask) and read.chart_fields[:3] == ["temperature", "humidity", "solar"] and read.chart_fields[-1] == "wind" - - -def test_a_named_reading_or_an_air_chart_is_not_every_reading_and_indoors_has_only_what_the_indoor_sensor_measures(): - for ask in ("temperature chart 90d", "rain chart 7d", "chart air 90d", "plot pm2.5 90d"): - assert not intent.wants_chart_all(ask) and intent.chart_fields(ask) == [] - assert intent.chart_fields("chart all 90d indoors") == ["temperature", "humidity", "dew_point"] - - -# ---------- what a phone types, and words that only look like other things ---------- -def test_a_phone_s_curly_apostrophe_reads_as_the_plain_one(): - for plain in ("what's the weather", "what's the temperature", "show what you've got", "what's the forecast"): - curly = plain.replace("'", "’") - assert intent.read(curly, NOW, EVERY_SOURCE).fast == intent.read(plain, NOW, EVERY_SOURCE).fast, curly - assert intent.read(curly, NOW, EVERY_SOURCE).fast is not None, curly - - -def test_all_time_and_every_day_are_periods_not_every_air_reading(): - for text in ("pm2.5 chart all time", "pm2.5 every day this week", "highest pm2.5 of all-time"): - assert intent.air_named(text) == ["pm2_5"], text - for text in ("aq all week", "air quality all metrics 1d", "chart everything in the air 7d"): # every reading still means every one - assert intent.air_named(text) == ["pm2_5", "pm10", "pm1", "co2", "voc_index", "nox_index"], text - assert call("count days over PM2.5 of 90 per year all time")[0] == "air_days" - - -def test_co2_with_a_subscript_two_is_the_air_reading(): - assert call("co₂ chart 7d")[1]["metrics"] == ["co2"] and call("chart CO₂ 1d")[0] == "air_quality" - assert intent.needs_data("co₂") and intent.needs_data("pm1") and intent.mentions_air("co₂") - - -def test_indoor_dew_point_and_feels_like_come_from_the_indoor_sensor(): - for text in ("indoor dew point chart", "indoor feels like chart 7d", "indoor dew point 90d"): - assert call(text)[1]["groups"] == "indoor", text - assert call("dew point chart")[1]["groups"] == "outdoor" # unasked, they stay the outdoor sensor's - assert call("indoor and outdoor dew point chart 7d")[1]["groups"] == "outdoor,indoor" - - -def test_the_lowest_uv_per_month_is_the_lowest_daily_high_not_the_highest(): - tool, args, _ = intent.period_figures_call("lowest uv by month", NOW, ["Ecowitt"]) - assert (tool, args["stat"], args["of"], args["group_by"]) == ("weather_days", "min", "uv_max", "month") - assert intent.period_figures_call("uv by month", NOW, ["Ecowitt"])[1]["stat"] == "max" # a UV index is its day's high - assert intent.period_figures_call("lowest wind by month", NOW, ["Ecowitt"]) is None # wind has no lowest to ask for - - -def test_the_air_table_is_the_one_in_series_and_panels_imports_on_its_own(): - import subprocess - import sys - from lib.airgradient.metrics import LABELS, MARK_LOW, RATINGS - from lib.series import AIR - assert list(LABELS) == list(AIR) == [m for _, m in intent.AIR_METRICS] and MARK_LOW == ("co2",) and RATINGS["pm2_5"] == (9.0, 55.4) - run = subprocess.run([sys.executable, "-c", "import lib.panels"], capture_output=True, text=True) - assert run.returncode == 0, run.stderr # no circular import through airgradient - - -def test_the_models_first_step_must_fetch_for_data_may_just_reply_to_chat_and_gets_no_tools_about_the_bot(): - assert [intent.read(t, NOW).tool_choice for t in ("will it rain tomorrow?", "thanks!", "what can you do")] == ["required", "auto", "none"] - - -def test_two_readings_on_two_axes_is_asked_for_in_so_many_words_and_goes_to_the_weather_history_chart(): - from datetime import datetime - from tests.fakes import TZ - now = datetime(2026, 10, 27, 12, tzinfo=TZ) - for said in ("graph combine uvi and solar radiation on two axis", "plot temperature and humidity on two axes", "uv vs solar, dual axis", - "graph uv and solar 2 axes", "plot uv and solar with a secondary axis", "graph uv and solar overlaid"): - assert intent.read(said, now).two_axes, said - for said in ("plot temperature and humidity", "graph uv on two axes", "plot rain", "what is the axis of the earth"): - assert not intent.read(said, now).two_axes, said # one reading, or no such request - read = intent.read("graph combine uvi and solar radiation on two axis", now) - assert read.chart_in_code and read.chart_fields == ["uv", "solar"] and read.fast[0] == "weather_history" - - -def test_the_air_sensors_own_temperature_and_humidity_are_offered_only_when_the_airgradient_is_named_with_them(): - from datetime import datetime - from tests.fakes import TZ - now = datetime(2026, 10, 27, 12, tzinfo=TZ) - for said in ("plot airgradient humidity over ecowitt outdoor humidity", "what is the air gradient temperature", "ag humidity 7d"): - assert intent.wants_air_extra(said) and intent.read(said, now).air_extra and "air_extra" in intent.topics(said), said - for said in ("plot humidity", "how hot is it", "air quality now", "plot pm2.5 and temperature", "what's the average humidity yesterday"): - assert not intent.wants_air_extra(said) and not intent.read(said, now).air_extra, said - - -def test_calendar_months_with_their_year_are_a_period_from_the_first_of_one_to_the_end_of_the_other(): - now = datetime(2026, 11, 7, 20, 18) - day = lambda *a: datetime(*a) - assert intent.spans_in("co2 chart oct 2025 to oct 2026", now) == [("Oct 2025 - Oct 2026", day(2025, 10, 1), day(2026, 10, 31, 23, 59, 59))] - assert intent.spans_in("rain between jan 2026 and March 2026", now)[0][1:] == (day(2026, 1, 1), day(2026, 3, 31, 23, 59, 59)) - assert intent.spans_in("humidity chart October 2025", now) == [("Oct 2025", day(2025, 10, 1), day(2025, 10, 31, 23, 59, 59))] - assert intent.spans_in("co2 chart nov 2025 - nov 2026", now)[0][2] == day(2026, 11, 7, 23, 59, 59) # up to today - read = intent.read("co2 chart oct 2025 to oct 2026", now, {"Ecowitt": 1, "AirGradient": 1}) - assert read.fast[1]["start_date"] == "2025-10-01 00:00:00" and read.fast[1]["end_date"] == "2026-10-31 23:59:59" - assert not intent.read("co2 chart dec 2026", now, {"AirGradient": 1}).chart_in_code # a month ahead: not the last day, the model's - - -def test_a_readings_full_history_is_the_longest_chart_and_history_alone_is_too_unless_a_period_is_named(): - now = datetime(2026, 11, 7, 20, 52) - for text in ("co2 full history", "co2 history", "full history of co2", "pm2.5 all history", "co2 whole history", "humidity history", - "temperature full history"): - read = intent.read(text, now, {"Ecowitt": 1, "AirGradient": 1}) - assert read.chart_in_code and read.fast[2].endswith("on record"), text # not the reading now - assert intent.spans_in("co2 history 7d", now)[0][0] == "last 7 days" - assert intent.spans_in("rain history this week", now)[0][0] == "last 7 days" - - -def test_values_at_an_interval_go_to_the_model_for_the_readings_tool_but_a_chart_of_them_is_still_drawn_in_code(): - for text in ("What was the humidity each hour for the last 5 hours", "temperature every 30 minutes today", "temperature every ten minutes today", - "temperature every half an hour today", "temperature every couple of hours today", "temperature in 15 minute increments today", - "pm2.5 every ten minutes today", "humidity hour by hour yesterday", "rain per hour today", - "highest hourly rain each month this year", "max rain per hour by month"): # (an hour's figure, never a day's) - assert call(text) is None, text - for text in ("hourly rain chart today", "rain per hour chart 7d", "plot hourly temperature today", "hourly pm2.5 chart 24h"): - assert intent.read(text, NOW).chart_in_code, text - for text in ("max wind speed in miles per hour this week", "highest gust in kilometres per hour this week", "max gust today in km/h per hour"): - assert call(text) is not None, text # a speed's unit, not an interval - assert intent.ALL.search("pm2.5 every ten minutes") is None and intent.ALL.search("everything every day") +def test_weather_now_and_the_gauges_are_the_stations_and_a_period_makes_them_the_models(): + for text in ("weather", "weather now", "Weather Now", "current weather", "ecowitt", "ecowitt now", "show me the weather now please"): + r = intent.read(text, NOW, EVERY_SOURCE) + assert r.weather_now and r.chart is None and r.shortcut, text + for text in ("dashboard", "gauges", "show me the dashboard"): + assert intent.read(text, NOW, EVERY_SOURCE).dashboard, text + for text in ("weather today", "how's the weather now", "weather tomorrow", "weather this week vs last week", "dashboard last week"): + r = intent.read(text, NOW, EVERY_SOURCE) + assert not (r.weather_now or r.dashboard or r.report), text + assert not intent.read("weather now", NOW, ["AirGradient"]).weather_now # (no station) + + +def test_a_named_readings_chart_and_a_period_is_summary_with_the_words_as_they_are(): + for text, readings, period in (("humidity chart 7d", ["humidity"], "7d"), ("chart rain this month", ["rain"], "this month"), + ("humidity 7d", ["humidity"], "7d"), ("Temperature chart last month", ["temperature"], "last month"), + ("indoor temperature chart 7d", ["indoor temperature"], "7d"), ("pm2.5 plot 3d", ["pm2.5"], "3d"), + ("temperature and rain chart 7d", ["temperature", "rain"], "7d"), ("weather 30d", ["weather"], "30d"), + ("co2 graph yesterday", ["co2"], "yesterday"), + ("humidity, pressure chart 2 weeks", ["humidity", "pressure"], "2 weeks"), + ("humidity 7d?", ["humidity"], "7d")): + assert chart(text) == ("summary", {"readings": readings, "period": period, "chart": True}), text + + +def test_anything_beside_the_chart_is_the_models(): + for text in ("average temperature 7d", "plot uv and solar on two axes 7d", "lowest temperature on record", "highest humidity this week", + "temps this week", "chart weather", "humidity chart", "plot pressure this week: is a storm coming?", "weather all week", + "how hot is it", "rain today", "humidity 1d", "humidity chart next week", "chart chart 7d", "rain chart 7d vs last week", + "temperature chart 99999 years ago", "hello", "what can you do", "pollen", "forecast"): + assert chart(text) is None, text + assert intent.read("humidity chart 7d", NOW, ["Pollen", "Forecast"]).chart is None # (nothing to draw from) + + +def test_the_words_are_read_against_the_readings_the_service_holds(): + station_only = Catalogue.of(air=False) + assert chart("co2 chart 7d") and chart("co2 chart 7d", station_only) is None + + +def test_every_button_and_alert_chart_is_a_fixed_call(): + calls = {text: chart(text) for text in [*templates.chart_sentences(), *pictures.CHARTS.values()]} + assert calls == { + "Rain chart 1d": ("summary", {"readings": ["rain"], "period": "1d", "chart": True}), + "Weather chart 1d": ("summary", {"readings": ["weather"], "period": "1d", "chart": True}), + "Temperature chart 1d": ("summary", {"readings": ["temperature"], "period": "1d", "chart": True}), + "Humidity chart 1d": ("summary", {"readings": ["humidity"], "period": "1d", "chart": True}), + "Air quality all metrics 1d": ("summary", {"readings": ["air"], "period": "1d", "chart": True}), + "Particulates chart 1d": ("summary", {"readings": ["pm2.5", "pm10", "pm1"], "period": "1d", "chart": True}), + "Wind chart 1d": ("summary", {"readings": ["wind"], "period": "1d", "chart": True}), + "UV chart 1d": ("summary", {"readings": ["uv"], "period": "1d", "chart": True})} + + +@pytest.mark.parametrize("text", ["status", "humidity 7d", "how hot is it", "thanks", "will it rain later?"]) +def test_the_effort_is_read_for_every_message(text): + assert intent.read(text, NOW, EVERY_SOURCE).effort == intent.reasoning_effort(text) diff --git a/tests/test_live_bands.py b/tests/test_live_bands.py index 3a476317..f919a97e 100644 --- a/tests/test_live_bands.py +++ b/tests/test_live_bands.py @@ -6,6 +6,7 @@ from lib.ecowitt.live import BUCKET, readings_in from lib.tools import Turn from tests.fakes import archived_station +from tests import old_tools T = 1_800_000_000 // BUCKET * BUCKET @@ -29,7 +30,7 @@ async def chart_of_the_last_day(eco): now = datetime.now(eco.tz) args = {"groups": "outdoor", "start_date": f"{(now - timedelta(days=1)):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}", "chart": True} turn = Turn() - await eco.tools[1].handler(args, turn) + await old_tools.weather_history(eco, args, turn) return turn.charts[0].panels[0].lines[0] @@ -68,7 +69,7 @@ async def test_a_chart_of_a_week_has_the_true_extremes_of_each_half_hour_in_its_ async def line(): turn = Turn() - await eco.tools[1].handler(args, turn) + await old_tools.weather_history(eco, args, turn) return turn.charts[0].panels[0].lines[0] plain = await line() slot = plain.x[len(plain.x) // 2] # a half hour in the middle of the period diff --git a/tests/test_minute_lines.py b/tests/test_minute_lines.py index b535e4bd..12bd704f 100644 --- a/tests/test_minute_lines.py +++ b/tests/test_minute_lines.py @@ -5,12 +5,13 @@ from lib.ecowitt.api import MINUTE, cycle_seconds from lib.tools import Turn from tests.fakes import config, ecowitt_transport, home_assistant_transport +from tests import old_tools async def chart(eco, hours, groups="outdoor"): now = eco.now() turn = Turn() - out = json.loads(await eco.tools[1].handler({"groups": groups, "chart": True, "start_date": f"{now - timedelta(hours=hours):%Y-%m-%d %H:%M:%S}", + out = json.loads(await old_tools.weather_history(eco, {"groups": groups, "chart": True, "start_date": f"{now - timedelta(hours=hours):%Y-%m-%d %H:%M:%S}", "end_date": f"{now:%Y-%m-%d %H:%M:%S}"}, turn)) return out, turn diff --git a/tests/test_periods.py b/tests/test_periods.py index 773dd4b8..c966ea59 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -25,15 +25,6 @@ def shaded(markup): return [b.text for row in markup.inline_keyboard for b in row if b.style == "primary"] -def test_the_old_row_is_always_week_month_quarter_and_year(): - """(The buttons of a chart the service can't replay, which ask its question again.)""" - assert labels(periods.keyboard()) == [[("1D", "pd:1"), ("7D", "pd:7"), ("1M", "pd:30"), ("3M", "pd:90"), ("1Y", "pd:365")]] - assert [t for t, _ in labels(periods.keyboard(30))[0]] == ["1D", "7D", "1M", "3M", "1Y"] and shaded(periods.keyboard(30)) == ["1M"] # the chart's own period is shaded - assert shaded(periods.keyboard(61)) == [] and shaded(periods.keyboard()) == [] - assert shaded(periods.keyboard(365)) == ["1Y"] - assert periods.days_in("pd:1") == 1 and periods.days_in("pd:90") == 90 and periods.days_in("pd:365") == 365 and periods.days_in("pd:30000") is None and periods.days_in("al:on:x") is None - - def test_a_charts_buttons_are_its_drawn_bys_periods_labelled_as_the_service_labels_them_its_own_shaded(): drawn_by = {"tool": "summary", "arguments": {"readings": ["outdoor.temperature"], "period": "last 30 days", "chart": True}, "periods": list(OVER_TIME)} @@ -47,15 +38,6 @@ def test_a_charts_buttons_are_its_drawn_bys_periods_labelled_as_the_service_labe assert periods.call_key("summary", {"b": 1, "a": [2]}) == periods.call_key("summary", {"a": [2], "b": 1}) == 'summary {"a":[2],"b":1}' -def test_a_question_keeps_its_words_and_swaps_its_period(): - for ask, expected in (("Temperature chart 30d", "Temperature chart 90d"), ("chart air quality last month", "chart air quality 90d"), - ("rain chart for the last week", "rain chart 90d"), ("weather chart", "weather chart 90d"), - ("plot humidity and rain 3m", "plot humidity and rain 90d")): - assert intent.with_period(ask, 90, NOW) == expected - assert intent.period_days("Temperature chart 30d", NOW) == 30 and intent.period_days("weather chart", NOW) == 1 - assert intent.period_days("chart 24h", NOW) == 1 and intent.period_days("chart 365d", NOW) == 365 - - def test_only_the_newest_charts_are_remembered(): charted = periods.Charted() for i in range(periods.REMEMBERED + 5): @@ -149,9 +131,9 @@ async def test_a_chart_is_sent_with_its_periods_under_it_and_its_call_is_remembe await bot.respond(update, CONTEXT, "Temperature chart 30d") caption, markup = sent[0] assert caption == "Temperature" and labels(markup) == [ROW] and shaded(markup) == ["1M"] - assert calls(bot) == [{"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 30 days", "chart": True}] + assert calls(bot) == [{"readings": ["temperature"], "period": "30d", "chart": True}] # the words as they are record = bot.charted.get(1, 101) - assert record["drawn_by"]["arguments"]["period"] == "last 30 days" and record["words"] is False + assert record["drawn_by"]["arguments"]["period"] == "30d" and record["words"] is False async def test_pressing_a_period_replays_the_charts_call_with_that_period_in_place(alert_state, monkeypatch): @@ -236,7 +218,8 @@ class Replies: async def reply_photo(self, photo, **kw): sent.append(kw["reply_markup"]) return NS(message_id=7) - got = await botmod.deliver(Replies(), "", [b"p"], markup=keyboard(), titles=["T"], period_row=periods.keyboard()) + row = periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}) + got = await botmod.deliver(Replies(), "", [b"p"], markup=keyboard(), titles=["T"], period_row=row) assert got.carried is False and labels(sent[0])[0][0][0] == "1D" and got.photo.message_id == 7 @@ -274,7 +257,7 @@ async def test_two_wordings_of_one_chart_share_one_picture(alert_state, monkeypa bot, sent = make_bot(alert_state, monkeypatch), [] update = pressed(bot, sent) await bot.respond(update, CONTEXT, "Temperature chart 7d") - await bot.respond(update, CONTEXT, "temperature chart for the last 7 days") + await bot.respond(update, CONTEXT, "temperature chart 7d?") assert len(calls(bot)) == 1 and sent[1][0] == "copy 1" # the same call: drawn once, sent as Telegram's copy @@ -297,26 +280,7 @@ async def answer(text=None): pass for period in ("1m", "7d", "1m"): await bot.on_period_button(press(msg, f"pd:{period}", answer), CONTEXT) - assert uploads == [b"last 7 days"] and edits == ["upload", "7d", "edit 1"] # 1M drawn and uploaded once; then both by Telegram's copy - - -async def test_redrawing_a_chart_from_a_button_shows_no_typing_or_thinking(alert_state, monkeypatch): - bot = make_bot(alert_state, monkeypatch) - actions = [] - - async def chat_action(*a, **k): - actions.append(a) - drafts = [] - - async def draft(*a, **k): - drafts.append(a) - context = NS(bot=NS(send_chat_action=chat_action, send_message_draft=draft, id=99)) - msg = chat_message([], []) - update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - await bot.respond(update, context, "Temperature chart 30d", redraw=msg) - assert actions == [] and drafts == [] - await bot.respond(update, context, "Temperature chart 7d") # a question of its own still does - assert actions + assert uploads == [b"7d"] and edits == ["upload", "7d", "edit 1"] # 1M drawn and uploaded once; then both by Telegram's copy def pressed(bot, sent): @@ -334,7 +298,7 @@ async def test_a_chart_just_drawn_is_sent_again_at_once_and_then_as_telegrams_co update = pressed(bot, sent) await bot.respond(update, CONTEXT, "Temperature chart 1d") asked = len(calls(bot)) - assert asked == 1 and sent == [(b"last 24 hours", "Temperature")] + assert asked == 1 and sent == [(b"1d", "Temperature")] await bot.respond(update, CONTEXT, "Temperature chart 1d") assert len(calls(bot)) == asked and sent[-1] == ("copy 1", "Temperature") # drawn lately: no new call, Telegram's copy history = bot.chats[(1, None)].history @@ -395,7 +359,7 @@ async def edit_media(media, reply_markup=None): context, "Temperature chart 7d") await settle(bot) assert sorted(uploads) == uploads_of("1d", "1m", "3m", "1y") # 1D, 1M, 3M, 1Y: not the 7D just sent - assert all(c["period"] in ("last 7 days", "1d", "1m", "3m", "1y") for c in calls(bot)) + assert all(c["period"] in ("7d", "1d", "1m", "3m", "1y") for c in calls(bot)) asked = len(calls(bot)) async def answer(text=None): @@ -447,8 +411,7 @@ async def test_a_period_that_cannot_be_drawn_is_left_out_and_the_others_are_uplo await bot.respond(pressed(bot, []), context, "Temperature chart 7d") await settle(bot) assert sorted(uploads) == uploads_of("1d", "1m", "1y") - drawn_by = bot.images.held(periods.call_key("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], - "period": "last 7 days", "chart": True})).drawn_by + drawn_by = bot.images.held(periods.call_key("summary", {"readings": ["temperature"], "period": "7d", "chart": True})).drawn_by key = lambda p: periods.call_key("summary", periods.with_period(drawn_by, p)) assert bot.images.has_copy(key("1m")) and not bot.images.has_copy(key("3m")) @@ -478,7 +441,7 @@ async def test_a_chart_uploaded_ahead_is_used_for_30_minutes_and_then_drawn_afre bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) await bot.respond(pressed(bot, []), context, "Temperature chart 7d") await settle(bot) - key = periods.call_key("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "1m", "chart": True}) + key = periods.call_key("summary", {"readings": ["temperature"], "period": "1m", "chart": True}) clock[0] = 29 * 60 assert bot.images.has_copy(key) and isinstance(bot.images.get(key)[0], str) clock[0] = 31 * 60 @@ -492,62 +455,13 @@ async def test_a_redrawn_chart_carries_a_short_answer_in_its_caption_and_a_long_ async def reply_text(text, **kw): replies.append(text) msg.reply_text = reply_text - assert await bot._redraw(msg, "Last 7 days: 72% avg.", b"png", "Humidity", periods.keyboard(7), "q") + row = periods.periods_keyboard({"tool": "summary", "arguments": {"period": "7d"}, "periods": [dict(p) for p in OVER_TIME]}) + assert await bot._redraw(msg, "Last 7 days: 72% avg.", b"png", "Humidity", row, {}) assert edits[0][0] == "Humidity\n\nLast 7 days: 72% avg." and replies == [] # one message, as when the chart was first sent - assert await bot._redraw(msg, "x" * botmod.CAPTION_LIMIT, b"png", "Humidity", periods.keyboard(7), "q") + assert await bot._redraw(msg, "x" * botmod.CAPTION_LIMIT, b"png", "Humidity", row, {}) assert edits[1][0] == "Humidity" and replies == ["x" * botmod.CAPTION_LIMIT] # too long for a caption: its own message -async def test_pressing_a_period_under_a_chart_the_model_drew_keeps_its_answer_in_the_caption(alert_state, monkeypatch): - """A chart the model drew with a call the service has no equivalent of: its question is asked again, as before.""" - bot, edits, replies = make_bot(alert_state, monkeypatch), [], [] - monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") - - class Agent: - ready = True - - async def run(self, working, system, effort, turn=None, **kw): - turn.charts.append(Chart("Humidity and Temperature", "", [Panel("Humidity", "%", [Line("Ecowitt", [1, 2], [1.0, 2.0])])])) - return "Last 7 days (21-27 Oct):\nHumidity: Ecowitt 72.1% avg." - bot.agent = Agent() - msg = chat_message([], edits) - - async def reply_text(text, **kw): - replies.append(text) - msg.reply_text = reply_text - bot.charted.remember(1, 50, "overlay ecowitt outdoor humidity with airgradient humidity, on another axis the temperatures") - - async def answer(text=None): - pass - await bot.on_period_button(press(msg, "pd:7", answer), CONTEXT) - assert replies == [] and edits and "Humidity: Ecowitt 72.1% avg." in edits[0][0] - - -async def test_a_chart_the_model_drew_through_an_old_tool_gets_a_drawn_by_and_its_buttons_replay_it(alert_state, monkeypatch): - from lib.tools import Tool, Tools - bot, sent = make_bot(alert_state, monkeypatch), [] - monkeypatch.setattr(botmod, "render_data", lambda data, tz, times=None: b"png") - - async def weather_history(args, turn): - turn.charts.append(Chart("Pressure", "", [Panel("Pressure", "hPa", [Line("Pressure", [1, 2], [1.0, 2.0])])])) - return json.dumps({"period": "Fri 25 Sep 2026 - Thu 1 Oct 2026"}) - tools = Tools([Tool("weather_history", "", {"type": "object", "properties": {}}, weather_history)]) - - class Agent: - ready = True - - async def run(self, working, system, effort, turn=None, **kw): - await tools.call("weather_history", json.dumps({"groups": "pressure", "chart": True, "chart_field": "pressure", - "start_date": "2026-09-25 00:00:00", "end_date": "2026-10-01 23:59:59"}), turn) - return "Pressure fell all week." - bot.agent = Agent() - await bot.respond(pressed(bot, sent), CONTEXT, "how did the pressure change from 25 Sep to 1 Oct, and why?") - record = bot.charted.get(1, 101) - assert record["drawn_by"] == {"tool": "summary", "arguments": {"readings": ["pressure.relative"], "period": "2026-09-25 to 2026-10-01", - "chart": True}, "periods": [dict(p) for p in OVER_TIME]} - assert record["words"] is True - - async def test_the_keyboards_charts_are_drawn_ahead_and_a_press_is_answered_from_them(alert_state, monkeypatch): clock = [0.0] bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) @@ -559,14 +473,14 @@ async def test_the_keyboards_charts_are_drawn_ahead_and_a_press_is_answered_from assert bot._sentence_call("Air quality all metrics 1d", now) is None # no air sensor here: nothing to draw asked, sent = len(calls(bot)), [] await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert len(calls(bot)) == asked and sent[0][0] == b"last 24 hours" # the one drawn ahead: no new call + assert len(calls(bot)) == asked and sent[0][0] == b"1d" # the one drawn ahead: no new call clock[0] += 400 # too old to answer with: the press draws afresh await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") assert len(calls(bot)) == asked + 1 asked = len(calls(bot)) await bot.draw_buttons_ahead(context.bot) drawn = [c["readings"] for c in calls(bot)[asked:]] - assert ["outdoor.humidity", "indoor.humidity"] in drawn and ["outdoor.temperature", "indoor.temperature"] not in drawn # just drawn: left alone + assert ["humidity"] in drawn and ["temperature"] not in drawn # just drawn: left alone async def test_the_keyboards_charts_are_drawn_ahead_as_background_requests(alert_state, monkeypatch): @@ -592,10 +506,10 @@ async def test_the_keyboards_charts_are_uploaded_ahead_only_while_the_bot_is_in_ bot.noticed() clock[0] += 120 await bot.draw_buttons_ahead(context.bot) - assert (-1001, b"last 24 hours", True) in uploads + assert (-1001, b"1d", True) in uploads sent = [] await bot.respond(pressed(bot, sent), context, "Temperature chart 1d") - assert sent[0][0] == "file last 24 hours" # a press sends Telegram's copy + assert sent[0][0] == "file 1d" # a press sends Telegram's copy await settle(bot) # (the press's other periods, uploaded ahead) uploads.clear() clock[0] += 120 @@ -615,7 +529,7 @@ async def test_the_chart_of_an_alert_sent_lately_is_drawn_ahead_with_the_keyboar clock = [0.0] bot, uploads, context = preloading_bot(alert_state, monkeypatch, clock=clock) bot.alert_charts.clock = lambda: clock[0] - uv, temperature = ["solar_and_uvi.uvi"], ["outdoor.temperature", "indoor.temperature"] + uv, temperature = ["uv"], ["temperature"] drawn = lambda since: [c["readings"] for c in calls(bot)[since:]] await bot.draw_buttons_ahead(context.bot) assert uv not in drawn(0) and temperature in drawn(0) # UV is no button: not drawn until an alert diff --git a/tests/test_pollen.py b/tests/test_pollen.py index b687f26f..a0706d94 100644 --- a/tests/test_pollen.py +++ b/tests/test_pollen.py @@ -6,6 +6,7 @@ from lib.pollen import LEVEL_EMOJI, LEVELS, Pollen, parse_melbourne_pollen from lib.warm import in_sync_hours from tests.fakes import TZ, config +from tests import old_tools SEASON_DAY = date(2026, 11, 10) # a day in the pollen season (October to December), whatever day the tests run @@ -55,7 +56,7 @@ async def test_the_lines_have_a_level_emoji_and_never_name_the_district(tmp_path pollen, _ = make(tmp_path, lambda: page(grass="High", asthma="High")) await pollen.start() assert pollen.lines() == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🔴 High"] - out = json.loads(await pollen.handle({})) + out = json.loads(await old_tools.pollen(pollen, {})) assert out["lines"] == pollen.lines() and "Central" not in json.dumps(out) and out["asthma_updated"] == "1 Oct 2026 4:00pm" await pollen.close() @@ -65,7 +66,7 @@ async def test_a_forecast_for_another_day_and_a_missing_asthma_forecast_are_said with caplog.at_level("WARNING"): await pollen.start() assert pollen.lines() == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] - assert json.loads(await pollen.handle({}))["asthma_note"] == "The page had no thunderstorm asthma level for this district when it was last read." + assert json.loads(await old_tools.pollen(pollen, {}))["asthma_note"] == "The page had no thunderstorm asthma level for this district when it was last read." assert "no thunderstorm asthma level for Central on the page" in caplog.text # in season the page should have one await pollen.close() @@ -124,20 +125,10 @@ def handler(request): pollen = Pollen(config(tmp_path, pollen=True), httpx.MockTransport(handler)) pollen.now = lambda: datetime.combine(SEASON_DAY, dtime(12, 0)) await pollen.start() - assert pollen.lines() == [] and "No pollen levels" in await pollen.handle({}) + assert pollen.lines() == [] and "No pollen levels" in await old_tools.pollen(pollen, {}) await pollen.close() -def test_pollen_words_need_data_and_a_bare_pollen_question_is_fetched_without_the_model(): - from lib import intent - now = datetime(2026, 10, 1, 12, 0) - for text in ("pollen", "Hay fever", "thunderstorm asthma risk"): - assert intent.read(text, now, ["Ecowitt", "AirGradient", "Pollen"]).fast[0] == "pollen_asthma" - assert intent.read("pollen", now).fast is None - for text in ("is the pollen bad today?", "any asthma risk"): - assert intent.read(text, now, ["Ecowitt", "AirGradient", "Pollen"]).needs_data - - def make_on(tmp_path, day, hour=12, html=None): """A Pollen source whose clock says this day (the season is October to December).""" pollen, calls = make(tmp_path, html) @@ -158,7 +149,7 @@ async def test_out_of_season_nothing_is_fetched_not_even_at_start_with_an_empty_ await pollen.start() assert await pollen.warm(True) == "Pollen out of season" and await pollen.warm(False) == "Pollen out of season" assert calls == [] and pollen.lines() == [] - out = json.loads(await pollen.handle({})) + out = json.loads(await old_tools.pollen(pollen, {})) assert out == {"error": "Pollen and thunderstorm asthma forecasts only run from October to December."} and calls == [] await pollen.close() @@ -168,12 +159,12 @@ async def test_last_seasons_page_is_not_shown_and_the_report_leaves_the_block_ou pollen, _ = make_on(tmp_path, date(2026, 12, 20), html=lambda: page(grass="High", day=date(2026, 12, 20))) await pollen.start() assert pollen.lines()[0].startswith("Grass pollen forecast: 🔴 High") - assert json.loads(await pollen.handle({"cached": True}))["time"] # when the page was fetched, for the report's heading + assert json.loads(await old_tools.pollen(pollen, {"cached": True}))["time"] # when the page was fetched, for the report's heading await pollen.close() january, calls = make_on(tmp_path, date(2027, 1, 5)) # the saved page is still in the database await january.start() assert january.data is not None and january.lines() == [] and january.current()["grass"] is None and calls == [] - result = await january.handle({"cached": True}) + result = await old_tools.pollen(january, {"cached": True}) assert "error" in json.loads(result) assert "Pollen" not in report.report({"pollen_asthma": result}, date(2027, 1, 5)) # no block in the report await january.close() diff --git a/tests/test_report.py b/tests/test_report.py index d0e4521f..b10f65cd 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -32,73 +32,7 @@ def _turn(**kw): return NS(charts=[Chart("Rain", "", [Panel("Rain", "mm", bars=bars)])], chart_fields=[], chart_field=None, average_asked=False, **kw) -def test_a_weather_chart_caption_gives_the_period_then_low_and_high_per_series(): - from zoneinfo import ZoneInfo - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "8.1", "low_when": "at 5:30am", "low_date": "Wed 30 Sep 2026", - "high": "24.3", "high_when": "around 3pm", "high_date": "Sat 3 Oct 2026"}, - "indoor.temperature": {"unit": "℃", "low": "18.0", "low_when": "at 6am", "low_date": "Wed 30 Sep 2026", - "high": "22.5", "high_when": "at 4pm", "high_date": "Sat 3 Oct 2026"}}}) - caption = report.chart_caption("weather_history", {}, result, _turn(), ZoneInfo("Australia/Melbourne")) - assert caption.splitlines() == ["Tue 29 Sep – Tue 06 Oct 2026", - "Temperature (outdoor): low 8.1 °C, Wed 30 Sep at 5:30am · high 24.3 °C, Sat 3 Oct around 3pm", - "Temperature (indoor): low 18.0 °C, Wed 30 Sep at 6am · high 22.5 °C, Sat 3 Oct at 4pm"] - - -def test_an_average_chart_caption_leads_with_the_average(): - from zoneinfo import ZoneInfo - turn = _turn() - turn.average_asked = True - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": { - "outdoor.temperature": {"unit": "℃", "low": "8.1", "high": "24.3", "average": "15.2"}}}) - assert report.chart_caption("weather_history", {}, result, turn, ZoneInfo("UTC")).splitlines()[1] == \ - "Temperature: average 15.2 °C (low 8.1, high 24.3)" - - -def test_a_rain_chart_caption_is_the_least_and_most_rain(): - from zoneinfo import ZoneInfo - turn = _turn() - turn.chart_fields = ["rain"] - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "series": {"rainfall.daily": {"unit": "mm", "low": "0", "high": "7.2"}}}) - lines = report.chart_caption("weather_history", {}, result, turn, ZoneInfo("UTC")).splitlines() - assert lines[1].startswith("☔ Rain per day: least 0 mm (") and "most 7.2 mm (" in lines[1] and "8.6 mm in all" in lines[1] - assert len(lines) == 2 - - -def test_an_air_chart_caption_gives_each_metrics_peak_rating_and_average(): - from zoneinfo import ZoneInfo - result = json.dumps({"period": "Tue 29 Sep 2026 - Tue 06 Oct 2026", "pm2_5": { - "unit": "µg/m³", "high": 34.2, "high_time": "Wed 30 Sep 2026 3:00pm", "high_rating": "🟠 Poor", "average": 8.1}, - "pm10": {"unit": "µg/m³", "high": 50, "high_time": "x", "average": 9}}) - caption = report.chart_caption("air_quality", {"metrics": ["pm2_5"]}, result, _turn(), ZoneInfo("UTC")) - assert caption.splitlines()[1] == "• PM2.5: peak 34.2 µg/m³ (Wed 30 Sep 3:00pm) · 🟠 Poor · average 8.1" - assert len(caption.splitlines()) == 2 - - -def test_no_caption_when_the_tool_failed_or_drew_nothing(): - from zoneinfo import ZoneInfo - from types import SimpleNamespace as NS - assert report.chart_caption("weather_history", {}, json.dumps({"error": "x"}), _turn(), ZoneInfo("UTC")) is None - assert report.chart_caption("weather_history", {}, json.dumps({"series": {}}), NS(charts=[]), ZoneInfo("UTC")) is None - - # ---------- a days lookup (the model's day tools' charts that answer the question) ---------- -def test_a_days_count_lookup_gives_the_count_the_condition_and_the_period(): - result = json.dumps({"period": "Wed 5 Oct 2022 - Sat 3 Oct 2026", "days_checked": 1454, "matching_days": 137, "condition": "UV index ≥ 10"}) - assert report.lookup("days", result, [], [], TODAY) == "137 of 1,454 days with UV index ≥ 10 (Wed 5 Oct 2022 – Sat 3 Oct 2026)." - averaged = json.dumps({"period": "a - b", "days_checked": 10, "matching_days": 2, "note_averaged": "x"}) - assert "may fall slightly short" in report.lookup("days", averaged, [], [], TODAY) - assert report.lookup("days", json.dumps({"error": "bad"}), [], [], TODAY) is None - - -def test_a_figure_per_period_lookup_gives_the_figure_over_the_whole_period(): - result = json.dumps({"period": "Fri 4 Oct 2024 - Sat 3 Oct 2026", "days_checked": 731, "matching_days": 731, - "stat": {"what": "Total rain", "of": "rain", "unit": "mm"}, "value": 1234.5, "by_month": {"2024-10": 0.0}}) - assert report.lookup("days", result, [], [], TODAY) == "Total rain: 1234.5 mm over 731 days (Fri 4 Oct 2024 – Sat 3 Oct 2026)." - hot = json.dumps({"period": "a 2025 - b 2026", "days_checked": 3, "matching_days": 3, "stat": {"what": "Highest temperature", "of": "temp_max", "unit": "℃"}, "value": 41.2}) - assert report.lookup("days", hot, [], [], TODAY).startswith("Highest temperature: 41.2 °C over 3 days") - - def test_when_gives_the_form_the_tools_use_in_their_time_field(): from datetime import datetime from lib.timeutil import when diff --git a/tests/test_service_about.py b/tests/test_service_about.py index 5ff42889..79c90a4b 100644 --- a/tests/test_service_about.py +++ b/tests/test_service_about.py @@ -6,7 +6,7 @@ from datetime import timedelta from types import SimpleNamespace as NS -from lib import prompt, templates +from lib import templates from lib.airgradient import AirGradient from lib.alerts import forecast as forecast_alert, menu, particulates, weather from lib.ecowitt.glance import UVI_ALERT @@ -62,7 +62,7 @@ async def test_arguments_are_refused_with_how_to_call_it(): def test_the_lists_are_the_ones_the_bots_prompt_menu_and_help_had(): - assert ab.NEVER_AVAILABLE == prompt.NEVER_AVAILABLE and ab.WITHOUT == prompt.WITHOUT and ab.ALERT_WORDS == prompt.ALERT_WORDS + assert "lightning" in ab.NEVER_AVAILABLE and set(ab.WITHOUT) == {"Pollen", "Forecast"} and "gusts" in ab.ALERT_WORDS # (the old prompt's lists, kept here) assert ab.TYPES == {kind: v for kind, v in menu.TYPES.items() if v[1] != "Irrigation"} # (irrigation: a server of its own) assert ab.MEASURES == templates.MEASURES for sources in (EVERY, ["Ecowitt"], ["AirGradient", "Pollen"], []): @@ -90,7 +90,7 @@ async def test_what_it_measures_and_doesnt_for_the_sources_there_are(tmp_path, a alone = await world(tmp_path / "alone", archived_cache, air=False, others=False) got = await call(alone) assert list(got["measures"]) == [STATION] - assert got["not_available"] == [*ab.NEVER_AVAILABLE, *prompt.WITHOUT.values(), "air quality"] + assert got["not_available"] == [*ab.NEVER_AVAILABLE, *ab.WITHOUT.values(), "air quality"] assert [a["kind"] for a in got["alerts"]] == ["rain", "gusts", "uv", "temps"] # the station's alerts alone assert "scan" not in got["tools"] and "forecast" not in got["tools"] and "outlook" in got["tools"] await close(alone) @@ -110,7 +110,7 @@ def test_each_alert_has_its_rule_and_the_thresholds_the_rules_use(monkeypatch): assert rules["pollen_and_asthma"]["thresholds"] == {"from_level": "High"} and "from 7:30am" in rules["pollen_and_asthma"]["rule"] assert rules["rain"]["thresholds"] == {"dry_minutes": 60, "quiet_hours": "00:00-06:00"} assert rules["rain"]["rule"].endswith("None from 12am to 6am: one summary of the rain in those hours after them.") - assert all(a["what"] == prompt.ALERT_WORDS[a["kind"]] and a["name"] == menu.LABELS[a["kind"]] for a in rules.values()) + assert all(a["what"] == ab.ALERT_WORDS[a["kind"]] and a["name"] == menu.LABELS[a["kind"]] for a in rules.values()) monkeypatch.setattr(ab, "RAIN_QUIET_HOURS", None) # the service's settings, as the config sets them monkeypatch.setattr(ab, "ALERT_COOLDOWN_MINUTES", 90) rules = {a["kind"]: a for a in ab.alerts(EVERY)} diff --git a/tests/test_service_base.py b/tests/test_service_base.py index 3a31f623..9cca2409 100644 --- a/tests/test_service_base.py +++ b/tests/test_service_base.py @@ -6,9 +6,7 @@ import pytest -from lib import intent from lib.periods_text import PeriodError -from lib.prompt import PROMPT from lib.service import common, daylook, names from lib.service.common import (CHART_NOTE, FRESH, Refusal, ServiceTool, answer, charts_field, period_properties, read_period, refuse, refuse_period, request_meta, with_charts) @@ -59,7 +57,7 @@ async def handler(args, meta): tool = ServiceTool("probe", "A probe.", {"type": "object", "properties": {}}, handler, open_world=True) assert tool.annotations == {"readOnlyHint": True, "openWorldHint": True} tools = Tools([tool.tool()]) - assert got(await tools.call("probe", '{"x": 1}', Turn(text="plot it", chart_asked=True, meta={"chart_points": 500}))) == {"ok": True} + assert got(await tools.call("probe", '{"x": 1}', Turn(chart_asked=True, meta={"chart_points": 500}))) == {"ok": True} assert seen[-1] == ({"x": 1}, {"chart_points": 500, "fetch": True, "priority": "normal"}) # the Turn's words never reach it await tools.call("probe", "{}", Turn(ahead=True)) # a chart drawn ahead is a background request assert seen[-1][1]["priority"] == "background" @@ -264,8 +262,6 @@ def test_all_is_every_station_reading_in_the_usual_chart_order_with_the_settings monkeypatch.setattr(names, "FEELS_LIKE_IN_ALL", True) monkeypatch.setattr(names, "VPD_IN_ALL", True) assert named("all") == [*usual[:8], "outdoor.feels_like", "outdoor.vpd", *usual[8:]] - assert intent.chart_fields("weather all week") == ["temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", - "vpd", "wind"] # the bot's "weather all week" reads the same settings held = Catalogue.of({"outdoor": {"temperature": "℃"}, "indoor": {"temperature": "℃"}, "pressure": {"relative": "hPa"}, "wind": {"wind_speed": "km/h"}, "rainfall": {"daily": "mm"}, "rainfall_piezo": {"daily": "mm"}, "solar_and_uvi": {"uvi": ""}}, air=False) @@ -379,8 +375,8 @@ def test_a_day_with_no_solar_radiation_has_no_cloud_step(): assert day_look(today | {"temp_max": 36.0}, latitude=MELBOURNE, day=SUMMER, so_far=True)["word"] == "very hot" -def test_a_days_look_uses_only_the_prompts_weather_emojis(): - allowed = next(line for line in PROMPT.splitlines() if "Use only these" in line) +def test_a_days_look_uses_only_the_weather_emojis_the_bot_always_used(): + allowed = "☀️ 🌤️ ⛅ ☁️ 🌦️ 🌧️ ⛈️ 💨 🥵 🥶 🌫️" # (the old prompt's list) assert all(emoji in allowed for emoji in LOOKS.values()) assert daylook.FIGURES == ("rain", "wind_gust", "temp_max", "temp_min", "solar_avg") # the days tool's names @@ -396,3 +392,23 @@ def test_a_clear_sky_follows_the_season_and_the_latitude(): def test_the_service_modules_say_what_they_offer(): for module in (common, names, daylook): assert all(hasattr(module, name) for name in module.__all__), module.__name__ + + +def test_the_ten_are_built_in_order_each_where_its_source_is_and_found_by_name(): + from lib.service.context import Context + from types import SimpleNamespace as NS + from lib.service import ORDER, Service, build + from tests.fakes import TZ + station = NS(name="Ecowitt", tz=TZ, storage=None, latitude=-37.8) + everything = build(Context(eco=station, air=NS(name="AirGradient", tz=TZ), forecast=NS(), pollen=NS(), tz=TZ)) + assert [t.name for t in everything] == list(ORDER) + assert [t.name for t in build(Context(tz=TZ))] == ["summary", "readings", "relate", "scan", "about"] # no source: what needs none + service = Service(everything) + assert service["summary"] is service.get("summary") and "days" in service and service.get("nothing") is None + assert [t.name for t in service] == list(ORDER) and service.held(["a"]) == ["a"] # (no context: every name is held) + + +def test_the_bot_asks_for_its_charts_as_drawn(): + from lib.service.common import AS_DRAWN, MAX_CHART_POINTS, request_meta + assert request_meta({"chart_points": AS_DRAWN})["chart_points"] == AS_DRAWN + assert request_meta({"chart_points": 10_000})["chart_points"] == MAX_CHART_POINTS diff --git a/tests/test_service_current.py b/tests/test_service_current.py index fd7279be..ad177e33 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -11,7 +11,7 @@ from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.airgradient import AirGradient from lib.ecowitt.days import day_values_on -from lib.intent import NOW_GROUPS +from tests.old_tools import NOW_GROUPS from lib.service import current as cur from lib.service.common import FRESH from lib.service.context import Context @@ -19,6 +19,7 @@ from lib.service.names import AIR_DEVICE, STATION, Catalogue from lib.timeutil import clock_text, to_local from tests.fakes import TZ, air_transport, archived_station, config +from tests import old_tools WHEN = re.compile(r"^(at|around) \d{1,2}(:\d\d)?[ap]m$|^sometime between ") @@ -189,7 +190,7 @@ async def test_the_lines_are_the_reports_and_weather_nows_words(tmp_path, archiv tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) got = await call(tool) eco, today = tool.ctx.eco, tool.ctx.now().date() - weather_now, air_quality = await eco._realtime({"groups": NOW_GROUPS}), await air.handle({}) # today's tools, on the same readings + weather_now, air_quality = await old_tools.weather_now(eco, {"groups": NOW_GROUPS}), await old_tools.air_quality(air, {}) # today's tools, on the same readings written = "\n\n".join(f"{got['headings'][d]}\n" + "\n".join(got["lines"][d]) for d in (STATION, AIR_DEVICE)) assert written == report.report({"weather_now": weather_now, "air_quality": air_quality}, today) assert "\n".join(got["lines"][STATION]) == report.weather_now(weather_now) @@ -216,11 +217,11 @@ async def test_the_lines_are_the_reports_and_weather_nows_words(tmp_path, archiv async def test_named_readings_are_worded_as_the_bots_plain_lookups(tmp_path, archived_cache, changes): tool, _, air = await world(tmp_path, archived_cache, live(time.time(), **changes)) eco, today = tool.ctx.eco, tool.ctx.now().date() - weather_now = await eco._realtime({"groups": NOW_GROUPS}) + weather_now = await old_tools.weather_now(eco, {"groups": NOW_GROUPS}) for names, sides, asked in LOOKUPS: got = await call(tool, readings=asked) assert "\n".join(got["lines"][STATION]) == report.lookup("reading", weather_now, names, sides, today), asked - air_quality = await air.handle({}) + air_quality = await old_tools.air_quality(air, {}) for names, asked in ((["pm10"], ["pm10"]), (["co2", "pm2_5"], ["co2", "pm2.5"]), ([], ["air"]), ([], ["airgradient"])): got = await call(tool, readings=asked) assert "\n".join(got["lines"][AIR_DEVICE]) == report.lookup("air", air_quality, names, [], today), asked @@ -377,7 +378,7 @@ async def test_a_device_that_doesnt_answer_is_said_so_and_the_other_still_answer assert got["lines"][STATION] == ["• not available right now"] and got["headings"][STATION] == "Weather station" assert list(got["sensors"]) == ["air"] and got["as_of"] written = "\n\n".join(f"{got['headings'][d]}\n" + "\n".join(got["lines"][d]) for d in (STATION, AIR_DEVICE)) - assert written == report.report({"weather_now": "Error calling tool: busy", "air_quality": await air.handle({})}, + assert written == report.report({"weather_now": "Error calling tool: busy", "air_quality": await old_tools.air_quality(air, {})}, tool.ctx.now().date()) # the report's words for it async def down(extras=()): diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 0449b848..9d088283 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -154,9 +154,6 @@ def test_the_tool_list_is_the_ten_service_tools_with_their_own_descriptions_and_ assert [t.name for t in built] == evalkit.service_tool_names() offered = evalkit.make_service_tools([]) assert set(offered.by_name) == set(evalkit.service_tool_names()) - # (the two lists are never offered together; the one name they share is the service's own `readings`, not the bot's) - assert set(offered.by_name) & set(evalkit.tool_names()) == {"readings"} - assert offered.by_name["readings"].parameters != evalkit.make_tools([]).by_name["readings"].parameters for tool, schema in zip(built, offered.schemas): assert schema == {"type": "function", "function": {"name": tool.name, "description": tool.description, "parameters": tool.parameters}} diff --git a/tests/test_service_forecast.py b/tests/test_service_forecast.py index 2054b3ae..1385c721 100644 --- a/tests/test_service_forecast.py +++ b/tests/test_service_forecast.py @@ -14,6 +14,7 @@ from lib.service.forecast import DESCRIPTION, PARAMETERS, days_text, read_ahead, tools from lib.timeutil import day_text from tests.fakes import TZ, config +from tests import old_tools NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm, as the plan's periods table is asked @@ -131,7 +132,7 @@ async def test_the_lines_are_weather_forecasts_and_each_day_has_its_figures(tmp_ assert forecast_tool.name == "forecast" and forecast_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} out = got(await forecast_tool.call({})) assert calls == ["api.open-meteo.com", "ensemble-api.open-meteo.com"] # nothing held: fetched, as weather_forecast does - old = got(await forecast.handle({})) + old = got(await old_tools.forecast(forecast, {})) assert out["lines"] == old["lines"] and len(out["lines"]) == 7 and out["lines"][0].startswith("Today: 🌧️ Rain. 11–16°C") today = forecast.now().date() assert out["period"]["asked"] == "the next 7 days" and out["period"]["text"].startswith("the next 7 days: ") @@ -145,13 +146,13 @@ async def test_the_lines_are_weather_forecasts_and_each_day_has_its_figures(tmp_ assert out["fetched_at"] == fetched.isoformat() and out["as_of"]["time"] == fetched.isoformat() assert list(out) == ["period", "as_of", "fresh", "text", "lines", "days", "place", "source", "fetched_at"] for n in range(1, 8): # "next N days" is weather_forecast's `days: N`, line for line - assert got(await forecast_tool.call({"period": f"next {n} days"}))["lines"] == got(await forecast.handle({"days": n}))["lines"] + assert got(await forecast_tool.call({"period": f"next {n} days"}))["lines"] == got(await old_tools.forecast(forecast, {"days": n}))["lines"] await forecast.close() async def test_a_day_ahead_has_its_own_line_as_weather_forecast_writes_it(tmp_path): forecast, _, ctx = make(tmp_path) - week = got(await forecast.handle({"days": 7}))["lines"] + week = got(await old_tools.forecast(forecast, {"days": 7}))["lines"] tomorrow = got(await tool(ctx).call({"period": "tomorrow"})) assert tomorrow["lines"] == [week[1]] and tomorrow["period"]["text"].startswith("tomorrow: ") day = forecast.now().date() + timedelta(days=4) @@ -165,7 +166,7 @@ async def test_its_text_is_the_bots_forecast_section_word_for_word(tmp_path): today = forecast.now().date() for words, days in (("next 3 days", 3), ("the next 7 days", 7), ("today", 1)): out = got(await tool(ctx).call({"period": words})) - old = await forecast.handle({"days": days, "cached": True}) + old = await old_tools.forecast(forecast, {"days": days, "cached": True}) assert out["text"] == report.lookup("forecast", old, [], [], today) == report.report({"weather_forecast": old}, today) assert out["text"].startswith(f"Forecast (Melbourne, {report._stamp(json.loads(old), today)})\n• Today: ") later = today + timedelta(days=1) # asked the next day, the time it was fetched has its day @@ -177,7 +178,7 @@ async def test_its_text_is_the_bots_forecast_section_word_for_word(tmp_path): async def test_with_no_place_the_heading_has_only_the_time(tmp_path): forecast, _, ctx = make(tmp_path, place="") out = got(await tool(ctx).call({"period": "today"})) - old = await forecast.handle({"days": 1}) + old = await old_tools.forecast(forecast, {"days": 1}) assert "place" not in out and out["text"] == report.lookup("forecast", old, [], [], forecast.now().date()) await forecast.close() @@ -186,7 +187,7 @@ async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing forecast, calls, ctx = make(tmp_path) out = got(await tool(ctx).call({}, {"fetch": False})) assert out == {"error": "No forecast is available right now."} and calls == [] # (weather_forecast's words, with cached) - assert got(await forecast.handle({"cached": True})) == out + assert got(await old_tools.forecast(forecast, {"cached": True})) == out await forecast.warm(True) calls.clear() held = got(await tool(ctx).call({"period": "tomorrow"}, {"fetch": False})) diff --git a/tests/test_service_legacy.py b/tests/test_service_legacy.py deleted file mode 100644 index 8c1f1163..00000000 --- a/tests/test_service_legacy.py +++ /dev/null @@ -1,109 +0,0 @@ -"""The service's tools registered (lib/service/__init__.py), and the bot's old calls read as the service's (lib/service/legacy.py).""" - -from datetime import datetime -from types import SimpleNamespace as NS - -from lib import intent -from lib.service import ORDER, Service, build, legacy -from lib.service.common import AS_DRAWN, MAX_CHART_POINTS, request_meta -from lib.service.context import Context -from lib.tools import Turn -from tests.fakes import TZ - -NOW = datetime(2026, 11, 10, 14, 5) # Tue 10 Nov 2026 2:05pm - - -def test_the_ten_are_built_in_order_each_where_its_source_is_and_found_by_name(): - station = NS(name="Ecowitt", tz=TZ, storage=None, latitude=-37.8) - everything = build(Context(eco=station, air=NS(name="AirGradient", tz=TZ), forecast=NS(), pollen=NS(), tz=TZ)) - assert [t.name for t in everything] == list(ORDER) - assert [t.name for t in build(Context(tz=TZ))] == ["summary", "readings", "relate", "scan", "about"] # no source: what needs none - service = Service(everything) - assert service["summary"] is service.get("summary") and "days" in service and service.get("nothing") is None - assert [t.name for t in service] == list(ORDER) and service.held(["a"]) == ["a"] # (no context: every name is held) - - -def test_the_bot_asks_for_its_charts_as_drawn(): - assert request_meta({"chart_points": AS_DRAWN})["chart_points"] == AS_DRAWN - assert request_meta({"chart_points": 10_000})["chart_points"] == MAX_CHART_POINTS - - -def read(text): - r = intent.read(text, NOW, ("Ecowitt", "AirGradient", "Pollen", "Forecast")) - return r, Turn.of(r, text) - - -def test_a_chart_asked_for_plainly_is_summarys_call_with_its_period_in_the_services_words(): - for text, want in (("Rain chart 1d", {"readings": ["rainfall.rain"], "period": "last 24 hours", "chart": True}), - ("Temperature chart 7d", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 7 days", "chart": True}), - ("indoor temperature chart 7d", {"readings": ["indoor.temperature"], "period": "last 7 days", "chart": True}), - ("pressure chart this month", {"readings": ["pressure.relative"], "period": "this month", "chart": True}), - ("average temperature 7d", {"readings": ["outdoor.temperature", "indoor.temperature"], "period": "last 7 days", - "chart": True, "average": True}), - ("plot uv and solar on two axes 7d", {"readings": ["solar_and_uvi.uvi", "solar_and_uvi.solar"], "period": "last 7 days", - "chart": True, "layout": "two_axes"}), - ("lowest temperature on record", {"readings": ["outdoor.temperature", "indoor.temperature"], # (the bot's "on record") - "period": "2022-11-12 to now", "chart": True}), - ("Particulates chart 1d", {"readings": ["air.pm2_5", "air.pm10", "air.pm1"], "period": "last 24 hours", "chart": True})): - r, turn = read(text) - assert legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == ("summary", want), text - - -def test_the_lookups_are_the_tools_that_word_them(): - for text, want in (("how hot is it", ("current", {"readings": ["temperature"]})), - ("indoor temperature", ("current", {"readings": ["indoor temperature"]})), - ("co2", ("current", {"readings": ["air.co2"]})), ("air quality now", ("current", {"readings": ["air"]})), - ("what can you do", ("about", {}))): - assert legacy.lookup(read(text)[0]) == want, text - for text, want in (("forecast", ("forecast", {"period": "the next 7 days"})), ("pollen", ("pollen", {})), - ("highest temperature yesterday", ("summary", {"readings": ["outdoor.temperature", "indoor.temperature"], - "period": "yesterday", "chart": False})), - ("rain by month this year", ("days", {"count_only": True, "group_by": "month", "stat": "sum", "of": "rain", - "period": "2026-01-01 to now"}))): - r, turn = read(text) - assert legacy.lookup(r) is None and legacy.translate(*r.fast[:2], turn, now=NOW, tz=TZ) == want, text - assert legacy.report(("Ecowitt", "AirGradient", "Pollen", "Forecast")) == [("current", {}), ("pollen", {}), - ("forecast", {"period": "next 3 days"})] - - -def test_a_period_is_words_the_service_reads_as_the_same_span_else_whole_days_else_times(): - assert legacy.period("2026-11-09 14:05:00", "2026-11-10 14:05:00", ["last 24 hours"], NOW, TZ) == {"period": "last 24 hours"} - assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this week"], NOW, TZ) == {"period": "this week"} - assert legacy.period("2026-11-04 00:00:00", "2026-11-10 23:59:59", ["this month"], NOW, TZ) == {"period": "2026-11-04 to now"} - assert legacy.period("2026-11-01 00:00:00", None, [], NOW, TZ) == {"period": "2026-11-01 to now"} - assert legacy.period("2026-11-09 06:00:00", "2026-11-09 11:59:59", [], NOW, TZ) == {"start": "2026-11-09 06:00", "end": "2026-11-09 12:00"} - assert legacy.period("2026-01-01", "2026-11-10", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to now"} - assert legacy.period("2026-01-01", "2026-10-31", [], NOW, TZ, whole_days=True) == {"period": "2026-01-01 to 2026-10-31"} # past: fixed - - -def test_the_periods_a_chart_the_model_drew_is_worth_drawing_over_are_its_tools(): - assert [p["period"] for p in legacy.periods_of("summary", {"period": "last 7 days"})] == ["1d", "7d", "1m", "3m", "1y"] - assert [p["period"] for p in legacy.periods_of("summary", {"period": "last 7 days", "average": True})] == ["7d", "1m", "3m", "1y"] - assert legacy.periods_of("summary", {"start": "2026-11-09 06:00"}) == [] # a time can't be swapped for a period - assert [p["label"] for p in legacy.periods_of("days", {"group_by": "month"})] == ["3M", "1Y", "All"] - assert legacy.periods_of("days", {"group_by": "year"}) == [] and legacy.translate("plot_chart", {}, now=NOW, tz=TZ) is None - - -def test_the_models_own_arguments_that_change_its_chart_are_carried_as_the_old_tools_honour_them(): - """weather_history's two_axes is the model's as much as the words' (query: turn.two_axes or args two_axes), with two readings.""" - week = {"start_date": "2026-11-03 14:05:00", "end_date": "2026-11-10 14:05:00", "chart": True} - _, turn = read("plot uv and solar 7d") - assert not turn.two_axes - tool, args = legacy.translate("weather_history", {**week, "chart_fields": ["uv", "solar"], "two_axes": True}, turn, now=NOW, tz=TZ) - assert tool == "summary" and args["layout"] == "two_axes" and args["readings"] == ["solar_and_uvi.uvi", "solar_and_uvi.solar"] - tool, args = legacy.translate("weather_history", {**week, "chart_fields": ["uv", "solar", "temperature"], "two_axes": True}, - Turn(text="plot those"), now=NOW, tz=TZ) - assert len(args["readings"]) == 4 - assert "layout" not in args # (three readings: a panel each, as the old tool drew them) - - -def test_a_days_call_is_grouped_and_filtered_as_the_old_tool_read_it(): - """weather_days and air_days put in group_by from the words when the model left it out, and weather_days drops a holiday or - weekend filter the words never asked for: both change the bars drawn.""" - _, turn = read("days with uv over 9 per month this year") - days = {"start_date": "2026-01-01", "end_date": "2026-11-10", "where": [{"field": "uv_max", "op": ">", "value": 9}]} - for name in ("weather_days", "air_days"): - assert legacy.translate(name, days, turn, now=NOW, tz=TZ)[1].get("group_by") == "month", name - assert "only" not in legacy.translate("weather_days", {**days, "only": "weekend"}, turn, now=NOW, tz=TZ)[1] - _, turn = read("how many weekends had uv over 9 this year") - assert legacy.translate("weather_days", {**days, "only": "weekend"}, turn, now=NOW, tz=TZ)[1]["only"] == "weekend" diff --git a/tests/test_service_pollen.py b/tests/test_service_pollen.py index d82a8ffd..1e96185f 100644 --- a/tests/test_service_pollen.py +++ b/tests/test_service_pollen.py @@ -11,6 +11,7 @@ from lib.service.pollen import DESCRIPTION, PARAMETERS, tools from tests.fakes import TZ from tests.test_pollen import SEASON_DAY, make, page +from tests import old_tools def got(text: str) -> dict: @@ -33,7 +34,7 @@ async def test_the_lines_are_pollen_asthmas_and_each_level_has_its_emoji_and_day assert pollen_tool.name == "pollen" and pollen_tool.annotations == {"readOnlyHint": True, "openWorldHint": True} out = got(await pollen_tool.call({})) assert len(calls) == 1 # nothing held: fetched, as pollen_asthma does - old = got(await pollen.handle({})) + old = got(await old_tools.pollen(pollen, {})) assert out["lines"] == old["lines"] == ["Grass pollen forecast: 🔴 High", "Thunderstorm asthma forecast: 🟠 Moderate"] assert out["grass"] == {"level": "High", "emoji": "🔴", "day": "2026-11-10", "day_text": "Tue 10 Nov 2026"} assert out["asthma"] == {"level": "Moderate", "emoji": "🟠", "updated": "1 Oct 2026 4:00pm"} @@ -48,7 +49,7 @@ async def test_the_lines_are_pollen_asthmas_and_each_level_has_its_emoji_and_day async def test_its_text_is_the_bots_pollen_section_word_for_word(tmp_path): pollen, _ = make(tmp_path, lambda: page(grass="Low", asthma="Low")) out = got(await tool(context(pollen)).call({})) - old = await pollen.handle({"cached": True}) + old = await old_tools.pollen(pollen, {"cached": True}) assert out["text"] == report.lookup("pollen", old, [], [], SEASON_DAY) == report.report({"pollen_asthma": old}, SEASON_DAY) assert out["text"].endswith("\n• Grass pollen forecast: 🟢 Low\n• Thunderstorm asthma forecast: 🟢 Low") later = SEASON_DAY + timedelta(days=1) @@ -59,7 +60,7 @@ async def test_its_text_is_the_bots_pollen_section_word_for_word(tmp_path): async def test_a_forecast_for_another_day_says_its_day_and_a_missing_asthma_level_is_said_so(tmp_path): pollen, _ = make(tmp_path, lambda: page(grass="Moderate", day=SEASON_DAY + timedelta(days=1), season=False)) out = got(await tool(context(pollen)).call({})) - old = got(await pollen.handle({})) + old = got(await old_tools.pollen(pollen, {})) assert out["lines"] == old["lines"] == ["Grass pollen forecast: 🟠 Moderate (forecast for Wed 11 Nov)"] assert out["grass"]["day"] == "2026-11-11" and out["asthma"] is None and out["asthma_note"] == old["asthma_note"] await pollen.close() @@ -68,7 +69,7 @@ async def test_a_forecast_for_another_day_says_its_day_and_a_missing_asthma_leve async def test_with_fetch_false_it_answers_from_what_is_held_and_fetches_nothing(tmp_path): pollen, calls = make(tmp_path) out = got(await tool(context(pollen)).call({}, {"fetch": False})) - assert out == {"error": "No pollen levels are available right now."} == got(await pollen.handle({"cached": True})) and calls == [] + assert out == {"error": "No pollen levels are available right now."} == got(await old_tools.pollen(pollen, {"cached": True})) and calls == [] await pollen.warm(True) calls.clear() held = got(await tool(context(pollen)).call({}, {"fetch": False})) @@ -80,7 +81,7 @@ async def test_out_of_season_it_gives_pollen_asthmas_answer_and_fetches_nothing( pollen, calls = make(tmp_path) pollen.now = lambda: datetime(2026, 1, 15, 12, 0) out = await tool(context(pollen, date(2026, 1, 15))).call({}) - assert out == await pollen.handle({}) and got(out) == {"error": OFF_SEASON} and calls == [] + assert out == await old_tools.pollen(pollen, {}) and got(out) == {"error": OFF_SEASON} and calls == [] await pollen.close() diff --git a/tests/test_service_readings.py b/tests/test_service_readings.py index 87d75a0e..0c2e358b 100644 --- a/tests/test_service_readings.py +++ b/tests/test_service_readings.py @@ -7,12 +7,13 @@ import pytest -from lib.history import INTERVALS, MAX_ROWS, History +from lib.history import INTERVALS, MAX_ROWS from lib.service import readings from lib.service.common import FRESH from lib.service.context import Context from lib.service.names import Catalogue from lib.storage import Storage +from tests.old_tools import History from lib.storage.catalogue import CLOUD from lib.timeutil import local_epoch from lib.tools import Tools, Turn @@ -210,6 +211,6 @@ async def test_only_the_arguments_reach_it_and_its_metadata_changes_nothing(stor put(storage, "outdoor", "5min", [{"ts": at(9, 1, 5 * i), "humidity": 80 + i} for i in range(9)]) args = {"reading": "outdoor.humidity", "period": "last hour", "interval": "5min"} direct = await tool(storage).call(args) - via_bot = await Tools([tool(storage).tool()]).call("readings", json.dumps(args), Turn(text="humidity every 30 minutes", per_day=True)) + via_bot = await Tools([tool(storage).tool()]).call("readings", json.dumps(args), Turn(per_day=True)) assert via_bot == direct and json.loads(direct)["interval"] == "5min" assert await tool(storage).call(args, {"fetch": False, "priority": "background"}) == direct # nothing is fetched here anyway diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py index 8c7a89cc..b335040c 100644 --- a/tests/test_service_relate.py +++ b/tests/test_service_relate.py @@ -218,7 +218,7 @@ async def test_a_chart_is_sent_in_the_points_the_request_asks_for_and_only_when_ lines = [s for p in small["charts"][0]["panels"] for s in p["series"] if s["kind"] in ("line", "band")] assert lines and all(len(s["points"]) <= 20 for s in lines) (made,) = relate.tools(ctx) - asked = json.loads(await Tools([made.tool()]).call("relate", "{}", Turn(text="plot pressure against rain", chart_asked=True))) + asked = json.loads(await Tools([made.tool()]).call("relate", "{}", Turn(chart_asked=True))) assert "charts" not in asked # the words of the question never reach it: only `chart` draws await eco.close() diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index 9695d384..52829b4c 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -7,7 +7,6 @@ from tests import report_words as report # (the bot's words before step 2: the oracle) from lib.airgradient import AirGradient -from lib.bot import _as_drawn from lib.compose import Composer from lib.ecowitt.days import day_values_on from lib.service import summary @@ -17,6 +16,7 @@ from lib.tools import Turn from tests.fakes import TZ, air_transport, archived_station, config from tests.test_chart_json import errors as schema_errors +from tests import old_tools async def make(tmp_path, archived_cache, air: bool = False, **air_options): @@ -112,7 +112,7 @@ async def test_an_average_is_by_time_and_comes_with_each_days(tmp_path, archived temp = out["series"]["outdoor.temperature"] assert temp["low"] < temp["average"] < temp["high"] and temp["average_text"] == f"{temp['average']} °C" assert all("average" in row for row in temp["daily"].values()) - old = json.loads(await ctx.eco._history({"start_date": f"{days_ago(6)} 00:00:00", "end_date": datetime.now(TZ).strftime( + old = json.loads(await old_tools.weather_history(ctx.eco, {"start_date": f"{days_ago(6)} 00:00:00", "end_date": datetime.now(TZ).strftime( "%Y-%m-%d %H:%M:%S"), "groups": "outdoor", "average": True})) assert float(old["series"]["outdoor.temperature"]["average"]) == temp["average"] # weather_history's own await close(ctx) @@ -141,7 +141,7 @@ async def test_rain_is_the_mm_that_fell_its_total_and_its_wettest_day(tmp_path, assert round(sum(r["total"] for r in every["series"]["rainfall.rain"]["daily"].values()), 1) == rain["total"] drawn = await ask(tool, readings=["rain"], period="last 14 days") # the chart's total is the same old_turn = Turn() - old = json.loads(await ctx.eco._history({"start_date": f"{days_ago(13)} 00:00:00", "end_date": datetime.now(TZ).strftime( + old = json.loads(await old_tools.weather_history(ctx.eco, {"start_date": f"{days_ago(13)} 00:00:00", "end_date": datetime.now(TZ).strftime( "%Y-%m-%d %H:%M:%S"), "groups": "rainfall", "chart_field": "rain", "chart": True}, old_turn)) assert drawn["rain_total_mm"] == old["rain_total_mm"] == rain["total"] long = await ask(tool, readings=["rain"], period="3m", chart=False) @@ -164,7 +164,7 @@ async def test_the_air_sensors_figures_are_air_qualitys_with_their_wording(tmp_p out = await ask(tool, readings=["pm2.5", "co2", "air.temperature"], period="last 2 days", chart=False) assert list(out["series"]) == ["air.pm2_5", "air.co2", "air.temperature"] start, end = (datetime.fromisoformat(out["period"][k]).strftime("%Y-%m-%d %H:%M:%S") for k in ("start", "end")) - old = json.loads(await ctx.air.handle({"start_date": start, "end_date": end, "metrics": ["air_temperature"]})) + old = json.loads(await old_tools.air_quality(ctx.air, {"start_date": start, "end_date": end, "metrics": ["air_temperature"]})) pm = out["series"]["air.pm2_5"] for k in ("low", "high", "average", "high_rating", "average_rating", "high_aqi_us", "high_band", "average_aqi_us", "average_band"): assert pm[k] == old["pm2_5"][k], k @@ -332,9 +332,8 @@ async def old_caption(ctx, out: dict, tool: str, args: dict) -> str: args = {"start_date": start.strftime("%Y-%m-%d %H:%M:%S"), "end_date": (end - timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"), "chart": True, **args} turn = Turn() - handler = ctx.eco._history if tool == "weather_history" else ctx.air.handle - result = await handler(args, turn) - drawn_args, drawn = _as_drawn(tool, args, turn) + result = await (old_tools.weather_history(ctx.eco, args, turn) if tool == "weather_history" else old_tools.air_quality(ctx.air, args, turn)) + drawn_args, drawn = old_tools.as_drawn(tool, args, turn) return report.chart_caption(tool, drawn_args, result, drawn, TZ) @@ -365,7 +364,7 @@ async def test_with_no_chart_the_figures_come_in_the_words_the_bot_writes_for_a_ ["humidity", "pressure"])): out = await ask(tool, **args) start, end = (datetime.fromisoformat(out["period"][k]) for k in ("start", "end")) - result = await ctx.eco._history({"start_date": start.strftime("%Y-%m-%d %H:%M:%S"), + result = await old_tools.weather_history(ctx.eco, {"start_date": start.strftime("%Y-%m-%d %H:%M:%S"), "end_date": (end - timedelta(seconds=1)).strftime("%Y-%m-%d %H:%M:%S"), **old}) assert "charts" not in out and out["text"] == report.lookup("extremes", result, names, [], ctx.now().date()), args rain = await ask(tool, readings=["rain", "pm2.5"], period="yesterday") diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index ddf81e35..0240b2ba 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -162,8 +162,6 @@ async def open(self, tmp_path, archive): from lib.compose import Composer from lib.ecowitt import Ecowitt from lib.forecast import Forecast - from lib.history import History - from lib.tools import Tools from tests.fakes import TZ, config, ecowitt_transport from tests.test_pollen import make as make_pollen, page from tests.test_service_current import Station, live @@ -189,16 +187,12 @@ async def open(self, tmp_path, archive): source.poke = lambda: None self.eco, self.air, self.pollen, self.forecast = eco, air, pollen, forecast self.composer = Composer(eco, air) - history = await History.open(eco, air) - self.tools = Tools([t for s in self.sources for t in s.tools] + self.composer.tools + history.tools) + from lib import model_tools + from lib.service import Service from lib.service.context import Context - try: - from lib.service import Service - except ImportError: # (before the switch, when the answers were recorded: the bot had no service) - self.service = None - else: - self.service = Service.of(await Context.open(eco=eco, air=air, composer=self.composer, forecast=forecast, pollen=pollen, tz=TZ, - clock=lambda: FROZEN)) + self.service = Service.of(await Context.open(eco=eco, air=air, composer=self.composer, forecast=forecast, pollen=pollen, tz=TZ, + clock=lambda: FROZEN)) + self.tools = model_tools.tools(self.service) self.tz, self.cfg = TZ, cfg return self @@ -222,8 +216,7 @@ def gauges(sheet): return b"gauges" monkeypatch.setattr(botmod, "render_data", render) monkeypatch.setattr(botmod.gauges, "render", gauges) - return botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), self.sources, alert_state, - **({"service": self.service} if self.service else {})) + return botmod.Bot(NS(tz=self.tz), Agent(None, "m", self.tools), self.sources, alert_state, service=self.service) def message(self, message_id=50): world = self @@ -323,33 +316,41 @@ async def asked(world, alert_state, monkeypatch, text) -> dict: # Every question the bot answers in code: the keyboard's charts (templates.chart_sentences, the same with irrigation: only Wind goes), -# then each of intent's shortcuts and plain lookups (bot._answer: a chart made in code, the dashboard, a lookup, the report and -# "weather now") +# then each of intent's shortcuts (bot._answer: a named reading's chart and a period, the dashboard, the report and "weather now") from lib import templates # noqa: E402 KEYBOARD = templates.chart_sentences(False) SHORTCUTS = [ - # the report and "weather now" (written in code from weather_now, air_quality, pollen_asthma, weather_forecast) + # the report and "weather now" (written in code from current, pollen and forecast) "Report", "weather now", "status", - # a reading now (lookup "reading") - "how hot is it", "is it raining", "humidity", "wind", "indoor temperature", "uv", "pressure", - # the air now (fast path air_quality {}, lookup "air") - "air quality now", "co2", "how's the air", - # pollen, forecast, what the bot can do, the gauges - "pollen", "forecast", "what can you do", "dashboard", - # a days count and a figure per month or year (weather_days, lookup "days"; the per-month ones draw bars) - "how many days was the temperature over 18 this year", "how many days was humidity under 60 last month", + # the gauges + "dashboard", + # a named reading's chart and a period (summary with the words as they are; the caption goes with it) + "temperature chart 7d", "humidity 7d", "rain chart 7d", "pressure chart this month", "temperature and rain chart 7d", + "weather 30d", "indoor temperature chart 7d", "wind direction plot 3m", "temperature chart last month", "air quality chart 7d", + "pm2.5 chart 3d", +] +# What the bot answered in code until step 3 and the model answers now (with no model: NO_MODEL) +TO_THE_MODEL = [ + "how hot is it", "is it raining", "humidity", "wind", "indoor temperature", "uv", "pressure", # a reading now + "air quality now", "co2", "how's the air", # the air now + "pollen", "forecast", "what can you do", + "how many days was the temperature over 18 this year", "how many days was humidity under 60 last month", # days "how many days was pm2.5 over 15 this week", "days with uv over 9 per month this year", "rain by month this year", "average temperature per month this year", - # extremes of a short period (weather_history without a chart, lookup "extremes") - "highest temperature yesterday", "high and low today", "lowest humidity yesterday", "average pressure yesterday", + "highest temperature yesterday", "high and low today", "lowest humidity yesterday", "average pressure yesterday", # extremes "strongest gust today", "temps today", - # a chart made in code (weather_history or air_quality with a chart, captioned in code) - "temperature chart 7d", "humidity 7d", "rain chart 7d", "pressure chart this month", "temperature and rain chart 7d", - "weather 30d", "weather all week", "average temperature 7d", "plot uv and solar on two axes 7d", "indoor temperature chart 7d", - "wind direction plot 3m", "temperature chart last month", "lowest temperature on record", "highest humidity this week", - "temps this week", "air quality chart 7d", "pm2.5 chart 3d", "chart weather", + "weather all week", "average temperature 7d", "plot uv and solar on two axes 7d", "lowest temperature on record", # charts beside + "highest humidity this week", "temps this week", "chart weather", # a question ] +CHANGED = {"air quality chart 7d"} # a shortcut whose words the service reads as every air reading now (until step 3: PM2.5 alone) + + +@pytest.mark.parametrize("text", TO_THE_MODEL) +async def test_what_was_answered_in_code_goes_to_the_model(world, alert_state, monkeypatch, text): + from lib.bot import NO_MODEL + got = await asked(world, alert_state, monkeypatch, text) + assert got["history"] == NO_MODEL and got["charts"] == [] and got["gauges"] == [] @pytest.mark.parametrize("text", KEYBOARD + SHORTCUTS) @@ -360,7 +361,7 @@ async def test_the_bots_own_answers_are_unchanged(world, alert_state, monkeypatc period_buttons_are_drawn_bys(world, got) -@pytest.mark.parametrize("question, press", [("Temperature chart 1d", "7D"), ("Rain chart 1d", "1M"), ("rain by month this year", "1Y")]) +@pytest.mark.parametrize("question, press", [("Temperature chart 1d", "7D"), ("Rain chart 1d", "1M"), ("humidity 7d", "1Y")]) async def test_a_period_button_redraws_the_same_chart_as_before(world, alert_state, monkeypatch, question, press): """A press on a period button under a chart: the chart over that period, put into the same message.""" bot = world.bot(alert_state, monkeypatch) @@ -381,20 +382,7 @@ async def answer(text=None, **k): await bot.on_period_button(NS(callback_query=query, effective_message=under, effective_chat=under.chat, effective_user=NS(username="rob", full_name="Rob", id=7)), CONTEXT) got = {"charts": world.charts, "edits": [e[:2] for e in world.edits]} - name = f"press {press} under {question}" - if RECORD or press != "1Y" or "month" not in question: - pinned(name, got) - return - # The deliberate change: a count per month's buttons are its drawn_by's periods, read by the service: "1y" is the 365 whole days to - # yesterday (the old 1Y asked "... 365d", which the bot read as 364 whole days and today). The chart is otherwise the same. - want = golden()[name] - (chart,), (old,) = got["charts"], want["charts"] - assert chart["period"] == ["2025-11-10", "2026-11-09"] and old["period"] == ["2025-11-11", "2026-11-09"] - assert chart["subtitle"] == old["subtitle"].replace("Tue 11 Nov 2025", "Mon 10 Nov 2025").replace("364 days", "365 days") - assert {k: v for k, v in chart.items() if k not in ("period", "subtitle", "sha", "panels")} == \ - {k: v for k, v in old.items() if k not in ("period", "subtitle", "sha", "panels")} - assert got["edits"] == [["photo", "Total rain, Mon 10 Nov 2025 – Mon 9 Nov 2026\n\nTotal rain: 248 mm over 365 days (Mon 10 Nov 2025 – " - "Mon 9 Nov 2026)."]] + pinned(f"press {press} under {question}", got) @pytest.mark.parametrize("kind", ["gusts", "uv", "temps", "particulates"]) diff --git a/tests/test_snapshots.py b/tests/test_snapshots.py index 87620855..1a993737 100644 --- a/tests/test_snapshots.py +++ b/tests/test_snapshots.py @@ -1,7 +1,6 @@ import json from datetime import datetime, time as dtime -from lib import intent from lib.forecast import Forecast from lib.forecast.source import FORECAST_REFRESH_SECONDS from lib.pollen import Pollen @@ -10,6 +9,7 @@ from tests.fakes import TZ, config from tests.test_forecast import transport as forecast_transport from tests.test_pollen import SEASON_DAY, make as make_pollen, page, transport as pollen_transport +from tests import old_tools def rows(store, kind: str) -> int: @@ -108,8 +108,8 @@ async def test_the_report_always_uses_the_cache_for_pollen_and_forecast(tmp_path pollen = Pollen(config(tmp_path, pollen=True), pollen_transport(lambda: page(), calls)) forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9), None, forecast_transport(calls)) assert not pollen.wants("report") and not forecast.wants("sitrep") and pollen.wants("pollen today") and forecast.wants("forecast") - for tool, args in intent.report_calls(["Pollen", "Forecast"]): - out = json.loads(await {"pollen_asthma": pollen.handle, "weather_forecast": forecast.handle}[tool](args)) + for out in (json.loads(await old_tools.pollen(pollen, {"cached": True})), + json.loads(await old_tools.forecast(forecast, {"days": 3, "cached": True}))): assert "error" in out # nothing cached yet: the report goes without it, no request made assert calls == [] await pollen.close() diff --git a/tests/test_templates.py b/tests/test_templates.py index 4b2a3e09..e1c8913f 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -18,22 +18,26 @@ def test_a_button_label_is_its_sentence_without_the_emoji_and_typed_text_is_left def test_every_button_asks_something_the_bot_understands(): + """Status is the report; each chart button is a named reading's chart over a day: summary with the readings the service reads its + words as. (Help & Alerts never reaches intent: bot.on_message answers it.)""" + from zoneinfo import ZoneInfo + from lib.service.names import CATALOGUE + tz = ZoneInfo("Australia/Melbourne") + now = NOW.replace(tzinfo=tz) + def read(label): - return intent.read(templates.sentence(label), NOW) + return intent.read(templates.sentence(label), now, ("Ecowitt", "AirGradient"), tz) assert read("\U0001f4cb Status").report - weather = read("\U0001f326️ Weather") - assert intent.wants_chart_all(templates.sentence("\U0001f326️ Weather")) and weather.chart_in_code - assert weather.chart_fields[0] == "temperature" and weather.chart_fields[-1] == "wind" - for label, groups in (("\U0001f327️ Rain", "rainfall"), ("\U0001f4c8 Temperature", "outdoor,indoor"), - ("\U0001f4a7 Humidity", "outdoor,indoor"), ("\U0001f4a8 Wind", "wind")): - name, args, _ = read(label).fast - assert name == "weather_history" and args["chart"] is True and args["groups"] == groups and read(label).chart_in_code - assert read("\U0001f4a7 Humidity").chart_field == "humidity" and read("\U0001f327️ Rain").rain_caption - name, args, _ = read("\U0001f3ed Air Quality").fast - assert name == "air_quality" and args["chart"] is True and set(args["metrics"]) == {"pm1", "pm2_5", "pm10", "co2", "voc_index", "nox_index"} - name, args, _ = read("\U0001f52c Particulates").fast - assert name == "air_quality" and args["chart"] is True and set(args["metrics"]) == {"pm1", "pm2_5", "pm10"} - assert read(templates.CAPABILITIES).about_the_bot + for label, names in (("\U0001f327️ Rain", ["rainfall.rain"]), ("\U0001f4c8 Temperature", ["outdoor.temperature", "indoor.temperature"]), + ("\U0001f4a7 Humidity", ["outdoor.humidity", "indoor.humidity"]), ("\U0001f4a8 Wind", ["wind.wind_speed", "wind.wind_direction"]), + ("\U0001f3ed Air Quality", ["air.pm2_5", "air.pm10", "air.pm1", "air.co2", "air.voc_index", "air.nox_index"]), + ("\U0001f52c Particulates", ["air.pm2_5", "air.pm10", "air.pm1"])): + tool, args = read(label).chart + assert tool == "summary" and args["chart"] is True and args["period"] == "1d", label + assert [r.name for r in CATALOGUE.resolve(args["readings"], default=None)] == names, label + tool, args = read("\U0001f326️ Weather").chart + readings = [r.name for r in CATALOGUE.resolve(args["readings"], default=None)] + assert readings[0] == "outdoor.temperature" and readings[-1] == "wind.wind_direction" def test_the_keyboard_is_persistent_and_has_every_button(): diff --git a/tests/test_tools.py b/tests/test_tools.py deleted file mode 100644 index cc2b00cb..00000000 --- a/tests/test_tools.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Tools.call: which call drew each chart of a question (Turn.chart_calls), when the model's calls in one step run together.""" - -import asyncio -import json - -from lib.tools import Tool, Tools, Turn - -OBJECT = {"type": "object", "properties": {}} - - -async def test_each_chart_is_put_down_to_the_call_that_added_it_when_calls_run_together(): - """The model's calls in one step are made together (llm gathers them): a call that draws nothing but finishes after another drew - its chart doesn't claim that chart.""" - drawn = asyncio.Event() - - async def draws(args, turn): - turn.charts.append("chart") - drawn.set() - return "drew" - - async def waits(args, turn): - await drawn.wait() # (started first, finishes last) - await asyncio.sleep(0) - return "nothing drawn" - tools = Tools([Tool("waits", "", OBJECT, waits), Tool("draws", "", OBJECT, draws)]) - turn = Turn() - await asyncio.gather(tools.call("waits", json.dumps({"a": 1}), turn), tools.call("draws", json.dumps({"b": 2}), turn)) - assert turn.charts == ["chart"] - assert turn.chart_calls == [("draws", {"b": 2})] - - -async def test_charts_added_outside_any_call_have_no_call(): - async def draws(args, turn): - turn.charts.append("theirs") - return "drew" - tools = Tools([Tool("draws", "", OBJECT, draws)]) - turn = Turn() - turn.charts.append("ours") - await tools.call("draws", "{}", turn) - turn.charts.append("ours too") - assert turn.chart_calls == [(None, {}), ("draws", {}), (None, {})] From bf2a14b6401908c63b55ade78834243497dc8d5e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:28:48 +0000 Subject: [PATCH 049/125] bot.deliver: bold headings are the report's alone now Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bot.py b/lib/bot.py index 20953c05..11822e78 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -341,7 +341,7 @@ async def deliver(msg: Message, text: str, photos: list[bytes], link: tuple[str, (photos_first: sent after the pictures, carrying the buttons: the report and its gauges). link = (label, url) adds a small italic link line at the end of the text. markup (the button keyboard) rides on the last text, or on the single photo when there is no text (a group of photos can't carry one). period_row (the period buttons) rides on a single photo instead, and then the keyboard waits. - bold_headings: the text is the report (or a pollen / forecast lookup), whose heading names are set in bold.""" + bold_headings: the text is the report, whose heading names are set in bold.""" text = text.strip() if photos: text = strip_chart_talk(text) From 39c8e18de67e6a15e908eef08dfc2b3b6adff661 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:46:09 +0000 Subject: [PATCH 050/125] Step 3 review fixes: the air link, " 1d", outlook's forecast days, the bot's chart_note - The AirGradient live-chart link goes under an answer whose calls read the air (bot.reads_air: current when a reading asked for is the air's alone, summary's air series, readings/relate's air reading, days' air fields, scan), never under a refusal, current of every sensor, or an error reply. - " 1d" ("temperature 1d", "co2 24h") is its chart in code again: a bare reading and a period given as a number of a day; a day in words ("yesterday") or less stays the model's. - The forecast days an outlook result shows (today's and tomorrow's lines) are recorded for the forecast-revised alert. - The model is sent the bot's chart_note (the bot sends the chart, the reply its caption), not the service's "draw it". - find_days and find_air_days, called by nothing in lib since the swap, move to tests/old_tools.py as the tests' oracle. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 9 ++- lib/airgradient/days.py | 37 ++---------- lib/bot.py | 54 +++++++++++++----- lib/ecowitt/days.py | 71 +---------------------- lib/intent.py | 11 ++-- lib/model_tools.py | 17 ++++-- tests/old_tools.py | 107 ++++++++++++++++++++++++++++++++--- tests/test_bot.py | 2 +- tests/test_days.py | 12 +++- tests/test_intent.py | 13 ++++- tests/test_service_days.py | 3 +- tests/test_service_switch.py | 75 ++++++++++++++++++++++++ 12 files changed, 270 insertions(+), 141 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 59e76828..04f77854 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -491,12 +491,15 @@ Each step ships on its own, with the tests and evals green and the bot working t 3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period hints, the prefetch and the corrections from the words go. The bot offers the ten as they are (`lib/model_tools.py`: each result - kept whole for drawing and its buttons, the model sent it with each chart as its title and period), with its persona, the server's + kept whole for drawing and its buttons, the model sent it with each chart as its title and period and the bot's own `chart_note`: + the bot sends the chart, the reply its caption), with its persona, the server's instructions and the time (`lib/prompt.py`); tool_choice is the model's own, the reasoning effort still comes from the words. Its shortcuts (`lib/intent.py`) are fixed calls built directly: a named reading's chart and a period (summary with the person's words - for both, the keyboard's and the alerts' sentences among them), weather now, the report (current, pollen, the next 3 days' + for both, the keyboard's and the alerts' sentences among them; with no chart word, over more than a day or a day given as a number, + "co2 1d"), weather now, the report (current, pollen, the next 3 days' forecast) and the gauges; everything else it answered in code goes to the model. The turn ends on a step whose every result is - complete. `lib/service/legacy.py` is gone; the `Turn` is only the engines' options, set by the service from its arguments. `--live` + complete. The live-chart link goes under an answer whose calls read the air (`bot.reads_air`), and the forecast days shown, by + `forecast` or `outlook`, are recorded for the forecast alert. `lib/service/legacy.py` is gone; the `Turn` is only the engines' options, set by the service from its arguments. `--live` asks the model as the bot does (its prompt, the ten tools; a question answered in code is scored by its fixed calls). 4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. diff --git a/lib/airgradient/days.py b/lib/airgradient/days.py index 59af30b5..693f71a6 100644 --- a/lib/airgradient/days.py +++ b/lib/airgradient/days.py @@ -1,39 +1,10 @@ -"""Find, rank, count and total days by the air-quality sensor's readings, from the day rows alone (it never asks -AirGradient; storage.days works each day out as its readings are written, the sensor's glitches taken out). The same fields as a day's -highest (_max), lowest (_min) or mean (_avg) of each metric, e.g. pm2_5_max > 25 for the days particles passed 25 µg/m³. The counting, -ranking, grouping and bar charts are shared with the station's (lib/daytable.py); lib/service/days.py reads the day rows itself.""" +"""The air-quality sensor's day fields, for the service's `days` (lib/service/days.py, which reads the day rows itself: storage.days works +each day out as its readings are written, the sensor's glitches taken out): a day's highest (_max), lowest (_min) or mean (_avg) of each +metric, e.g. pm2_5_max > 25 for the days particles passed 25 µg/m³. (air_days' own engine, find_air_days, is the tests' oracle now: +tests/old_tools.py.)""" -import logging -from datetime import datetime, tzinfo - -from ..daytable import analyse, prepare from .metrics import ALL_METRICS, CHART_UNITS -log = logging.getLogger(__name__) - SUFFIX_KIND = ("max", "min", "avg") FIELDS = {f"{m}_{kind}": CHART_UNITS[m] for m in ALL_METRICS for kind in SUFFIX_KIND} ALWAYS_SHOWN = ("pm2_5_max",) # every listed day shows it; days rank by it when nothing else is named - -async def find_air_days(store, tz: tzinfo, args: dict, now: datetime, turn=None) -> dict: - """The answer, from one read of the day rows (readings.AirReadings.day_figures).""" - asked = prepare(args, FIELDS, ALWAYS_SHOWN, now.date()) - if isinstance(asked, str): - return {"error": asked} - days, shown = asked.days, asked.shown - figures = await store.day_figures(asked.first, asked.last, shown) - values, counts = figures.values, figures.counts - checked = [d for d in days if any(d in values[n] for n in shown)] - got = analyse(values, asked, checked, tz, turn) - out = got.out - hourly = [d for d in checked if d in figures.hourly] - if hourly and any(n.endswith(("_max", "_min")) for n in shown): - out["note_hourly"] = (f"{len(hourly)} of these days only exist as hourly averages, so their highs and lows are hourly " - "averages and a short spike is smoothed. Say so briefly if it matters.") - missing = sum(1 for d in days if not counts.get(d)) - if missing: - out["note_missing"] = f"{missing} day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted." - if not checked: - out["note"] = "No stored readings for this period yet (the bot may still be downloading history)." - log.info("Air days %s to %s: %d checked, %d match", asked.first, asked.last, len(checked), len(got.matches)) - return out diff --git a/lib/bot.py b/lib/bot.py index 11822e78..fbe65074 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -202,15 +202,29 @@ def complete_reply(results: list[str]) -> str | None: return "\n\n".join(replies) if replies else None -def reads_air(result: dict) -> bool: - """Did this result read the air sensor (a reading of it, or a chart or a day from it)?""" - def walk(value) -> bool: - if isinstance(value, dict): - return any(str(k).startswith("air.") or k == "air" or walk(v) for k, v in value.items()) - if isinstance(value, list): - return any(walk(v) for v in value) - return isinstance(value, str) and "AirGradient" in value - return walk(result) +def reads_air(name: str, args: dict, result: dict, catalogue) -> bool: + """Is this call's answer about the air (its live-chart link goes under the reply)? Read from what the call read, never from a + refusal (its `words` and `names` list every reading): `current` when a reading it was asked for is the air sensor's alone ("pm2.5", + "air"; not every sensor, as for "how warm is it", nor "all"); `summary` when a series is the air's; `readings` and `relate` when + their reading is; `days` when a field named is the air sensor's; `scan` always (the air against the weather).""" + from .service.days import AIR_DEVICE as DAYS_AIR, DEVICE_OF + from .service.names import AIR_DEVICE, _split + if not isinstance(result, dict) or "error" in result: + return False + if name == "current": + for word in _split(args.get("readings")): + found = catalogue._lookup(word) + if not isinstance(found, str) and found and all(r.device == AIR_DEVICE for r in found): + return True + return False + if name == "summary": + return any(str(k).startswith("air.") for k in result.get("series") or {}) + if name in ("readings", "relate"): + return str(result.get("reading") or "").startswith("air.") + if name == "days": + fields = [c.get("field") for c in args.get("where") or [] if isinstance(c, dict)] + [args.get("sort_by"), args.get("of")] + return any(DEVICE_OF.get(f) == DAYS_AIR for f in fields if isinstance(f, str)) + return name == "scan" def chat_tag(chat_id: int) -> str: @@ -1145,11 +1159,20 @@ async def _written_in_code(self, report: bool, shown: list, ahead: bool = False) shown.extend(self._shown_forecast(by_tool.get("forecast"))) return "\n\n".join(sections) or "No readings are available right now." - def _shown_forecast(self, out: dict | None) -> list: + def _shown_forecast(self, out: dict | None, tool: str = "forecast") -> list: """The forecast days a forecast result shows (the Forecast source's own), remembered for the chat once the answer is sent (a later - revision of them is worth telling it).""" + revision of them is worth telling it). An `outlook` result shows today's and tomorrow's lines in `forecast` (its description has + the model copy them): those days, as many as it has lines.""" source = self.by_name.get("Forecast") - if source is None or not out or "error" in out or not out.get("days"): + if source is None or not out or "error" in out: + return [] + if tool == "outlook": + lines = out.get("forecast") + if not isinstance(lines, list) or not lines: + return [] + today = now_local(self.cfg.tz).date() + return [d for d in source.days or [] if 0 <= (d["date"] - today).days <= 1][:len(lines)] + if not out.get("days"): return [] shown = {day.get("date") for day in out["days"] if isinstance(day, dict)} return [d for d in source.days or [] if d["date"].isoformat() in shown] @@ -1406,8 +1429,8 @@ async def _answer(self, msg: Message, read, turn: Turn, shown: list, working: li kept = [r for r in turn.results if r] answer.charts = [chart for _, _, out in kept for chart in out.get("charts") or [] if isinstance(chart, dict)] for name, _, out in kept: - if name == "forecast": - shown.extend(self._shown_forecast(out)) + if name in ("forecast", "outlook"): + shown.extend(self._shown_forecast(out, name)) return answer async def _send(self, msg: Message, bot, read, turn: Turn, shown: list, answer: Answer, added: list[dict], now: datetime, @@ -1424,7 +1447,8 @@ async def _send(self, msg: Message, bot, read, turn: Turn, shown: list, answer: used = [m for m in added if m["role"] == "tool"] log.info("%s: %s in %.1fs, tools %d, charts %d, %d chars", chat_tag(msg.chat_id), "Replied" if answer.ok else "Error reply", time.monotonic() - started, len(used), len(photos), len(reply)) - used_air = any(r and r[0] in ("current", "summary", "readings", "days", "relate", "scan") and reads_air(r[2]) for r in turn.results) + catalogue = self._catalogue() + used_air = answer.ok and any(r and reads_air(*r, catalogue) for r in turn.results) # (an error reply gets no link) air = self.by_name.get("AirGradient") markup = templates.keyboard(self.irrigation is not None) if self._keyboard_stale(msg) else None refresh = answer.ok and read.report and 0 < len(reply) <= TG_LIMIT and not markup # the report, to be refreshed in place diff --git a/lib/ecowitt/days.py b/lib/ecowitt/days.py index e1da6e9b..79987798 100644 --- a/lib/ecowitt/days.py +++ b/lib/ecowitt/days.py @@ -1,4 +1,5 @@ -"""Find, rank and count days by what the station read, from the storage alone (never asks Ecowitt). +"""The station's day fields and how a day's figures are read from storage (never asks Ecowitt), for the service's `days` and `current` +and `summary` (lib/service). (weather_days' own engine, find_days, is the tests' oracle now: tests/old_tools.py.) Questions like "the hottest day it also rained" or "how many days over 35" compare readings on the same day across a long period, which the history tool's summaries can't answer. Each day's figures are @@ -10,17 +11,11 @@ """ import logging -import operator -from datetime import date, datetime, tzinfo +from datetime import date -from ..daytable import analyse, lists_days, prepare from ..series import WEATHER -from ..storage import Storage from ..storage.catalogue import column_of from ..storage.read import Reader -from ..timeutil import day_text -from .api import daily_run -from .calendar import PublicHolidays log = logging.getLogger(__name__) @@ -81,63 +76,3 @@ def day_values_on(r: Reader, mac: str, shown: list[str], days) -> tuple[dict[str values[name][d] = v source[d] = max(source.get(d, src), src, key=COARSER.get) return values, {d: "daily" if s == "1day" else s for d, s in source.items()} - - -async def find_days(storage: Storage, mac: str, tz: tzinfo, args: dict, now: datetime, turn=None) -> dict: - asked = prepare(args, FIELD_UNITS, ALWAYS_SHOWN, now.date()) - if isinstance(asked, str): - return {"error": asked} - only = args.get("only") - if only not in (None, "public_holiday", "weekend"): - return {"error": "only must be public_holiday or weekend"} - calendar = PublicHolidays(tz) - if only == "public_holiday" and not calendar.available: - return {"error": calendar.problem()} - kind = {None: lambda d: True, "weekend": lambda d: d.weekday() >= 5, - "public_holiday": lambda d: calendar.name(d) is not None}[only] - first, last, shown, where, sort_by = asked.first, asked.last, asked.shown, asked.where, asked.sort_by - days = asked.days - values, source = await storage.read(day_values_on, mac, shown, days) - - checked = [d for d in days if kind(d) and any(d in values[n] for n in shown)] - got = analyse(values, asked, checked, tz, turn, - lambda d: {**({"holiday": calendar.name(d)} if only == "public_holiday" else {}), - "source": "daily" if source.get(d) == "daily" else "exact"}, - {"public_holiday": "public holidays only", "weekend": "weekends only"}.get(only, "")) - out, matches, ranked, rank, holds, row = got.out, got.matches, got.ranked, got.rank, got.holds, got.row - - # Days that would have ranked higher had a trace of rain counted: the answer should mention them - trace: list[date] = [] - rain_cond = next((c for c in where if c["field"] == "rain" and c["op"] in (">", ">=") and c["value"] > 0), None) - if rain_cond: - relaxed = [{"field": "rain", "op": ">", "value": 0} if c is rain_cond else c for c in where] - matched = set(matches) - better = operator.lt if args.get("order", "desc") == "asc" else operator.gt - for d in rank(d for d in checked if holds(d, relaxed)): - if d in matched: - break # from here on the real matches rank at least as high - if not ranked or better(values[sort_by][d], values[sort_by][ranked[0]]): # strictly ahead, not a tie - trace.append(d) - if len(trace) == 2: - break - - exact_days = sorted(d for d in checked if source.get(d) != "daily") - if not lists_days(args): - trace = [] # just the figures - if trace: - out["trace_rain_days"] = [row(d) for d in trace] - out["note_trace"] = (f"These days rank higher but had less than {rain_cond['value']:g} mm of rain (a trace), so they " - "are not in \"days\". Mention the first as a short footnote.") - if any(source.get(d) == "daily" for d in checked): - out["exact_from"] = day_text(exact_days[0]) if exact_days else None - out["note_daily"] = (f"Days marked \"daily\" come from daily readings that run {daily_run(tz, first, last)}, so their rain and dates " - "are approximate (a morning shower can be counted on the day before). Say so briefly if any " - "listed day is marked daily, or if the period reaches back before exact_from.") - if AVERAGED & set(shown) and any(source.get(d) != "5min" for d in checked): - out["note_averaged"] = ("For these readings, days from 30-minute or daily data use each interval's average, so a day's true peak " - "(or low) may be a little beyond what is listed: a count of days at or past a limit can fall slightly short " - "near the limit. Say so briefly.") - if not checked: - out["note"] = "No cached readings for this period yet (the bot may still be downloading history)." - log.info("Days %s to %s: %d checked, %d match, %d exact", first, last, len(checked), len(matches), len(exact_days)) - return out diff --git a/lib/intent.py b/lib/intent.py index 1f8ea3c1..1c630288 100644 --- a/lib/intent.py +++ b/lib/intent.py @@ -143,7 +143,9 @@ def mentions_air(text: str) -> bool: # their readings, as the service's words SENTENCE_READINGS = {"air quality all metrics": ["air"], "particulates": ["pm2.5", "pm10", "pm1"]} BARE_MIN = timedelta(days=1) # " " with no chart word is a chart only over more than a day ("humidity 7d"; not - # "rain today": a figure to read) + # "rain today" or "rain yesterday": a figure to read), or over a day given as a number ("temperature 1d", + # "co2 24h": the chart's own 1D, as before step 3) +NUMERIC = re.compile(r"\d+\s*(d|h|days?|hours?|hrs?)", I) APOSTROPHES = str.maketrans("’‘", "''") # a phone's typographic apostrophes ("what’s"), read as the plain one every pattern uses @@ -162,7 +164,7 @@ def _readings(words: list[str], catalogue) -> list[str] | None: def _period(words: list[str], now: datetime, tz: tzinfo, bare: bool) -> str | None: """These words as a period the service reads (summary's, not whole days), passed on as they are; None when it can't read them (or, - bare: when they are a day or less).""" + bare: when they are a day or less, but for a day given as a number: "1d", "24h").""" from .periods_text import PeriodError, read_period said = " ".join(words) if not said: @@ -171,12 +173,13 @@ def _period(words: list[str], now: datetime, tz: tzinfo, bare: bool) -> str | No read = read_period(said, None, None, now=now, tz=tz, default=said) except (PeriodError, ValueError): return None - return said if not bare or read.end - read.start > BARE_MIN else None + span = read.end - read.start + return said if not bare or span > BARE_MIN or span == BARE_MIN and NUMERIC.fullmatch(said) else None def chart_call(text: str, now: datetime, tz: tzinfo, catalogue=None) -> tuple[str, dict] | None: """The service call of a message that is only a named reading's chart and a period: " chart ", "chart - " or " " (over more than a day): summary {readings: the words, period: the words, chart: true}; None + " or " " (over more than a day, or "1d"): summary {readings: the words, period: the words, chart: true}; None for anything else (a question beside it, an average, two axes, no period: the model's). `catalogue`: the service's readings (default: every reading it knows).""" if catalogue is None: diff --git a/lib/model_tools.py b/lib/model_tools.py index 53be5e5a..aad61587 100644 --- a/lib/model_tools.py +++ b/lib/model_tools.py @@ -2,7 +2,8 @@ and parameters, as they are. The bot draws the charts itself, so it asks for them as drawn (request `_meta` `chart_points: "drawn"`) and keeps each whole result on the question's Turn (`Turn.results`: for drawing, the period buttons, the complete result that ends the turn, the forecast days shown; a call that gave no JSON object leaves None); the model is sent the result less the charts' data (`for_model`): each chart as its title and period, -with `chart_note`, `caption`, `reply` and `complete` as they are.""" +with `caption`, `reply` and `complete` as they are, and `chart_note` the bot's (BOT_CHART_NOTE: the service's asks the model to draw +the chart from data it is no longer sent; the bot sends the picture with the reply as its caption).""" import json @@ -10,11 +11,19 @@ from .tools import Tool, Tools, Turn, json_result +BOT_CHART_NOTE = ("The bot sends this chart with your reply as its caption: keep your text to the figures. Don't describe the chart or " + "say it was sent.") + + def for_model(out: dict) -> dict: - """A result as the model is sent it: `charts` as [{title, period}] (the bot draws them), everything else as it is.""" + """A result as the model is sent it: `charts` as [{title, period}] (the bot draws them) and `chart_note` saying so (BOT_CHART_NOTE), + everything else as it is.""" if not isinstance(out.get("charts"), list): return out - return {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} + told = {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} + if "chart_note" in out: + told["chart_note"] = BOT_CHART_NOTE + return told def tool(service_tool) -> Tool: @@ -40,4 +49,4 @@ def tools(service) -> Tools: return Tools([tool(t) for t in service]) -__all__ = ["for_model", "tool", "tools"] +__all__ = ["BOT_CHART_NOTE", "for_model", "tool", "tools"] diff --git a/tests/old_tools.py b/tests/old_tools.py index 294f277c..a44ddefa 100644 --- a/tests/old_tools.py +++ b/tests/old_tools.py @@ -1,20 +1,23 @@ """The bot's twelve old tools' handlers, as they answered before the model got the service's tools (docs/mcp-service.md 6, step 3), kept -for the tests only: they drive the engines the service wraps the way the old tools did (HistoryQuery, AirGradient.history, find_days, -link, the readings), and they are the oracle the service's words were ported against (with tests/report_words.py). The corrections +for the tests only: they drive the engines the service wraps the way the old tools did (HistoryQuery, AirGradient.history, the day +rows, link, the readings), and they are the oracle the service's words were ported against (with tests/report_words.py). The corrections from the person's words are gone with step 3. Deleted with the bot (step 6).""" import asyncio import logging +import operator import time as clock from collections.abc import Callable from dataclasses import replace -from datetime import datetime, time +from datetime import date, datetime, time -from lib.airgradient.days import find_air_days +from lib.airgradient.days import ALWAYS_SHOWN as AIR_SHOWN, FIELDS as AIR_FIELDS from lib.airgradient.metrics import EXTRA from lib.captions import wants_chart -from lib.ecowitt.api import GROUPS -from lib.ecowitt.days import find_days +from lib.daytable import analyse, lists_days, prepare +from lib.ecowitt.api import GROUPS, daily_run +from lib.ecowitt.calendar import PublicHolidays +from lib.ecowitt.days import ALWAYS_SHOWN, AVERAGED, FIELD_UNITS, day_values_on from lib.ecowitt.glance import glance from lib.ecowitt.link import link from lib.ecowitt.query import HistoryQuery, chart_field, stack_names @@ -23,7 +26,7 @@ interval_starts, read_days, read_intervals, row_count, station_fields, station_metrics) from lib.pollen.source import OFF_SEASON from lib.series import READING_GROUPS, WEATHER, find -from lib.timeutil import local_date, local_epoch, now_local, parse_local, when +from lib.timeutil import day_text, local_date, local_epoch, now_local, parse_local, when from lib.tools import Turn, json_result log = logging.getLogger(__name__) @@ -253,5 +256,93 @@ async def handle(self, args: dict, turn: Turn | None = None) -> str: return json_result(out) -__all__ = ["History", "NOW_GROUPS", "air_current", "as_drawn", "air_days", "air_quality", "forecast", "parse_groups", "pollen", "weather_days", + +# ---------- the day tools' engines (the service's days reads the day rows itself: lib/service/days.py) ---------- +async def find_days(storage, mac: str, tz, args: dict, now: datetime, turn=None) -> dict: + """weather_days' engine: the station's days from its day rows (lib/ecowitt/days.py day_values_on), counted and ranked by + lib/daytable.py, with the old tool's notes.""" + asked = prepare(args, FIELD_UNITS, ALWAYS_SHOWN, now.date()) + if isinstance(asked, str): + return {"error": asked} + only = args.get("only") + if only not in (None, "public_holiday", "weekend"): + return {"error": "only must be public_holiday or weekend"} + calendar = PublicHolidays(tz) + if only == "public_holiday" and not calendar.available: + return {"error": calendar.problem()} + kind = {None: lambda d: True, "weekend": lambda d: d.weekday() >= 5, + "public_holiday": lambda d: calendar.name(d) is not None}[only] + first, last, shown, where, sort_by = asked.first, asked.last, asked.shown, asked.where, asked.sort_by + days = asked.days + values, source = await storage.read(day_values_on, mac, shown, days) + + checked = [d for d in days if kind(d) and any(d in values[n] for n in shown)] + got = analyse(values, asked, checked, tz, turn, + lambda d: {**({"holiday": calendar.name(d)} if only == "public_holiday" else {}), + "source": "daily" if source.get(d) == "daily" else "exact"}, + {"public_holiday": "public holidays only", "weekend": "weekends only"}.get(only, "")) + out, matches, ranked, rank, holds, row = got.out, got.matches, got.ranked, got.rank, got.holds, got.row + + # Days that would have ranked higher had a trace of rain counted: the answer should mention them + trace: list[date] = [] + rain_cond = next((c for c in where if c["field"] == "rain" and c["op"] in (">", ">=") and c["value"] > 0), None) + if rain_cond: + relaxed = [{"field": "rain", "op": ">", "value": 0} if c is rain_cond else c for c in where] + matched = set(matches) + better = operator.lt if args.get("order", "desc") == "asc" else operator.gt + for d in rank(d for d in checked if holds(d, relaxed)): + if d in matched: + break # from here on the real matches rank at least as high + if not ranked or better(values[sort_by][d], values[sort_by][ranked[0]]): # strictly ahead, not a tie + trace.append(d) + if len(trace) == 2: + break + + exact_days = sorted(d for d in checked if source.get(d) != "daily") + if not lists_days(args): + trace = [] # just the figures + if trace: + out["trace_rain_days"] = [row(d) for d in trace] + out["note_trace"] = (f"These days rank higher but had less than {rain_cond['value']:g} mm of rain (a trace), so they " + "are not in \"days\". Mention the first as a short footnote.") + if any(source.get(d) == "daily" for d in checked): + out["exact_from"] = day_text(exact_days[0]) if exact_days else None + out["note_daily"] = (f"Days marked \"daily\" come from daily readings that run {daily_run(tz, first, last)}, so their rain and dates " + "are approximate (a morning shower can be counted on the day before). Say so briefly if any " + "listed day is marked daily, or if the period reaches back before exact_from.") + if AVERAGED & set(shown) and any(source.get(d) != "5min" for d in checked): + out["note_averaged"] = ("For these readings, days from 30-minute or daily data use each interval's average, so a day's true peak " + "(or low) may be a little beyond what is listed: a count of days at or past a limit can fall slightly short " + "near the limit. Say so briefly.") + if not checked: + out["note"] = "No cached readings for this period yet (the bot may still be downloading history)." + log.info("Days %s to %s: %d checked, %d match, %d exact", first, last, len(checked), len(matches), len(exact_days)) + return out + + +async def find_air_days(store, tz, args: dict, now: datetime, turn=None) -> dict: + """air_days' engine: the answer, from one read of the air sensor's day rows (readings.AirReadings.day_figures).""" + asked = prepare(args, AIR_FIELDS, AIR_SHOWN, now.date()) + if isinstance(asked, str): + return {"error": asked} + days, shown = asked.days, asked.shown + figures = await store.day_figures(asked.first, asked.last, shown) + values, counts = figures.values, figures.counts + checked = [d for d in days if any(d in values[n] for n in shown)] + got = analyse(values, asked, checked, tz, turn) + out = got.out + hourly = [d for d in checked if d in figures.hourly] + if hourly and any(n.endswith(("_max", "_min")) for n in shown): + out["note_hourly"] = (f"{len(hourly)} of these days only exist as hourly averages, so their highs and lows are hourly " + "averages and a short spike is smoothed. Say so briefly if it matters.") + missing = sum(1 for d in days if not counts.get(d)) + if missing: + out["note_missing"] = f"{missing} day(s) in this period have no stored readings (not downloaded yet, or the sensor was off) and are not counted." + if not checked: + out["note"] = "No stored readings for this period yet (the bot may still be downloading history)." + log.info("Air days %s to %s: %d checked, %d match", asked.first, asked.last, len(checked), len(got.matches)) + return out + + +__all__ = ["History", "find_air_days", "find_days", "NOW_GROUPS", "air_current", "as_drawn", "air_days", "air_quality", "forecast", "parse_groups", "pollen", "weather_days", "weather_history", "weather_link", "weather_now"] diff --git a/tests/test_bot.py b/tests/test_bot.py index 9eecbdf5..fccb2332 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -708,7 +708,7 @@ async def send_chat_action(*a, **k): bot = Bot(NS(tz=TZ), Agent(client, "m", model_tools.tools([Summary()])), [], alert_state) await bot.respond(update, NS(bot=telegram(send_chat_action)), "how humid was it this week?") told = json.loads(seen[-1]["content"]) - assert told["charts"] == [{"title": "Humidity", "period": chart["period"]}] and told["chart_note"] == "note" + assert told["charts"] == [{"title": "Humidity", "period": chart["period"]}] and told["chart_note"] == model_tools.BOT_CHART_NOTE (caption, markup), = sent assert caption.startswith("Humidity") and "Humid all week." in caption assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d"] diff --git a/tests/test_days.py b/tests/test_days.py index bfaa6c7b..642fa5fe 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -200,12 +200,11 @@ async def test_public_holidays_are_the_local_ones_not_the_models_guess(station): async def test_weekends_and_unknown_places(station): from zoneinfo import ZoneInfo - from lib.ecowitt import days eco, _ = station out = await ask(eco, start_date="2026-08-03", end_date="2026-08-16", only="weekend", limit=10) # two weekends assert out["days_checked"] == 4 and all(r["date"].startswith(("Sat", "Sun")) for r in out["days"]) assert "error" in await ask(eco, start_date="2026-08-03", end_date="2026-08-16", only="bank_holiday") - elsewhere = await days.find_days(eco.storage, eco.mac, ZoneInfo("Europe/Paris"), + elsewhere = await old_tools.find_days(eco.storage, eco.mac, ZoneInfo("Europe/Paris"), {"start_date": "2026-08-03", "end_date": "2026-08-16", "only": "public_holiday"}, datetime.now(ZoneInfo("Europe/Paris")).replace(tzinfo=None)) assert "aren't known for this time zone" in elsewhere["error"] # says so instead of guessing @@ -360,3 +359,12 @@ async def test_a_figure_per_month_with_no_matching_day_promises_no_chart(station out = json.loads(await old_tools.weather_days(eco, dict(start_date=str(first), end_date=str(last), count_only=True, group_by="month", stat="max", of="temp_max", where=[{"field": "temp_max", "op": ">", "value": 99}]), turn)) assert out["by_month"] and all(v is None for v in out["by_month"].values()) and "chart" not in out and turn.charts == [] + + +def test_the_old_day_tools_engines_are_the_tests_oracle_alone(): + """weather_days' and air_days' engines answer no one since the swap (the service's days reads the day rows itself): they live with + the old tools' handlers in tests/old_tools.py, not in lib.""" + from lib.airgradient import days as air_days + from lib.ecowitt import days as station_days + assert not hasattr(station_days, "find_days") and not hasattr(air_days, "find_air_days") + assert callable(old_tools.find_days) and callable(old_tools.find_air_days) diff --git a/tests/test_intent.py b/tests/test_intent.py index a25b8255..ef28bda4 100644 --- a/tests/test_intent.py +++ b/tests/test_intent.py @@ -106,12 +106,23 @@ def test_a_named_readings_chart_and_a_period_is_summary_with_the_words_as_they_a def test_anything_beside_the_chart_is_the_models(): for text in ("average temperature 7d", "plot uv and solar on two axes 7d", "lowest temperature on record", "highest humidity this week", "temps this week", "chart weather", "humidity chart", "plot pressure this week: is a storm coming?", "weather all week", - "how hot is it", "rain today", "humidity 1d", "humidity chart next week", "chart chart 7d", "rain chart 7d vs last week", + "how hot is it", "rain today", "rain yesterday", "humidity past day", "temperature 12h", "humidity chart next week", "chart chart 7d", "rain chart 7d vs last week", "temperature chart 99999 years ago", "hello", "what can you do", "pollen", "forecast"): assert chart(text) is None, text assert intent.read("humidity chart 7d", NOW, ["Pollen", "Forecast"]).chart is None # (nothing to draw from) +def test_a_bare_reading_and_a_day_given_as_a_number_is_its_chart_as_before_the_swap(): + """"temperature 1d", "co2 24h": the chart of the last day (step 3 gate's intent drew these); a day in words ("yesterday", "past day") + or less than a day ("12h", "today") is a figure to read, the model's.""" + for text, readings, period in (("temperature 1d", ["temperature"], "1d"), ("co2 1d", ["co2"], "1d"), ("pm2.5 1d", ["pm2.5"], "1d"), + ("humidity 1d", ["humidity"], "1d"), ("temperature 24h", ["temperature"], "24h"), + ("co2 1 day", ["co2"], "1 day")): + assert chart(text) == ("summary", {"readings": readings, "period": period, "chart": True}), text + for text in ("temperature yesterday", "temperature today", "co2 12h", "humidity past day", "pm2.5 last 24 hours"): + assert chart(text) is None, text + + def test_the_words_are_read_against_the_readings_the_service_holds(): station_only = Catalogue.of(air=False) assert chart("co2 chart 7d") and chart("co2 chart 7d", station_only) is None diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 7874b006..c9030ba4 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -10,9 +10,8 @@ import pytest from tests import report_words as report # (the bot's words before step 2: the oracle) -from lib.airgradient.days import find_air_days +from tests.old_tools import find_air_days, find_days # (weather_days' and air_days' engines: the oracle) from lib.airgradient.readings import AirReadings -from lib.ecowitt.days import find_days from lib.partday import over, parse_stretch from lib.service import days as days_tool from lib.service.common import CHART_NOTE, FRESH diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 0240b2ba..5bb3d2f6 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -406,3 +406,78 @@ async def test_an_alerts_chart_is_the_same_as_before(world, monkeypatch, kind): keyboard = golden().get(pictures.CHARTS[kind]) if keyboard: # (the UV chart is no button) assert chart == keyboard["charts"][0] + + +# ---------- what follows from the model's calls ---------- +class Scripted: + """A model that makes these steps' calls ([(tool, arguments)] each), then answers `reply` (an exception: raised instead).""" + + def __init__(self, steps: list[list[tuple[str, dict]]], reply): + self.steps, self.reply = list(steps), reply + self.chat = NS(completions=self) + + async def create(self, **kw): + if self.steps: + calls = [NS(id=f"c{i}", function=NS(name=name, arguments=json.dumps(args))) for i, (name, args) in enumerate(self.steps.pop(0))] + return NS(choices=[NS(message=NS(content="", tool_calls=calls))], usage=None) + if isinstance(self.reply, BaseException): + raise self.reply + return NS(choices=[NS(message=NS(content=self.reply, tool_calls=None))], usage=None) + + +async def asked_the_model(world, alert_state, monkeypatch, text, steps, reply="ok") -> list: + """Ask the bot `text` with a scripted model (Scripted), the air sensor's live-chart link configured: the text or caption of each + message it sent.""" + from lib.llm import Agent + bot = world.bot(alert_state, monkeypatch) + bot.agent = Agent(Scripted(steps, reply), "m", world.tools) + world.air.link = ("live chart", "https://air.example") + msg = world.message() + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob", id=7)) + await bot.respond(update, CONTEXT, text) + return [s[1] for s in world.sent] + + +LINK_CASES = [ # (question, the model's steps, does the live-chart link go under the reply) + ("what's the temperature outside", [[("current", {})]], False), # every sensor read: not an air answer + ("what's it like out", [[("current", {"readings": ["all"]})]], False), + ("how much rain this week", [[("summary", {"readings": ["rainfall total"]})], # a refusal lists every reading's words + [("summary", {"readings": ["rain"], "period": "7d"})]], False), + ("temperature readings", [[("readings", {"readings": ["temperature"], "period": "today"})]], False), # refused (bad arguments) + ("hottest days", [[("days", {"sort_by": "temp_max", "period": "this month"})]], False), + ("how's the air", [[("current", {"readings": ["air"]})]], True), + ("pm2.5 and temperature now", [[("current", {"readings": ["pm2.5", "temperature"]})]], True), + ("how was the air this week?", [[("summary", {"readings": ["pm2.5"], "period": "7d"})]], True), + ("smoky days", [[("days", {"where": [{"field": "pm2_5_max", "op": ">", "value": 15}], "period": "this month"})]], True), +] + + +@pytest.mark.parametrize("text, steps, link", LINK_CASES) +async def test_the_air_link_goes_under_an_answer_that_read_the_air_and_no_other(world, alert_state, monkeypatch, text, steps, link): + """The live-chart link follows what was read (as before the swap, when air_quality's call brought it), never a key or a word + anywhere in a result: not `current` of every sensor, nor a refusal's catalogue of readings.""" + said = await asked_the_model(world, alert_state, monkeypatch, text, steps) + assert said and all(("live chart" in s) is link for s in said), said + + +async def test_an_error_reply_gets_no_air_link(world, alert_state, monkeypatch): + """The air was read, then the model timed out: the apology goes alone.""" + said = await asked_the_model(world, alert_state, monkeypatch, "how's the air", [[("current", {"readings": ["air"]})]], TimeoutError()) + assert said == ["Sorry, that took too long. Please try again in a moment."] + + +async def test_the_forecast_days_an_outlook_shows_are_recorded_for_the_forecast_alert(world, alert_state, monkeypatch): + """outlook's result carries Open-Meteo's lines for today and tomorrow, for the model to copy: once sent, a revision of those days is + worth telling the chat, as for forecast's.""" + from datetime import timedelta + await asked_the_model(world, alert_state, monkeypatch, "will it rain later?", [[("outlook", {})]], "Possibly.") + today = FrozenDate.today() + assert sorted(alert_state.forecast_sent(-5)) == [today, today + timedelta(days=1)] + + +@pytest.mark.parametrize("text", ["temperature 1d", "co2 1d", "pm2.5 1d"]) +async def test_a_bare_reading_and_1d_is_still_its_chart_without_the_model(world, alert_state, monkeypatch, text): + """As before the swap: "temperature 1d" is the chart of the last day, drawn in code (no model needed).""" + from lib.bot import NO_MODEL + got = await asked(world, alert_state, monkeypatch, text) + assert got["history"] != NO_MODEL and len(got["charts"]) == 1 From 249087aeef029948b60b19abca806bff20aa6a32 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 11:50:29 +0000 Subject: [PATCH 051/125] Server instructions: every question fetched afresh, a follow-up or a challenge too The bot strips tool turns from its history, so the results' `fresh` note isn't there when the model decides a follow-up. One line in the instructions says it; trims elsewhere keep them under 1500. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 2 +- lib/service/instructions.py | 23 +++++++++++++---------- tests/test_service_instructions.py | 8 ++++++++ 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 7b261bf7..546b8683 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -85,7 +85,7 @@ answer the question right in one round of calls? Section 7's evals ask exactly t - **The tool descriptions and the results are the contract.** Every rule a choice of tool or the reading of a result depends on is in that tool's description (which questions it answers, an example call for each, how to read what comes back) or in the result itself (`value_is`, `how_to_read`, `note_*`, `missing`, `warning`). The server's `instructions` repeat a short summary (the devices and their - nicknames, Indoor and Outdoor, the readings' names, units), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking + nicknames, Indoor and Outdoor, the readings' names, units, and that every question, a follow-up or a challenge too, is fetched afresh: a client may drop earlier tool turns, and with them `fresh`), but nothing depends on them: on the 2026-07-28 protocol a client only gets them by asking (`server/discover`), and many don't pass them to their model. The persona (a friendly Telegram bot, plain text, bullets) is the client's. - **Periods in words, worked out by the service.** Every tool that takes a period takes `period`, the person's own words for it, passed diff --git a/lib/service/instructions.py b/lib/service/instructions.py index be98db7b..119af0da 100644 --- a/lib/service/instructions.py +++ b/lib/service/instructions.py @@ -4,8 +4,9 @@ --instructions`, docs 7). It says: the devices there are (the Context's sources) and the nicknames people use for them, which readings are Indoor and Outdoor, -the readings' names, the units each reading comes in (from the catalogue: only the readings held), the station's time zone, and that a period is passed on -in the person's own words. `instructions(ctx)` builds it; INSTRUCTIONS is it for every device and every reading the service knows. +the readings' names, the units each reading comes in (from the catalogue: only the readings held), the station's time zone, that a period is passed on +in the person's own words, and that every question is fetched afresh (the results say so too, `fresh`, but a client may drop +earlier tool turns from its history). `instructions(ctx)` builds it; INSTRUCTIONS is it for every device and every reading the service knows. """ from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue @@ -63,13 +64,13 @@ def instructions(ctx=None) -> str: devices.append("the weather station (Ecowitt; \"ecowitt\", \"the weather station\", \"the station\"), outdoors, with an " "indoor sensor") if air: - devices.append("the air-quality sensor (AirGradient; \"ag\", \"airgradient\", \"air gradient\", \"the air sensor\")") - extra = [*(["the forecast for the station's place (Open-Meteo)"] if forecast else []), - *(["Melbourne's grass pollen and thunderstorm asthma forecast (October to December)"] if pollen else [])] + devices.append("the air sensor (AirGradient, for air quality; \"ag\", \"airgradient\", \"air gradient\")") + extra = [*(["a forecast (Open-Meteo)"] if forecast else []), + *(["grass pollen and thunderstorm asthma (Melbourne, Oct–Dec)"] if pollen else [])] lines = [f"The devices: {'; '.join(devices) or 'none'}." + (f" Also: {'; '.join(extra)}." if extra else "")] if station: - sides = ("Indoor and Outdoor: a bare reading is the weather station's: temperature and humidity are both outdoor and indoor " - "(outdoor.temperature, indoor.temperature); dew point, feels like and the rest outdoor.") + sides = ("Indoor and Outdoor: a bare reading is the station's; temperature and humidity are both " + "(outdoor.temperature, indoor.temperature), the rest outdoor.") if air: sides += (" The air sensor is outdoors: its own temperature and humidity are only air.temperature and air.humidity; " "no indoor air quality.") @@ -77,11 +78,13 @@ def instructions(ctx=None) -> str: held = Catalogue(r for r in catalogue if (r.device == STATION and station) or (r.device == AIR_DEVICE and air)) if held.names: lines.append(f"Names (sensor.reading): {names(held)}.") - lines.append(f"Units: {units(held)}. Rain is the mm that fell.") + lines.append(f"Units: {units(held)}. Rain: mm that fell.") zone = getattr(ctx.zone, "key", None) if ctx is not None and (ctx.tz or ctx.eco or ctx.air) else None when = f"The station's clock is {zone} time; " if zone else "Times are the station's local time; " - lines.append(when + "pass a period on in the person's own words (`period`: \"past week\", \"since 6am\"): the tools " - "read it and say how.") + lines.append(when + "pass a period in the person's own words (`period`: \"past week\", \"since 6am\"); the tools " + "read it.") + lines.append("Fetch for every question; never reuse earlier figures: call again at once, unasked, on a follow-up or a " + "challenge (\"that's wrong\").") return "\n".join(lines) diff --git a/tests/test_service_instructions.py b/tests/test_service_instructions.py index 618f6012..811c52d8 100644 --- a/tests/test_service_instructions.py +++ b/tests/test_service_instructions.py @@ -24,6 +24,14 @@ def test_the_default_names_every_device_its_nicknames_indoor_and_outdoor_and_the assert "rainfall and rainfall_piezo: rain_rate, rain" in text and "air: pm2_5, pm10" in text +def test_every_question_is_fetched_afresh_a_follow_up_and_a_challenge_too(): + # the results say so (common.FRESH), but the bot drops tool turns from its history: the model decides a follow-up without them + for text in (INSTRUCTIONS, instructions(Context(eco=object(), tz=MELBOURNE)), instructions(Context(air=object(), tz=MELBOURNE))): + last = text.splitlines()[-1] + assert "every question" in last and "never reuse earlier figures" in last + assert "follow-up" in last and "challenge" in last and "at once, unasked" in last + + def test_names_list_each_sensor_with_its_readings_sensors_alike_together(): listed = names(CATALOGUE) assert listed.startswith("outdoor and indoor: temperature, humidity") and "; pressure: relative, absolute; " in listed From 93047ea4d2db790ae74a23907d26af7cb4e8a733 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 12:03:30 +0000 Subject: [PATCH 052/125] Step 3 gate: days says how to get a figure per month or year; hottest today via current's context - days: a stat or a count over more than a month with no group_by carries note_group_by (one figure for the whole period; call again with group_by month or year if that was asked), which keeps it from being complete, so a model that left group_by out calls again. The final gate's one recurring miss, on DeepSeek. - service_cases: "hottest today" also accepts current with context, whose today carries the high and when it was. - tests/test_service_current.py: the PM2.5 AQI is checked against its band, not a range (it moves with the clock). - docs/mcp-service.md: step 3 done, with the gate's results. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 31 ++++++++++++++++++------------- lib/service/days.py | 4 ++++ tests/evals/service_cases.json | 16 +++++++++++++--- tests/test_service_current.py | 2 +- tests/test_service_days.py | 14 +++++++++++++- 5 files changed, 49 insertions(+), 18 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 546b8683..67d33cc0 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -493,19 +493,24 @@ Each step ships on its own, with the tests and evals green and the bot working t links and the scan, a period given as times) its buttons ask its question again, as before. Left for later: `current` and `outlook` read the sources' kept live readings through private members (`Ecowitt._live`, `AirGradient._current`); `fetch: false` doesn't stop the air sensor's inline fetch; `tests/report_words.py` keeps the old report's words as the tests' reference, deleted with the bot. -3. **The swap**, gated on the live evals (all cases, the production model and one other, with the tool list alone and with the - instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the period - hints, the prefetch and the corrections from the words go. The bot offers the ten as they are (`lib/model_tools.py`: each result - kept whole for drawing and its buttons, the model sent it with each chart as its title and period and the bot's own `chart_note`: - the bot sends the chart, the reply its caption), with its persona, the server's - instructions and the time (`lib/prompt.py`); tool_choice is the model's own, the reasoning effort still comes from the words. Its - shortcuts (`lib/intent.py`) are fixed calls built directly: a named reading's chart and a period (summary with the person's words - for both, the keyboard's and the alerts' sentences among them; with no chart word, over more than a day or a day given as a number, - "co2 1d"), weather now, the report (current, pollen, the next 3 days' - forecast) and the gauges; everything else it answered in code goes to the model. The turn ends on a step whose every result is - complete. The live-chart link goes under an answer whose calls read the air (`bot.reads_air`), and the forecast days shown, by - `forecast` or `outlook`, are recorded for the forecast alert. `lib/service/legacy.py` is gone; the `Turn` is only the engines' options, set by the service from its arguments. `--live` - asks the model as the bot does (its prompt, the ten tools; a question answered in code is scored by its fixed calls). +3. **The swap** (done), gated on the live evals (all cases, the production model and one other, with the tool list alone and with + the instructions): the model gets the ten tools; the bot's prompt keeps only its persona; the twelve, the `Turn`'s inputs, the + period hints, the prefetch and the corrections from the words go. The bot offers the ten as they are (`lib/model_tools.py`: each + result kept whole for drawing and its buttons, the model sent it with each chart as its title and period and the bot's own + `chart_note`: the bot sends the chart, the reply its caption), with its persona, the server's instructions and the time + (`lib/prompt.py`); tool_choice is the model's own, the reasoning effort still comes from the words. Its shortcuts (`lib/intent.py`) + are fixed calls built directly: a named reading's chart and a period (summary with the person's words for both, the keyboard's and + the alerts' sentences among them; with no chart word, over more than a day or a day given as a number, "co2 1d"), weather now, the + report (current, pollen, the next 3 days' forecast) and the gauges; everything else it answered in code goes to the model. The turn + ends on a step whose every result is complete. The live-chart link goes under an answer whose calls read the air (`bot.reads_air`), + and the forecast days shown, by `forecast` or `outlook`, are recorded for the forecast alert. `lib/service/legacy.py` is gone; the + `Turn` is only the engines' options, set by the service from its arguments. `--live` asks the model as the bot does (its prompt, + the ten tools; a question answered in code is scored by its fixed calls). The gate, one run each of 94 cases (DeepSeek v4.1 flash, + the production model, and gpt-6-luna): the bot as it runs 90 and 92 (today's bot with the twelve: 90); the tool list alone 91 and + 92; with the instructions 91 and 93. What fails is mostly a model leaving `group_by` out of a figure per month or year (the twelve + had it filled in from the words): `days` says so in its result (`note_group_by`) and the model calls again; the rest are one-off or + refusals a model corrects in its next call. Expectations are widened where another call answers as well, not the descriptions + tightened. The instructions say every question is fetched afresh, a follow-up or a challenge too. 4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the diff --git a/lib/service/days.py b/lib/service/days.py index 8fb04d2b..7bf17e31 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -54,6 +54,8 @@ ONLY = {"public_holiday": "public holidays only", "weekend": "weekends only"} # (the chart's subtitle says which) ORDERS = ("desc", "asc") OP_WORDS = {"==": "=", "≥": ">=", "≤": "<=", "=>": ">=", "=<": "<="} # ops written another way +GROUP_BY_NOTE = ("One figure for the whole period. If a figure per month or per year was asked for (\"per month\", \"by year\", " + "\"each year\"), call again with group_by \"month\" or \"year\".") ARGUMENTS = ("where", "sort_by", "order", "count_only", "group_by", "stat", "of", "limit", "only", "hours", "period", "start", "end", "chart_answers_it") OLD_NAMES = {"start_date": "start", "end_date": "end"} # weather_days' and air_days' names @@ -457,6 +459,8 @@ def row_extra(d: date) -> dict: engine_period = out.pop("period") out.pop("chart", None) # (the bot's hint: chart_note says what to do with a chart) out.update(self._notes(call, asked, held, got, checked, days, daily_out, devices, merged, first_held)) + if (call.stat or call.count_only) and not call.group_by and (last - first).days >= 31: # one figure over months: was a breakdown meant? + out["note_group_by"] = GROUP_BY_NOTE line = answer_line(out, engine_period, call.stretch) fields = {"answer": line, **({"hours": {"text": call.stretch.text, "how_to_read": HOURS_HOW}} if call.stretch else {}), **out} charts = with_charts(turn.charts, tz, meta) diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index d2d067d6..71ad00d3 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -1386,8 +1386,9 @@ "note": "a judgement on the conditions now: current, then the model's words" }, "lookup-hottest-today": { - "tools": [ - "summary" + "any_tools": [ + "summary", + "current" ], "args": { "summary": { @@ -1401,9 +1402,18 @@ ], "optional": true } + }, + "current": { + "context": true, + "readings": { + "reads_any": [ + "outdoor.temperature" + ], + "optional": true + } } }, - "note": "the high of a short period: summary (today is its default)" + "note": "the high of a short period: summary (today is its default); or current with context, whose today carries the high and its time" }, "lookup-hottest-vs": { "tools": [ diff --git a/tests/test_service_current.py b/tests/test_service_current.py index ed75ee59..ca07e7f3 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -139,7 +139,7 @@ async def test_every_reading_now_with_its_value_unit_words_and_emoji(tmp_path, a assert s["pressure"]["absolute"]["text"] == "1009.5 hPa" assert "rainfall_piezo" not in s # every reading the sensors have now: this station has no piezo gauge pm = s["air"]["pm2_5"] - assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and 51 <= pm["aqi_us"] <= 100 and pm["band"] == "moderate" + assert pm["value"] == 12.0 and pm["unit"] == "µg/m³" and pm["text"] == "12.0 µg/m³" and pm["band"] == ("good" if pm["aqi_us"] <= 50 else "moderate" if pm["aqi_us"] <= 100 else pm["band"]) # (moves with the clock) assert pm["rating"].endswith(("good", "poor")) assert s["air"]["co2"]["text"] == "450 ppm" and s["air"]["nox_index"]["text"] == "1.0" and s["air"]["voc_index"]["text"] == "100" assert s["air"]["temperature"]["unit"] == "°C" and "rating" not in s["air"]["temperature"] # the sensor's own: no rating diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 37ccbb3a..a4cb12b0 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -105,7 +105,7 @@ def truth(d: date) -> tuple[float, float]: def engine_part(out: dict) -> dict: """A days result as weather_days and air_days had it: without the service's head, its answer line, charts, looks and sources.""" out = {k: v for k, v in out.items() if k not in ("period", "as_of", "fresh", "answer", "chart_note", "charts", "reply", "complete", - "note", "chart")} + "note", "chart", "note_group_by")} for key in ("days", "trace_rain_days"): if key in out: out[key] = [{k: v for k, v in row.items() if k not in ("day_look", "source")} for row in out[key]] @@ -433,3 +433,15 @@ async def test_charts_are_sent_to_the_requests_budget(world): assert chart_of(both)["source"] == "Ecowitt weather station and AirGradient sensor" replay = copy.deepcopy(chart_of(both)["drawn_by"]["arguments"]) assert chart_of(await ask(world, **replay)) == chart_of(both) + + +async def test_one_figure_over_months_says_how_to_get_one_per_month_or_year(world): + """A stat or a count over more than a month with no group_by is one figure; the result says how to get one per month or year, so a + model that left group_by out ("rain per month") calls again, and it is never the whole answer.""" + from lib.service.days import GROUP_BY_NOTE + whole = await ask(world, stat="sum", of="rain", period="last 90 days", chart_answers_it=True) + assert whole["note_group_by"] == GROUP_BY_NOTE and "complete" not in whole + assert "note_group_by" not in await ask(world, stat="sum", of="rain", period="last 90 days", group_by="month") + assert "note_group_by" not in await ask(world, stat="sum", of="rain", period="last 7 days") # (a week: one figure is the answer) + counted = await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], count_only=True, period="last 90 days") + assert counted["note_group_by"] == GROUP_BY_NOTE From 21d72897cc0ba263d9e759fa9e05b876622427e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 12:32:10 +0000 Subject: [PATCH 053/125] Evals: a chat line with any tool call fails again only-that-its-cold and now-what go back to their first expectations (no call at all): the relaxation let a model that fetches readings for small talk pass, which the old prompt forbade. The eval shows it again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- tests/evals/service_cases.json | 16 ++++++++++++---- tests/test_service_evals.py | 10 +++++----- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index 71ad00d3..5062c85a 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -1195,13 +1195,17 @@ }, "only-that-its-cold": { "not_tools": [ + "current", "summary", "readings", "days", "relate", - "scan" + "scan", + "outlook", + "forecast", + "pollen" ], - "note": "a chat reply, not a request (the bot once answered it with the temperatures). With no conversation before it and only the tool list, a plain client may take it as a look at now (current, forecast, outlook, pollen: the first live run did, every time), which costs a call but answers nothing wrong; keeping the model from it is the client's prompt (the bot's needs_data), not a tool description. What it must not do is read a period's history" + "note": "a chat reply, not a request (the bot once answered it with the temperatures)" }, "how-cold-is-it": { "tools": [ @@ -1221,13 +1225,17 @@ }, "now-what": { "not_tools": [ + "current", "summary", "readings", "days", "relate", - "scan" + "scan", + "outlook", + "forecast", + "pollen" ], - "note": "'now' alone is not a weather question. With no conversation before it and only the tool list, a plain client may take it as a look at now (current, forecast, outlook, pollen: the first live run did, every time), which costs a call but answers nothing wrong; keeping the model from it is the client's prompt (the bot's needs_data), not a tool description. What it must not do is read a period's history" + "note": "'now' alone is not a weather question" }, "chart-with-forecast": { "tools": [ diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 14c0f926..80aad283 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -427,18 +427,18 @@ def test_a_rolling_period_in_words_is_not_a_month_that_its_days_happen_to_cover( assert ek._means({"start": "2026-09-01"}, "September", "days") is None -def test_what_a_plain_client_fairly_reads_into_a_bare_word_or_a_chat_line_passes_and_history_does_not(): +def test_a_bare_word_read_fairly_passes_and_a_chat_line_with_any_call_fails(): """The calls the first live run made that answer the question as a client with only the tool list reads it (each case's note says - why): "metrics" as the readings now, a weather report for today (Tuesday) as the report, a chat line with nothing before it as a - look at now. A period's history is still wrong for all of them.""" + why): "metrics" as the readings now, a weather report for today (Tuesday) as the report. A chat line ("only that it's cold", "ok + now what?") is not a request: any call fails it, so the eval shows a model that fetches readings for small talk.""" check = evalkit.check_calls assert check([("current", {})], EXPECT["metrics-bare"]) == [] and check([("about", {})], EXPECT["metrics-bare"]) == [] report = [("current", {}), ("forecast", {"period": "today"}), ("pollen", {})] assert check(report, EXPECT["weather-report-for-a-day"]) == [] for cid in ("only-that-its-cold", "now-what"): - assert check(report, EXPECT[cid]) == [] and check([("current", {"readings": ["temperature"]})], EXPECT[cid]) == [], cid assert check([], EXPECT[cid]) == [], cid - assert check([("summary", {"period": "today"})], EXPECT[cid]), cid + for call in (report, [("current", {"readings": ["temperature"]})], [("summary", {"period": "today"})]): + assert check(call, EXPECT[cid]), (cid, call) assert check([("summary", {})], EXPECT["metrics-bare"]) From a78b225d61e87fe4498addecbae2d72978775f5e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 12:46:00 +0000 Subject: [PATCH 054/125] Evals: --live answers the bot's model from the real tools over a frozen world The bot-mode live eval answered every call "no data", so the model never saw a real result, note or refusal and never took a second round. Now each call is answered by the real ten tools (wrapped as the bot wraps them) over the evals' frozen world: the fake station's archive, an AirGradient, forecast and pollen fakes, the clock at Tue 29 Sep 2026 14:05 Melbourne, built once per run (tests/evalworld.py, which tests/test_service_evals.py now uses too). A bot-mode case is scored over the whole turn: any call may meet the expectation (a refused call later corrected passes), not_tools hold for every call, more than 8 calls fails ("ran away"); each run's calls, refusals and the reply's start are printed. --service keeps its one-round CANNED scoring. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 6 +- scripts/eval_prompts.py | 29 +++-- tests/evalkit.py | 110 +++++++++++++++---- tests/evalworld.py | 153 ++++++++++++++++++++++++++ tests/test_evals.py | 13 ++- tests/test_service_evals.py | 213 +++++++++++++++++++----------------- 6 files changed, 391 insertions(+), 133 deletions(-) create mode 100644 tests/evalworld.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 67d33cc0..a2309ab6 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -531,7 +531,11 @@ Each step ships on its own, with the tests and evals green and the bot working t ours), and again with the server's instructions, and checked for the tools and arguments it picks and, where it matters, the answer. They run against the production model and at least one other, so the interface isn't tuned to one model's habits. The cases carry over from `tests/evals/cases.json`, with their periods checked as the service reads them, and gain one for each periods form, each - routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. + routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. The tools-alone runs + answer every call "no data" and score the first round (what the descriptions lead to); the bot's run (`--live`) answers each call + from the real tools over a frozen world (the fake station's archive and the other sources' fakes at the cases' fixed time), so the + model sees real results, notes and refusals and is scored over its whole turn: any call may meet the expectation, none may be a + forbidden tool, and more than 8 calls fails. - **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, and with only `period` changed to each of its `periods`, the same chart over that period, never an error; `day_look` against its rule. diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index f4efd04d..378e5034 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -4,10 +4,16 @@ report, the gauges, "weather now", a named reading's chart and a period) are checked over cases.json, and every service expectation is checked against the tools it names (each one they take). -With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) with recording -stand-in tools, and checks which tool it called and with what. Nothing is fetched. The bot's own request is the default: its system -prompt (the persona, the server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them, its reasoning -effort from the words, and a question it answers in code scored by its fixed calls without asking the model. +With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) and checks +which tools it called and with what. Nothing is fetched. The bot's own request is the default: its system prompt (the persona, the +server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them, its reasoning effort from the words, and a +question it answers in code scored by its fixed calls without asking the model. Each call is answered by the real tool over the +evals' frozen world (tests/evalworld.py: the fake station's archive, an AirGradient, forecast and pollen fakes, the clock at Tue 29 Sep +2026 14:05 Melbourne; built once per run, about ten seconds), wrapped as the bot wraps it, so the model sees real results, notes and +refusals and calls again until it replies (the turn ends on a complete result, as the bot's does; after 10 steps of calls the +model is made to answer). A case is scored over the whole turn: an expected call passes if any call makes it (a refused call later +corrected passes), a forbidden tool fails in any round, more than 8 calls fails ("ran away"); each run's number of calls, refusals and +the reply's start are printed. python scripts/eval_prompts.py # the decisions made in code, and the service expectations python scripts/eval_prompts.py --live # and the model, as the bot asks it @@ -15,9 +21,10 @@ python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? With --service: the ten tools alone (docs/mcp-service.md 7): the model is offered only their names, descriptions and parameters, with a -neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; --instructions adds the server's -instructions (lib/service/instructions.py) after the neutral line, as a client that passes them on would. Without --live it checks the -expectations themselves. +neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; every call is answered "no data", so its +first round is what is scored (what the descriptions lead a model to). --instructions adds the server's instructions +(lib/service/instructions.py) after the neutral line, as a client that passes them on would. Without --live it checks the expectations +themselves. python scripts/eval_prompts.py --service # every case has a service expectation, each one the tools take python scripts/eval_prompts.py --live --service # and the model, with the ten tools alone @@ -68,7 +75,13 @@ async def main() -> int: for p in problems: print(f" {p}") print(f"{len(cases) - decided} of {len(cases)} cases: the decisions made in code hold\n") - failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, bot=True) + if not client: + failed = await evalkit.run_service(cases, expectations, repeat=args.repeat, effort=args.effort, bot=True) + return 1 if failed or decided else 0 + from tests import evalworld + async with evalworld.world() as service: # (built once: the frozen world the model's calls are answered from) + failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, bot=True, + service=service) return 1 if failed or decided else 0 diff --git a/tests/evalkit.py b/tests/evalkit.py index b7b71b94..65582253 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -7,8 +7,9 @@ checked offline by tests/test_service_evals.py, and asked of a model by `python scripts/eval_prompts.py --live` three ways: - the bot's own request (`bot=True`, the default of --live): its system prompt (lib/prompt.py: the persona, the server's instructions, the date and time), the ten tools as the bot offers them, its reasoning effort from the words; a question the bot - answers in code is not asked of the model, its fixed calls are scored instead; - - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM); + answers in code is not asked of the model, its fixed calls are scored instead. Each call is answered by the real tool over the + evals' frozen world (tests/evalworld.py), so the model takes as many rounds as it needs, and the whole turn is scored (run_service); + - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM), every call answered CANNED (one round); - `--service --instructions`: that, with the server's instructions (lib/service/instructions.py) after the neutral line. """ @@ -187,24 +188,86 @@ def shortcut_expectation(expect: dict) -> dict: return {**expect, "args": args} -def bot_system(now: datetime = NOW) -> str: - """The bot's system prompt at `now` (the station's local time): its persona, the server's instructions, the date and time.""" +def bot_system(now: datetime = NOW, ctx=None) -> str: + """The bot's system prompt at `now` (the station's local time): its persona, the server's instructions (over `ctx`, as the bot builds + them over its own; over eval_context() when none is given), the date and time.""" from zoneinfo import ZoneInfo - return prompt.build(now.replace(tzinfo=ZoneInfo(NOW_TZ)), service_instructions()) + from lib.service.instructions import instructions + told = instructions(ctx) if ctx is not None else service_instructions() + return prompt.build(now.replace(tzinfo=ZoneInfo(NOW_TZ)), told) + + +MAX_CALLS = 8 # a bot-mode turn that makes more tool calls than this has run away: it fails, whatever it called + + +@dataclass +class LiveTurn: + """One question asked as the bot asks it: every call of the turn in order (refused ones too), how many of their results were + refusals (an `error`), the reply, and whether the bot answered it in code (its fixed calls, no model).""" + calls: list + reply: str + refused: int = 0 + in_code: bool = False -async def run_live(case: Case, client, model: str, effort: str | None = None) -> tuple[list[tuple[str, dict]], str]: + def line(self) -> str: + """`3 calls, 1 refused: "the reply's first 200 characters"`.""" + return (f"{len(self.calls)} call{'s' * (len(self.calls) != 1)}, {self.refused} refused: " + f"{json.dumps(self.reply[:200], ensure_ascii=False)}") + + +REPEATED = "[You already made this exact call" # (lib/llm.py's answer to a repeat, the first result after it) + + +def refusal(text: str) -> bool: + """Is this tool result, as the model was sent it, a refusal: an `error`, or the tool loop's own "Error..." (no such tool, arguments + that aren't JSON, the tool failed)?""" + body = text.split("\n", 1)[-1] if text.startswith(REPEATED) else text + if body.startswith("Error"): + return True + try: + out = json.loads(body) + except ValueError: + return False + return isinstance(out, dict) and "error" in out + + +def turn_calls(messages: list[dict]) -> tuple[list[tuple[str, dict]], int]: + """The tool calls of a turn's messages (as lib/llm.py's Agent leaves them: each assistant step's calls, then their results in + order), in the order made, and how many of their results were refusals.""" + calls, refused = [], 0 + for i, m in enumerate(messages): + if m.get("role") != "assistant" or not m.get("tool_calls"): + continue + for c, result in zip(m["tool_calls"], messages[i + 1:i + 1 + len(m["tool_calls"])]): + try: + args = json.loads(c["function"]["arguments"] or "{}") + except ValueError: + args = {} + calls.append((c["function"]["name"], args if isinstance(args, dict) else {})) + refused += result.get("role") == "tool" and refusal(str(result.get("content", ""))) + return calls, refused + + +async def run_live(case: Case, client, model: str, effort: str | None = None, service=None) -> LiveTurn: """The bot's own request (docs/mcp-service.md 4): a question it answers in code gives its fixed calls (no model); any other is asked of the model with the bot's system prompt, the ten tools as it offers them, its reasoning effort from the words, tool_choice auto, - and the turn ended on a complete result as the bot ends it. Returns the calls made and the reply.""" + and the turn ended on a complete result as the bot ends it. With `service` (evalworld.world: the ten tools over the frozen world) + each call is answered by the real tool, wrapped as the bot wraps it (lib/model_tools.py: the model is sent for_model of the + result), so the model calls again until it replies (at most lib/llm.py's MAX_STEPS steps, then it is made to answer); without, every + call is answered CANNED. Returns the whole turn.""" + from lib import model_tools r = read(case) if (calls := shortcut_calls(r)) is not None: - return list(calls), "(answered in code)" - calls = [] + return LiveTurn(list(calls), "(answered in code)", in_code=True) messages = [*case.history, {"role": "user", "content": content(case)}] - reply = await Agent(client, model, make_service_tools(calls)).run(messages, bot_system(), effort or r.effort, tool_choice="auto", - turn=Turn(), finish=lambda _, results: complete_reply(results)) - return calls, reply + asked = len(messages) + tools = model_tools.tools(service) if service is not None else make_service_tools([]) + system = bot_system(ctx=getattr(service, "ctx", None)) + reply = await Agent(client, model, tools).run(messages, system, effort or r.effort, tool_choice="auto", turn=Turn(), + finish=lambda _, results: complete_reply(results)) + calls, refused = turn_calls(messages[asked:]) + return LiveTurn(calls, reply, refused) # ---------- the service's ten tools, offered alone (docs/mcp-service.md 6, step 2; 7) ---------- @@ -501,29 +564,36 @@ def calls_text(calls: list[tuple[str, dict]]) -> str: async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, - effort: str | None = None, instructions: str | None = None, bot: bool = False, out=print) -> int: - """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times with - the ten tools alone (and the server's `instructions`, when given) and its calls scored against it (check_calls), as `--live` scores - cases.json. Prints a line per case (`out`), with the calls of a run that fails; returns how many cases fail.""" + effort: str | None = None, instructions: str | None = None, bot: bool = False, service=None, out=print) -> int: + """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times and + its calls scored against it (check_calls). Without `bot`: the ten tools alone (and the server's `instructions`, when given), every + call answered CANNED, so its first round is what is scored (what the descriptions lead to). With `bot`: as the bot asks (run_live), + over `service` (evalworld.world) when given, and scored over the whole turn: an expected tool or arguments pass if any call of the + turn makes them (a refused call later corrected passes), not_tools hold for every call, and a turn of more than MAX_CALLS calls + fails (it ran away); each run's calls, refusals and the reply's start are printed under the case. Prints a line per case (`out`), + with the calls of a run that fails; returns how many cases fail.""" failed = 0 for case in cases: expect = expectations.get(case.id) problems = service_problems(expect) - line = "ok" if not problems else "FAIL" + line, runs = "ok" if not problems else "FAIL", [] if client and not problems: passes = 0 for _ in range(repeat): if bot: - calls, _reply = await run_live(case, client, model, effort) - in_code = shortcut_calls(read(case)) is not None + turn = await run_live(case, client, model, effort, service) + calls, in_code = turn.calls, turn.in_code + runs.append(turn.line()) else: calls, _reply, in_code = *await run_live_service(case, client, model, effort, instructions), False why = check_calls(calls, shortcut_expectation(expect) if in_code else expect) + if bot and len(calls) > MAX_CALLS: + why.insert(0, f"ran away: {len(calls)} calls (more than {MAX_CALLS})") passes += not why problems += [*(f" run: {w}" for w in why[:3]), f" called: {calls_text(calls)}"] if why else [] line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + (" code" if bot and in_code else "") out(f"{line:>10} {case.id} ({case.ask})") - for p in problems: + for p in [*runs, *problems]: out(f" {p}") failed += bool(problems) what = "the bot's prompt and the ten tools" if bot else f"the service's ten tools alone{', with its instructions' if instructions else ''}" diff --git a/tests/evalworld.py b/tests/evalworld.py new file mode 100644 index 00000000..676d9446 --- /dev/null +++ b/tests/evalworld.py @@ -0,0 +1,153 @@ +"""The evals' frozen world: the service's ten tools over the fake station's archive, an AirGradient on the same file, Open-Meteo and the +pollen page (all faked, nothing fetched), with the clock fixed at the evals' NOW (evalkit.NOW: Tue 29 Sep 2026 14:05, Melbourne) in +lib/ and the engines. tests/test_service_evals.py calls the expected calls against it (at_eval_now, build_archive, real_context, with +pytest's monkeypatch), and `scripts/eval_prompts.py --live` answers the bot's model from it (`world`: built once per run, outside +pytest), so the model sees real results, notes and refusals and can take a second round.""" + +import asyncio +import datetime as _dt +import importlib +import pkgutil +import sys +import tempfile +import time as _time +from contextlib import asynccontextmanager +from datetime import datetime, time as dtime +from pathlib import Path +from zoneinfo import ZoneInfo + +import pytest + +from tests import evalkit + +EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() + + +class _DatetimeType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.datetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.datetime) + + +class _EvalDatetime(_dt.datetime, metaclass=_DatetimeType): + @classmethod + def now(cls, tz=None): + return _dt.datetime.fromtimestamp(EVAL_NOW, tz) + + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW) + + +class _DateType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _dt.date) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _dt.date) + + +class _EvalDate(_dt.date, metaclass=_DateType): + @classmethod + def today(cls): + return _dt.datetime.fromtimestamp(EVAL_NOW).date() + + +def at_eval_now(patch: pytest.MonkeyPatch, *also: str): + """The clock fixed at EVAL_NOW in every module of lib/ and tests/ (and the modules named in `also`, a test module whatever pytest + names it): every module of lib/ is imported first (whatever was imported before), then every name bound to datetime or date is the + fixed one, and time.time() (and the archive's epoch_now) returns EVAL_NOW; the process's zone is the station's (as conftest sets + it), so a naive local time is Melbourne's. `patch.undo()` puts it all back.""" + import lib + import tests.fakes, tests.test_pollen, tests.test_service_forecast # noqa: F401 + for info in pkgutil.walk_packages(lib.__path__, "lib."): + importlib.import_module(info.name) + patch.setenv("TZ", evalkit.NOW_TZ) + _time.tzset() + patch.setattr(_time, "time", lambda: EVAL_NOW) + for name, module in list(sys.modules.items()): + if module is None or not (name in ("lib", *also) or name.startswith(("lib.", "tests."))): + continue + for attr, value in list(vars(module).items()): + if value is _dt.datetime: + patch.setattr(module, attr, _EvalDatetime) + elif value is _dt.date: + patch.setattr(module, attr, _EvalDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: EVAL_NOW) + + +async def _inline(func, /, *args, **kwargs): + return func(*args, **kwargs) + + +async def build_archive(folder: Path) -> Path: + """The fake station's whole archive (its ecobot.sqlite in `folder`), built at the clock as it is (at_eval_now first), its pacing off.""" + from lib.ecowitt import Archive, Ecowitt, api, archive + from tests.fakes import config, ecowitt_transport + with pytest.MonkeyPatch.context() as patch: + patch.setattr(api, "MIN_GAP_SECONDS", 0) + patch.setattr(archive, "PACE_SECONDS", 0) + patch.setattr(asyncio, "to_thread", _inline) + transport, _ = ecowitt_transport() + eco = Ecowitt(config(folder), transport=transport) + await eco.start() + await Archive(eco).run_once() + await eco.close() + return config(folder).storage_path + + +async def real_context(folder: Path, archive: Path): + """The ten tools' sources, faked, at the clock as it is (at_eval_now), their files in `folder` (not the archive's): the archived + station, an AirGradient on the same file, both together, Open-Meteo, the pollen page in season; the context's own clock is EVAL_NOW.""" + import json + + from lib.airgradient import AirGradient + from lib.compose import Composer + from lib.forecast import Forecast + from lib.service.context import Context + from tests.fakes import air_transport, archived_station, config + from tests.test_pollen import make as pollen_source + from tests.test_service_forecast import open_meteo + eco, _ = await archived_station(folder, archive) + air = AirGradient(config(folder), transport=air_transport(rows_per_day=24)[0], storage=eco.storage) + await air.start() + forecast = Forecast(config(folder, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, open_meteo([])) + noon = datetime.combine(evalkit.NOW.date(), dtime(12, 0)) + forecast.now = lambda: noon + pollen, _ = pollen_source(folder) + ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen, clock=lambda: EVAL_NOW) + (summary,) = [t for t in evalkit.service_tools(ctx) if t.name == "summary"] + held = json.loads(await summary.call({"readings": ["air"], "period": "last 30 days", "chart": False})) # (the air's month, held) + assert "error" not in held + return ctx + + +async def close(ctx): + """Close the sources real_context started.""" + await ctx.pollen.close() + await ctx.air.close() + await ctx.eco.close() + + +@asynccontextmanager +async def world(folder: Path | None = None): + """The frozen world for a whole run outside pytest: the clock fixed (at_eval_now), the archive built under it, and the lib.service + Service of the ten tools over real_context; everything put back on leaving. `folder`: where its files go (a temporary one).""" + from lib.service import Service + patch = pytest.MonkeyPatch() + with tempfile.TemporaryDirectory(prefix="ecobot-eval-") as tmp: + root = Path(folder or tmp) + (root / "archive").mkdir(parents=True, exist_ok=True) + (root / "world").mkdir(parents=True, exist_ok=True) + try: + at_eval_now(patch) + ctx = await real_context(root / "world", await build_archive(root / "archive")) + try: + yield Service.of(ctx) + finally: + await close(ctx) + finally: + patch.undo() + _time.tzset() diff --git a/tests/test_evals.py b/tests/test_evals.py index c77459f5..c4c0a814 100644 --- a/tests/test_evals.py +++ b/tests/test_evals.py @@ -46,14 +46,15 @@ async def test_the_bots_live_run_is_its_own_request_and_its_shortcuts_ask_no_mod from tests.test_agent import FakeLLM from tests.test_service_evals import case client = FakeLLM([[("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})], "Done."]) - calls, reply = await evalkit.run_live(case("3m-average"), client, "m") - assert calls == [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})] and reply == "Done." + turn = await evalkit.run_live(case("3m-average"), client, "m") + assert turn.calls == [("summary", {"readings": ["temperature"], "period": "last 3 months", "average": True})] + assert turn.reply == "Done." and turn.refused == 0 and not turn.in_code first = client.requests[0] assert first["messages"][0] == {"role": "system", "content": evalkit.bot_system()} assert first["messages"][0]["content"].startswith("You are a friendly weather bot on Telegram") and first["tool_choice"] == "auto" assert [t["function"]["name"] for t in first["tools"]] == evalkit.service_tool_names() assert first["extra_body"]["reasoning"]["effort"] == evalkit.read(case("3m-average")).effort - assert await evalkit.run_live(case("report"), None, "m") == ( - [("current", {}), ("pollen", {}), ("forecast", {"period": "next 3 days"})], "(answered in code)") - calls, _ = await evalkit.run_live(case("button-rain-chart"), None, "m") - assert calls == [("summary", {"readings": ["rain"], "period": "7d", "chart": True})] + assert await evalkit.run_live(case("report"), None, "m") == evalkit.LiveTurn( + [("current", {}), ("pollen", {}), ("forecast", {"period": "next 3 days"})], "(answered in code)", in_code=True) + turn = await evalkit.run_live(case("button-rain-chart"), None, "m") + assert turn.calls == [("summary", {"readings": ["rain"], "period": "7d", "chart": True})] and turn.in_code diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 80aad283..ab2e75c7 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -9,28 +9,19 @@ real date.""" import asyncio -import datetime as _dt -import importlib import json import os -import pkgutil import subprocess import sys -import time as _time -from datetime import datetime, time as dtime +from datetime import datetime from pathlib import Path from types import SimpleNamespace as NS -from unittest import mock -from zoneinfo import ZoneInfo import pytest -from lib.airgradient import AirGradient -from lib.compose import Composer -from lib.forecast import Forecast from lib.service.context import Context -from tests import evalkit -from tests.fakes import TZ, air_transport, archived_station, config +from tests import evalkit, evalworld +from tests.fakes import TZ CASES = evalkit.load_cases() EXPECT = evalkit.load_service_cases() @@ -203,84 +194,21 @@ def test_each_description_is_short_and_each_schema_is_json_schema(name): # At the evals' NOW (Tue 29 Sep 2026 14:05, Melbourne), whatever the real date: the expectations are written for it ("this month" is # September to the 28th, "June to August 2026" is in the fake's history). Every datetime.now(), date.today() and time.time() in lib/ # and tests/ reads it, and the fake station's archive is built under it (the idea of tests/test_service_switch.py's freeze, kept here). -EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() - - -class _DatetimeType(type): - def __instancecheck__(cls, obj): - return isinstance(obj, _dt.datetime) - - def __subclasscheck__(cls, sub): - return issubclass(sub, _dt.datetime) - - -class _EvalDatetime(_dt.datetime, metaclass=_DatetimeType): - @classmethod - def now(cls, tz=None): - return _dt.datetime.fromtimestamp(EVAL_NOW, tz) - - @classmethod - def today(cls): - return _dt.datetime.fromtimestamp(EVAL_NOW) - - -class _DateType(type): - def __instancecheck__(cls, obj): - return isinstance(obj, _dt.date) - - def __subclasscheck__(cls, sub): - return issubclass(sub, _dt.date) - - -class _EvalDate(_dt.date, metaclass=_DateType): - @classmethod - def today(cls): - return _dt.datetime.fromtimestamp(EVAL_NOW).date() +EVAL_NOW = evalworld.EVAL_NOW def at_eval_now(patch: pytest.MonkeyPatch): - """The clock fixed at EVAL_NOW in every module of lib/ and tests/ (and this one, whatever pytest names it): every module of lib/ is - imported first (whatever was imported before), then every name bound to datetime or date is the fixed one, and time.time() (and - the archive's epoch_now) returns EVAL_NOW.""" - import lib - import tests.fakes, tests.test_pollen, tests.test_service_forecast # noqa: F401 - for info in pkgutil.walk_packages(lib.__path__, "lib."): - importlib.import_module(info.name) - patch.setattr(_time, "time", lambda: EVAL_NOW) - for name, module in list(sys.modules.items()): - if module is None or not (name in ("lib", __name__) or name.startswith(("lib.", "tests."))): - continue - for attr, value in list(vars(module).items()): - if value is _dt.datetime: - patch.setattr(module, attr, _EvalDatetime) - elif value is _dt.date: - patch.setattr(module, attr, _EvalDate) - patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: EVAL_NOW) - - -async def _inline(func, /, *args, **kwargs): - return func(*args, **kwargs) + """evalworld.at_eval_now, this module included (whatever pytest names it).""" + evalworld.at_eval_now(patch, __name__) @pytest.fixture(scope="module") def eval_archive(tmp_path_factory): """The fake station's whole archive (its ecobot.sqlite) built at EVAL_NOW, once for the module.""" - from lib.ecowitt import Archive, Ecowitt, api, archive - from tests.fakes import ecowitt_transport - - async def build(path): - transport, _ = ecowitt_transport() - eco = Ecowitt(config(path), transport=transport) - await eco.start() - await Archive(eco).run_once() - await eco.close() - return config(path).storage_path path = tmp_path_factory.mktemp("eval-now") with pytest.MonkeyPatch.context() as patch: at_eval_now(patch) - with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ - mock.patch.object(asyncio, "to_thread", _inline): - return asyncio.run(build(path)) + return asyncio.run(evalworld.build_archive(path)) def calls_for(tool: str) -> list[tuple[str, dict]]: @@ -288,22 +216,7 @@ def calls_for(tool: str) -> list[tuple[str, dict]]: async def real_context(tmp_path, archive) -> Context: - """The ten tools' sources, faked, at the clock as it is (at_eval_now): the archived station, an AirGradient on the same file, both - together, Open-Meteo, the pollen page in season; the context's own clock is EVAL_NOW.""" - from tests.test_pollen import make as pollen_source - from tests.test_service_forecast import open_meteo - eco, _ = await archived_station(tmp_path, archive) - air = AirGradient(config(tmp_path), transport=air_transport(rows_per_day=24)[0], storage=eco.storage) - await air.start() - forecast = Forecast(config(tmp_path, forecast=True, forecast_lat=-37.8, forecast_lon=144.9, place="Melbourne"), None, open_meteo([])) - noon = datetime.combine(evalkit.NOW.date(), dtime(12, 0)) - forecast.now = lambda: noon - pollen, _ = pollen_source(tmp_path) - ctx = await Context.open(eco=eco, air=air, composer=Composer(eco, air), forecast=forecast, pollen=pollen, clock=lambda: EVAL_NOW) - (summary,) = [t for t in evalkit.service_tools(ctx) if t.name == "summary"] - held = json.loads(await summary.call({"readings": ["air"], "period": "last 30 days", "chart": False})) # (the air's month, held) - assert "error" not in held - return ctx + return await evalworld.real_context(tmp_path, archive) @pytest.mark.parametrize("tool", evalkit.service_tool_names()) @@ -323,9 +236,7 @@ async def test_every_expected_call_is_answered_not_refused(tool, tmp_path, eval_ refused[case_id] = (args, out["error"]) assert refused == {}, json.dumps(refused, indent=1, ensure_ascii=False) finally: - await ctx.pollen.close() - await ctx.air.close() - await ctx.eco.close() + await evalworld.close(ctx) # ---------- the live run, with a scripted model ---------- @@ -480,3 +391,109 @@ def fails(args): assert fails({"sort_by": "temp_max", "order": "asc"}) == ["order"] assert fails({"sort_by": "temp_max", "count_only": True}) == ["count_only"] assert fails({"stat": "avg", "of": "temp_avg"}) == ["stat"] + + +# ---------- the bot's live run over the frozen world, with a scripted model ---------- +# `--live` answers the bot's model from the real ten tools (evalworld.world), so a turn can take more than one round: it is scored over +# the whole turn. These run it with a model that reads what its calls gave, over the same world (the module's archive, at EVAL_NOW). +class Reacting: + """An OpenAI-style client whose steps are scripted: each a text (the reply), a list of (tool, args), or a function of what the last + step's calls gave (each result as the model was sent it, parsed) that returns one. Past the script it says "Done.".""" + + def __init__(self, *steps): + self.steps, self.requests, self.seen = list(steps), [], [] + self.chat = NS(completions=NS(create=self.create)) + + async def create(self, **kw): + self.requests.append(kw) + given = [] + for m in reversed(kw["messages"]): + if m["role"] != "tool": + break + text = m["content"].split("\n", 1)[-1] if m["content"].startswith(evalkit.REPEATED) else m["content"] + given.insert(0, json.loads(text)) + self.seen.append(given) + step = self.steps.pop(0) if self.steps else "Done." + step = step(given) if callable(step) else step + calls = None if isinstance(step, str) else [NS(id=f"c{i}", function=NS(name=n, arguments=json.dumps(a))) + for i, (n, a) in enumerate(step)] + return NS(choices=[NS(message=NS(content=step if isinstance(step, str) else "", tool_calls=calls))], usage=None) + + +@pytest.fixture +async def eval_service(tmp_path, eval_archive, monkeypatch): + """The ten tools over the frozen world (what evalworld.world gives a run), on the module's archive.""" + from lib.service import Service + at_eval_now(monkeypatch) + ctx = await real_context(tmp_path, eval_archive) + yield Service.of(ctx) + await evalworld.close(ctx) + + +async def bot_run(case_id: str, model: Reacting, service) -> tuple[int, str]: + lines = [] + failed = await evalkit.run_service([case(case_id)], EXPECT, model, "m", bot=True, service=service, out=lines.append) + return failed, "\n".join(lines) + + +async def test_a_refused_call_then_a_corrected_one_passes_and_the_refusal_is_counted(eval_service): + model = Reacting([("summary", {"readings": ["flux capacitor"], "period": "3m", "average": True})], + lambda given: [("summary", {"readings": ["temperature"], "period": "3m", "average": True})] if "error" in given[0] + else "gave up", + "Averaged 14.2 °C.") + failed, text = await bot_run("3m-average", model, eval_service) + assert failed == 0, text + assert "1/1 3m-average" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text + assert "isn't a reading this service knows" in model.seen[1][0]["error"] # (the real refusal, as the model was sent it) + assert model.requests[0]["messages"][0]["content"] == evalkit.bot_system(ctx=eval_service.ctx) + + +async def test_a_second_call_made_on_a_note_passes(eval_service): + """rain-per-month: one figure for the year comes back with days' note_group_by; the model acts on it and asks again by month.""" + asked = {"stat": "sum", "of": "rain", "period": "this year"} + model = Reacting([("days", asked)], + lambda given: [("days", {**asked, "group_by": "month"})] if "note_group_by" in given[0] else "One figure.", + lambda given: f"{len(given[0]['by_month'])} months.") + failed, text = await bot_run("rain-per-month", model, eval_service) + assert failed == 0, text + assert '2 calls, 0 refused: "9 months."' in text # (January to September: the real days, by month) + without = Reacting([("days", asked)], lambda given: "One figure.") + failed, text = await bot_run("rain-per-month", without, eval_service) + assert failed == 1 and "group_by" in text and '1 call, 0 refused: "One figure."' in text + + +async def test_a_forbidden_tool_in_a_later_round_fails(eval_service): + model = Reacting([("relate", {})], [("days", {"stat": "max", "of": "pressure_max", "group_by": "month"})], "Weak.") + failed, text = await bot_run("pressure-rain-correlation", model, eval_service) + assert failed == 1 and "0/1 FAIL pressure-rain-correlation" in text and "should not have called days" in text + assert "2 calls, 0 refused" in text + + +async def test_a_turn_of_more_than_eight_calls_has_run_away_and_fails(eval_service): + many = [[("days", {"stat": "sum", "of": "rain", "group_by": "month", "period": f"last {n} days"})] for n in range(40, 49)] + failed, text = await bot_run("rain-per-month", Reacting(*many, "Rain by month."), eval_service) + assert failed == 1 and "ran away: 9 calls (more than 8)" in text and "9 calls, 0 refused" in text + failed, text = await bot_run("rain-per-month", Reacting(*many[:8], "Rain by month."), eval_service) + assert "ran away" not in text and '8 calls, 0 refused: "Rain by month."' in text + + +async def test_a_turn_is_capped_at_the_agents_steps(): + """However long the model keeps calling, the turn takes at most lib/llm.py's MAX_STEPS (10) steps of calls, then it is made to + answer.""" + from lib import llm + assert llm.MAX_STEPS == 10 + model = Reacting(*[[("about", {})]] * 30) + turn = await evalkit.run_live(case("3m-average"), model, "m") + assert len(model.requests) == llm.MAX_STEPS + 1 and len(turn.calls) == llm.MAX_STEPS + assert model.requests[-1]["tool_choice"] == "none" + + +async def test_the_world_is_built_at_the_frozen_clock_and_its_tools_give_real_results_then_the_clock_is_put_back(): + import time + async with evalworld.world() as service: + assert time.time() == EVAL_NOW + out = json.loads(await service["days"].call({"stat": "sum", "of": "rain", "group_by": "month", "period": "this year"})) + assert "error" not in out and out["period"]["text"] == "this year: Thu 1 Jan – Mon 28 Sep 2026" + assert list(out["by_month"]) == [f"2026-{m:02d}" for m in range(1, 10)] and out["days_checked"] + assert [t.name for t in service] == evalkit.service_tool_names() + assert time.time() != EVAL_NOW From 6745cbdc2f875f245434dd303218ee9695f9c83c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 12:58:40 +0000 Subject: [PATCH 055/125] days refuses `of` without `stat`; a chart reading with nothing to draw is left out - days: `of` with no `stat` counted the days and dropped `of` ("rain total per month" ended on "313 of 313 days" in the live check). It is refused, saying to send stat too (sum, avg, max, min), so the model corrects it in its next call. The two-readings-by-month expectation now asks for its stat. - query: a reading whose figures come from today's day row but which has no readings in the window (the last hours near midnight) made summary's chart fail with a KeyError; its line is left out. test_bench_storage failed on it after 9pm. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/ecowitt/query.py | 2 ++ lib/service/days.py | 5 ++++- tests/evals/service_cases.json | 9 ++++++++- tests/test_ecowitt.py | 9 +++++++++ tests/test_service_days.py | 10 ++++++++++ 5 files changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/ecowitt/query.py b/lib/ecowitt/query.py index f58fbab8..bddfda72 100644 --- a/lib/ecowitt/query.py +++ b/lib/ecowitt/query.py @@ -451,6 +451,8 @@ def _series_entry(self, k: str) -> tuple[Line, str] | None: line = self._shaded(self.lines.get(k), self.lines.get(band) if band else None) elif how == "days": line = self._shaded(self._day_line(k, at), self._day_line(band, at) if band else None) + elif k not in self.store: # its figures came from the day rows, but no readings in the window to draw (a quiet last hours) + return None else: line = build_line(self._series_readings(k), self.tz, self.span.total_seconds(), smooth=k in SMOOTH_SERIES, force_daily=self.turn.average_asked, until=now_local(self.tz).date()) diff --git a/lib/service/days.py b/lib/service/days.py index 7bf17e31..18cb6182 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -149,7 +149,7 @@ def parameters(fields: list[str]) -> dict: "description": "What the period, or each month or year, gives: count (default: the matching days), or the max, min, " "avg or sum of `of` over the matching days (\"rain per month\": sum of rain; \"the hottest day each " "year\": max of temp_max; \"average humidity per year\": avg of humidity_avg)."}, - "of": {**one, "description": "The field stat takes the max, min, avg or sum of (not needed for count)."}, + "of": {**one, "description": "The field stat takes the max, min, avg or sum of; always with stat (not needed for count)."}, "limit": {"type": "integer", "description": f"How many days to list (default 5, at most {MAX_LIMIT}). The total is always " "counted."}, "only": {"type": "string", "enum": list(ONLY), @@ -279,6 +279,9 @@ def read(self, args: dict) -> Call: group_by = str(args["group_by"]).strip().lower() if args.get("group_by") else None if group_by not in (None, "month", "year"): raise Refusal(f"group_by is month or year, not {args['group_by']!r}.") + if args.get("of") and not args.get("stat"): # (else it counts days and `of` is lost: "rain per month" as "313 of 313 days") + raise Refusal(f"`of` names the field `stat` works on: send `stat` too ({', '.join(s for s in STATS if s != 'count')}; " + f"\"rain per month\": stat sum, of rain), or leave `of` out to count days.", stats=list(STATS)) stat = str(args.get("stat") or "count").strip().lower() if stat not in STATS: raise Refusal(f"stat is one of {', '.join(STATS)}, not {args['stat']!r}.", stats=list(STATS)) diff --git a/tests/evals/service_cases.json b/tests/evals/service_cases.json index 5062c85a..177d7922 100644 --- a/tests/evals/service_cases.json +++ b/tests/evals/service_cases.json @@ -1778,6 +1778,13 @@ "args": { "days": { "group_by": "month", + "stat": { + "one_of": [ + "avg", + "max", + "min" + ] + }, "of": { "regex": "^(pm2_5|co2)_", "e.g.": "pm2_5_avg" @@ -1792,7 +1799,7 @@ } } }, - "note": "two readings by month: a days call for each (a figure per month), or summary of both (its breakdown is by month for a long period); the period is the model's choice" + "note": "two readings by month: a days call for each (a figure per month, with its stat), or summary of both (its breakdown is by month for a long period); the period is the model's choice" }, "chart-weather-90d": { "tools": [ diff --git a/tests/test_ecowitt.py b/tests/test_ecowitt.py index 2447bb41..7ff84e9e 100644 --- a/tests/test_ecowitt.py +++ b/tests/test_ecowitt.py @@ -1543,3 +1543,12 @@ def with_a_failure(self, *args): "end_date": f"{today - timedelta(days=2)} 23:59:59"})) await eco.close() assert "HTTP 502" in " ".join(out.get("missing", [])) and "warning" in out + + +def test_a_reading_with_figures_but_no_readings_in_the_window_draws_no_line_rather_than_failing(): + """Late at night the last hours can hold no readings while today's day row still gives the reading's high and low: the chart leaves + that reading's line out (None) instead of a KeyError on its missing series (it broke summary's chart of the last 3 hours).""" + from lib.ecowitt.query import HistoryQuery + q = object.__new__(HistoryQuery) + q.drawing, q.store, q.units = ("raw", 0), {}, {"outdoor.temperature": "°C"} + assert q._series_entry("outdoor.temperature") is None diff --git a/tests/test_service_days.py b/tests/test_service_days.py index a4cb12b0..9040c199 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -445,3 +445,13 @@ async def test_one_figure_over_months_says_how_to_get_one_per_month_or_year(worl assert "note_group_by" not in await ask(world, stat="sum", of="rain", period="last 7 days") # (a week: one figure is the answer) counted = await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], count_only=True, period="last 90 days") assert counted["note_group_by"] == GROUP_BY_NOTE + + +async def test_of_without_stat_is_refused_saying_to_send_stat_not_counted_as_days(world): + """`of` with no `stat` used to count the days and drop `of` ("rain per month" answered "313 of 313 days"); it is refused, saying + to send stat too, so a model corrects it in its next call.""" + out = await ask(world, of="rain", group_by="month", period="this year") + assert "error" in out and "send `stat` too" in out["error"] and "sum" in out["error"] + fixed = await ask(world, stat="sum", of="rain", group_by="month", period="this year") + assert "error" not in fixed and fixed["answer"].startswith("Total rain") + assert "error" not in await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], period="this year") # (a count: no `of`) From 52df1156438ce3c92902108c037b73b6e59eba42 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:00:04 +0000 Subject: [PATCH 056/125] Evals --live: a fresh world per run, refused calls meet nothing, the reply is scored - Each run of each case gets fresh tools over a new copy of the frozen world's archive (evalworld.World.fresh; the archive is still built once, a copy is about 0.1 s): a call could fill the shared file from the fakes (a day in 2023 moved "on record" back from 2025), so results depended on case order, --ids and --repeat. - turn_calls gives each call's refusal; the expected tools and arguments are met only by calls that were not refused (not_tools still hold for every call), so a refused matching call followed by a give-up reply fails. - A bot-mode turn fails if its reply is empty or the Agent's fallback (lib/llm.py FALLBACK, now a constant), or if it ends on a refused call with none answered after it (evalkit.check_turn). - --service's wording: every call is answered "no data" and every call of the turn is scored (the Agent may loop), not "its first round"; its behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 9 ++-- lib/llm.py | 4 +- scripts/eval_prompts.py | 19 ++++---- tests/evalkit.py | 85 +++++++++++++++++++++++---------- tests/evalworld.py | 43 ++++++++++++----- tests/test_service_evals.py | 93 ++++++++++++++++++++++++++++--------- 6 files changed, 183 insertions(+), 70 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a2309ab6..bf440d80 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -532,10 +532,11 @@ Each step ships on its own, with the tests and evals green and the bot working t They run against the production model and at least one other, so the interface isn't tuned to one model's habits. The cases carry over from `tests/evals/cases.json`, with their periods checked as the service reads them, and gain one for each periods form, each routing rule (a record or a day, a chart or a figure per month), `outlook`, `about` and `chart_answers_it`. The tools-alone runs - answer every call "no data" and score the first round (what the descriptions lead to); the bot's run (`--live`) answers each call - from the real tools over a frozen world (the fake station's archive and the other sources' fakes at the cases' fixed time), so the - model sees real results, notes and refusals and is scored over its whole turn: any call may meet the expectation, none may be a - forbidden tool, and more than 8 calls fails. + answer every call "no data" and score every call of the turn (what the descriptions lead to); the bot's run (`--live`) answers + each call from the real tools over a frozen world (the fake station's archive, copied fresh for each run of each case, and the other + sources' fakes at the cases' fixed time), so the model sees real results, notes and refusals and is scored over its whole turn: any + call that was not refused may meet the expectation, none may be a forbidden tool, and more than 8 calls, an empty or fallback reply, + or a turn ending on a refused call fails. - **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, and with only `period` changed to each of its `periods`, the same chart over that period, never an error; `day_look` against its rule. diff --git a/lib/llm.py b/lib/llm.py index 06d013ae..a9729a93 100644 --- a/lib/llm.py +++ b/lib/llm.py @@ -21,6 +21,8 @@ # Tool results past twice a full query's data (10,000 tokens) get the chat a heads-up: that much input rides on every later step WARN_TOKENS = 2 * POINT_BUDGET * TOKENS_PER_POINT +FALLBACK = "Sorry, I couldn't get an answer together - try a narrower question." # the reply when the model's last answer is empty + LIMIT_NOTICE = ("(System: tool limit reached. Answer now using only the data already fetched, " "and briefly say if anything is missing.)") @@ -143,7 +145,7 @@ async def run_calls(calls: list[dict]) -> list[str]: entry["tool_calls"] = [_tool_call(tc) for tc in tool_calls] messages.append(entry) if not tool_calls or final: - return content.strip() or "Sorry, I couldn't get an answer together - try a narrower question." + return content.strip() or FALLBACK results = await run_calls(tool_calls) if finish and (reply := finish(tool_calls, results)): log.info("The turn ended on a complete result (%s): no LLM %d", diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 378e5034..9bbeab37 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -9,11 +9,13 @@ server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them, its reasoning effort from the words, and a question it answers in code scored by its fixed calls without asking the model. Each call is answered by the real tool over the evals' frozen world (tests/evalworld.py: the fake station's archive, an AirGradient, forecast and pollen fakes, the clock at Tue 29 Sep -2026 14:05 Melbourne; built once per run, about ten seconds), wrapped as the bot wraps it, so the model sees real results, notes and +2026 14:05 Melbourne; the archive built once per run, about ten seconds, and each run of each case given fresh tools over its own +copy of it, so no case's calls change another's answers), wrapped as the bot wraps it, so the model sees real results, notes and refusals and calls again until it replies (the turn ends on a complete result, as the bot's does; after 10 steps of calls the -model is made to answer). A case is scored over the whole turn: an expected call passes if any call makes it (a refused call later -corrected passes), a forbidden tool fails in any round, more than 8 calls fails ("ran away"); each run's number of calls, refusals and -the reply's start are printed. +model is made to answer). A case is scored over the whole turn: an expected call passes if any call that was not refused makes it (a +refused call later corrected passes), a forbidden tool fails in any round, refused or not, more than 8 calls fails ("ran away"), and +so does an empty reply, the Agent's fallback reply (the model's last answer was empty) or a turn that ends on a refused call with +none answered after it; each run's number of calls, refusals and the reply's first 200 characters are printed. python scripts/eval_prompts.py # the decisions made in code, and the service expectations python scripts/eval_prompts.py --live # and the model, as the bot asks it @@ -21,8 +23,9 @@ python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? With --service: the ten tools alone (docs/mcp-service.md 7): the model is offered only their names, descriptions and parameters, with a -neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; every call is answered "no data", so its -first round is what is scored (what the descriptions lead a model to). --instructions adds the server's instructions +neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; every call is answered "no data" (the +model may call again or reply, up to the Agent's 10 steps), and every call of the turn is scored (what the descriptions lead a model +to, with nothing real to react to). --instructions adds the server's instructions (lib/service/instructions.py) after the neutral line, as a client that passes them on would. Without --live it checks the expectations themselves. @@ -79,9 +82,9 @@ async def main() -> int: failed = await evalkit.run_service(cases, expectations, repeat=args.repeat, effort=args.effort, bot=True) return 1 if failed or decided else 0 from tests import evalworld - async with evalworld.world() as service: # (built once: the frozen world the model's calls are answered from) + async with evalworld.world() as world: # (the archive built once; each run of each case gets fresh tools over a copy of it) failed = await evalkit.run_service(cases, expectations, client, model, repeat=args.repeat, effort=args.effort, bot=True, - service=service) + world=world) return 1 if failed or decided else 0 diff --git a/tests/evalkit.py b/tests/evalkit.py index 65582253..a2128fdd 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -9,7 +9,8 @@ instructions, the date and time), the ten tools as the bot offers them, its reasoning effort from the words; a question the bot answers in code is not asked of the model, its fixed calls are scored instead. Each call is answered by the real tool over the evals' frozen world (tests/evalworld.py), so the model takes as many rounds as it needs, and the whole turn is scored (run_service); - - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM), every call answered CANNED (one round); + - `--service`: the ten tools alone with a neutral system line and the date (SERVICE_SYSTEM), every call answered CANNED ("no data": + the model may call again or reply, and every call of the turn is scored); - `--service --instructions`: that, with the server's instructions (lib/service/instructions.py) after the neutral line. """ @@ -203,13 +204,22 @@ def bot_system(now: datetime = NOW, ctx=None) -> str: @dataclass class LiveTurn: - """One question asked as the bot asks it: every call of the turn in order (refused ones too), how many of their results were - refusals (an `error`), the reply, and whether the bot answered it in code (its fixed calls, no model).""" + """One question asked as the bot asks it: every call of the turn in order (refused ones too), the reply, whether each call's result + was a refusal (an `error`; `refusals`, in the calls' order), and whether the bot answered it in code (its fixed calls, no model).""" calls: list reply: str - refused: int = 0 + refusals: list = field(default_factory=list) in_code: bool = False + @property + def refused(self) -> int: + """How many of the calls were refused.""" + return sum(self.refusals) + + def answered(self) -> list: + """The calls that were not refused.""" + return [c for c, no in zip(self.calls, self.refusals + [False] * len(self.calls)) if not no] + def line(self) -> str: """`3 calls, 1 refused: "the reply's first 200 characters"`.""" return (f"{len(self.calls)} call{'s' * (len(self.calls) != 1)}, {self.refused} refused: " @@ -232,10 +242,10 @@ def refusal(text: str) -> bool: return isinstance(out, dict) and "error" in out -def turn_calls(messages: list[dict]) -> tuple[list[tuple[str, dict]], int]: +def turn_calls(messages: list[dict]) -> list[tuple[str, dict, bool]]: """The tool calls of a turn's messages (as lib/llm.py's Agent leaves them: each assistant step's calls, then their results in - order), in the order made, and how many of their results were refusals.""" - calls, refused = [], 0 + order), in the order made: (tool, arguments, whether its result was a refusal).""" + calls = [] for i, m in enumerate(messages): if m.get("role") != "assistant" or not m.get("tool_calls"): continue @@ -244,15 +254,15 @@ def turn_calls(messages: list[dict]) -> tuple[list[tuple[str, dict]], int]: args = json.loads(c["function"]["arguments"] or "{}") except ValueError: args = {} - calls.append((c["function"]["name"], args if isinstance(args, dict) else {})) - refused += result.get("role") == "tool" and refusal(str(result.get("content", ""))) - return calls, refused + calls.append((c["function"]["name"], args if isinstance(args, dict) else {}, + result.get("role") == "tool" and refusal(str(result.get("content", ""))))) + return calls async def run_live(case: Case, client, model: str, effort: str | None = None, service=None) -> LiveTurn: """The bot's own request (docs/mcp-service.md 4): a question it answers in code gives its fixed calls (no model); any other is asked of the model with the bot's system prompt, the ten tools as it offers them, its reasoning effort from the words, tool_choice auto, - and the turn ended on a complete result as the bot ends it. With `service` (evalworld.world: the ten tools over the frozen world) + and the turn ended on a complete result as the bot ends it. With `service` (evalworld.World.fresh: the ten tools over the frozen world) each call is answered by the real tool, wrapped as the bot wraps it (lib/model_tools.py: the model is sent for_model of the result), so the model calls again until it replies (at most lib/llm.py's MAX_STEPS steps, then it is made to answer); without, every call is answered CANNED. Returns the whole turn.""" @@ -266,8 +276,8 @@ async def run_live(case: Case, client, model: str, effort: str | None = None, se system = bot_system(ctx=getattr(service, "ctx", None)) reply = await Agent(client, model, tools).run(messages, system, effort or r.effort, tool_choice="auto", turn=Turn(), finish=lambda _, results: complete_reply(results)) - calls, refused = turn_calls(messages[asked:]) - return LiveTurn(calls, reply, refused) + made = turn_calls(messages[asked:]) + return LiveTurn([(n, a) for n, a, _ in made], reply, [no for *_, no in made]) # ---------- the service's ten tools, offered alone (docs/mcp-service.md 6, step 2; 7) ---------- @@ -563,15 +573,36 @@ def calls_text(calls: list[tuple[str, dict]]) -> str: return "; ".join(f"{n} {json.dumps(a, ensure_ascii=False)}" for n, a in calls) or "nothing" +def check_turn(turn: LiveTurn, expect: dict) -> list[str]: + """Failures of a bot-mode turn (run_live) against the case's expectation, over the whole turn. A turn answered in code: its fixed + calls against shortcut_expectation. Else: the expected tools and arguments are met by any call that was not refused (a refused call + later corrected passes; a refused one alone meets nothing), not_tools hold for every call, refused or not; and the turn fails if it + made more than MAX_CALLS calls (it ran away), if its reply is empty or the Agent's fallback (lib/llm.py FALLBACK: the model's last + answer was empty), or if it ended on a refused call with no call answered after it.""" + from lib.llm import FALLBACK + fails = [f"ran away: {len(turn.calls)} calls (more than {MAX_CALLS})"] if len(turn.calls) > MAX_CALLS else [] + if turn.in_code: + return fails + check_calls(turn.calls, shortcut_expectation(expect)) + fails += check_calls(turn.answered(), {k: v for k, v in expect.items() if k != "not_tools"}) + fails += check_calls(turn.calls, {"not_tools": expect.get("not_tools", [])}) + if not turn.reply.strip(): + fails.append("the reply is empty") + elif turn.reply.strip() == FALLBACK: + fails.append("the reply is the Agent's fallback (the model's last answer was empty)") + if turn.refusals[-1:] == [True]: + fails.append(f"the turn ended on a refused call ({calls_text(turn.calls[-1:])}), none answered after it") + return fails + + async def run_service(cases: list[Case], expectations: dict[str, dict], client=None, model: str = "", *, repeat: int = 1, - effort: str | None = None, instructions: str | None = None, bot: bool = False, service=None, out=print) -> int: + effort: str | None = None, instructions: str | None = None, bot: bool = False, world=None, out=print) -> int: """The service's evals: each case's expectation checked (service_problems) and, with a client, the model asked `repeat` times and - its calls scored against it (check_calls). Without `bot`: the ten tools alone (and the server's `instructions`, when given), every - call answered CANNED, so its first round is what is scored (what the descriptions lead to). With `bot`: as the bot asks (run_live), - over `service` (evalworld.world) when given, and scored over the whole turn: an expected tool or arguments pass if any call of the - turn makes them (a refused call later corrected passes), not_tools hold for every call, and a turn of more than MAX_CALLS calls - fails (it ran away); each run's calls, refusals and the reply's start are printed under the case. Prints a line per case (`out`), - with the calls of a run that fails; returns how many cases fail.""" + its calls scored against it. Without `bot`: the ten tools alone (and the server's `instructions`, when given), every call answered + CANNED ("no data"), so the model may call again or reply as it likes (lib/llm.py's loop, up to its MAX_STEPS) and every call of the + turn is scored (check_calls: what the descriptions lead to, with nothing real to react to). With `bot`: as the bot asks (run_live), + each run of each case over its own fresh tools from `world` (evalworld.World.fresh: a new copy of the frozen world's archive) when + given, and scored over the whole turn (check_turn: the reply too); each run's calls, refusals and the reply's start are printed + under the case. Prints a line per case (`out`), with the calls of a run that fails; returns how many cases fail.""" failed = 0 for case in cases: expect = expectations.get(case.id) @@ -580,15 +611,19 @@ async def run_service(cases: list[Case], expectations: dict[str, dict], client=N if client and not problems: passes = 0 for _ in range(repeat): + in_code = False if bot: - turn = await run_live(case, client, model, effort, service) + if world is not None: + async with world.fresh() as service: + turn = await run_live(case, client, model, effort, service) + else: + turn = await run_live(case, client, model, effort) calls, in_code = turn.calls, turn.in_code runs.append(turn.line()) + why = check_turn(turn, expect) else: - calls, _reply, in_code = *await run_live_service(case, client, model, effort, instructions), False - why = check_calls(calls, shortcut_expectation(expect) if in_code else expect) - if bot and len(calls) > MAX_CALLS: - why.insert(0, f"ran away: {len(calls)} calls (more than {MAX_CALLS})") + calls, _reply = await run_live_service(case, client, model, effort, instructions) + why = check_calls(calls, expect) passes += not why problems += [*(f" run: {w}" for w in why[:3]), f" called: {calls_text(calls)}"] if why else [] line = f"{passes}/{repeat}" + ("" if passes == repeat else " FAIL") + (" code" if bot and in_code else "") diff --git a/tests/evalworld.py b/tests/evalworld.py index 676d9446..0009331d 100644 --- a/tests/evalworld.py +++ b/tests/evalworld.py @@ -1,13 +1,15 @@ """The evals' frozen world: the service's ten tools over the fake station's archive, an AirGradient on the same file, Open-Meteo and the pollen page (all faked, nothing fetched), with the clock fixed at the evals' NOW (evalkit.NOW: Tue 29 Sep 2026 14:05, Melbourne) in lib/ and the engines. tests/test_service_evals.py calls the expected calls against it (at_eval_now, build_archive, real_context, with -pytest's monkeypatch), and `scripts/eval_prompts.py --live` answers the bot's model from it (`world`: built once per run, outside -pytest), so the model sees real results, notes and refusals and can take a second round.""" +pytest's monkeypatch), and `scripts/eval_prompts.py --live` answers the bot's model from it (`world`: the archive built once per +run, outside pytest; each run of each case gets fresh tools over its own copy, World.fresh), so the model sees real results, notes +and refusals and can take a second round.""" import asyncio import datetime as _dt import importlib import pkgutil +import shutil import sys import tempfile import time as _time @@ -131,23 +133,42 @@ async def close(ctx): await ctx.eco.close() +class World: + """The frozen world's archive, built once, and a fresh set of the ten tools over a new copy of it for each run (`fresh`): a tool call + can fill the station's file from the fakes (an old day asked for is fetched and stored, and "on record" then starts earlier), so a + run shares nothing with the one before it, whatever cases, --ids or --repeat came first. At the clock as it is (at_eval_now).""" + + def __init__(self, root: Path, archive: Path): + self.root, self.archive, self.runs = root, archive, 0 + + @asynccontextmanager + async def fresh(self): + """The lib.service Service of the ten tools over real_context on a new copy of the archive, in a folder of its own; closed and + removed on leaving.""" + from lib.service import Service + self.runs += 1 + folder = self.root / f"run-{self.runs}" + folder.mkdir(parents=True) + ctx = await real_context(folder, self.archive) + try: + yield Service.of(ctx) + finally: + await close(ctx) + shutil.rmtree(folder, ignore_errors=True) + + @asynccontextmanager async def world(folder: Path | None = None): - """The frozen world for a whole run outside pytest: the clock fixed (at_eval_now), the archive built under it, and the lib.service - Service of the ten tools over real_context; everything put back on leaving. `folder`: where its files go (a temporary one).""" - from lib.service import Service + """The frozen world for a whole run outside pytest: the clock fixed (at_eval_now), the archive built under it once, and a World that + gives each run of each case its own tools over a fresh copy of it; everything put back on leaving. `folder`: where its files go (a + temporary one).""" patch = pytest.MonkeyPatch() with tempfile.TemporaryDirectory(prefix="ecobot-eval-") as tmp: root = Path(folder or tmp) (root / "archive").mkdir(parents=True, exist_ok=True) - (root / "world").mkdir(parents=True, exist_ok=True) try: at_eval_now(patch) - ctx = await real_context(root / "world", await build_archive(root / "archive")) - try: - yield Service.of(ctx) - finally: - await close(ctx) + yield World(root / "runs", await build_archive(root / "archive")) finally: patch.undo() _time.tzset() diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index ab2e75c7..03c44d7d 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -395,7 +395,8 @@ def fails(args): # ---------- the bot's live run over the frozen world, with a scripted model ---------- # `--live` answers the bot's model from the real ten tools (evalworld.world), so a turn can take more than one round: it is scored over -# the whole turn. These run it with a model that reads what its calls gave, over the same world (the module's archive, at EVAL_NOW). +# the whole turn. These run it with a model that reads what its calls gave, over the same world (the module's archive, at EVAL_NOW, +# copied fresh for each run). class Reacting: """An OpenAI-style client whose steps are scripted: each a text (the reply), a list of (tool, args), or a function of what the last step's calls gave (each result as the model was sent it, parsed) that returns one. Past the script it says "Done.".""" @@ -421,59 +422,58 @@ async def create(self, **kw): @pytest.fixture -async def eval_service(tmp_path, eval_archive, monkeypatch): - """The ten tools over the frozen world (what evalworld.world gives a run), on the module's archive.""" - from lib.service import Service +def eval_world(tmp_path, eval_archive, monkeypatch): + """The frozen world (what evalworld.world gives a run: fresh tools over a new copy of the archive for each run), on the module's + archive.""" at_eval_now(monkeypatch) - ctx = await real_context(tmp_path, eval_archive) - yield Service.of(ctx) - await evalworld.close(ctx) + return evalworld.World(tmp_path, eval_archive) -async def bot_run(case_id: str, model: Reacting, service) -> tuple[int, str]: +async def bot_run(case_id: str, model: Reacting, world) -> tuple[int, str]: lines = [] - failed = await evalkit.run_service([case(case_id)], EXPECT, model, "m", bot=True, service=service, out=lines.append) + failed = await evalkit.run_service([case(case_id)], EXPECT, model, "m", bot=True, world=world, out=lines.append) return failed, "\n".join(lines) -async def test_a_refused_call_then_a_corrected_one_passes_and_the_refusal_is_counted(eval_service): +async def test_a_refused_call_then_a_corrected_one_passes_and_the_refusal_is_counted(eval_world): model = Reacting([("summary", {"readings": ["flux capacitor"], "period": "3m", "average": True})], lambda given: [("summary", {"readings": ["temperature"], "period": "3m", "average": True})] if "error" in given[0] else "gave up", "Averaged 14.2 °C.") - failed, text = await bot_run("3m-average", model, eval_service) + failed, text = await bot_run("3m-average", model, eval_world) assert failed == 0, text assert "1/1 3m-average" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text assert "isn't a reading this service knows" in model.seen[1][0]["error"] # (the real refusal, as the model was sent it) - assert model.requests[0]["messages"][0]["content"] == evalkit.bot_system(ctx=eval_service.ctx) + async with eval_world.fresh() as service: + assert model.requests[0]["messages"][0]["content"] == evalkit.bot_system(ctx=service.ctx) -async def test_a_second_call_made_on_a_note_passes(eval_service): +async def test_a_second_call_made_on_a_note_passes(eval_world): """rain-per-month: one figure for the year comes back with days' note_group_by; the model acts on it and asks again by month.""" asked = {"stat": "sum", "of": "rain", "period": "this year"} model = Reacting([("days", asked)], lambda given: [("days", {**asked, "group_by": "month"})] if "note_group_by" in given[0] else "One figure.", lambda given: f"{len(given[0]['by_month'])} months.") - failed, text = await bot_run("rain-per-month", model, eval_service) + failed, text = await bot_run("rain-per-month", model, eval_world) assert failed == 0, text assert '2 calls, 0 refused: "9 months."' in text # (January to September: the real days, by month) without = Reacting([("days", asked)], lambda given: "One figure.") - failed, text = await bot_run("rain-per-month", without, eval_service) + failed, text = await bot_run("rain-per-month", without, eval_world) assert failed == 1 and "group_by" in text and '1 call, 0 refused: "One figure."' in text -async def test_a_forbidden_tool_in_a_later_round_fails(eval_service): +async def test_a_forbidden_tool_in_a_later_round_fails(eval_world): model = Reacting([("relate", {})], [("days", {"stat": "max", "of": "pressure_max", "group_by": "month"})], "Weak.") - failed, text = await bot_run("pressure-rain-correlation", model, eval_service) + failed, text = await bot_run("pressure-rain-correlation", model, eval_world) assert failed == 1 and "0/1 FAIL pressure-rain-correlation" in text and "should not have called days" in text assert "2 calls, 0 refused" in text -async def test_a_turn_of_more_than_eight_calls_has_run_away_and_fails(eval_service): +async def test_a_turn_of_more_than_eight_calls_has_run_away_and_fails(eval_world): many = [[("days", {"stat": "sum", "of": "rain", "group_by": "month", "period": f"last {n} days"})] for n in range(40, 49)] - failed, text = await bot_run("rain-per-month", Reacting(*many, "Rain by month."), eval_service) + failed, text = await bot_run("rain-per-month", Reacting(*many, "Rain by month."), eval_world) assert failed == 1 and "ran away: 9 calls (more than 8)" in text and "9 calls, 0 refused" in text - failed, text = await bot_run("rain-per-month", Reacting(*many[:8], "Rain by month."), eval_service) + failed, text = await bot_run("rain-per-month", Reacting(*many[:8], "Rain by month."), eval_world) assert "ran away" not in text and '8 calls, 0 refused: "Rain by month."' in text @@ -490,10 +490,61 @@ async def test_a_turn_is_capped_at_the_agents_steps(): async def test_the_world_is_built_at_the_frozen_clock_and_its_tools_give_real_results_then_the_clock_is_put_back(): import time - async with evalworld.world() as service: + async with evalworld.world() as world, world.fresh() as service: assert time.time() == EVAL_NOW out = json.loads(await service["days"].call({"stat": "sum", "of": "rain", "group_by": "month", "period": "this year"})) assert "error" not in out and out["period"]["text"] == "this year: Thu 1 Jan – Mon 28 Sep 2026" assert list(out["by_month"]) == [f"2026-{m:02d}" for m in range(1, 10)] and out["days_checked"] assert [t.name for t in service] == evalkit.service_tool_names() assert time.time() != EVAL_NOW + + +async def test_each_run_has_its_own_copy_of_the_world_so_a_case_scores_the_same_whatever_ran_before(eval_world): + """A call can fill the station's file from the fakes (a day in 2023, fetched and stored, moves "on record" back to it): each run of + each case gets fresh tools over a new copy of the archive, so the same case run first and again after another gives the same.""" + def holidays(): + return Reacting([("days", {"only": "public_holiday", "sort_by": "temp_max"})], lambda given: given[0]["period"]["text"]) + first = await bot_run("public-holidays", holidays(), eval_world) + assert first[0] == 0 and '"on record: Sat 29 Mar 2025 – Mon 28 Sep 2026"' in first[1] + old_day = {"readings": ["outdoor.temperature"], "start": "2023-11-10 11:00", "end": "2023-11-11 11:00"} + assert (await bot_run("a-day-in-2023", Reacting([("summary", old_day)], "Mild."), eval_world))[0] == 0 + assert await bot_run("public-holidays", holidays(), eval_world) == first + + +async def test_a_matching_call_that_was_refused_meets_nothing_and_a_forbidden_one_still_fails(eval_world): + """3m-average: the expected summary, with an argument it doesn't take, is refused; an answered call follows, then a give-up reply.""" + refused = ("summary", {"readings": ["temperature"], "period": "3m", "average": True, "bogus": 1}) + assert evalkit.check_calls([refused], EXPECT["3m-average"]) == [] # (its tool and arguments match: only its refusal tells) + failed, text = await bot_run("3m-average", Reacting([refused], [("about", {})], "Sorry, I can't average that."), eval_world) + assert failed == 1 and "did not call summary (called: about)" in text and "2 calls, 1 refused" in text + failed, text = await bot_run("pressure-rain-correlation", + Reacting([("relate", {})], [("days", {"stat": "max", "of": "pressure_max", "bogus": 1})], + [("about", {})], "Weak."), eval_world) + assert failed == 1 and "should not have called days" in text and "3 calls, 1 refused" in text + + +async def test_a_turn_whose_reply_is_empty_or_the_fallback_or_that_ends_on_a_refusal_fails(eval_world): + from lib.llm import FALLBACK + asked = ("summary", {"readings": ["temperature"], "period": "3m", "average": True}) + failed, text = await bot_run("3m-average", Reacting([asked], ""), eval_world) # (the Agent replies FALLBACK) + assert failed == 1 and "the reply is the Agent's fallback" in text and f'1 call, 0 refused: "{FALLBACK}"' in text + bad = ("summary", {**asked[1], "bogus": 1}) + failed, text = await bot_run("3m-average", Reacting([asked], [bad], "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "the turn ended on a refused call (summary" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text + failed, text = await bot_run("3m-average", Reacting([bad], [asked], "Averaged 14.2 °C."), eval_world) + assert failed == 0, text + assert evalkit.check_turn(evalkit.LiveTurn([asked], " ", [False]), EXPECT["3m-average"]) == ["the reply is empty"] + assert evalkit.check_turn(evalkit.LiveTurn([asked], "Averaged.", [False]), EXPECT["3m-average"]) == [] + + +async def test_the_tools_alone_answer_no_data_to_every_call_and_score_every_call_of_the_turn(): + """--service: every call is answered CANNED and the model may call again (the Agent's loop): a call in its second round counts, + and the docs say so (not "the first round").""" + import ast + model = Reacting([("forecast", {})], lambda given: [("outlook", {})] if given == [json.loads(evalkit.CANNED)] else "?", "No data.") + lines = [] + assert await evalkit.run_service([case("will-it-rain")], EXPECT, model, "m", out=lines.append) == 0, lines + assert len(model.requests) == 3 + script_doc = ast.get_docstring(ast.parse((ROOT / "scripts" / "eval_prompts.py").read_text())) + for text in (script_doc, evalkit.run_service.__doc__, evalkit.__doc__, (ROOT / "docs" / "mcp-service.md").read_text()): + assert "first round" not in text and "(one round)" not in text From 3cf01876d97175731f9e81c2994888f311e70e5b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:10:54 +0000 Subject: [PATCH 057/125] Live evals: fail a refused call no later call to the same tool corrects check_turn looked only at the turn's very last call, so a refused call followed by an unrelated answered call passed, and in a parallel step the verdict depended on call order. LiveTurn now carries each call's step (turn_calls gives it) and LiveTurn.uncorrected() lists the refused calls with no call to the same tool answered in a later step; any such call fails the turn. Calls in one step are simultaneous, so an answered call beside a refused one corrects nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 2 +- scripts/eval_prompts.py | 5 +++-- tests/evalkit.py | 32 +++++++++++++++++++++++--------- tests/test_service_evals.py | 31 ++++++++++++++++++++++++++++++- 4 files changed, 57 insertions(+), 13 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index bf440d80..b1bc5e2e 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -536,7 +536,7 @@ Each step ships on its own, with the tests and evals green and the bot working t each call from the real tools over a frozen world (the fake station's archive, copied fresh for each run of each case, and the other sources' fakes at the cases' fixed time), so the model sees real results, notes and refusals and is scored over its whole turn: any call that was not refused may meet the expectation, none may be a forbidden tool, and more than 8 calls, an empty or fallback reply, - or a turn ending on a refused call fails. + or a refused call that no call to the same tool answered in a later step corrects fails. - **The contract:** a test per tool and resource for the arguments it takes and the shape it returns (`test_contract`); the periods table at its fixed times (step 1); charts against their schema; every chart's `drawn_by`, replayed, draws the same chart, and with only `period` changed to each of its `periods`, the same chart over that period, never an error; `day_look` against its rule. diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 9bbeab37..8a6b615a 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -14,8 +14,9 @@ refusals and calls again until it replies (the turn ends on a complete result, as the bot's does; after 10 steps of calls the model is made to answer). A case is scored over the whole turn: an expected call passes if any call that was not refused makes it (a refused call later corrected passes), a forbidden tool fails in any round, refused or not, more than 8 calls fails ("ran away"), and -so does an empty reply, the Agent's fallback reply (the model's last answer was empty) or a turn that ends on a refused call with -none answered after it; each run's number of calls, refusals and the reply's first 200 characters are printed. +so does an empty reply, the Agent's fallback reply (the model's last answer was empty) or a refused call that no call to the same +tool answered in a later step corrects (one in the same step was made with it); each run's number of calls, refusals and the +reply's first 200 characters are printed. python scripts/eval_prompts.py # the decisions made in code, and the service expectations python scripts/eval_prompts.py --live # and the model, as the bot asks it diff --git a/tests/evalkit.py b/tests/evalkit.py index a2128fdd..6e86bc73 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -205,11 +205,14 @@ def bot_system(now: datetime = NOW, ctx=None) -> str: @dataclass class LiveTurn: """One question asked as the bot asks it: every call of the turn in order (refused ones too), the reply, whether each call's result - was a refusal (an `error`; `refusals`, in the calls' order), and whether the bot answered it in code (its fixed calls, no model).""" + was a refusal (an `error`; `refusals`, in the calls' order), whether the bot answered it in code (its fixed calls, no model), and + the model's step each call was made in (`steps`, in the calls' order: the calls of one step are made together; without them, each + call is its own step).""" calls: list reply: str refusals: list = field(default_factory=list) in_code: bool = False + steps: list = field(default_factory=list) @property def refused(self) -> int: @@ -220,6 +223,15 @@ def answered(self) -> list: """The calls that were not refused.""" return [c for c, no in zip(self.calls, self.refusals + [False] * len(self.calls)) if not no] + def uncorrected(self) -> list: + """The refused calls no call to the same tool answered after: one answered in a later step corrects a refusal, one in the same + step doesn't (they were made together), nor does one to another tool.""" + refusals = self.refusals + [False] * len(self.calls) + steps = self.steps + list(range(len(self.steps), len(self.calls))) + return [c for c, no, step in zip(self.calls, refusals, steps) + if no and not any(d[0] == c[0] and not no_d and later > step + for d, no_d, later in zip(self.calls, refusals, steps))] + def line(self) -> str: """`3 calls, 1 refused: "the reply's first 200 characters"`.""" return (f"{len(self.calls)} call{'s' * (len(self.calls) != 1)}, {self.refused} refused: " @@ -242,20 +254,21 @@ def refusal(text: str) -> bool: return isinstance(out, dict) and "error" in out -def turn_calls(messages: list[dict]) -> list[tuple[str, dict, bool]]: +def turn_calls(messages: list[dict]) -> list[tuple[str, dict, bool, int]]: """The tool calls of a turn's messages (as lib/llm.py's Agent leaves them: each assistant step's calls, then their results in - order), in the order made: (tool, arguments, whether its result was a refusal).""" - calls = [] + order), in the order made: (tool, arguments, whether its result was a refusal, the step it was made in, from 0).""" + calls, step = [], -1 for i, m in enumerate(messages): if m.get("role") != "assistant" or not m.get("tool_calls"): continue + step += 1 for c, result in zip(m["tool_calls"], messages[i + 1:i + 1 + len(m["tool_calls"])]): try: args = json.loads(c["function"]["arguments"] or "{}") except ValueError: args = {} calls.append((c["function"]["name"], args if isinstance(args, dict) else {}, - result.get("role") == "tool" and refusal(str(result.get("content", ""))))) + result.get("role") == "tool" and refusal(str(result.get("content", ""))), step)) return calls @@ -277,7 +290,7 @@ async def run_live(case: Case, client, model: str, effort: str | None = None, se reply = await Agent(client, model, tools).run(messages, system, effort or r.effort, tool_choice="auto", turn=Turn(), finish=lambda _, results: complete_reply(results)) made = turn_calls(messages[asked:]) - return LiveTurn([(n, a) for n, a, _ in made], reply, [no for *_, no in made]) + return LiveTurn([(n, a) for n, a, *_ in made], reply, [no for _, _, no, _ in made], steps=[s for *_, s in made]) # ---------- the service's ten tools, offered alone (docs/mcp-service.md 6, step 2; 7) ---------- @@ -578,7 +591,8 @@ def check_turn(turn: LiveTurn, expect: dict) -> list[str]: calls against shortcut_expectation. Else: the expected tools and arguments are met by any call that was not refused (a refused call later corrected passes; a refused one alone meets nothing), not_tools hold for every call, refused or not; and the turn fails if it made more than MAX_CALLS calls (it ran away), if its reply is empty or the Agent's fallback (lib/llm.py FALLBACK: the model's last - answer was empty), or if it ended on a refused call with no call answered after it.""" + answer was empty), or if a refused call was left uncorrected (LiveTurn.uncorrected): no call to the same tool was answered in a + later step (one answered in the same step was made with it, and one to another tool answers something else, so neither corrects it).""" from lib.llm import FALLBACK fails = [f"ran away: {len(turn.calls)} calls (more than {MAX_CALLS})"] if len(turn.calls) > MAX_CALLS else [] if turn.in_code: @@ -589,8 +603,8 @@ def check_turn(turn: LiveTurn, expect: dict) -> list[str]: fails.append("the reply is empty") elif turn.reply.strip() == FALLBACK: fails.append("the reply is the Agent's fallback (the model's last answer was empty)") - if turn.refusals[-1:] == [True]: - fails.append(f"the turn ended on a refused call ({calls_text(turn.calls[-1:])}), none answered after it") + if left := turn.uncorrected(): + fails.append(f"a refused call was not corrected ({calls_text(left)}): no call to the same tool answered in a later step") return fails diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 03c44d7d..82a1ea3d 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -530,13 +530,42 @@ async def test_a_turn_whose_reply_is_empty_or_the_fallback_or_that_ends_on_a_ref assert failed == 1 and "the reply is the Agent's fallback" in text and f'1 call, 0 refused: "{FALLBACK}"' in text bad = ("summary", {**asked[1], "bogus": 1}) failed, text = await bot_run("3m-average", Reacting([asked], [bad], "Averaged 14.2 °C."), eval_world) - assert failed == 1 and "the turn ended on a refused call (summary" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text + assert failed == 1 and "a refused call was not corrected (summary" in text and '2 calls, 1 refused: "Averaged 14.2 °C."' in text failed, text = await bot_run("3m-average", Reacting([bad], [asked], "Averaged 14.2 °C."), eval_world) assert failed == 0, text assert evalkit.check_turn(evalkit.LiveTurn([asked], " ", [False]), EXPECT["3m-average"]) == ["the reply is empty"] assert evalkit.check_turn(evalkit.LiveTurn([asked], "Averaged.", [False]), EXPECT["3m-average"]) == [] +# A refusal is corrected by a call to the same tool answered in a later step: not by one to another tool after it, and not by one made +# in the same step (calls of one step are made together, so their order in it changes nothing). +ASKED = ("summary", {"readings": ["temperature"], "period": "3m", "average": True}) +BAD = ("summary", {**ASKED[1], "bogus": 1}) + + +async def test_a_refused_call_followed_by_another_tools_answered_call_fails(eval_world): + failed, text = await bot_run("3m-average", Reacting([ASKED], [BAD], [("about", {})], "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "a refused call was not corrected (summary" in text and "3 calls, 1 refused" in text + + +async def test_a_refused_call_in_a_step_fails_whatever_the_order_of_the_steps_calls(eval_world): + for step in ([BAD, ("about", {})], [("about", {}), BAD], [BAD, ASKED]): + failed, text = await bot_run("3m-average", Reacting(step, "Averaged 14.2 °C."), eval_world) + assert failed == 1 and "a refused call was not corrected (summary" in text and "2 calls, 1 refused" in text, step + + +async def test_a_refused_call_corrected_in_a_later_step_by_the_same_tool_passes(eval_world): + model = Reacting([ASKED], [BAD, ("about", {})], [("about", {}), ASKED], "Averaged 14.2 °C.") + turn = await evalkit.run_live(case("3m-average"), model, "m", service=None) + assert turn.steps == [0, 1, 1, 2, 2] and turn.uncorrected() == [] + failed, text = await bot_run("3m-average", Reacting([ASKED], [BAD, ("about", {})], [("about", {}), ASKED], "Averaged 14.2 °C."), + eval_world) + assert failed == 0, text + assert '5 calls, 1 refused: "Averaged 14.2 °C."' in text + assert evalkit.LiveTurn([ASKED, BAD, ASKED], "Averaged.", [False, True, False], steps=[0, 1, 1]).uncorrected() == [BAD] + assert evalkit.LiveTurn([BAD, ASKED], "Averaged.", [True, False]).uncorrected() == [] # (no steps: each call is its own) + + async def test_the_tools_alone_answer_no_data_to_every_call_and_score_every_call_of_the_turn(): """--service: every call is answered CANNED and the model may call again (the Agent's loop): a call in its second round counts, and the docs say so (not "the first round").""" From 03715143cedf944df676655cfb716e19cc7232f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:39:34 +0000 Subject: [PATCH 058/125] Step 4: alerts in the service, an alert log the bot delivers from MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rules (rain with its quiet-hours summary, gusts, UV, the temperature crossing, particulates, pollen and thunderstorm asthma, the forecast revised) append events to the alert log (lib/alert_log.py: alerts.sqlite in DATA_DIR, monotonic ids, since(id, expired=False), an in-process wait) with expires, link and the chart as data with its drawn_by; their texts are today's but the forecast's. lib/service/alerts.py starts them on their triggers. Their state is the service's own alert_state.json, moved once out of bot_state.json so nothing re-fires after the upgrade. The forecast alert is station-wide: the first forecast fetched from 6am is the day's baseline for today and tomorrow; a move of the high over 2°C or the rain chance crossing 50% alerts (one event per day, saying what changed) and becomes the baseline. The per-chat record of the forecast days shown is gone. The bot delivers from the log (AlertDelivery): each unexpired event after the last id it handled (kept in bot_state.json) to the chats subscribed to its kind, the chart drawn from the event's data, the 🔄 naming the event so it replays its chart's drawn_by. Irrigation alerts are sent as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 37 +++- ecobot.py | 57 +++--- lib/alert_log.py | 121 +++++++++++++ lib/alerts/forecast.py | 112 ++++++++---- lib/alerts/menu.py | 12 +- lib/alerts/notify.py | 152 +++++++++------- lib/alerts/particulates.py | 30 ++-- lib/alerts/pictures.py | 28 ++- lib/alerts/pollen_and_asthma.py | 19 +- lib/alerts/store.py | 70 ++++++++ lib/alerts/weather.py | 54 ++++-- lib/bot.py | 98 +++++------ lib/config.py | 10 ++ lib/model_tools.py | 2 +- lib/service/about.py | 9 +- lib/service/alerts.py | 56 ++++++ tests/test_alert_log.py | 301 ++++++++++++++++++++++++++++++++ tests/test_alert_menu.py | 49 +++--- tests/test_alerts.py | 225 ++++++++++++------------ tests/test_forecast_alert.py | 269 +++++++++++----------------- tests/test_service_switch.py | 9 - 21 files changed, 1171 insertions(+), 549 deletions(-) create mode 100644 lib/alert_log.py create mode 100644 lib/alerts/store.py create mode 100644 lib/service/alerts.py create mode 100644 tests/test_alert_log.py diff --git a/docs/mcp-service.md b/docs/mcp-service.md index bf440d80..9b297f2c 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -511,8 +511,41 @@ Each step ships on its own, with the tests and evals green and the bot working t had it filled in from the words): `days` says so in its result (`note_group_by`) and the model calls again; the rest are one-off or refusals a model corrects in its next call. Expectations are widened where another call answers as well, not the descriptions tightened. The instructions say every question is fetched afresh, a follow-up or a challenge too. -4. **Alerts in the service.** The rules, their state and config move service-side and append events to the alert log, with `expires`, - `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. +4. **Alerts in the service** (done). The rules, their state and config move service-side and append events to the alert log, with + `expires`, `link` and `chart` (with its `drawn_by`); the forecast alert gets its station-wide baseline. The bot delivers from the log. + - **The log** (`lib/alert_log.py`): 3.6's events, `since(id, expired=False)`, `get(id)`, `last_id()`, and `wait(after)`, an asyncio + notification on each append that step 5's listen will use. Its own SQLite file in `DATA_DIR` (`alerts.sqlite`), not the readings + file: it must exist whatever sources run (pollen and the forecast need no readings file), it is written in tiny rows from the event + loop while the readings file takes bulk writes from worker threads, and it can be looked at or deleted alone. Ids are + AUTOINCREMENT, so they never go back; events older than 30 days are dropped when it opens. Times are ISO local with their offset. + - **The rules** (`lib/alerts/`: weather, particulates, pollen and asthma, forecast) append events and know nothing of chats or + Telegram; `lib/service/alerts.py` (`AlertRules`) starts them on today's triggers. Their texts are today's, byte for byte, but the + forecast's. `expires`: rain (started, stopped, the overnight summary) an hour, gusts and UV their rearm time (an hour), the + temperature crossing its cooldown, particulates the next check (30 minutes), pollen the end of the day it is about, a forecast the + end of the day it is about. `link`: the AirGradient dashboard (particulates), the pollen site. `chart`: the alert chart as the + service gives it (`pictures.chart_data`: the button sentence's `summary` call, every point as drawn, as the bot's pictures were), + `drawn_by` included; made when the alert fires, whoever is listening (before, only when some chat got the alert). `data`: the + figures behind each. + - **Their state** is the service's (`lib/alerts/store.py`, `alert_state.json` beside `bot_state.json`): the first start with no + `alert_state.json` moves the rules' keys out of `bot_state.json`'s `monitor` (once), so nothing re-fires after the upgrade; the + irrigation controller's stay in the bot's file. **Config**: the quiet hours and the cooldown stay `RAIN_QUIET_HOURS` and + `ALERT_COOLDOWN_MINUTES`, handed to the rules (and `about`) by the service; the thresholds stay the rules' own constants, which + `about` reads, as no setting changes them today. + - **The forecast alert is station-wide** (deliberate): the first forecast fetched from 6 am is the day's baseline for today and + tomorrow (no alert); a later one alerts, one event per day, when the high moves by more than 2°C or the chance of at least 1 mm + crosses 50%, and becomes that day's baseline. The 30% band against flip-flopping goes with the per-chat baseline (3.6 says + "crosses 50%"). Its text says what changed: "🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is + now likely (80%, was 10%).\nNow: 🌧️ Rain. 10–19°C, 80% chance of rain". The bot no longer records the forecast days each answer + showed (`record_forecast`, `forecast_sent`, `shown` through the turn): nothing needs them, and the old record is dropped. + - **The bot delivers** (`lib/alerts/notify.AlertDelivery`): it waits on the log in process, sends each unexpired event after the last + id it handled (kept in `bot_state.json` as `alerts_read`) through the Notifier as before (the chats subscribed to its kind, silent + unless the chat turned sound on, the bell, the link as the footer), with the chart drawn from the event's data, uploaded once. Its + first start begins after the newest event; after a gap it skips what expired. The 🔄 under a chart names the event + (`al:refresh::`) and replays the chart's `drawn_by` from the log (a chart drawn ahead since the message changed is still + sent first); an alert sent before the log, or one dropped from it, draws its type's chart as before. Irrigation alerts are sent by + the bot as before. + - Tests: the rules' tests assert events appended (`tests/test_alerts.py`), the log and the delivery (`tests/test_alert_log.py`), the + forecast baseline (`tests/test_forecast_alert.py`). 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the diff --git a/ecobot.py b/ecobot.py index 4ec8e523..1f49543d 100644 --- a/ecobot.py +++ b/ecobot.py @@ -21,13 +21,12 @@ from lib import charts from lib.airgradient import AirGradient from lib.airgradient import metrics as air_metrics -from lib.alerts.forecast import ForecastMonitor +from lib.alert_log import AlertLog from lib.alerts.irrigation import IrrigationMonitor from lib.alerts.menu import LABELS, available_kinds -from lib.alerts.notify import AlertState, Notifier -from lib.alerts.particulates import CHECK_SECONDS as PARTICULATES_CHECK_SECONDS, ParticulatesMonitor -from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor -from lib.alerts.weather import WeatherMonitor +from lib.alerts.notify import AlertDelivery, AlertState, Notifier +from lib.alerts.store import AlertStore +from lib.alerts.weather import WeatherMonitor # (the weather rules, started by AlertRules; named here for the startup tests) from lib.bot import AHEAD_SECONDS, TURN_SECONDS, Bot, Tasks, polling_error from lib.ecowitt import Archive, Ecowitt from lib.ecowitt.source import HA_IMPORT_SECONDS @@ -40,6 +39,7 @@ from lib.service import Service from lib.service import about as service_about from lib.service import names as service_names +from lib.service.alerts import AlertRules from lib.service.context import Context from lib.compose import Composer from lib.sources import Source @@ -109,29 +109,23 @@ async def start(kind: type[Source], *args, **kwargs) -> Source | None: return sources, cfg -def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks) -> tuple[list[str], WeatherMonitor | None]: - """Hook up the alert monitor of every source that started and of the irrigation controller. The weather alerts start in - warm_up, once the station has been read. Returns the alert types now running, and the weather monitor.""" - eco, air, pollen, forecast = (bot.by_name.get(name) for name in ("Ecowitt", "AirGradient", "Pollen", "Forecast")) - running: list[str] = [] - weather = WeatherMonitor(eco, bot.state, notify, cfg.alert_cooldown_minutes * 60, cfg.rain_quiet_hours) if eco else None - if air: - tasks.start(every(PARTICULATES_CHECK_SECONDS, ParticulatesMonitor(air, bot.state, notify).check)) - running += ParticulatesMonitor.KINDS - if forecast: - forecast.warmer.after.append(ForecastMonitor(forecast, bot.state, notify).check) # after each refresh (in the day) - running += ForecastMonitor.KINDS - if pollen: - pollen.warmer.after.append(PollenAndAsthmaMonitor(pollen, bot.state, notify).check) # after each refresh (in the day) - running += PollenAndAsthmaMonitor.KINDS +def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, alert_log: AlertLog) -> tuple[list[str], AlertRules]: + """Hook up the service's alert rules over every source that started (lib/service/alerts.py: they append to the alert log, which the + bot delivers from, AlertDelivery) and the irrigation controller's (sent by the bot itself until it is a server of its own). The + weather rules start in warm_up, once the station has been read. Returns the alert types now running, and the rules.""" + store = AlertStore(cfg.alert_state_path, moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) + rules = AlertRules(bot.by_name, store, alert_log, cfg.alert_cooldown_minutes * 60, cfg.rain_quiet_hours, bot.service) + tasks.start(AlertDelivery(alert_log, notify, bot.state, cfg.tz).run()) + running = rules.start(tasks) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run - tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, eco, forecast).run()) + tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, bot.by_name.get("Ecowitt"), + bot.by_name.get("Forecast")).run()) tasks.start(every(VALVE_CHECK_SECONDS, bot.watchdog.check)) running += IrrigationMonitor.KINDS - return running, weather + return running, rules -async def warm_up(bot: Bot, weather: WeatherMonitor | None, running: list[str], tasks: Tasks, tg_bot=None): +async def warm_up(bot: Bot, rules: AlertRules | None, running: list[str], tasks: Tasks, tg_bot=None): """Fetch everything once, together, and log one summary line; then start what waited for it: the weather alerts, the archives (copying each source's history into its cache), the keyboard's charts drawn ahead every few minutes.""" eco, air = bot.by_name.get("Ecowitt"), bot.by_name.get("AirGradient") @@ -141,12 +135,8 @@ async def ecowitt_part(): # from what was just fetched. A failed first refresh must not stop the alerts or the archive: safely() logs it await safely(eco.warm, True) try: - await weather.init() - eco.warmer.after.append(weather.check) # checked on every fresh refresh - running[:0] = WeatherMonitor.KINDS - await weather.check() - if eco.fast is not None: # Home Assistant: the rain alert looks at each new reading as it comes in, not only at the minute's refresh - eco.on_live.append(weather.check_rain) + if rules is not None: + await rules.start_weather(running) except Exception as e: log.error("Weather alerts couldn't start (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) if eco.fast is not None: @@ -259,6 +249,8 @@ async def main(): else: log.warning("OPENROUTER_API_KEY is not set: running without the model, so answers are limited") state = AlertState(cfg.state_path) + alert_log = AlertLog(cfg.alert_log_path, cfg.tz) # the alerts the rules decide, which the bot delivers + stack.callback(alert_log.close) if cfg.admin_only and not cfg.admin_chat_ids and not any(chat < 0 for chat in state.chats): log.warning("Admin only is on but no group is known yet and ADMIN_CHAT_IDS is empty, so nobody can use the bot: " "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") @@ -271,7 +263,8 @@ async def main(): service = Service.of(await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), pollen=by_name.get("Pollen"), tz=cfg.tz)) log.info("Service tools: %s", ", ".join(t.name for t in service)) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(service)), sources, state, irrigation, tasks, service=service) + bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(service)), sources, state, irrigation, tasks, service=service, + alert_log=alert_log) bot.register(app) stop = asyncio.Event() @@ -299,10 +292,10 @@ async def main(): log.info("%s", line) notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's await bot.publish_commands(app.bot) # the / menu - running, weather = start_alerts(cfg, bot, notify, tasks) + running, rules = start_alerts(cfg, bot, notify, tasks, alert_log) for source in sources: # keeping warm: everything questions need, refreshed before they arrive tasks.start(source.warmer.run()) - tasks.start(warm_up(bot, weather, running, tasks, app.bot)) + tasks.start(warm_up(bot, rules, running, tasks, app.bot)) await stop.wait() diff --git a/lib/alert_log.py b/lib/alert_log.py new file mode 100644 index 00000000..f0709fea --- /dev/null +++ b/lib/alert_log.py @@ -0,0 +1,121 @@ +"""The alert log (docs/mcp-service.md 3.6): every alert the service's rules decide, as an event a client reads and delivers. + +An event is {id, kind, time, expires, title, text, data, [link: {label, url}], [chart]}: + - id: monotonic (1, 2, ...), never reused, so a client resumes from the last one it handled; + - kind: the alert type (lib/alerts/menu.py TYPES: rain, gusts, uv, temps, particulates, pollen_and_asthma, forecast); + - time, expires: ISO local times with their offset; after `expires` the event is no longer news (a client back after a gap skips it); + - title: a few words; text: ready to send as it is; data: the figures behind it; + - link: the page that goes with it; chart: its chart as data (3.7), with the call that draws it again (`drawn_by`). + +Kept in its own SQLite file in DATA_DIR (alerts.sqlite), not the readings file: the log exists whatever sources are configured (the pollen +and forecast alerts need no readings file), it is written from the event loop in tiny rows while the readings file is written in bulk from +worker threads, and it can be looked at or removed on its own. Events older than KEEP_SECONDS are dropped when it opens; the ids carry on. + +A reader in the same process waits for new events with `wait(after)` (an asyncio notification on each append): the bot's delivery today, +the MCP listen of step 5.""" + +import asyncio +import json +import logging +import sqlite3 +import threading +import time as clock +from datetime import datetime, tzinfo + +log = logging.getLogger(__name__) + +KEEP_SECONDS = 30 * 86400 + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS alerts ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + kind TEXT NOT NULL, + time REAL NOT NULL, + expires REAL, + title TEXT NOT NULL, + text TEXT NOT NULL, + data TEXT, + link TEXT, + chart TEXT +); +""" + + +def _iso(ts: float | None, tz: tzinfo) -> str | None: + return None if ts is None else datetime.fromtimestamp(ts, tz).isoformat(timespec="seconds") + + +class AlertLog: + def __init__(self, path, tz: tzinfo, now=clock.time): + """path: the log's file (made when there is none). tz: the zone its times are written in. now: the epoch clock (tests).""" + self.tz, self.now = tz, now + self._lock = threading.Lock() + self.db = sqlite3.connect(path, check_same_thread=False, timeout=30) + self.db.execute("PRAGMA journal_mode=WAL") + self.db.executescript(SCHEMA) + self.db.execute("DELETE FROM alerts WHERE time < ?", (self.now() - KEEP_SECONDS,)) + self.db.commit() + self._new = asyncio.Event() + + def close(self): + with self._lock: + self.db.close() + + def append(self, kind: str, text: str, title: str, data: dict | None = None, expires: float | None = None, + link: tuple[str, str] | None = None, chart: dict | None = None, time: float | None = None) -> dict: + """Record an alert (expires: an epoch, None for never; link: (label, url); chart: the chart's data with its drawn_by) and wake the + readers waiting. Returns the event.""" + at = self.now() if time is None else time + with self._lock: + cur = self.db.execute("INSERT INTO alerts (kind, time, expires, title, text, data, link, chart) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + (kind, at, expires, title, text, json.dumps(data or {}, ensure_ascii=False), + json.dumps({"label": link[0], "url": link[1]}, ensure_ascii=False) if link else None, + json.dumps(chart, ensure_ascii=False) if chart else None)) + self.db.commit() + event_id = cur.lastrowid + woken, self._new = self._new, asyncio.Event() + woken.set() + log.info("Alert %d (%s): %s", event_id, kind, title) + return self.get(event_id) + + def _event(self, row) -> dict: + event_id, kind, at, expires, title, text, data, link, chart = row + event = {"id": event_id, "kind": kind, "time": _iso(at, self.tz), "expires": _iso(expires, self.tz), "title": title, "text": text, + "data": json.loads(data) if data else {}} + if link: + event["link"] = json.loads(link) + if chart: + event["chart"] = json.loads(chart) + return event + + def get(self, event_id: int) -> dict | None: + """One event by its id (None when there is none, or it was dropped), expired or not.""" + with self._lock: + row = self.db.execute("SELECT * FROM alerts WHERE id=?", (event_id,)).fetchone() + return self._event(row) if row else None + + def since(self, after: int = 0, expired: bool = False) -> list[dict]: + """The events after the id `after`, oldest first; only those not yet expired unless `expired`.""" + query, args = "SELECT * FROM alerts WHERE id > ?", [after] + if not expired: + query += " AND (expires IS NULL OR expires > ?)" + args.append(self.now()) + with self._lock: + rows = self.db.execute(query + " ORDER BY id", args).fetchall() + return [self._event(row) for row in rows] + + def last_id(self) -> int: + """The newest event's id (0 when there has been none): what a reader starting now has already seen.""" + with self._lock: + row = self.db.execute("SELECT seq FROM sqlite_sequence WHERE name='alerts'").fetchone() + return row[0] if row else 0 + + async def wait(self, after: int, timeout: float | None = None) -> bool: + """Until there is an event after the id `after` (True), or `timeout` seconds have passed (False).""" + try: + async with asyncio.timeout(timeout): + while self.last_id() <= after: + await self._new.wait() + return True + except TimeoutError: + return False diff --git a/lib/alerts/forecast.py b/lib/alerts/forecast.py index 82287805..209ead51 100644 --- a/lib/alerts/forecast.py +++ b/lib/alerts/forecast.py @@ -1,58 +1,98 @@ -"""A forecast changed after it was sent: told to the chat that was sent it. - -When a chat has been shown a day's forecast (in the report or an answer) and a later refresh revises that day substantially, -that chat gets one message with the old and the new line for each changed day. Substantial is: - - rain flips: it was rainy (chance of at least 1 mm of 50% or more) and is now dry (30% or less), or the other way round (the - gap between 30 and 50 stops small wobbles flip-flopping); a day with only Open-Meteo's older "chance of rain" figure is - compared on that; - - the highest temperature differs by more than 2 degrees. -After the alert, the day as now forecast is the chat's new baseline, so the same revision never repeats, a further one does. -The forecast only refreshes from 6 am to 6 pm, so that is when this can fire. +"""The forecast revised: station-wide, for today and tomorrow (docs/mcp-service.md 3.6). + +Each day, the first forecast fetched after 6 am is the baseline for today and tomorrow. Every later fetch is compared with it, day by +day, and a day that changed substantially is an alert, saying what changed: + - the chance of rain crosses 50% (it was under and is now at or over, or the other way round); the chance of at least 1 mm, or, for a + day with only Open-Meteo's older "chance of rain" figure on either side, that one; + - the highest temperature moves by more than 2 degrees. +The forecast alerted on becomes that day's new baseline, so the same revision never repeats and a further one does. The forecast only +refreshes from 6 am to 6 pm, so that is when this can fire. Each alert is an event in the alert log (lib/alert_log.py), news until the +end of the day it is about. """ import logging +from datetime import date, datetime, timedelta -from ..forecast.source import day_label, describe_day +from ..forecast.source import describe_day +from ..timeutil import at_hour from .menu import kinds_of log = logging.getLogger(__name__) RAIN_FROM_PCT = 50 -DRY_BELOW_PCT = 30 TEMP_CHANGE_C = 2.0 +BASELINE_HOUR = 6 # the first forecast fetched from this hour (local) is the day's baseline +DAYS = 2 # today and tomorrow -def revised(old: dict, new: dict) -> bool: - """Is `new` a substantial revision of what was sent (`old`)?""" - key = "rain_1mm_pct" if old.get("rain_1mm_pct") is not None and new.get("rain_1mm_pct") is not None else "rain_chance_pct" - before, after = old.get(key), new.get(key) - if before is not None and after is not None and ( - (before >= RAIN_FROM_PCT and after <= DRY_BELOW_PCT) or (before <= DRY_BELOW_PCT and after >= RAIN_FROM_PCT)): - return True +def _chance_key(old: dict, new: dict) -> str: + return "rain_1mm_pct" if old.get("rain_1mm_pct") is not None and new.get("rain_1mm_pct") is not None else "rain_chance_pct" + + +def changes(old: dict, new: dict) -> list[str]: + """What changed substantially from `old` (the baseline) to `new`, in words ("the high is now 19°C (was 24°C)"); [] for nothing.""" + out = [] hot_before, hot_after = old.get("max_c"), new.get("max_c") - return hot_before is not None and hot_after is not None and abs(hot_after - hot_before) > TEMP_CHANGE_C + if hot_before is not None and hot_after is not None and abs(hot_after - hot_before) > TEMP_CHANGE_C: + out.append(f"the high is now {hot_after:.0f}°C (was {hot_before:.0f}°C)") + key = _chance_key(old, new) + before, after = old.get(key), new.get(key) + if before is not None and after is not None and (before < RAIN_FROM_PCT) != (after < RAIN_FROM_PCT): + out.append(f"rain is now {'likely' if after >= RAIN_FROM_PCT else 'unlikely'} ({after}%, was {before}%)") + return out + + +def revised(old: dict, new: dict) -> bool: + """Is `new` a substantial revision of the baseline `old`?""" + return bool(changes(old, new)) + + +def _stored(d: dict) -> dict: + return {**d, "date": d["date"].isoformat()} class ForecastMonitor: KINDS = kinds_of("Forecast") - def __init__(self, forecast, state, notify): - """notify: the Notifier (chats=[chat] sends to that one).""" - self.forecast, self.state, self.notify = forecast, state, notify + def __init__(self, forecast, state, alerts): + """state: the rules' store (AlertStore). alerts: the alert log.""" + self.forecast, self.state, self.alerts = forecast, state, alerts async def check(self): - """After each forecast refresh: tell each chat (with alerts on) about the days it was sent that have since changed.""" - today = self.forecast.now().date() - current = {d["date"]: d for d in self.forecast.days or []} - if not current: + """After each forecast refresh: today's baseline once a forecast fetched from 6 am is there; then an alert for each of today and + tomorrow that has changed substantially from its baseline, which it then replaces.""" + now = self.forecast.now() + today = now.date() + tz = getattr(self.forecast, "tz", None) + if now.hour < BASELINE_HOUR or not self.forecast.days: return - for chat_id in self.state.forecast_chats(): - if not self.state.subscribed(chat_id, "forecast"): - continue - changes = [(day, old, current[day]) for day, old in sorted(self.state.forecast_sent(chat_id).items()) - if day >= today and day in current and revised(old, current[day])] - if not changes: + fetched = getattr(self.forecast, "fetched_at", None) + if fetched is not None and tz is not None and fetched < at_hour(today, BASELINE_HOUR, tz): + return # (the forecast held is from before 6 am: not yet today's) + current = {d["date"]: d for d in self.forecast.days if 0 <= (d["date"] - today).days < DAYS} + m = self.state.monitor.setdefault("forecast", {}) + if m.get("day") != today.isoformat(): # the first forecast of the day: the baseline, nothing to compare + m.clear() + m.update(day=today.isoformat(), baseline={d.isoformat(): _stored(new) for d, new in current.items()}) + log.info("Forecast alert: today's baseline set (%s)", ", ".join(sorted(m["baseline"]))) + self.state.save() + return + baseline = m.setdefault("baseline", {}) + for day, new in sorted(current.items()): + old = baseline.get(day.isoformat()) + if old is None: + baseline[day.isoformat()] = _stored(new) continue - lines = [f"• {day_label(day, today)}: was {describe_day(old)}\n now {describe_day(new)}" for day, old, new in changes] - if await self.notify("\U0001f504 The forecast has changed since I sent it:\n" + "\n".join(lines), kind="forecast", chats=[chat_id]): - self.state.record_forecast(chat_id, [new for _, _, new in changes], today) + if said := changes(old, new): + self._emit(day, today, old, new, said, tz) + baseline[day.isoformat()] = _stored(new) + self.state.save() + + def _emit(self, day: date, today: date, old: dict, new: dict, said: list[str], tz): + label = "today" if day == today else "tomorrow" + text = f"\U0001f504 The forecast for {label} has changed: {' and '.join(said)}.\nNow: {describe_day(new)}" + key = _chance_key(old, new) + data = {"date": day.isoformat(), "was": {"max_c": old.get("max_c"), key: old.get(key), "summary": old.get("summary")}, + "now": {"max_c": new.get("max_c"), key: new.get(key), "summary": new.get("summary")}} + ends = at_hour(day + timedelta(days=1), 0, tz) if tz else datetime.combine(day + timedelta(days=1), datetime.min.time()).timestamp() + self.alerts.append("forecast", text, f"The forecast for {label} changed", data, expires=ends) diff --git a/lib/alerts/menu.py b/lib/alerts/menu.py index 37b7b129..5fc89042 100644 --- a/lib/alerts/menu.py +++ b/lib/alerts/menu.py @@ -11,7 +11,9 @@ al:on|off::alerts al:snd::on|off a type's alerts, or its sound, on or off al:open:bell: al:close: the bell under an alert of that type al:on|off::bell: al:snd::on|off: its two toggles - al:refresh: the chart of an alert of that type, drawn again + al:refresh:[:] the chart of an alert of that type, drawn again: the alert 's + (in the alert log), its chart's drawn_by replayed; without one (an + alert sent before the log), the type's chart """ from itertools import batched @@ -48,12 +50,14 @@ def _verb(on: bool) -> str: return "on" if on else "off" -def alert_keyboard(kind: str, muted: set[str], loud: set[str] | None, open: str | None = None, refresh: bool = False) -> InlineKeyboardMarkup: +def alert_keyboard(kind: str, muted: set[str], loud: set[str] | None, open: str | None = None, refresh: bool = False, + event: int | None = None) -> InlineKeyboardMarkup: """The buttons under an alert of type `kind`: one bell (🔔 ▸, ▾ once `open` is BELL) that opens up to two toggles, Alert (this type's alerts in this chat) and, only while that is on and in a private chat (`loud` is not None), Sound (whether they make a notification - sound). refresh (the alert carries a chart): 🔄 beside the bell, which draws the chart again.""" + sound). refresh (the alert carries a chart): 🔄 beside the bell, which draws the chart again (event: the alert's id in the log, whose + chart's drawn_by it replays).""" is_open = open == BELL - rows = [[opener("🔔", is_open, f"al:open:{BELL}:{kind}", f"al:close:{kind}"), *([button("🔄", f"al:refresh:{kind}")] if refresh else [])]] + rows = [[opener("🔔", is_open, f"al:open:{BELL}:{kind}", f"al:close:{kind}"), *([button("🔄", f"al:refresh:{kind}" + (f":{event}" if event is not None else ""))] if refresh else [])]] if is_open: on = kind not in muted rows.append([toggle_button("Alert", on, lambda turn_on: f"al:{_verb(turn_on)}:{kind}:{BELL}:{kind}")]) diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 2e9c2b7c..fe5b6f12 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -2,25 +2,28 @@ Alerts go to every chat the bot knows about (Telegram can't list a bot's chats, so they are remembered as messages arrive) unless it unsubscribed (per alert type, with the buttons under each alert or /alerts). A chat that -blocked or removed the bot is marked gone: it gets nothing, and has its settings back when it next writes. Chats and -monitor state live in a small JSON file, so restarts neither forget chats nor repeat alerts. Alerts are sent silently, with the -settings buttons and, when there is one, a small italic footer with a link label. +blocked or removed the bot is marked gone: it gets nothing, and has its settings back when it next writes. Chats, their +settings and the last alert delivered live in a small JSON file (bot_state.json), so restarts neither forget chats nor repeat alerts. +Alerts are sent silently, with the settings buttons and, when there is one, a small italic footer with a link label. + +The alerts themselves are the service's: its rules append them to the alert log (lib/alert_log.py), and AlertDelivery sends each to the +chats subscribed to its kind. Only the irrigation controller's are still sent here directly (lib/alerts/irrigation.py), until it is a +server of its own. """ import asyncio -import json import logging -import os import time from collections.abc import Awaitable, Callable, Collection -from datetime import date, timedelta +from datetime import timedelta from telegram.error import BadRequest, ChatMigrated, Forbidden, NetworkError, RetryAfter, TelegramError, TimedOut from ..entities import with_link from ..logs import QUOTES from .menu import ALL, LABELS, alert_keyboard -from .pictures import CHARTS, AlertCharts, Picture +from .pictures import CHARTS, AlertCharts, Picture, picture_of +from .store import load, write log = logging.getLogger(__name__) @@ -28,21 +31,6 @@ FLOOD_WAIT_MAX = 60 # Telegram's flood limit asks to wait: a longer wait is not waited out (that chat misses the alert) -def _load(path) -> dict: - """The saved state, {} when there is none. A file that can't be read is moved aside, as the next save would replace it, - so its chats and settings can still be recovered by hand.""" - try: - with open(path) as f: - return json.load(f) - except FileNotFoundError: - return {} - except (OSError, ValueError) as e: - aside = f"{path}.damaged-{time.strftime('%Y%m%d-%H%M%S')}" - os.replace(path, aside) - log.error("Couldn't read %s (%s): moved it to %s and starting with no known chats", path, e, aside) - return {} - - def _flood_wait(e: RetryAfter) -> float: """The seconds Telegram asks to wait (python-telegram-bot gives a number, or a timedelta once PTB_TIMEDELTA is set).""" wait = e.retry_after @@ -50,23 +38,21 @@ def _flood_wait(e: RetryAfter) -> float: class AlertState: - """Known chats (with alerts on/off) and monitor state, saved to a JSON file.""" + """Known chats (with alerts on/off), the irrigation controller's state and the last alert delivered, saved to a JSON file + (bot_state.json). The alert rules keep theirs apart (lib/alerts/store.py: alert_state.json).""" def __init__(self, path): self.path = path - data = _load(path) + data = load(path) or {} self.chats: dict[int, dict] = {int(k): v for k, v in data.get("chats", {}).items()} - self.monitor: dict = data.get("monitor", {}) + self.monitor: dict = data.get("monitor", {}) # the irrigation controller's (until it is a server of its own) self.charts: dict[str, str] = data.get("charts", {}) # the question behind each chart sent, for its period buttons + self.read: int | None = data.get("alerts_read") # the id of the last alert in the log the bot handled (AlertDelivery) def save(self): """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" - tmp = f"{self.path}.tmp" - with open(tmp, "w") as f: - json.dump({"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts}, f, indent=1) - f.flush() - os.fsync(f.fileno()) - os.replace(tmp, self.path) + write(self.path, {"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts, + **({"alerts_read": self.read} if self.read is not None else {})}) def add_chat(self, chat_id: int, title: str): """A message from this chat (or the bot added to it): known from now on, and back if it was gone.""" @@ -99,13 +85,10 @@ def set_alerts(self, chat_id: int, on: bool): self.set_kind(chat_id, ALL, on) def migrate_chat(self, old: int, new: int): - """A group became a supergroup: its settings, and the forecast it was sent, move to the new chat id.""" + """A group became a supergroup: its settings move to the new chat id.""" entry = self.chats.pop(old, None) if entry is not None: self.chats.setdefault(new, entry) - sent = self.monitor.get("forecast_sent", {}) - if str(old) in sent: - sent.setdefault(str(new), sent.pop(str(old))) log.info("Alerts: chat %s became %s", old, new) self.save() @@ -173,24 +156,6 @@ def set_keyboard(self, chat_id: int, version: str): self.chats[chat_id]["keyboard"] = version self.save() - def record_forecast(self, chat_id: int, days: list[dict], today: date): - """Remember the forecast days this chat was just sent (a newer send replaces the baseline for the same day, the other - days keep theirs); days before today are dropped.""" - sent = self.monitor.setdefault("forecast_sent", {}).setdefault(str(chat_id), {}) - for d in days: - sent[d["date"].isoformat()] = {**d, "date": d["date"].isoformat()} - for day in [k for k in sent if k < today.isoformat()]: - del sent[day] - self.save() - - def forecast_sent(self, chat_id: int) -> dict: - """{date: the day as it was sent} for this chat.""" - return {date.fromisoformat(k): {**v, "date": date.fromisoformat(k)} - for k, v in self.monitor.get("forecast_sent", {}).get(str(chat_id), {}).items()} - - def forecast_chats(self) -> list[int]: - return [int(c) for c in self.monitor.get("forecast_sent", {})] - def subscribed(self, chat_id: int, kind: str) -> bool: """Does this chat get this alert type?""" return chat_id in self.chats and not self.chats[chat_id].get("gone") and kind not in self.muted(chat_id) @@ -207,13 +172,14 @@ def __init__(self, bot, state: AlertState, charts: AlertCharts | None = None): async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = None, chart: Callable[[], Awaitable[Picture | None]] | None = None, chats: list[int] | None = None, - since: int | None = None) -> int: + since: int | None = None, event: int | None = None) -> int: """Send an alert (silently) to the chats subscribed to its type (`kind`, one of menu.TYPES): of `chats` (say, the one sent something that has since changed), else of every chat. Chats the bot can no longer post to are marked gone. Returns how many it was sent to. link = (label, url) adds a clickable label to the footer; each carries the settings buttons. chart draws the alert's picture (None: the text alone), and is called only when some chat gets the alert and the bot doesn't hold the chart with the alert's data already (`since`: the time of the newest reading the alert is about; AlertCharts.held). The text is the picture's - caption (the text alone if Telegram refuses it); it is uploaded once and the chats after the first are sent Telegram's copy.""" + caption (the text alone if Telegram refuses it); it is uploaded once and the chats after the first are sent Telegram's copy. event: the + alert's id in the log, which its 🔄 names (so it replays the call that drew the alert's chart).""" targets = self.state.alert_chats(kind) if chats is None else [c for c in chats if self.state.subscribed(c, kind)] text, entities = with_link(text, link) photo = None @@ -225,7 +191,7 @@ async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = No self.charts.keep(kind, picture, since) started, sent = time.monotonic(), 0 for chat_id in targets: - ok, message = await self._send(chat_id, text, entities, kind, photo) + ok, message = await self._send(chat_id, text, entities, kind, photo, event=event) sent += ok if photo and (sizes := getattr(message, "photo", None)): photo = sizes[-1].file_id # the largest size: the picture as sent @@ -234,12 +200,13 @@ async def __call__(self, text: str, kind: str, link: tuple[str, str] | None = No log.info("Alert sent to %d chat(s) in %.1fs: %s", sent, time.monotonic() - started, text, extra=QUOTES) return sent - async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None): + async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None, event: int | None = None): """The message itself (returned): silent unless the chat turned sound on for this type, with the alert type's settings button (the bell). With a photo it is the picture with the text as its caption, and a Refresh that draws the chart again; a picture Telegram refuses falls back to the text alone.""" quiet = kind not in self.state.loud(chat_id) - markup = lambda refresh: alert_keyboard(kind, self.state.muted(chat_id), self.state.loud(chat_id) if chat_id > 0 else None, refresh=refresh) + markup = lambda refresh: alert_keyboard(kind, self.state.muted(chat_id), self.state.loud(chat_id) if chat_id > 0 else None, refresh=refresh, + event=event) if photo: try: return await self.bot.send_photo(chat_id, photo, caption=text, caption_entities=entities, disable_notification=quiet, @@ -251,16 +218,17 @@ async def _post(self, chat_id: int, text: str, entities, kind: str, photo: bytes return await self.bot.send_message(chat_id, text, entities=entities, disable_web_page_preview=True, disable_notification=quiet, reply_markup=markup(False)) - async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None = None, again: bool = True) -> tuple[bool, object]: + async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes | str | None = None, again: bool = True, + event: int | None = None) -> tuple[bool, object]: """Send an alert (see _post) to one chat; a chat the bot can no longer post to is marked gone. Telegram's flood limit (when it asks for a short wait) and a dropped connection get one more try; a timeout doesn't, as the message may have arrived. Whatever fails for one chat is logged, so the others still get the alert. (whether it was sent, the message sent)""" try: try: - return True, await self._post(chat_id, text, entities, kind, photo) + return True, await self._post(chat_id, text, entities, kind, photo, event) except ChatMigrated as e: # the group became a supergroup: follow it, and send again there self.state.migrate_chat(chat_id, e.new_chat_id) - return await self._send(e.new_chat_id, text, entities, kind, photo) if e.new_chat_id != chat_id else (False, None) + return await self._send(e.new_chat_id, text, entities, kind, photo, event=event) if e.new_chat_id != chat_id else (False, None) except Forbidden as e: # kicked from the group, or blocked in a private chat self.state.mark_gone(chat_id, f"can't post: {e}") except BadRequest as e: @@ -273,7 +241,67 @@ async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes raise log.info("Alert to %s: %s; trying again in %gs", chat_id, e, wait) await asyncio.sleep(wait) - return await self._send(chat_id, text, entities, kind, photo, again=False) + return await self._send(chat_id, text, entities, kind, photo, again=False, event=event) except Exception as e: # Telegram refused it, or the state file couldn't be saved log.warning("Alert to %s failed: %s", chat_id, e, exc_info=not isinstance(e, TelegramError)) return False, None + + +class AlertDelivery: + """The bot's side of the alert log (lib/alert_log.py, docs/mcp-service.md section 4): it reads each new event and sends it, as the + Notifier does, to the chats subscribed to its kind, with its link, its chart drawn from the event's chart data (and the 🔄 that + replays the chart's drawn_by) or the text alone. The id of the last event handled is kept in bot_state.json (AlertState.read), so a + restart resumes after it; the events that expired meanwhile are skipped (the morning's rain is not news by the afternoon). With no id + kept (the first start) it begins after the newest event: what came before is not news either.""" + + def __init__(self, log, notify: "Notifier", state: AlertState, tz): + self.log, self.notify, self.state, self.tz = log, notify, state, tz + if self.state.read is None: + self._handled(self.log.last_id()) + + @property + def last(self) -> int: + return self.state.read or 0 + + def _handled(self, event_id: int): + self.state.read = event_id + try: + self.state.save() + except Exception as e: # (the next one saved covers it; at worst a restart sends it again) + log.warning("Couldn't save the last alert delivered (%s: %s)", type(e).__name__, e) + + async def run(self): + """Forever: deliver what is new, then wait for more.""" + while True: + await self.deliver_new() + await self.log.wait(self.last) + + async def deliver_new(self) -> int: + """Send each unexpired event after the last handled, oldest first; returns how many were sent.""" + newest = self.log.last_id() + sent = 0 + for event in self.log.since(self.last): + try: + await self.deliver(event) + sent += 1 + except Exception as e: # one alert that fails never holds up the next + log.error("Alert %d couldn't be delivered (%s: %s)", event["id"], type(e).__name__, e, exc_info=True) + self._handled(event["id"]) + if newest > self.last: # (only expired events after the last handled: skipped) + self._handled(newest) + return sent + + async def deliver(self, event: dict) -> int: + """One event to the chats subscribed to its kind; returns how many it reached.""" + link = (event["link"]["label"], event["link"]["url"]) if event.get("link") else None + chart, data, since = None, event.get("chart"), None + if data: + from ..specs import from_json + try: + since = from_json(data).newest + except Exception: + since = None + + async def chart() -> Picture | None: + return await picture_of(data, self.tz) + return await self.notify(event["text"], kind=event["kind"], link=link, chart=chart, since=since, event=event["id"]) diff --git a/lib/alerts/particulates.py b/lib/alerts/particulates.py index 7ee31090..35f20ac3 100644 --- a/lib/alerts/particulates.py +++ b/lib/alerts/particulates.py @@ -5,6 +5,8 @@ ANTISPIKE_REQUIRE_CONSECUTIVE (2) readings are all that high (a spike never does); "back to safe" when both are at AQI 100 or below in two readings in a row (rules.py: a check that brings no new reading counts for nothing). Every episode gets the pair. Particles only: masks filter particles, not gases like CO2/VOC/NOx. +Each is an event in the alert log (lib/alert_log.py) with the sensor's dashboard as its link and the 1-day particulates chart as data; +it is news until the next check (CHECK_SECONDS). """ import logging @@ -24,8 +26,10 @@ class ParticulatesMonitor: KINDS = kinds_of("AirGradient") - def __init__(self, air, state, notify): - self.air, self.state, self.notify = air, state, notify + def __init__(self, air, state, alerts, service=None): + """state: the rules' store (AlertStore). alerts: the alert log. service: the service's tools (the chart's call), else built over + the sensor.""" + self.air, self.state, self.alerts, self.service = air, state, alerts, service async def check(self, latest=None, now: datetime | None = None): """latest: the sensor's latest reading (AirGradient.latest(): the reading, when it was taken, what it has been sustained at).""" @@ -47,20 +51,26 @@ async def check(self, latest=None, now: datetime | None = None): good = (pm25 is None or pm25 <= SAFE_PM25) and (pm10 is None or pm10 <= SAFE_PM10) rules.run(m, "above", bad) rules.run(m, "below", good) - since = int(when.timestamp()) if when is not None else None # the reading the alert is about: a chart drawn with it is sent as it is if not m["unsafe"] and m["above"] >= rules.CONFIRM_READINGS: m["unsafe"] = True - await self.notify("\U0001f637 Unhealthy air outside — wear a P2/N95 mask today. " + self._levels(reading), - link=self.air.link, kind="particulates", chart=self._picture, since=since) + self._emit(True, "\U0001f637 Unhealthy air outside — wear a P2/N95 mask today. " + self._levels(reading), "Unhealthy air: wear a mask", + reading, when, await self._chart()) elif m["unsafe"] and m["below"] >= rules.CONFIRM_READINGS: m["unsafe"] = False - await self.notify("✅ Outdoor air is safe again. " + self._levels(reading), link=self.air.link, kind="particulates", - chart=self._picture, since=since) + self._emit(False, "✅ Outdoor air is safe again. " + self._levels(reading), "Outdoor air safe again", reading, when, await self._chart()) self.state.save() - async def _picture(self) -> pictures.Picture | None: - """The 1-day particulates chart (what the Particulates button gives), for the alert; None when it cannot be made.""" - return await pictures.chart(self.air, pictures.CHARTS["particulates"], self.air.tz) + def _emit(self, unsafe: bool, text: str, title: str, reading: dict, when: datetime | None, chart: dict | None): + """The alert, in the log: news until the next check.""" + data = {"unsafe": unsafe, "at": when.astimezone(self.air.tz).isoformat(timespec="seconds") if when else None, + **{f"{key}_ugm3": (reading.get(key) or {}).get("value") for key in ("pm2_5", "pm10")}} + if "aqi_us" in (reading.get("pm2_5") or {}): + data["pm2_5_aqi_us"] = reading["pm2_5"]["aqi_us"] + self.alerts.append("particulates", text, title, data, expires=self.alerts.now() + CHECK_SECONDS, link=self.air.link, chart=chart) + + async def _chart(self) -> dict | None: + """The 1-day particulates chart (what the Particulates button gives) as data, for the alert; None when it cannot be made.""" + return await pictures.chart_data(self.air, pictures.CHARTS["particulates"], self.air.tz, self.service) @staticmethod def _levels(reading: dict) -> str: diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index 39e1e89a..d3f646f9 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -1,6 +1,7 @@ """The chart that goes with an alert: the same picture a typed request for it would give ("Wind chart 1d" is what the Wind button sends), so what an alert shows is defined once, by the button sentences, each a fixed service call (lib/intent.chart_call: "Wind chart 1d" is summary -{readings: ["wind"], period: "1d", chart: true}), which the service draws. AlertCharts keeps those charts with the bot's other charts (the ImageCache, +{readings: ["wind"], period: "1d", chart: true}), which the service draws: the rule puts the chart's data, with its drawn_by, in the alert's +event (chart_data), and the bot draws it (picture_of). AlertCharts keeps those charts with the bot's other charts (the ImageCache, by call), so one is drawn once and uploaded once however many times it is sent.""" import asyncio @@ -44,23 +45,38 @@ def _service_of(source, tz): return Service.of(Context(eco=source if name == "Ecowitt" else None, air=source if name == "AirGradient" else None, tz=tz)) -async def chart(source, text: str, tz, service=None) -> Picture | None: - """The chart for the request `text`, drawn by the service the way the bot would answer it; None when it cannot be made (the alert then - goes out as text). `source` is the station or the air sensor; `service` the service's tools (the bot's), else built over `source`.""" +async def chart_data(source, text: str, tz, service=None) -> dict | None: + """The chart for the request `text` as data (3.7's JSON, with the `drawn_by` that draws it again), as the service gives it (every point, + as drawn): what an alert event carries. None when it cannot be made (the alert then goes out as text). `source` is the station or the air + sensor; `service` the service's tools, else built over `source`.""" try: tool, args = call_of(text, now_local(tz), tz) service = service or _service_of(source, tz) out = json.loads(await service[tool].call(args, {"chart_points": CHART_POINTS})) if "error" in out: raise ValueError(out["error"]) - data = out["charts"][0] + return out["charts"][0] + except Exception as e: + log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) + return None + + +async def picture_of(data: dict, tz) -> Picture | None: + """A chart given as data, drawn (by the bot's renderer); None when it cannot be.""" + try: spec = from_json(data) return Picture(await asyncio.to_thread(render_data, data, tz), spec.caption(now_local(tz).date()), spec.newest, data.get("drawn_by")) except Exception as e: - log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) + log.warning("The alert's chart couldn't be drawn: %s: %s", type(e).__name__, e) return None +async def chart(source, text: str, tz, service=None) -> Picture | None: + """The chart for the request `text`, drawn by the service the way the bot would answer it; None when it cannot be made.""" + data = await chart_data(source, text, tz, service) + return await picture_of(data, tz) if data else None + + class AlertCharts: """The charts alerts carry (CHARTS), kept in the bot's ImageCache under the call their request is read as (the keyboard's "Wind chart 1d" is the same chart), so each is drawn once and uploaded once: diff --git a/lib/alerts/pollen_and_asthma.py b/lib/alerts/pollen_and_asthma.py index b16b2f0b..8fa7191a 100644 --- a/lib/alerts/pollen_and_asthma.py +++ b/lib/alerts/pollen_and_asthma.py @@ -4,13 +4,15 @@ A warning when grass pollen or the thunderstorm asthma risk is High 🔴 or Extreme 🟣 (the scale is Low 🟢, Moderate 🟠, High 🔴, Extreme 🟣; "No data" counts as no reading). One alert per metric and day: another on a new day that is still High, and again when it rises (High to Extreme); none while it stays the same; none before 7:30 am. Once it drops below High the metric is ready to warn again. +Each is an event in the alert log (lib/alert_log.py), with the pollen site as its link, news until the end of its day. """ import logging import time +from datetime import timedelta from ..pollen.parse import LEVEL_EMOJI, LEVELS -from ..timeutil import day_text +from ..timeutil import at_hour, day_text from .menu import kinds_of log = logging.getLogger(__name__) @@ -26,8 +28,9 @@ class PollenAndAsthmaMonitor: KINDS = kinds_of("Pollen") - def __init__(self, pollen, state, notify): - self.pollen, self.state, self.notify = pollen, state, notify + def __init__(self, pollen, state, alerts): + """state: the rules' store (AlertStore). alerts: the alert log.""" + self.pollen, self.state, self.alerts = pollen, state, alerts async def check(self): if not self.pollen.in_season() or self.pollen.now().timetuple()[3:5] < ALERT_FROM: # October to December only; not before 7:30 am @@ -49,5 +52,13 @@ async def check(self): m[key] = {"day": str(today), "level": reading["level"]} for_day = reading.get("date") when = f" (forecast for {day_text(for_day, year=False)})" if for_day and for_day != today else "" - await self.notify(f"{LEVEL_EMOJI[reading['level']]} {LABELS[key]} is {reading['level']}{when}.{ADVICE[key]}", link=LINK, kind="pollen_and_asthma") + self.alerts.append("pollen_and_asthma", f"{LEVEL_EMOJI[reading['level']]} {LABELS[key]} is {reading['level']}{when}.{ADVICE[key]}", + f"{LABELS[key]}: {reading['level']}", + {"metric": key, "level": reading["level"], "for": (for_day or today).isoformat()}, + expires=self._end_of(for_day or today), link=LINK) self.state.save() + + def _end_of(self, day) -> float: + """The epoch at which `day` (local) ends.""" + tz = getattr(self.pollen, "tz", None) + return at_hour(day + timedelta(days=1), 0, tz) if tz else self.alerts.now() + 86400 diff --git a/lib/alerts/store.py b/lib/alerts/store.py new file mode 100644 index 00000000..99b51373 --- /dev/null +++ b/lib/alerts/store.py @@ -0,0 +1,70 @@ +"""The alert rules' own state (alert_state.json in DATA_DIR): what each rule last alerted and the runs it is counting, so a restart neither +forgets nor repeats. The service's, apart from the bot's chats and settings (bot_state.json), which the rules know nothing of. + +Before step 4 of docs/mcp-service.md the rules kept it in bot_state.json's "monitor": the first start with no alert_state.json moves it +here (MOVED), so nothing alerted before the upgrade alerts again. The irrigation controller's (irrigation_monitor, irrigation_watchdog) +stay with the bot until it moves to its own server; the forecast each chat was sent (forecast_sent) goes: the forecast alert is +station-wide now.""" + +import json +import logging +import os +import time + +log = logging.getLogger(__name__) + +MOVED = ("rain", "night", "cross", "gust", "uv", "particulates", "pollen_and_asthma") # the rules' keys in the bot's old "monitor" +DROPPED = ("forecast_sent",) + + +def load(path) -> dict | None: + """A JSON state file, None when there is none. One that can't be read is moved aside, as the next save would replace it, so what it + held can still be recovered by hand ({} then).""" + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return None + except (OSError, ValueError) as e: + aside = f"{path}.damaged-{time.strftime('%Y%m%d-%H%M%S')}" + os.replace(path, aside) + log.error("Couldn't read %s (%s): moved it to %s and starting afresh", path, e, aside) + return {} + + +def write(path, data: dict): + """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" + tmp = f"{path}.tmp" + with open(tmp, "w") as f: + json.dump(data, f, indent=1) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + + +class AlertStore: + """The rules' state: `monitor`, a dict each rule keeps its own key in, and save().""" + + def __init__(self, path, moved_from=None): + """moved_from: the bot's state (lib/alerts/notify.AlertState), whose rules' state is moved here when this file is new.""" + self.path = path + data = load(path) + self.monitor: dict = (data or {}).get("monitor", {}) + if data is None: + if moved_from is not None: + self._move(moved_from) + self.save() + + def _move(self, bot_state): + old = bot_state.monitor + moved = [key for key in MOVED if key in old] + for key in moved: + self.monitor[key] = old.pop(key) + dropped = [key for key in DROPPED if old.pop(key, None) is not None] + if moved or dropped: + log.info("Alerts: the rules' state moved from %s to %s (%s)", bot_state.path, self.path, ", ".join(moved) or "nothing") + self.save() # (here first: a crash between the two saves leaves it in both, never in neither) + bot_state.save() + + def save(self): + write(self.path, {"monitor": self.monitor}) diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index 7c8a9863..b8a0085c 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -12,6 +12,8 @@ sensor noise flip-flopping. The crossing has a back-off rule (rules.py): after an alert, a change is held for ALERT_COOLDOWN_MINUTES and then announced if the state still differs from the one last alerted; if it is back where it was, nothing is sent. +Each alert is an event appended to the alert log (lib/alert_log.py), news for a while (rain RAIN_EXPIRES_SECONDS, gusts and UV their +rearm time, the crossing its cooldown); gusts, UV and the crossing carry their chart as data, with the call that draws it again. """ import asyncio @@ -32,6 +34,7 @@ GUST_ALERT_KMH = 40 GUST_REARM_SECONDS = 3600 UV_REARM_SECONDS = 3600 +RAIN_EXPIRES_SECONDS = 3600 # a rain alert is news for about an hour (the overnight summary too) def side(r: dict) -> str | None: @@ -45,8 +48,11 @@ def side(r: dict) -> str | None: class WeatherMonitor: KINDS = kinds_of("Ecowitt") - def __init__(self, station, state, notify, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None): - self.station, self.state, self.notify = station, state, notify + def __init__(self, station, state, alerts, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None, + service=None): + """state: the rules' store (AlertStore). alerts: the alert log the alerts are appended to. service: the service's tools (the + charts' calls), else built over the station.""" + self.station, self.state, self.alerts, self.service = station, state, alerts, service self.cooldown = cooldown_seconds self.quiet = quiet # (from hour, to hour) local, no rain alerts in between; None: always on self._rain_lock = asyncio.Lock() # the minute's check and the live reading's look at the rain are one at a time @@ -132,7 +138,8 @@ async def _rain_locked(self, rows: Rows): m["since"] = next(ts for ts in wet_times if latest_ts - ts < self.cooldown) rate = next(r for ts, w, r in reversed(wet) if w) if not quiet: - await self.notify("\U0001f327️ It's started raining" + (f" ({rate:g} mm/h)." if rate > 0 else "."), kind="rain") + self._emit("rain", "\U0001f327️ It's started raining" + (f" ({rate:g} mm/h)." if rate > 0 else "."), "Rain started", + {"rate_mm_h": rate, "since": self._iso(m["since"])}, RAIN_EXPIRES_SECONDS) elif m["alerted_state"] == "raining": if last_wet is None: # nothing in the last 3 hours (e.g. the bot was down): close it quietly log.info("Alerts: rain ended while not watching; no alert") @@ -144,7 +151,8 @@ async def _rain_locked(self, rows: Rows): fell = await self._fell(rows, since, last_wet) amount = f"{fell:.1f} mm fell" if fell else "Only a trace fell" took = duration(last_wet + 300 - since) - await self.notify(f"\U0001f324️ The rain has stopped. {amount} over {took}.", kind="rain") + self._emit("rain", f"\U0001f324️ The rain has stopped. {amount} over {took}.", "Rain stopped", + {"fell_mm": fell, "from": self._iso(since), "to": self._iso(last_wet + 300)}, RAIN_EXPIRES_SECONDS) m["since"] = None remember(m, state, latest_ts, alerted=not quiet) @@ -172,7 +180,9 @@ async def _night_summary(self, rows: Rows): fell = await self._fell(rows, night["first"], night["last"]) amount = f"{fell:.1f} mm" if fell else "a trace" still = " It's still raining." if self.state.monitor.get("rain", {}).get("alerted_state") == "raining" else "" - await self.notify(f"\U0001f327️ Overnight rain: {amount}, from about {clock(night['first'])} to {clock(night['last'] + 300)}.{still}", kind="rain") + self._emit("rain", f"\U0001f327️ Overnight rain: {amount}, from about {clock(night['first'])} to {clock(night['last'] + 300)}.{still}", + "Overnight rain", {"fell_mm": fell, "from": self._iso(night["first"]), "to": self._iso(night["last"] + 300), + "still_raining": bool(still)}, RAIN_EXPIRES_SECONDS) async def _gusts(self, rows: Rows): """Only readings since the last check count, so a restart doesn't re-announce an old gust.""" @@ -184,9 +194,10 @@ async def _gusts(self, rows: Rows): if over and not m["active"]: m["active"] = True gust, ts = max(over) - await self.notify(f"\U0001f4a8 Strong gusts: {gust:.0f} km/h at {clock_text(to_local(ts, self.tz))}" - f" (alerts above {GUST_ALERT_KMH} km/h).", kind="gusts", chart=lambda: self._picture(pictures.CHARTS["gusts"]), - since=latest_ts) + self._emit("gusts", f"\U0001f4a8 Strong gusts: {gust:.0f} km/h at {clock_text(to_local(ts, self.tz))}" + f" (alerts above {GUST_ALERT_KMH} km/h).", "Strong gusts", + {"gust_kmh": gust, "at": self._iso(ts), "threshold_kmh": GUST_ALERT_KMH}, GUST_REARM_SECONDS, + await self._chart(pictures.CHARTS["gusts"])) async def _uv(self, rows: Rows): """One alert per spell at or above UVI_ALERT, once it holds for two readings in a row (rules.py); only readings newer than the last @@ -208,9 +219,9 @@ async def _uv(self, rows: Rows): if m.get("streak", 0) >= rules.CONFIRM_READINGS and not m["active"]: m["active"] = True uv, ts = m["peak"] - await self.notify(f"\U0001f9f4 UV index {uv:g} at {clock_text(to_local(ts, self.tz))}" - f": very high. Sunscreen, a hat and shade (alerts at {UVI_ALERT} and above).", kind="uv", - chart=lambda: self._picture(pictures.CHARTS["uv"]), since=latest_ts) + self._emit("uv", f"\U0001f9f4 UV index {uv:g} at {clock_text(to_local(ts, self.tz))}" + f": very high. Sunscreen, a hat and shade (alerts at {UVI_ALERT} and above).", "Very high UV", + {"uv_index": uv, "at": self._iso(ts), "threshold": UVI_ALERT}, UV_REARM_SECONDS, await self._chart(pictures.CHARTS["uv"])) async def _cross(self, rows: Rows): ts, r = rows[-1] @@ -226,9 +237,11 @@ async def _cross(self, rows: Rows): held = ts - c["alerted_time"] # how long the side we last told about has stood was = f"{int(held // 86400)} days" if held >= 2 * 86400 else duration(held) icon = "\U0001f321️" if current == "warmer" else "\u2744\ufe0f" # a thermometer for warmer, a snowflake for cooler - await self.notify(f"{icon} It's now {abs(o - i):.1f}°C {current} outside than inside " - f"({o:.1f}°C vs {i:.1f}°C). It had been {'cooler' if current == 'warmer' else 'warmer'} for {was}.", kind="temps", - chart=lambda: self._picture(pictures.CHARTS["temps"]), since=ts) + chart = await self._chart(pictures.CHARTS["temps"]) + self._emit("temps", f"{icon} It's now {abs(o - i):.1f}°C {current} outside than inside " + f"({o:.1f}°C vs {i:.1f}°C). It had been {'cooler' if current == 'warmer' else 'warmer'} for {was}.", + f"{current.capitalize()} outside than inside", {"side": current, "outdoor_c": o, "indoor_c": i, "had_been_seconds": held}, + self.cooldown, chart) remember(c, current, ts) async def _fell(self, rows: Rows, since: int, until: int) -> float | None: @@ -238,6 +251,13 @@ async def _fell(self, rows: Rows, since: int, until: int) -> float | None: rows = await self.station.recent((rows[-1][0] - since) / 3600 + 0.25) return rain_amount(rows, since, until) - async def _picture(self, text: str) -> pictures.Picture | None: - """The chart a typed `text` ("Wind chart 1d") would give, for an alert; None when it cannot be made.""" - return await pictures.chart(self.station, text, self.tz) + def _emit(self, kind: str, text: str, title: str, data: dict, lasts: float, chart: dict | None = None): + """An alert, appended to the log: news for `lasts` seconds.""" + self.alerts.append(kind, text, title, data, expires=self.alerts.now() + lasts, chart=chart) + + def _iso(self, ts: int | None) -> str | None: + return None if ts is None else to_local(ts, self.tz).isoformat(timespec="seconds") + + async def _chart(self, text: str) -> dict | None: + """The chart a typed `text` ("Wind chart 1d") would give, as data with its drawn_by, for an alert; None when it cannot be made.""" + return await pictures.chart_data(self.station, text, self.tz, self.service) diff --git a/lib/bot.py b/lib/bot.py index fbe65074..168332a1 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -412,13 +412,15 @@ async def close(self): class Bot: def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None, - service: Service | None = None): + service: Service | None = None, alert_log=None): """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); its own when none is given. service: the service's tools (lib/service), which the bot's own code paths call (its shortcuts, report, gauges, alert charts and period buttons); built over `sources` when none is given. The model is offered the same tools - (agent.tools: lib/model_tools.py), with the server's instructions (instructions(service.ctx)) after the bot's persona.""" + (agent.tools: lib/model_tools.py), with the server's instructions (instructions(service.ctx)) after the bot's persona. alert_log: + the service's alert log (lib/alert_log.py), whose events the 🔄 under an alert's chart finds its chart's drawn_by in.""" self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation + self.alert_log = alert_log self._service = service self.tasks = tasks or Tasks() self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends @@ -678,8 +680,8 @@ async def on_alert_button(self, update: Update, context: ContextTypes.DEFAULT_TY query = update.callback_query action, *rest = (query.data or "").split(":")[1:] or [""] # the grammar is in alerts/menu.py kind = parent = opened = None - if action == "refresh" and len(rest) == 1: - await self._redraw_alert(query, rest[0]) + if action == "refresh" and (len(rest) == 1 or len(rest) == 2 and rest[1].isdigit()): # al:refresh:[:] + await self._redraw_alert(query, rest[0], int(rest[1]) if len(rest) == 2 else None) return if action == "open" and len(rest) in (1, 2): # al:open:[:] opened, parent = rest[0], rest[1] if len(rest) == 2 else None @@ -717,7 +719,8 @@ async def on_alert_button(self, update: Update, context: ContextTypes.DEFAULT_TY loud = self.state.loud(chat.id) if private else None await answer_query(query, toast) if parent: # an alert: only its buttons change - await self._edit(query, None, menu.alert_keyboard(parent, muted, loud, opened, refresh=self._redrawable(message, parent))) + await self._edit(query, None, menu.alert_keyboard(parent, muted, loud, opened, refresh=self._redrawable(message, parent), + event=self._alert_event(message))) else: # the /alerts message: its on/off summary is kept current too await self._edit(query, menu.title(muted, kinds), menu.keyboard(muted, kinds, opened, loud)) @@ -726,10 +729,29 @@ def _redrawable(message, kind: str) -> bool: """Does this alert carry a chart its Refresh can draw again (it went out as a picture)?""" return kind in pictures.CHARTS and bool(getattr(message, "photo", None)) - async def _redraw_alert(self, query, kind: str): + @staticmethod + def _alert_event(message) -> int | None: + """The alert-log id the 🔄 under this alert names (al:refresh::), so its buttons keep it when they are redrawn.""" + markup = getattr(message, "reply_markup", None) + for row in getattr(markup, "inline_keyboard", None) or (): + for b in row: + parts = (getattr(b, "callback_data", None) or "").split(":") + if parts[:2] == ["al", "refresh"] and len(parts) == 4 and parts[3].isdigit(): + return int(parts[3]) + return None + + def _alert_call(self, kind: str, event: int | None) -> tuple[str, dict] | None: + """The call that draws an alert's chart again: its chart's drawn_by, from the alert log (`event`: its id); None without one (an + alert sent before the log, or one dropped from it), when the type's own chart is drawn.""" + found = self.alert_log.get(event) if event is not None and self.alert_log is not None else None + drawn_by = (found or {}).get("chart", {}).get("drawn_by") if found and found.get("kind") == kind else None + return (drawn_by["tool"], drawn_by["arguments"]) if drawn_by else None + + async def _redraw_alert(self, query, kind: str, event: int | None = None): """A press on Refresh under an alert's chart: the chart with the latest readings, in the same message: the one drawn ahead since the - message was last changed (AlertCharts.newer_than; Telegram's copy when it was uploaded ahead), else drawn now and kept. The alert's - text (what happened, as it was sent) and its buttons stay as they are.""" + message was last changed (AlertCharts.newer_than; Telegram's copy when it was uploaded ahead), else drawn now (the alert's chart's + drawn_by replayed, found in the alert log by its id `event`; the type's chart for an alert from before the log) and kept. The + alert's text (what happened, as it was sent) and its buttons stay as they are.""" message = query.message source = self.by_name.get(menu.TYPES[kind][1]) if kind in menu.TYPES else None if source is None or not self._redrawable(message, kind): # an alert of a type, or from a source, the bot no longer has @@ -738,7 +760,11 @@ async def _redraw_alert(self, query, kind: str): photo, drawn = self.alert_charts.newer_than(kind, message), False if photo is None: try: - picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz, self.service), TURN_SECONDS) + if call := self._alert_call(kind, event): + made = await asyncio.wait_for(self._draw_call(*call, ahead=False), TURN_SECONDS) + picture = pictures.Picture(made[0], made[1], made[3], made[4]) if made else None + else: + picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz, self.service), TURN_SECONDS) except TimeoutError: picture = None if picture is None: # (pictures.chart has said why) the message stays as it was @@ -876,7 +902,7 @@ async def on_report_button(self, update: Update, context: ContextTypes.DEFAULT_T return pictured = bool(getattr(getattr(query, "message", None), "photo", None)) # the report is the caption of its gauges: they are drawn again too try: - text, gauge = await self._report(True, [], pictured) + text, gauge = await self._report(True, pictured) except Exception as e: # the message stays as it was log.warning("Report refresh failed: %s", e) await answer_query(query, "Couldn't refresh, please try again", show_alert=True) @@ -1141,10 +1167,9 @@ def _content(self, msg: Message, text: str, bot_id: int) -> str: sender = msg.from_user.full_name if msg.from_user else "Someone" return f"{sender} ({reply}): {text}" if reply else f"{sender}: {text}" - async def _written_in_code(self, report: bool, shown: list, ahead: bool = False) -> str: + async def _written_in_code(self, report: bool, ahead: bool = False) -> str: """The report, or "weather now", in the service's words: the readings now (current: each device's heading and lines), then the - pollen's and the forecast's own text, the calls made together (intent.report_calls; "weather now": current {}). The forecast - days it shows go into `shown`.""" + pollen's and the forecast's own text, the calls made together (intent.report_calls; "weather now": current {}).""" calls = intent.report_calls(self.by_name) if report else [intent.WEATHER_NOW_CALL] results = await asyncio.gather(*(self._service_call(name, args, ahead=ahead) for name, args in calls)) by_tool = {name: out for (name, _), out in zip(calls, results)} @@ -1156,31 +1181,12 @@ async def _written_in_code(self, report: bool, shown: list, ahead: bool = False) sections = [] if "error" in now else [ "\n".join([now["headings"][device], *now["lines"][device]]) for device in ("station", "air") if device in now.get("lines", {})] sections += [out["text"] for name in ("pollen", "forecast") if (out := by_tool.get(name)) and out.get("text")] - shown.extend(self._shown_forecast(by_tool.get("forecast"))) return "\n\n".join(sections) or "No readings are available right now." - def _shown_forecast(self, out: dict | None, tool: str = "forecast") -> list: - """The forecast days a forecast result shows (the Forecast source's own), remembered for the chat once the answer is sent (a later - revision of them is worth telling it). An `outlook` result shows today's and tomorrow's lines in `forecast` (its description has - the model copy them): those days, as many as it has lines.""" - source = self.by_name.get("Forecast") - if source is None or not out or "error" in out: - return [] - if tool == "outlook": - lines = out.get("forecast") - if not isinstance(lines, list) or not lines: - return [] - today = now_local(self.cfg.tz).date() - return [d for d in source.days or [] if 0 <= (d["date"] - today).days <= 1][:len(lines)] - if not out.get("days"): - return [] - shown = {day.get("date") for day in out["days"] if isinstance(day, dict)} - return [d for d in source.days or [] if d["date"].isoformat() in shown] - - async def _report(self, report: bool, shown: list, gauges: bool) -> tuple[str, bytes | None]: + async def _report(self, report: bool, gauges: bool) -> tuple[str, bytes | None]: """The report (or "weather now") written in code and, with `gauges`, its picture drawn alongside (None without one), in - TURN_SECONDS. The forecast days it shows go into `shown`.""" - written = self._written_in_code(report, shown) + TURN_SECONDS.""" + written = self._written_in_code(report) if gauges: return tuple(await asyncio.wait_for(asyncio.gather(written, self._status_gauges()), TURN_SECONDS)) return await asyncio.wait_for(written, TURN_SECONDS), None @@ -1370,14 +1376,14 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text chat = self.chats[self._key(msg)] started = time.monotonic() - turn, shown = Turn(), [] # (shown: the forecast days the answer shows) + turn = Turn() async with chat.lock: draft = Draft(context.bot, msg.chat_id, self._thread(msg)) if msg.chat.type == ChatType.PRIVATE else None drafting = asyncio.create_task(draft.run(stop_typing)) if draft else None # a private chat also gets the "Thinking..." draft working = [*chat.history, {"role": "user", "content": self._content(msg, text, context.bot.id)}] new_from = len(working) try: - answer = await self._answer(msg, read, turn, shown, working, draft) + answer = await self._answer(msg, read, turn, working, draft) chat.history = shorten_old(trim_history(strip_tool_turns(working))) for chart in answer.charts[:MAX_CHARTS]: # the charts, drawn from their data while "typing..." is still showing try: @@ -1397,9 +1403,9 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text finally: stop_typing.set() await asyncio.gather(*[t for t in (typing, drafting) if t]) # wait for any in-flight "typing" or draft so none is sent after the reply - await self._send(msg, context.bot, read, turn, shown, answer, working[new_from:], now, started) + await self._send(msg, context.bot, read, turn, answer, working[new_from:], now, started) - async def _answer(self, msg: Message, read, turn: Turn, shown: list, working: list[dict], draft) -> Answer: + async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], draft) -> Answer: """The answer, from the first way that gives one: a chart drawn moments ago, a named reading's chart drawn by the service, the gauges, the report or "weather now" written in code, else the model with the service's tools. `working` is the conversation, the question last; the answer joins it.""" @@ -1413,7 +1419,7 @@ async def _answer(self, msg: Message, read, turn: Turn, shown: list, working: li elif read.dashboard: answer = await asyncio.wait_for(self._dashboard(), TURN_SECONDS) elif read.report or read.weather_now: # written in code from the service's results, no model (the report: with its gauges) - text, gauge = await self._report(read.report, shown, read.report) + text, gauge = await self._report(read.report, read.report) answer = Answer(text, [gauge] if gauge else [], [""] if gauge else []) else: answer = Answer() @@ -1428,16 +1434,12 @@ async def _answer(self, msg: Message, read, turn: Turn, shown: list, working: li answer.reply = await self._ask_model(working, system, read, turn, draft, lambda tokens: self._warn(msg, tokens)) kept = [r for r in turn.results if r] answer.charts = [chart for _, _, out in kept for chart in out.get("charts") or [] if isinstance(chart, dict)] - for name, _, out in kept: - if name in ("forecast", "outlook"): - shown.extend(self._shown_forecast(out, name)) return answer - async def _send(self, msg: Message, bot, read, turn: Turn, shown: list, answer: Answer, added: list[dict], now: datetime, - started: float): + async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added: list[dict], now: datetime, started: float): """Send the answer, a single chart with the period buttons under it, the keyboard if the chat's is out of date; then keep what - follows from it: the chart for its period buttons and the next to ask, its other periods drawn ahead, the forecast days shown - (`shown`). `added`: the messages the answer added to the conversation.""" + follows from it: the chart for its period buttons and the next to ask, its other periods drawn ahead. `added`: the messages the + answer added to the conversation.""" reply, photos, titles = answer.reply, answer.photos, answer.titles caption = reply if answer.silent else None # a chart made in code: its text, kept with the chart for the next to ask the same if answer.silent and photos: @@ -1482,8 +1484,6 @@ async def _send(self, msg: Message, bot, read, turn: Turn, shown: list, answer: self.images.sent(kept, sent.photo) if kept and row is not None and drawn_by: # its other periods are uploaded ahead self.preload_soon(bot, drawn_by) - if answer.ok and shown: # it was sent: a later revision of these days is worth telling this chat - self.state.record_forecast(msg.chat_id, shown, now_local(self.cfg.tz).date()) if carried_keyboard: log.info("Buttons: sent keyboard %s to chat %s (it had %s)", self.keyboard_version, msg.chat_id, self.state.keyboard(msg.chat_id)) self.state.set_keyboard(msg.chat_id, self.keyboard_version) diff --git a/lib/config.py b/lib/config.py index 3586ad54..a33b23b9 100644 --- a/lib/config.py +++ b/lib/config.py @@ -248,6 +248,16 @@ class Config: log_width: int = _setting("LOG_WIDTH", 24, _whole) # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the bot's own debug lines; the libraries keep theirs + @property + def alert_state_path(self) -> Path: + """The alert rules' own state (lib/alerts/store.py), beside the bot's.""" + return self.state_path.parent / "alert_state.json" + + @property + def alert_log_path(self) -> Path: + """The alert log (lib/alert_log.py), beside the bot's state.""" + return self.state_path.parent / "alerts.sqlite" + @property def homeassistant(self) -> bool: return bool(self.homeassistant_url and self.homeassistant_token) diff --git a/lib/model_tools.py b/lib/model_tools.py index aad61587..09f280fe 100644 --- a/lib/model_tools.py +++ b/lib/model_tools.py @@ -1,7 +1,7 @@ """The service's ten tools (lib/service) as the bot offers them to its model (docs/mcp-service.md 4): each by its own name, description and parameters, as they are. The bot draws the charts itself, so it asks for them as drawn (request `_meta` `chart_points: "drawn"`) and keeps each whole result on the question's Turn (`Turn.results`: for drawing, the period buttons, the complete result that ends the -turn, the forecast days shown; a call that gave no JSON object leaves None); the model is sent the result less the charts' data (`for_model`): each chart as its title and period, +turn; a call that gave no JSON object leaves None); the model is sent the result less the charts' data (`for_model`): each chart as its title and period, with `caption`, `reply` and `complete` as they are, and `chart_note` the bot's (BOT_CHART_NOTE: the service's asks the model to draw the chart from data it is no longer sent; the bot sends the picture with the reply as its caption).""" diff --git a/lib/service/about.py b/lib/service/about.py index 611d5ade..4baa7c12 100644 --- a/lib/service/about.py +++ b/lib/service/about.py @@ -15,7 +15,7 @@ from datetime import datetime, tzinfo -from ..alerts.forecast import DRY_BELOW_PCT, RAIN_FROM_PCT, TEMP_CHANGE_C +from ..alerts.forecast import BASELINE_HOUR, RAIN_FROM_PCT, TEMP_CHANGE_C from ..alerts.particulates import CHECK_SECONDS, MASK_PM10, MASK_PM25, SAFE_PM10, SAFE_PM25 from ..alerts.pollen_and_asthma import ALERT_FROM, WARN_FROM from ..alerts.rules import CONFIRM_READINGS @@ -183,9 +183,10 @@ def alert_rules() -> dict[str, tuple[str, dict]]: "pollen_and_asthma": (f"Grass pollen or the thunderstorm asthma risk forecast {' or '.join(LEVELS[WARN_FROM:])}: once a day from " f"{_clock(*ALERT_FROM)} while it stays there, and again when it rises. October to December only.", {"from_level": LEVELS[WARN_FROM]}), - "forecast": (f"A day's forecast revised: its highest temperature by more than {TEMP_CHANGE_C:g}°C, or rain turning likely (a " - f"chance of at least 1 mm of {RAIN_FROM_PCT}% or more) from unlikely ({DRY_BELOW_PCT}% or less), or the reverse.", - {"max_change_c": TEMP_CHANGE_C, "rain_from_pct": RAIN_FROM_PCT, "dry_below_pct": DRY_BELOW_PCT}), + "forecast": (f"Today's or tomorrow's forecast revised from the first one fetched after {_clock(BASELINE_HOUR)} that day: its highest " + f"temperature by more than {TEMP_CHANGE_C:g}°C, or the chance of at least 1 mm of rain crossing {RAIN_FROM_PCT}%. The " + "forecast alerted on is the one later forecasts are compared with.", + {"max_change_c": TEMP_CHANGE_C, "rain_crossing_pct": RAIN_FROM_PCT, "baseline_from": f"{BASELINE_HOUR:02d}:00"}), } diff --git a/lib/service/alerts.py b/lib/service/alerts.py new file mode 100644 index 00000000..bfe30e86 --- /dev/null +++ b/lib/service/alerts.py @@ -0,0 +1,56 @@ +"""The service's alert rules (docs/mcp-service.md 3.6), each on the trigger it has: the weather alerts after every refresh of the station +(and the rain on each live reading), particulates every CHECK_SECONDS, pollen and the forecast after each refresh of their pages. Their +settings (quiet hours, cooldown) are the service's config, their state its own store (lib/alerts/store.py, alert_state.json), and what +they decide goes to the alert log (lib/alert_log.py), which clients read: they know nothing of chats or Telegram. + +The irrigation controller's alerts are not here: they move to its own server (step 5).""" + +import logging + +from ..alerts.forecast import ForecastMonitor +from ..alerts.particulates import CHECK_SECONDS, ParticulatesMonitor +from ..alerts.pollen_and_asthma import PollenAndAsthmaMonitor +from ..alerts.weather import ALERT_COOLDOWN_SECONDS, WeatherMonitor +from ..warm import every + +log = logging.getLogger(__name__) + + +class AlertRules: + def __init__(self, sources: dict, store, alerts, cooldown_seconds: int = ALERT_COOLDOWN_SECONDS, quiet: tuple[int, int] | None = None, + service=None): + """sources: by name (Ecowitt, AirGradient, Pollen, Forecast; those that started). store: the rules' state (AlertStore). alerts: the + alert log. service: the service's tools, which draw the alerts' charts.""" + self.sources, self.store, self.alerts = sources, store, alerts + eco, air = sources.get("Ecowitt"), sources.get("AirGradient") + self.weather = WeatherMonitor(eco, store, alerts, cooldown_seconds, quiet, service) if eco else None + self.particulates = ParticulatesMonitor(air, store, alerts, service) if air else None + self.forecast = ForecastMonitor(sources["Forecast"], store, alerts) if "Forecast" in sources else None + self.pollen = PollenAndAsthmaMonitor(sources["Pollen"], store, alerts) if "Pollen" in sources else None + + def start(self, tasks) -> list[str]: + """Start every rule but the weather's (start_weather, once the station has been read): the alert types now running.""" + running = [] + if self.particulates: + tasks.start(every(CHECK_SECONDS, self.particulates.check)) + running += ParticulatesMonitor.KINDS + if self.forecast: + self.sources["Forecast"].warmer.after.append(self.forecast.check) # after each refresh (in the day) + running += ForecastMonitor.KINDS + if self.pollen: + self.sources["Pollen"].warmer.after.append(self.pollen.check) # after each refresh (in the day) + running += PollenAndAsthmaMonitor.KINDS + return running + + async def start_weather(self, running: list[str]): + """The weather rules, once the station has been read: their state from the recent readings (first run), a first check, then one + after every refresh, and the rain on each live reading. Their alert types go first in `running` once they are hooked up.""" + if not self.weather: + return + eco = self.sources["Ecowitt"] + await self.weather.init() + eco.warmer.after.append(self.weather.check) # checked on every fresh refresh + running[:0] = WeatherMonitor.KINDS + await self.weather.check() + if eco.fast is not None: # Home Assistant: the rain alert looks at each new reading as it comes in, not only at the minute's refresh + eco.on_live.append(self.weather.check_rain) diff --git a/tests/test_alert_log.py b/tests/test_alert_log.py new file mode 100644 index 00000000..86cc2d04 --- /dev/null +++ b/tests/test_alert_log.py @@ -0,0 +1,301 @@ +"""The alert log (lib/alert_log.py), the rules' own store (lib/alerts/store.py) and the bot's delivery from the log +(lib/alerts/notify.AlertDelivery): docs/mcp-service.md 3.6 and section 4.""" + +import asyncio +from types import SimpleNamespace as NS + +import pytest + +from lib.alert_log import KEEP_SECONDS, AlertLog +from lib.alerts.menu import alert_keyboard +from lib.alerts.notify import AlertDelivery, AlertState, Notifier +from lib.alerts.pictures import Picture +from lib.alerts.store import AlertStore +from tests.fakes import TZ + +T0 = 1_790_000_000.0 # 2026-09-21, a time the tests' clock starts at + + +class Clock: + def __init__(self, t=T0): + self.t = t + + def __call__(self): + return self.t + + +def new_log(tmp_path, clock=None): + return AlertLog(tmp_path / "alerts.sqlite", TZ, now=clock or Clock()) + + +# ---------- the log ---------- +def test_events_are_kept_in_order_with_rising_ids_and_their_parts(tmp_path): + log = new_log(tmp_path) + chart = {"title": "Wind", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} + first = log.append("rain", "🌧️ It's started raining.", "Rain started", {"rate_mm_h": 1.2}, expires=T0 + 3600) + second = log.append("gusts", "💨 Strong gusts", "Strong gusts", expires=T0 + 3600, link=("live chart", "https://x"), chart=chart) + assert (first["id"], second["id"]) == (1, 2) and log.last_id() == 2 + assert first == {"id": 1, "kind": "rain", "time": "2026-09-22T00:13:20+10:00", "expires": "2026-09-22T01:13:20+10:00", + "title": "Rain started", "text": "🌧️ It's started raining.", "data": {"rate_mm_h": 1.2}} + assert second["link"] == {"label": "live chart", "url": "https://x"} and second["chart"] == chart and second["data"] == {} + assert [e["id"] for e in log.since(0)] == [1, 2] and [e["id"] for e in log.since(1)] == [2] and log.since(2) == [] + assert log.get(2) == second and log.get(3) is None + + +def test_the_log_survives_a_restart_and_its_ids_never_go_back(tmp_path): + clock = Clock() + log = new_log(tmp_path, clock) + for n in range(3): + log.append("uv", f"UV {n}", "Very high UV", expires=T0 + 3600) + log.close() + clock.t += KEEP_SECONDS + 1 # a month later: those are dropped when it opens again ... + again = new_log(tmp_path, clock) + assert again.since(0, expired=True) == [] and again.last_id() == 3 + assert again.append("uv", "UV 3", "Very high UV")["id"] == 4 # ... and the ids carry on + third = new_log(tmp_path, clock) + assert [e["text"] for e in third.since(0)] == ["UV 3"] + + +def test_since_leaves_out_what_has_expired_unless_asked(tmp_path): + clock = Clock() + log = new_log(tmp_path, clock) + log.append("rain", "short", "t", expires=T0 + 60) + log.append("pollen_and_asthma", "long", "t", expires=T0 + 86400) + log.append("rain", "never", "t") + clock.t += 120 + assert [e["text"] for e in log.since(0)] == ["long", "never"] + assert [e["text"] for e in log.since(0, expired=True)] == ["short", "long", "never"] + + +async def test_a_reader_waits_for_the_next_event(tmp_path): + log = new_log(tmp_path) + assert await log.wait(0, timeout=0.05) is False + waiter = asyncio.create_task(log.wait(0)) + await asyncio.sleep(0.01) + assert not waiter.done() + log.append("rain", "x", "t") + assert await asyncio.wait_for(waiter, 1) is True + assert await log.wait(0, timeout=0.01) is True # one is there already: no wait + assert await log.wait(1, timeout=0.05) is False + + +# ---------- the rules' store ---------- +def test_the_rules_state_moves_out_of_the_bots_file_once_so_nothing_fires_again(tmp_path): + bot = AlertState(tmp_path / "bot_state.json") + bot.add_chat(1, "chat") + bot.monitor.update(rain={"alerted_state": "raining", "alerted_time": 5}, uv={"active": True, "calm_since": None}, + particulates={"unsafe": True}, irrigation_monitor={"checked": "2026-10-01"}, forecast_sent={"1": {}}) + bot.save() + loaded = AlertState(bot.path) + store = AlertStore(tmp_path / "alert_state.json", moved_from=loaded) + assert store.monitor == {"rain": {"alerted_state": "raining", "alerted_time": 5}, "uv": {"active": True, "calm_since": None}, + "particulates": {"unsafe": True}} + assert AlertState(bot.path).monitor == {"irrigation_monitor": {"checked": "2026-10-01"}} # the controller's stays; the forecast record goes + assert AlertStore(store.path).monitor == store.monitor + again = AlertState(bot.path) + again.monitor["rain"] = {"alerted_state": "dry"} # (as an old bot_state.json copied back would have) + assert AlertStore(store.path, moved_from=again).monitor["rain"]["alerted_state"] == "raining" # moved once only + + +# ---------- the bot's delivery ---------- +class Telegram: + def __init__(self): + self.sent = [] + + async def send_message(self, chat_id, text, **kw): + self.sent.append((chat_id, text, None, kw)) + return NS(photo=None) + + async def send_photo(self, chat_id, photo, **kw): + self.sent.append((chat_id, kw["caption"], photo, kw)) + return NS(photo=(NS(file_id="small"), NS(file_id=f"copy of {chat_id}"))) + + +def rows(markup): + return [[(b.text, b.callback_data) for b in row] for row in markup.inline_keyboard] + + +CHART = {"title": "Wind", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} + + +def delivery(tmp_path, clock=None, chats=(1, 2, 3), state=None, monkeypatch=None): + log = new_log(tmp_path, clock) + state = state or AlertState(tmp_path / "bot_state.json") + for chat in chats: + state.add_chat(chat, str(chat)) + telegram = Telegram() + return AlertDelivery(log, Notifier(telegram, state), state, TZ), log, state, telegram + + +async def test_each_event_goes_to_the_chats_subscribed_to_its_kind_silently_unless_sound_is_on(tmp_path): + d, log, state, telegram = delivery(tmp_path) + state.set_kind(2, "rain", False) + state.set_sound(3, "rain", True) + log.append("rain", "🌧️ It's started raining.", "Rain started", expires=T0 + 3600) + assert await d.deliver_new() == 1 + assert [(chat, text, kw["disable_notification"]) for chat, text, _, kw in telegram.sent] == [(1, "🌧️ It's started raining.", True), + (3, "🌧️ It's started raining.", False)] + assert rows(telegram.sent[0][3]["reply_markup"]) == [[("🔔 ▸", "al:open:bell:rain")]] # the bell; no chart, no 🔄 + assert state.read == 1 and AlertState(state.path).read == 1 + + +async def test_an_events_link_is_its_footer(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("pollen_and_asthma", "🔴 Grass pollen forecast is High.", "Grass", expires=T0 + 3600, + link=("melbournepollen.com.au", "https://www.melbournepollen.com.au/")) + await d.deliver_new() + (chat, text, _, kw), = telegram.sent + assert text == "🔴 Grass pollen forecast is High.\nmelbournepollen.com.au" + assert [e.url for e in kw["entities"] if e.url] == ["https://www.melbournepollen.com.au/"] + + +async def test_an_events_chart_is_drawn_from_its_data_once_and_its_refresh_names_the_event(tmp_path, monkeypatch): + from lib.alerts import notify + drawn = [] + + async def picture_of(data, tz): + drawn.append(data) + return Picture(b"png", "Wind, today", None, data["drawn_by"]) + monkeypatch.setattr(notify, "picture_of", picture_of) + d, log, state, telegram = delivery(tmp_path) + state.set_kind(3, "gusts", False) + log.append("rain", "earlier", "Rain started", expires=T0 + 3600) + event = log.append("gusts", "💨 Strong gusts: 55 km/h at 3:05pm (alerts above 40 km/h).", "Strong gusts", expires=T0 + 3600, chart=CHART) + await d.deliver_new() + photos = [(chat, photo) for chat, _, photo, _ in telegram.sent if photo] + assert drawn == [CHART] and photos == [(1, b"png"), (2, "copy of 1")] # drawn once, uploaded once + assert rows(telegram.sent[-1][3]["reply_markup"]) == [[("🔔 ▸", "al:open:bell:gusts"), ("🔄", f"al:refresh:gusts:{event['id']}")]] + + +async def test_a_real_chart_in_an_event_is_drawn_as_a_picture(tmp_path, archived_cache): + from lib.alerts import pictures + from tests.fakes import archived_station + eco, _ = await archived_station(tmp_path, archived_cache) + data = await pictures.chart_data(eco, "Wind chart 1d", TZ) + assert data["drawn_by"]["tool"] == "summary" and data["drawn_by"]["arguments"]["period"] + (tmp_path / "d").mkdir() + d, log, state, telegram = delivery(tmp_path / "d", chats=(1,)) + log.append("gusts", "💨 Strong gusts", "Strong gusts", chart=data) + await d.deliver_new() + (_, _, photo, _), = telegram.sent + assert photo[:4] == b"\x89PNG" + await eco.close() + + +async def test_a_restart_resumes_after_the_last_event_handled_and_skips_what_expired_meanwhile(tmp_path): + clock = Clock() + d, log, state, telegram = delivery(tmp_path, clock, chats=(1,)) + log.append("rain", "first", "t", expires=T0 + 3600) + await d.deliver_new() + log.append("rain", "the morning's rain", "t", expires=T0 + 3600) # sent while the bot was down ... + log.append("pollen_and_asthma", "today's pollen", "t", expires=T0 + 86400) + clock.t += 2 * 3600 # ... and it is back two hours later + restarted = AlertDelivery(new_log(tmp_path, clock), Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 1 + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["first", "today's pollen"] # the rain is not news; the pollen still is + assert restarted.last == 3 + log.append("uv", "expired at once", "t", expires=clock.t - 1) + await restarted.deliver_new() + assert len(telegram.sent) == 2 and restarted.last == 4 # skipped, and not looked at again + + +async def test_the_first_start_begins_after_the_newest_event(tmp_path): + log = new_log(tmp_path) + log.append("rain", "old news", "t") + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "1") + telegram = Telegram() + d = AlertDelivery(log, Notifier(telegram, state), state, TZ) + assert d.last == 1 + await d.deliver_new() + assert telegram.sent == [] + + +async def test_the_delivery_runs_on_the_logs_notification(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + task = asyncio.create_task(d.run()) + try: + await asyncio.sleep(0.01) + log.append("uv", "UV 11", "t") + for _ in range(100): + if telegram.sent: + break + await asyncio.sleep(0.01) + assert [text for _, text, _, _ in telegram.sent] == ["UV 11"] + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +# ---------- the 🔄 under a delivered alert ---------- +class ChartQuery: + def __init__(self, data, kind="gusts", event=None): + self.data = data + self.message = NS(text=None, chat=NS(type="private", id=1), photo=(NS(file_id="large"),), caption="💨 Strong gusts", caption_entities=(), + reply_markup=alert_keyboard(kind, set(), set(), refresh=True, event=event), date=None, edit_date=None) + self.from_user, self.toast, self.media, self.edits = NS(id=7), "unset", [], [] + + async def answer(self, text=None, **kw): + self.toast = text + + async def edit_message_media(self, media, reply_markup=None): + self.media.append((media, reply_markup)) + + async def edit_message_reply_markup(self, reply_markup=None): + self.edits.append(reply_markup) + + +def a_bot(tmp_path, log, monkeypatch): + from lib.bot import Bot + state = AlertState(tmp_path / "s.json") + state.add_chat(1, "private") + bot = Bot(NS(tz=TZ), None, [NS(name="Ecowitt", tz=TZ)], state, alert_log=log) + calls = [] + + async def draw_call(tool, args, ahead=True): + calls.append((tool, args, ahead)) + return b"replayed png", "Wind, today", None, 1_800_000_000, {"tool": tool, "arguments": args}, {} + monkeypatch.setattr(bot, "_draw_call", draw_call) + return bot, calls + + +async def test_refresh_under_a_delivered_alert_replays_its_charts_drawn_by(tmp_path, monkeypatch): + log = new_log(tmp_path) + drawn_by = {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True, "points": "auto"}} + event = log.append("gusts", "💨 Strong gusts", "Strong gusts", chart={"title": "Wind", "drawn_by": drawn_by}) + bot, calls = a_bot(tmp_path, log, monkeypatch) + q = ChartQuery(f"al:refresh:gusts:{event['id']}", event=event["id"]) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [("summary", drawn_by["arguments"], False)] + (media, markup), = q.media + assert media.media.input_file_content == b"replayed png" and markup is q.message.reply_markup and q.toast is None + + +async def test_refresh_of_an_alert_not_in_the_log_draws_its_types_chart(tmp_path, monkeypatch): + from lib.alerts import pictures + asked = [] + + async def chart(source, text, tz, service=None): + asked.append(text) + return Picture(b"type png", "Wind, today", None) + monkeypatch.setattr(pictures, "chart", chart) + bot, calls = a_bot(tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery("al:refresh:gusts:99", event=99) # (dropped from the log) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [] and asked == ["Wind chart 1d"] and q.media[0][0].media.input_file_content == b"type png" + + +async def test_the_bell_under_a_delivered_alert_keeps_the_event_in_its_refresh(tmp_path, monkeypatch): + bot, _ = a_bot(tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery("al:open:bell:gusts", event=7) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert rows(q.edits[0])[0] == [("🔔 ▾", "al:close:gusts"), ("🔄", "al:refresh:gusts:7")] + + +@pytest.mark.parametrize("data", ["al:refresh:gusts:x", "al:refresh:gusts:1:2"]) +async def test_a_refresh_with_a_malformed_id_does_nothing(tmp_path, monkeypatch, data): + bot, calls = a_bot(tmp_path, new_log(tmp_path), monkeypatch) + q = ChartQuery(data) + await bot.on_alert_button(NS(callback_query=q), NS()) + assert calls == [] and q.media == [] and q.toast is None diff --git a/tests/test_alert_menu.py b/tests/test_alert_menu.py index 3ab6c80b..72673745 100644 --- a/tests/test_alert_menu.py +++ b/tests/test_alert_menu.py @@ -260,17 +260,14 @@ async def test_every_monitors_alert_names_its_type(tmp_path): from lib.alerts.particulates import ParticulatesMonitor from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor from lib.alerts.weather import WeatherMonitor - from tests.test_alerts import FakePollen, FakeStation, T0, air_reading, gusts, rain, uv - from tests.test_forecast_alert import TODAY, FakeForecast, day - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "chat") - kinds = [] - - async def notify(text, link=None, kind=None, **more): - kinds.append(kind) + from tests.test_alerts import FakePollen, FakeStation, T0, air_reading, asking, gusts, rain, store_and_log, uv + from tests.test_forecast_alert import FakeForecast, day + state, log, sent = store_and_log(tmp_path) + kinds = lambda: [e["kind"] for e in sent.events] async def weather(first, then): - mon = WeatherMonitor(FakeStation(first), state, notify) + mon = WeatherMonitor(FakeStation(first), state, log) + asking(mon, photo=None) await mon.check() mon.station.data = then await mon.check() @@ -278,26 +275,21 @@ async def weather(first, then): await weather(rain(0, 0, 1, 1), rain(0, 0, 1, 1, *[0] * 13)) await weather(gusts(10, 12), gusts(10, 12, 60)) await weather(uv(3, 5, start=T0 + 86400), uv(3, 5, 10, 10, start=T0 + 86400)) # later than the readings above: the monitors share one state - assert kinds == ["rain", "rain", "gusts", "uv"] - kinds.clear() - mask = ParticulatesMonitor(NS(tz=TZ, link=None), state, notify) + assert kinds() == ["rain", "rain", "gusts", "uv"] + mask = ParticulatesMonitor(NS(tz=TZ, link=None), state, log) + asking(mask, photo=None) for pm in (80, 80, 20, 20): await mask.check(air_reading(pm)) - assert kinds == ["particulates", "particulates"] - kinds.clear() + assert kinds()[4:] == ["particulates", "particulates"] pollen = FakePollen() pollen.grass = "High" - await PollenAndAsthmaMonitor(pollen, state, notify).check() - assert kinds == ["pollen_and_asthma"] - seen = [] - notifier = Notifier(Sent(), state) - - async def spy(text, **kw): - seen.append(kw["kind"]) - return await notifier(text, **kw) - state.record_forecast(1, [day(0, pct=90)], TODAY) - await ForecastMonitor(FakeForecast([day(0, pct=5)]), state, spy).check() - assert seen == ["forecast"] + await PollenAndAsthmaMonitor(pollen, state, log).check() + assert kinds()[6:] == ["pollen_and_asthma"] + forecast = ForecastMonitor(FakeForecast([day(0, pct=90)]), state, log) + await forecast.check() + forecast.forecast.fetch([day(0, pct=5)]) + await forecast.check() + assert kinds()[7:] == ["forecast"] def test_under_an_alert_one_bell_opens_the_alert_toggle_and_then_the_sound_toggle(): @@ -436,9 +428,10 @@ def test_every_alert_type_sent_is_registered_and_each_monitor_declares_what_it_s from lib.alerts.weather import WeatherMonitor monitors = [WeatherMonitor, ParticulatesMonitor, ForecastMonitor, PollenAndAsthmaMonitor, IrrigationMonitor] assert sorted(k for m in monitors for k in m.KINDS) == sorted(LABELS) # every type has exactly one monitor - for m in monitors: - sent = set(re.findall(r'kind="(\w+)"', Path(__import__(m.__module__, fromlist=["x"]).__file__).read_text())) - assert sent == set(m.KINDS), m.__name__ + for m in monitors: # each kind named where it is appended to the log (the irrigation controller's: where it is sent) + text = Path(__import__(m.__module__, fromlist=["x"]).__file__).read_text() + sent = set(re.findall(r'kind="(\w+)"|_emit\("(\w+)"|append\("(\w+)"', text)) + assert {k for found in sent for k in found if k} == set(m.KINDS), m.__name__ class SentWithPhotos(Sent): diff --git a/tests/test_alerts.py b/tests/test_alerts.py index d9215c7b..8bf7d076 100644 --- a/tests/test_alerts.py +++ b/tests/test_alerts.py @@ -5,9 +5,11 @@ import pytest from lib.airgradient import Latest +from lib.alert_log import AlertLog from lib.alerts.notify import AlertState, Notifier from lib.alerts.pictures import Picture from lib.alerts.particulates import ParticulatesMonitor +from lib.alerts.store import AlertStore from lib.alerts.weather import WeatherMonitor from lib.entities import with_link from tests.fakes import TZ @@ -47,12 +49,44 @@ async def readings(self, *a, **k): return self.data -def monitor(tmp_path, data): - state, sent = AlertState(tmp_path / "s.json"), [] +class Texts: + """The alerts a rule appended to its log, read as the list of their texts, oldest first (`events`: the events themselves).""" + + def __init__(self, log: AlertLog): + self.log = log + + @property + def events(self) -> list[dict]: + return self.log.since(0, expired=True) + + def _texts(self) -> list[str]: + return [e["text"] for e in self.events] + + def __eq__(self, other): + return self._texts() == list(other) + + def __len__(self): + return len(self.events) + + def __getitem__(self, i): + return self._texts()[i] + + def __iter__(self): + return iter(self._texts()) - async def notify(text, link=None, **kw): - sent.append(text) - m = WeatherMonitor(FakeStation(data), state, notify, cooldown_seconds=30 * 60) # 30 minutes, whatever the default is + def __repr__(self): + return repr(self._texts()) + + +def store_and_log(tmp_path): + """The rules' store and an alert log in `tmp_path`, and the texts appended to the log.""" + log = AlertLog(tmp_path / "alerts.sqlite", TZ) + return AlertStore(tmp_path / "alert_state.json"), log, Texts(log) + + +def monitor(tmp_path, data): + state, log, sent = store_and_log(tmp_path) + m = WeatherMonitor(FakeStation(data), state, log, cooldown_seconds=30 * 60) # 30 minutes, whatever the default is return m, state, sent @@ -228,32 +262,30 @@ class FakeAir: async def test_mask_alert_needs_two_bad_checks_and_pairs_with_all_clear(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append((text, link)) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) await mon.check(air_reading(80)) assert not sent # one puff of smoke isn't enough await mon.check(air_reading(20)) await mon.check(air_reading(80)) assert not sent # the streak was broken await mon.check(air_reading(90)) - assert len(sent) == 1 and "mask" in sent[0][0] and sent[0][1] == FakeAir.link + (event,) = sent.events + assert "mask" in event["text"] and event["link"] == {"label": "live chart", "url": "https://example.com"} + assert event["kind"] == "particulates" and event["data"]["pm2_5_ugm3"] == 90 and event["data"]["unsafe"] await mon.check(air_reading(90)) assert len(sent) == 1 # no repeats within an episode await mon.check(air_reading(30)) assert len(sent) == 1 await mon.check(air_reading(30)) - assert len(sent) == 2 and "safe again" in sent[1][0] + assert len(sent) == 2 and "safe again" in sent[1] and not sent.events[1]["data"]["unsafe"] async def test_mask_threshold_is_official_aqi_151(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) for _ in range(3): await mon.check(air_reading(55.4)) # AQI 150: unhealthy for sensitive groups only assert not sent @@ -263,11 +295,8 @@ async def notify(text, link=None, **kw): async def test_stale_air_readings_are_ignored(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) for _ in range(3): await mon.check(air_reading(200, age=timedelta(hours=3))) assert not sent @@ -353,14 +382,12 @@ async def send_message(self, chat_id, text, **kw): assert state.subscribed(2, "uv") and not state.subscribed(2, "rain") and AlertState(state.path).present() == [1, 2, 3] -def test_a_migrated_groups_forecast_moves_with_it(tmp_path): - from datetime import date +def test_a_migrated_group_keeps_its_settings(tmp_path): state = AlertState(tmp_path / "s.json") state.add_chat(-5, "group") - today = date(2026, 10, 3) - state.record_forecast(-5, [{"date": today, "max_c": 20.0, "rain_chance_pct": 90}], today) + state.set_kind(-5, "uv", False) state.migrate_chat(-5, -1005) - assert state.forecast_sent(-1005)[today]["rain_chance_pct"] == 90 and state.forecast_sent(-5) == {} and state.forecast_chats() == [-1005] + assert -5 not in state.chats and state.muted(-1005) == {"uv"} and AlertState(state.path).muted(-1005) == {"uv"} def test_a_damaged_state_file_is_kept_aside_not_overwritten(tmp_path, caplog): @@ -375,12 +402,15 @@ def test_a_damaged_state_file_is_kept_aside_not_overwritten(tmp_path, caplog): def test_a_save_is_on_disk_before_it_replaces_the_old_file(tmp_path, monkeypatch): - from lib.alerts import notify - calls, replace = [], notify.os.replace - monkeypatch.setattr(notify.os, "fsync", lambda fd: calls.append("fsync")) - monkeypatch.setattr(notify.os, "replace", lambda a, b: (calls.append("replace"), replace(a, b))) + from lib.alerts import store + calls, replace = [], store.os.replace + monkeypatch.setattr(store.os, "fsync", lambda fd: calls.append("fsync")) + monkeypatch.setattr(store.os, "replace", lambda a, b: (calls.append("replace"), replace(a, b))) AlertState(tmp_path / "s.json").add_chat(1, "Home") assert calls == ["fsync", "replace"] + calls.clear() + AlertStore(tmp_path / "alert_state.json").save() + assert calls == ["fsync", "replace"] * 2 # (a new store is written at once, then saved) async def test_one_chat_failing_never_stops_the_alert_reaching_the_others(tmp_path, monkeypatch): @@ -493,12 +523,9 @@ def current(self): def pollen_monitor(tmp_path): from lib.alerts.pollen_and_asthma import PollenAndAsthmaMonitor - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) + state, log, sent = store_and_log(tmp_path) pollen = FakePollen() - return PollenAndAsthmaMonitor(pollen, state, notify), pollen, sent + return PollenAndAsthmaMonitor(pollen, state, log), pollen, sent async def test_high_pollen_and_asthma_alert_once_per_metric_and_day(tmp_path): @@ -522,13 +549,15 @@ async def test_high_pollen_and_asthma_alert_once_per_metric_and_day(tmp_path): pollen.grass = "Extreme" # it rises to the top of the scale the same day: said again await mon.check() await mon.check() - assert sent[-1] == "🟣 Grass pollen forecast is Extreme." - sent.pop() + assert len(sent) == 4 and sent[-1] == "🟣 Grass pollen forecast is Extreme." pollen.grass = "High" # (and back, for what follows) pollen.today += timedelta(days=1) # a new day, still High pollen.fetched_at = time.time() await mon.check() - assert len(sent) == 4 and "Central" not in " ".join(sent) + assert len(sent) == 5 and "Central" not in " ".join(sent) + event = sent.events[-1] + assert event["kind"] == "pollen_and_asthma" and event["link"] == {"label": "melbournepollen.com.au", "url": "https://www.melbournepollen.com.au/"} + assert event["data"] == {"metric": "grass", "level": "High", "for": "2026-10-02"} and event["title"] == "Grass pollen forecast: High" async def test_a_restart_does_not_repeat_an_alert_and_a_missing_forecast_or_stale_page_is_ignored(tmp_path): @@ -537,7 +566,7 @@ async def test_a_restart_does_not_repeat_an_alert_and_a_missing_forecast_or_stal pollen.grass = "High" await mon.check() assert len(sent) == 1 - again = PollenAndAsthmaMonitor(pollen, mon.state, mon.notify) # the state file keeps what was sent + again = PollenAndAsthmaMonitor(pollen, AlertStore(mon.state.path), mon.alerts) # the state file keeps what was sent await again.check() assert len(sent) == 1 pollen.asthma = None # off-season: nothing to say @@ -700,97 +729,78 @@ def test_unsubscribing_from_all_keeps_future_alert_types_off_until_subscribed(tm assert again.subscribed(3, "rain") and not again.subscribed(3, "uv") and not again.subscribed(3, "newer still") -async def picture_of(kw): - """The picture an alert sent with these arguments would carry: what its chart draws (None: the text alone).""" - return await kw["chart"]() if kw.get("chart") else None +CHART = {"title": "a chart", "drawn_by": {"tool": "summary", "arguments": {"readings": ["wind"], "period": "1d", "chart": True}}} -def asking(mon, photo=b"png"): - """Replace a monitor's chart maker with one that records what was asked and answers `photo`; returns the list of requests.""" +def asking(mon, photo=CHART): + """Replace a monitor's chart maker with one that records what was asked and answers `photo` (a chart's data); returns the list of + requests.""" asked = [] - async def picture(*text): + async def chart(*text): asked.append(text[-1] if text else "particulates") return photo - mon._picture = picture + mon._chart = chart return asked async def test_the_crossing_alert_carries_the_temperature_chart_when_there_is_one(tmp_path): m, state, sent = monitor(tmp_path, temps(10, 20)) - photos = [] - - async def notify(text, link=None, **kw): - sent.append(text) - photos.append(await picture_of(kw)) - m.notify = notify asked = asking(m) await m.check() # learns: outdoor cooler m.station.data = temps(25, 20, T0 + 3 * 3600) await m.check() - assert len(sent) == 1 and photos == [b"png"] and asked == ["Temperature chart 1d"] + assert len(sent) == 1 and sent.events[0]["chart"] == CHART and asked == ["Temperature chart 1d"] + assert sent.events[0]["title"] == "Warmer outside than inside" and sent.events[0]["data"]["outdoor_c"] == 25 m.station.data = temps(10, 20, T0 + 6 * 3600) # and back, with no chart this time: the alert still goes out, as text asking(m, photo=None) await m.check() - assert len(sent) == 2 and photos[1] is None + assert len(sent) == 2 and "chart" not in sent.events[1] async def test_the_gusts_alert_carries_the_wind_chart(tmp_path): vals = [10, 12] m, state, sent = monitor(tmp_path, [(T0 + i * 300, {"wind.wind_gust": v}) for i, v in enumerate(vals)]) - seen = [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - m.notify = notify asked = asking(m) await m.check() # the first look sets the mark m.station.data = [(T0 + i * 300, {"wind.wind_gust": v}) for i, v in enumerate([10, 12, 55])] await m.check() - assert len(seen) == 1 and "Strong gusts" in seen[0][0] and seen[0][1] == b"png" and asked == ["Wind chart 1d"] + (event,) = sent.events + assert "Strong gusts" in event["text"] and event["chart"]["drawn_by"] == CHART["drawn_by"] and asked == ["Wind chart 1d"] + assert event["kind"] == "gusts" and event["data"]["gust_kmh"] == 55 and "link" not in event (tmp_path / "b").mkdir() - m2, _, _ = monitor(tmp_path / "b", [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12})]) - plain = [] - - async def notify2(text, link=None, **kw): - plain.append((kw["kind"], await picture_of(kw))) - m2.notify = notify2 + m2, _, plain = monitor(tmp_path / "b", [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12})]) asking(m2, photo=None) await m2.check() m2.station.data = [(T0, {"wind.wind_gust": 10}), (T0 + 300, {"wind.wind_gust": 12}), (T0 + 600, {"wind.wind_gust": 70})] await m2.check() - assert plain == [("gusts", None)] # no chart: text only + assert [(e["kind"], e.get("chart")) for e in plain.events] == [("gusts", None)] # no chart: text only async def test_both_particulates_alerts_carry_the_particulates_chart(tmp_path): - state, seen = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, seen = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) asked = asking(mon) for pm in (90, 90, 30, 30): await mon.check(air_reading(pm)) - assert [("mask" in t, "safe again" in t, p) for t, p in seen] == [(True, False, b"png"), (False, True, b"png")] and asked == ["particulates"] * 2 - quiet = ParticulatesMonitor(FakeAir(), AlertState(tmp_path / "t.json"), notify) + assert [("mask" in e["text"], "safe again" in e["text"], e.get("chart")) for e in seen.events] == [(True, False, CHART), (False, True, CHART)] + assert asked == ["particulates"] * 2 + (tmp_path / "t").mkdir() + state, log, quiet_seen = store_and_log(tmp_path / "t") + quiet = ParticulatesMonitor(FakeAir(), state, log) asking(quiet, photo=None) - seen.clear() for pm in (90, 90): await quiet.check(air_reading(pm)) - assert seen == [(seen[0][0], None)] + assert len(quiet_seen) == 1 and "chart" not in quiet_seen.events[0] async def test_other_alerts_send_no_picture(tmp_path): m, state, sent = monitor(tmp_path, None) - seen = [] - - async def notify(text, link=None, **kw): - seen.append(kw) - m.notify = notify + asked = asking(m) for data in (rain(0, 0, 0), rain(0, 0, 1)): m.station.data = data await m.check() - assert seen and all("chart" not in kw for kw in seen) + assert sent.events and all("chart" not in e for e in sent.events) and asked == [] async def test_the_alert_charts_are_the_typed_one_day_charts_drawn_from_each_sources_history(tmp_path, archived_cache): @@ -829,32 +839,22 @@ async def test_the_particulates_chart_draws_pm1_pm25_and_pm10_together(tmp_path) async def test_the_uv_alert_carries_the_uv_chart_once_per_spell(tmp_path): vals = [3, 5] - m, state, sent = monitor(tmp_path, uv(*vals)) - seen = [] - - async def notify(text, link=None, **kw): - seen.append((text, await picture_of(kw))) - m.notify = notify + m, state, seen = monitor(tmp_path, uv(*vals)) asked = asking(m) await m.check() # the first look sets the mark m.station.data = uv(3, 5, 11, 12) await m.check() - assert len(seen) == 1 and "UV index 12" in seen[0][0] and seen[0][1] == b"png" and asked == ["UV chart 1d"] + assert len(seen) == 1 and "UV index 12" in seen[0] and seen.events[0]["chart"] == CHART and asked == ["UV chart 1d"] m.station.data = uv(3, 5, 11, 12, 12) # the same spell: nothing more, and no second chart is made await m.check() assert len(seen) == 1 and asked == ["UV chart 1d"] (tmp_path / "b").mkdir() - plain, _, _ = monitor(tmp_path / "b", uv(3, 5)) - got = [] - - async def notify2(text, link=None, **kw): - got.append((kw["kind"], await picture_of(kw))) - plain.notify = notify2 + plain, _, got = monitor(tmp_path / "b", uv(3, 5)) asking(plain, photo=None) await plain.check() plain.station.data = uv(3, 5, 11, 12) await plain.check() - assert got == [("uv", None)] # no chart: text only + assert [(e["kind"], e.get("chart")) for e in got.events] == [("uv", None)] # no chart: text only def test_an_alert_rearms_only_once_its_condition_has_stopped_for_the_whole_wait(): @@ -887,15 +887,11 @@ async def test_uv_needs_two_distinct_readings_even_across_checks_and_a_restart(t await m.check() await m.check() # the same reading looked at again does not count twice assert sent == [] - restarted = WeatherMonitor(m.station, AlertState(state.path), m.notify, cooldown_seconds=30 * 60) # a restart: the run is in the state file - sent2 = [] - - async def notify(text, link=None, **kw): - sent2.append(text) - restarted.notify = notify + restarted = WeatherMonitor(m.station, AlertStore(state.path), AlertLog(tmp_path / "alerts.sqlite", TZ), # (the same log) + cooldown_seconds=30 * 60) # a restart: the run is in the state file restarted.station.data = uv(3, 5, 10, 10.5) await restarted.check() - assert len(sent2) == 1 and "UV index 10.5" in sent2[0] + assert len(sent) == 1 and "UV index 10.5" in sent[0] (tmp_path / "x").mkdir() m3, _, sent3 = monitor(tmp_path / "x", uv(3, 5)) await m3.check() @@ -922,11 +918,9 @@ async def test_a_difference_of_a_degree_or_less_is_not_a_crossing(tmp_path): async def test_particulates_count_readings_not_checks(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) first = air_reading(90) await mon.check(first) await mon.check(first) # the sensor said nothing new: still one reading @@ -934,18 +928,17 @@ async def notify(text, link=None, **kw): await mon.check(air_reading(30)) # a reading that is not unhealthy ends the run await mon.check(first) # and an old reading is not counted again assert sent == [] - again = ParticulatesMonitor(FakeAir(), AlertState(tmp_path / "s.json"), notify) # a restart keeps what was counted + again = ParticulatesMonitor(FakeAir(), AlertStore(state.path), log) # a restart keeps what was counted + asking(again, photo=None) await again.check(air_reading(90)) await again.check(air_reading(90)) assert len(sent) == 1 and "mask" in sent[0] async def test_a_single_spike_never_makes_the_air_unhealthy_but_two_readings_in_a_row_do(tmp_path): - state, sent = AlertState(tmp_path / "s.json"), [] - - async def notify(text, link=None, **kw): - sent.append(text) - mon = ParticulatesMonitor(FakeAir(), state, notify) + state, log, sent = store_and_log(tmp_path) + mon = ParticulatesMonitor(FakeAir(), state, log) + asking(mon, photo=None) stamp = datetime.now(timezone.utc) def reading(minutes, latest, before): # the lowest of the last readings, as air.latest() gives it @@ -960,7 +953,7 @@ def reading(minutes, latest, before): # the lowest of def test_the_default_wait_before_the_rain_has_stopped_is_an_hour(tmp_path): from lib.alerts.weather import ALERT_COOLDOWN_SECONDS - assert ALERT_COOLDOWN_SECONDS == 60 * 60 == WeatherMonitor(FakeStation([]), AlertState(tmp_path / "s.json"), None).cooldown + assert ALERT_COOLDOWN_SECONDS == 60 * 60 == WeatherMonitor(FakeStation([]), AlertStore(tmp_path / "s.json"), None).cooldown async def test_a_live_reading_alone_starts_the_rain_alert_without_the_rest_of_the_check(tmp_path): diff --git a/tests/test_forecast_alert.py b/tests/test_forecast_alert.py index 844177bd..09e984c3 100644 --- a/tests/test_forecast_alert.py +++ b/tests/test_forecast_alert.py @@ -1,13 +1,13 @@ -import json +"""The forecast alert, station-wide (docs/mcp-service.md 3.6): today's and tomorrow's forecast against the day's baseline (the first one +fetched from 6 am), an alert when the high moves by more than 2°C or the chance of rain crosses 50%, the alerted forecast the new baseline.""" + from datetime import date, datetime, time as dtime, timedelta -from lib.alerts.forecast import ForecastMonitor, revised -from lib.alerts.notify import AlertState, Notifier -from lib.forecast import Forecast -from lib.tools import Turn -from tests.fakes import TZ, config -from tests.test_forecast import make -from tests import old_tools +from lib.alert_log import AlertLog +from lib.alerts.forecast import ForecastMonitor, changes, revised +from lib.alerts.store import AlertStore +from tests.fakes import TZ +from tests.test_alerts import Texts TODAY = date(2026, 10, 3) @@ -17,195 +17,126 @@ def day(offset, max_c=20.0, pct=10, summary="☀️ Clear.", min_c=10.0): class FakeForecast: - """Just what the monitor reads: today and the current days.""" - - def __init__(self, days): - self.days = days + """Just what the monitor reads: the time, the days, when they were fetched.""" + tz = TZ - def now(self): - return datetime.combine(TODAY, dtime(12, 0)) + def __init__(self, days, hour=12, minute=0, today=TODAY): + self.days, self.today, self.hour, self.minute = days, today, hour, minute + self.fetched_at = self.at(hour, minute) + def at(self, hour, minute=0) -> float: + return datetime.combine(self.today, dtime(hour, minute), TZ).timestamp() -class FakeBot: - def __init__(self): - self.sent = [] + def now(self): + return datetime.combine(self.today, dtime(self.hour, self.minute)) - async def send_message(self, chat_id, text, **kw): - self.sent.append((chat_id, text)) + def fetch(self, days, hour=None, minute=0): + """A refresh: these days, fetched now (or at `hour`).""" + if hour is not None: + self.hour, self.minute = hour, minute + self.days, self.fetched_at = days, self.at(self.hour, self.minute) -def setup(tmp_path, days): - state, bot = AlertState(tmp_path / "s.json"), FakeBot() - for chat in (1, 2): - state.add_chat(chat, f"chat {chat}") - forecast = FakeForecast(days) - return ForecastMonitor(forecast, state, Notifier(bot, state)), forecast, state, bot +def setup(tmp_path, days, **kw): + store, log = AlertStore(tmp_path / "alert_state.json"), AlertLog(tmp_path / "alerts.sqlite", TZ) + forecast = FakeForecast(days, **kw) + return ForecastMonitor(forecast, store, log), forecast, Texts(log) -def test_substantial_means_rain_flips_or_a_max_temperature_over_2_degrees_different(): +def test_substantial_means_rain_crossing_50_or_a_max_temperature_over_2_degrees_different(): base = day(0, max_c=20.0, pct=95) assert revised(base, day(0, max_c=20.0, pct=10)) and revised(day(0, pct=10), day(0, pct=80)) - assert not revised(base, day(0, pct=60)) and not revised(base, day(0, pct=35)) and not revised(day(0, pct=20), day(0, pct=40)) + assert revised(base, day(0, pct=49)) and revised(day(0, pct=49), day(0, pct=50)) # across 50, however little + assert not revised(base, day(0, pct=50)) and not revised(day(0, pct=20), day(0, pct=49)) # on one side of it assert not revised(day(0, max_c=20.0), day(0, max_c=22.0)) and not revised(day(0, max_c=20.0), day(0, max_c=18.0)) assert revised(day(0, max_c=20.0), day(0, max_c=22.1)) and revised(day(0, max_c=20.0), day(0, max_c=17.9)) assert not revised(day(0, max_c=None, pct=None), day(0, max_c=25.0, pct=90)) # nothing to compare + assert changes(day(0, max_c=24.0, pct=10), day(0, max_c=19.0, pct=80)) == ["the high is now 19°C (was 24°C)", + "rain is now likely (80%, was 10%)"] -async def test_a_day_sent_as_rainy_that_turns_dry_is_told_once_to_that_chat(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=95, summary="⛈️ Thunderstorm."), day(1)]) - state.record_forecast(1, [day(0, pct=95, summary="⛈️ Thunderstorm."), day(1)], TODAY) - await mon.check() - assert bot.sent == [] # unchanged - forecast.days = [day(0, pct=10, summary="☀️ Clear."), day(1)] - await mon.check() - await mon.check() # the same revision does not repeat - assert len(bot.sent) == 1 and bot.sent[0][0] == 1 - text = bot.sent[0][1] - assert text.startswith("🔄 The forecast has changed since I sent it:\n• Today: was ⛈️ Thunderstorm. 10–20°C, 95% chance of rain\n now ☀️ Clear. 10–20°C, 10% chance of rain") - assert state.forecast_sent(1)[TODAY]["rain_chance_pct"] == 10 # the new baseline +def test_a_revision_compares_the_one_millimetre_chance_when_both_days_have_it_and_the_older_figure_otherwise(): + day = lambda **k: {"max_c": 18, **k} + assert revised(day(rain_1mm_pct=60), day(rain_1mm_pct=25)) # rainy -> dry + assert revised(day(rain_1mm_pct=20), day(rain_1mm_pct=55)) # dry -> rainy + assert not revised(day(rain_1mm_pct=45), day(rain_1mm_pct=35)) # under 50 both times + assert not revised(day(rain_chance_pct=94, rain_1mm_pct=95), day(rain_chance_pct=20, rain_1mm_pct=90)) # the new figure decides + assert revised(day(rain_chance_pct=90), day(rain_chance_pct=10)) # only the older figure on either side: as before + assert not revised(day(rain_chance_pct=94), day(rain_1mm_pct=50)) # an old baseline vs a new figure: not compared -async def test_dry_to_rain_and_max_temperature_changes_alert_and_a_further_change_alerts_again(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0), day(1, max_c=20.0)]) - state.record_forecast(1, [day(0), day(1, max_c=20.0)], TODAY) - forecast.days = [day(0, pct=80, summary="🌦️ Showers."), day(1, max_c=22.1)] +async def test_the_first_forecast_fetched_from_6am_is_the_baseline_and_alerts_nothing(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0, pct=90), day(1)], hour=5, minute=50) + await mon.check() # before 6 am: no baseline yet + assert mon.state.monitor.get("forecast") is None + forecast.fetch([day(0, pct=90), day(1)], hour=6, minute=5) + forecast.hour, forecast.fetched_at = 6, forecast.at(5, 55) # (6 am, but the forecast held was fetched before it) await mon.check() - assert len(bot.sent) == 1 # two changed days: one message - assert "• Today: was" in bot.sent[0][1] and "• Sunday: was" in bot.sent[0][1] - forecast.days = [day(0, pct=80, summary="🌦️ Showers."), day(1, max_c=24.3)] # 2.2 from the new baseline + assert mon.state.monitor.get("forecast") is None + forecast.fetch([day(0, pct=90), day(1), day(2)], hour=6, minute=15) await mon.check() - assert len(bot.sent) == 2 and bot.sent[1][1].count("• ") == 1 + m = mon.state.monitor["forecast"] + assert m["day"] == "2026-10-03" and sorted(m["baseline"]) == ["2026-10-03", "2026-10-04"] and sent == [] # today and tomorrow + assert m["baseline"]["2026-10-03"]["rain_chance_pct"] == 90 -async def test_small_changes_past_days_muted_chats_and_chats_never_sent_a_forecast_are_left_alone(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0), day(1)]) - state.record_forecast(1, [day(0), day(1)], TODAY) - forecast.days = [day(0, max_c=21.9, pct=40), day(1, max_c=18.5)] +async def test_a_move_of_the_high_over_2_degrees_alerts_with_what_changed_and_becomes_the_baseline(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1, max_c=24.0)], hour=6, minute=15) + await mon.check() # the baseline + forecast.fetch([day(0), day(1, max_c=22.5)], hour=9) + await mon.check() + assert sent == [] # 1.5 degrees: inside the threshold + forecast.fetch([day(0), day(1, max_c=19.0, pct=80, summary="🌧️ Rain.")], hour=10) await mon.check() - assert bot.sent == [] # inside the thresholds - state.record_forecast(1, [day(-1, pct=90), day(0), day(1)], TODAY) - forecast.days = [day(0, pct=70), day(1)] # yesterday is not in the forecast any more; today flips + assert sent == ["🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is now likely (80%, was 10%).\n" + "Now: 🌧️ Rain. 10–19°C, 80% chance of rain"] + (event,) = sent.events + assert event["kind"] == "forecast" and event["title"] == "The forecast for tomorrow changed" + assert event["data"] == {"date": "2026-10-04", "was": {"max_c": 24.0, "rain_chance_pct": 10, "summary": "☀️ Clear."}, + "now": {"max_c": 19.0, "rain_chance_pct": 80, "summary": "🌧️ Rain."}} + assert event["expires"] == "2026-10-05T00:00:00+11:00" # news until the end of the day it is about + assert mon.state.monitor["forecast"]["baseline"]["2026-10-04"]["max_c"] == 19.0 # the new baseline + forecast.fetch([day(0), day(1, max_c=20.5, pct=80, summary="🌧️ Rain.")], hour=11) await mon.check() - assert len(bot.sent) == 1 and "Yesterday" not in bot.sent[0][1] and bot.sent[0][1].count("• ") == 1 - state.record_forecast(2, [day(0, pct=90)], TODAY) - state.set_alerts(2, False) - forecast.days = [day(0, pct=5), day(1)] + assert len(sent) == 1 # 1.5 from the new baseline: nothing + forecast.fetch([day(0), day(1, max_c=21.5, pct=80, summary="🌧️ Rain.")], hour=12) await mon.check() - assert [chat for chat, _ in bot.sent] == [1, 1] and state.forecast_sent(2)[TODAY]["rain_chance_pct"] == 90 # muted: not told, not reset + assert len(sent) == 2 and "the high is now 22°C (was 19°C)" in sent[1] # 2.5 from it: told -async def test_a_revised_day_leaves_the_other_days_sent_with_it_to_be_told(tmp_path): - week = [day(i) for i in range(7)] - mon, forecast, state, bot = setup(tmp_path, week) - state.record_forecast(1, week, TODAY) - forecast.days = [*week[:2], day(2, pct=80), *week[3:]] # Monday turns rainy +async def test_rain_crossing_50_alerts_each_way_and_today_and_tomorrow_are_separate_alerts(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0, pct=40), day(1, pct=60), day(2)], hour=7) await mon.check() - forecast.days = [week[0], day(1, pct=80), day(2, pct=80), *week[3:]] # then Sunday does + forecast.fetch([day(0, pct=55), day(1, pct=45), day(2, pct=90)], hour=8) # both cross; the day after tomorrow is not watched await mon.check() - assert len(bot.sent) == 2 and "• Monday: was" in bot.sent[0][1] and "• Sunday: was" in bot.sent[1][1] - assert sorted(state.forecast_sent(1)) == [d["date"] for d in week] - - -async def test_an_answer_about_later_days_leaves_today_to_be_told(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=90), day(1)]) - state.record_forecast(1, [day(0, pct=90), day(1)], TODAY) # the morning report - state.record_forecast(1, [day(1)], TODAY) # "what about tomorrow?" - forecast.days = [day(0, pct=5), day(1)] + assert [t.split(":")[0] for t in sent] == ["🔄 The forecast for today has changed", "🔄 The forecast for tomorrow has changed"] + assert "rain is now likely (55%, was 40%)" in sent[0] and "rain is now unlikely (45%, was 60%)" in sent[1] + forecast.fetch([day(0, pct=60), day(1, pct=40), day(2, pct=90)], hour=9) # further, on the same side: nothing await mon.check() - assert len(bot.sent) == 1 and "• Today: was" in bot.sent[0][1] - - -async def test_what_was_sent_survives_a_restart_and_is_not_repeated(tmp_path): - mon, forecast, state, bot = setup(tmp_path, [day(0, pct=90)]) - state.record_forecast(1, [day(0, pct=90)], TODAY) - again = AlertState(tmp_path / "s.json") - assert again.forecast_sent(1)[TODAY]["rain_chance_pct"] == 90 - forecast.days = [day(0, pct=5)] - mon2 = ForecastMonitor(forecast, again, Notifier(bot, again)) - await mon2.check() - assert len(bot.sent) == 1 - await ForecastMonitor(forecast, AlertState(tmp_path / "s.json"), Notifier(bot, again)).check() - assert len(bot.sent) == 1 # the new baseline was saved too - - -async def forecast_result(forecast, period="next 2 days") -> dict: - """What the service's forecast answers the model.""" - from lib.service import Service - from lib.service.context import Context - return json.loads(await Service.of(Context(forecast=forecast, tz=TZ))["forecast"].call({"period": period})) - - -async def test_the_forecast_days_a_result_shows_are_noted_for_the_chat_and_a_failure_notes_none(tmp_path): - from types import SimpleNamespace as NS - from lib.bot import Bot - forecast, _ = make(tmp_path) - await forecast.start() - bot = Bot(NS(tz=TZ), None, [forecast], AlertState(tmp_path / "s.json")) - shown = bot._shown_forecast(await forecast_result(forecast)) - assert [d["date"] for d in shown] == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] - assert shown[0]["max_c"] == 16 and shown[0]["rain_chance_pct"] == 40 - assert bot._shown_forecast({"error": "No forecast is available right now."}) == [] and bot._shown_forecast(None) == [] - await forecast.close() - - -async def test_a_delivered_answer_records_the_forecast_for_its_chat_and_an_undelivered_one_does_not(tmp_path): - from types import SimpleNamespace as NS - from telegram.error import TelegramError - from lib.bot import Bot - forecast, _ = make(tmp_path) - await forecast.start() - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "chat") - - class Agent: - tools = None - - async def run(self, messages, system, effort, turn=None, **k): - turn.results.append(("forecast", {"period": "next 2 days"}, await forecast_result(forecast))) # (as lib/model_tools.py keeps it) - return "Today: showers" - bot = Bot(NS(tz=TZ), Agent(), [forecast], state) - - def update(fail): - async def reply_text(body, **kw): - if fail: - raise TelegramError("down") - msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, - chat=NS(type="private", title=None), from_user=NS(full_name="Rob"), reply_to_message=None) - return NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) - - async def send_chat_action(*a, **k): - pass - ctx = NS(bot=NS(send_chat_action=send_chat_action, id=99)) - await bot.respond(update(True), ctx, "what's the forecast") - assert state.forecast_sent(1) == {} # not delivered: not "sent" - await bot.respond(update(False), ctx, "what's the forecast") - assert sorted(state.forecast_sent(1)) == [forecast.now().date(), forecast.now().date() + timedelta(days=1)] - await forecast.close() - - -async def test_an_alert_for_one_chat_goes_to_it_alone_and_a_blocked_one_is_marked_gone(tmp_path): - from telegram.error import Forbidden - state = AlertState(tmp_path / "s.json") - state.add_chat(1, "a") - state.add_chat(2, "b") - sent = [] - - class Bot: - async def send_message(self, chat_id, text, **kw): - if chat_id == 2: - raise Forbidden("bot was blocked by the user") - sent.append((chat_id, text)) - notifier = Notifier(Bot(), state) - assert await notifier("hello", kind="forecast", chats=[1]) == 1 and [c for c, _ in sent] == [1] and sent[0][1] == "hello" - assert await notifier("hello", kind="forecast", chats=[2]) == 0 and state.chats[2]["gone"] + assert len(sent) == 2 -def test_a_revision_compares_the_one_millimetre_chance_when_both_days_have_it_and_the_older_figure_otherwise(): - from lib.alerts.forecast import revised - day = lambda **k: {"max_c": 18, **k} - assert revised(day(rain_1mm_pct=60), day(rain_1mm_pct=25)) # rainy -> dry - assert revised(day(rain_1mm_pct=20), day(rain_1mm_pct=55)) # dry -> rainy - assert not revised(day(rain_1mm_pct=45), day(rain_1mm_pct=35)) # a wobble in between - assert not revised(day(rain_chance_pct=94, rain_1mm_pct=95), day(rain_chance_pct=20, rain_1mm_pct=90)) # the new figure decides - assert revised(day(rain_chance_pct=90), day(rain_chance_pct=10)) # only the older figure on either side: as before - assert not revised(day(rain_chance_pct=94), day(rain_1mm_pct=50)) # an old baseline vs a new figure: not compared +async def test_a_new_day_starts_a_new_baseline_and_a_restart_keeps_it(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1)], hour=7) + await mon.check() + again = ForecastMonitor(forecast, AlertStore(mon.state.path), mon.alerts) # a restart: the baseline is in the store + forecast.fetch([day(0, pct=80), day(1)], hour=8) + await again.check() + assert len(sent) == 1 and "today" in sent[0] + forecast.today += timedelta(days=1) # the next day: its first forecast is the baseline + forecast.fetch([day(1, max_c=30.0), day(2)], hour=6, minute=10) + await again.check() + assert len(sent) == 1 and again.state.monitor["forecast"]["day"] == "2026-10-04" + + +async def test_the_old_per_chat_forecast_record_is_dropped_and_nothing_fires_after_the_upgrade(tmp_path): + from lib.alerts.notify import AlertState + bot_state = AlertState(tmp_path / "bot_state.json") + bot_state.add_chat(1, "chat") + bot_state.monitor["forecast_sent"] = {"1": {TODAY.isoformat(): {**day(0, pct=90), "date": TODAY.isoformat()}}} + bot_state.save() + store = AlertStore(tmp_path / "alert_state.json", moved_from=AlertState(bot_state.path)) + assert "forecast_sent" not in AlertState(bot_state.path).monitor and "forecast_sent" not in store.monitor + mon = ForecastMonitor(FakeForecast([day(0, pct=5)], hour=14), store, AlertLog(tmp_path / "alerts.sqlite", TZ)) + await mon.check() # the first look after the upgrade: the baseline, no alert + assert Texts(mon.alerts) == [] diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 5bb3d2f6..92ed2214 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -466,15 +466,6 @@ async def test_an_error_reply_gets_no_air_link(world, alert_state, monkeypatch): assert said == ["Sorry, that took too long. Please try again in a moment."] -async def test_the_forecast_days_an_outlook_shows_are_recorded_for_the_forecast_alert(world, alert_state, monkeypatch): - """outlook's result carries Open-Meteo's lines for today and tomorrow, for the model to copy: once sent, a revision of those days is - worth telling the chat, as for forecast's.""" - from datetime import timedelta - await asked_the_model(world, alert_state, monkeypatch, "will it rain later?", [[("outlook", {})]], "Possibly.") - today = FrozenDate.today() - assert sorted(alert_state.forecast_sent(-5)) == [today, today + timedelta(days=1)] - - @pytest.mark.parametrize("text", ["temperature 1d", "co2 1d", "pm2.5 1d"]) async def test_a_bare_reading_and_1d_is_still_its_chart_without_the_model(world, alert_state, monkeypatch, text): """As before the swap: "temperature 1d" is the chart of the last day, drawn in code (no model needed).""" From 4fc3b31d6d2b0b5eb354e79857832a95b9b20687 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:49:42 +0000 Subject: [PATCH 059/125] Step 4 review: a removed or replaced alert log restarts delivery; the forecast's 30% band is back - AlertLog has an identity (a random id in its meta table), kept in bot_state.json as alerts_log beside alerts_read. A start on another log (alerts.sqlite removed or replaced), or with a kept id past the log's newest, logs a warning and starts after the log's newest, instead of sending nothing until the new ids pass the old one. An id kept before the log had an identity is resumed from as before. - The forecast alert says rain is likely when the chance rises from under 50% to 50% or more, and unlikely only when it falls from 50% or more to 30% or less, so a chance hovering around 50% alerts once, not on every revision. about and the docs say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/mcp-service.md | 14 +++++++---- lib/alert_log.py | 6 +++++ lib/alerts/forecast.py | 16 ++++++++---- lib/alerts/notify.py | 20 ++++++++++++--- lib/service/about.py | 10 +++++--- tests/test_alert_log.py | 47 ++++++++++++++++++++++++++++++++++++ tests/test_forecast_alert.py | 32 ++++++++++++++++++------ 7 files changed, 120 insertions(+), 25 deletions(-) diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 9b297f2c..f16663d6 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -335,7 +335,8 @@ every 60 seconds, particulates every 30 minutes and only then, since its two-rea - **Delivery is the client's.** A client listens, reads `ecobot://alerts?since=`, and sends each alert to whoever it serves. Our bot does this for its subscribed chats until it is retired. - **The forecast alert is station-wide:** for today and tomorrow, it compares each new forecast with the first one fetched after 6am - that day (its baseline), alerts when the maximum moves by more than 2°C or the chance of rain crosses 50%, and makes the forecast it + that day (its baseline), alerts when the maximum moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or less: the band + keeps a chance hovering around 50% from alerting each way on every refresh), and makes the forecast it alerted on the new baseline. Its text says what changed ("The forecast for tomorrow has changed: was 24°C and dry, now 19°C with rain likely"), not "since I sent it", which only the bot could say. - **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open; once the bot is retired, alerts reach @@ -533,13 +534,16 @@ Each step ships on its own, with the tests and evals green and the bot working t `about` reads, as no setting changes them today. - **The forecast alert is station-wide** (deliberate): the first forecast fetched from 6 am is the day's baseline for today and tomorrow (no alert); a later one alerts, one event per day, when the high moves by more than 2°C or the chance of at least 1 mm - crosses 50%, and becomes that day's baseline. The 30% band against flip-flopping goes with the per-chat baseline (3.6 says - "crosses 50%"). Its text says what changed: "🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is + rises from under 50% to 50% or more, or falls from 50% or more to 30% or less, and becomes that day's baseline. The 30% band is + kept: without it a chance hovering around 50% (rounded to 5%, refetched every 15 minutes) alerts likely, unlikely, likely through + the day. Its text says what changed: "🔄 The forecast for tomorrow has changed: the high is now 19°C (was 24°C) and rain is now likely (80%, was 10%).\nNow: 🌧️ Rain. 10–19°C, 80% chance of rain". The bot no longer records the forecast days each answer showed (`record_forecast`, `forecast_sent`, `shown` through the turn): nothing needs them, and the old record is dropped. - **The bot delivers** (`lib/alerts/notify.AlertDelivery`): it waits on the log in process, sends each unexpired event after the last - id it handled (kept in `bot_state.json` as `alerts_read`) through the Notifier as before (the chats subscribed to its kind, silent - unless the chat turned sound on, the bell, the link as the footer), with the chart drawn from the event's data, uploaded once. Its + id it handled (kept in `bot_state.json` as `alerts_read`, with the log's identity as `alerts_log`, so a log removed or replaced + starts it afresh after that log's newest, with a warning, rather than waiting for the new ids to pass the old) through the + Notifier as before (the chats subscribed to its kind, silent unless the chat turned sound on, the bell, the link as the footer), + with the chart drawn from the event's data, uploaded once. Its first start begins after the newest event; after a gap it skips what expired. The 🔄 under a chart names the event (`al:refresh::`) and replays the chart's `drawn_by` from the log (a chart drawn ahead since the message changed is still sent first); an alert sent before the log, or one dropped from it, draws its type's chart as before. Irrigation alerts are sent by diff --git a/lib/alert_log.py b/lib/alert_log.py index f0709fea..ea18744c 100644 --- a/lib/alert_log.py +++ b/lib/alert_log.py @@ -10,6 +10,8 @@ Kept in its own SQLite file in DATA_DIR (alerts.sqlite), not the readings file: the log exists whatever sources are configured (the pollen and forecast alerts need no readings file), it is written from the event loop in tiny rows while the readings file is written in bulk from worker threads, and it can be looked at or removed on its own. Events older than KEEP_SECONDS are dropped when it opens; the ids carry on. +A new file starts its ids at 1 again, so each file has a random `identity` (kept in its meta table) beside the ids: a reader that kept +the last id it handled keeps the identity with it, and starts afresh when the file is another (lib/alerts/notify.AlertDelivery). A reader in the same process waits for new events with `wait(after)` (an asyncio notification on each append): the bot's delivery today, the MCP listen of step 5.""" @@ -17,6 +19,7 @@ import asyncio import json import logging +import secrets import sqlite3 import threading import time as clock @@ -38,6 +41,7 @@ link TEXT, chart TEXT ); +CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); """ @@ -54,7 +58,9 @@ def __init__(self, path, tz: tzinfo, now=clock.time): self.db.execute("PRAGMA journal_mode=WAL") self.db.executescript(SCHEMA) self.db.execute("DELETE FROM alerts WHERE time < ?", (self.now() - KEEP_SECONDS,)) + self.db.execute("INSERT OR IGNORE INTO meta (key, value) VALUES ('identity', ?)", (secrets.token_hex(8),)) self.db.commit() + self.identity: str = self.db.execute("SELECT value FROM meta WHERE key='identity'").fetchone()[0] self._new = asyncio.Event() def close(self): diff --git a/lib/alerts/forecast.py b/lib/alerts/forecast.py index 209ead51..3cc6f1da 100644 --- a/lib/alerts/forecast.py +++ b/lib/alerts/forecast.py @@ -2,8 +2,10 @@ Each day, the first forecast fetched after 6 am is the baseline for today and tomorrow. Every later fetch is compared with it, day by day, and a day that changed substantially is an alert, saying what changed: - - the chance of rain crosses 50% (it was under and is now at or over, or the other way round); the chance of at least 1 mm, or, for a - day with only Open-Meteo's older "chance of rain" figure on either side, that one; + - the chance of rain becomes likely (it was under 50% and is now 50% or over) or unlikely (it was 50% or over and is now 30% or + under); the chance of at least 1 mm, or, for a day with only Open-Meteo's older "chance of rain" figure on either side, that one. + The band between keeps a chance that hovers around 50% (the ensemble's, rounded to 5%, moving 45 / 50 / 45 between model runs) from + alerting likely, unlikely, likely on every refresh; - the highest temperature moves by more than 2 degrees. The forecast alerted on becomes that day's new baseline, so the same revision never repeats and a further one does. The forecast only refreshes from 6 am to 6 pm, so that is when this can fire. Each alert is an event in the alert log (lib/alert_log.py), news until the @@ -19,7 +21,8 @@ log = logging.getLogger(__name__) -RAIN_FROM_PCT = 50 +RAIN_FROM_PCT = 50 # rain is likely from this chance ... +DRY_BELOW_PCT = 30 # ... and unlikely again only at or under this one (from likely) TEMP_CHANGE_C = 2.0 BASELINE_HOUR = 6 # the first forecast fetched from this hour (local) is the day's baseline DAYS = 2 # today and tomorrow @@ -37,8 +40,11 @@ def changes(old: dict, new: dict) -> list[str]: out.append(f"the high is now {hot_after:.0f}°C (was {hot_before:.0f}°C)") key = _chance_key(old, new) before, after = old.get(key), new.get(key) - if before is not None and after is not None and (before < RAIN_FROM_PCT) != (after < RAIN_FROM_PCT): - out.append(f"rain is now {'likely' if after >= RAIN_FROM_PCT else 'unlikely'} ({after}%, was {before}%)") + if before is not None and after is not None: + if before < RAIN_FROM_PCT <= after: + out.append(f"rain is now likely ({after}%, was {before}%)") + elif before >= RAIN_FROM_PCT and after <= DRY_BELOW_PCT: + out.append(f"rain is now unlikely ({after}%, was {before}%)") return out diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index fe5b6f12..db3d22d9 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -48,11 +48,13 @@ def __init__(self, path): self.monitor: dict = data.get("monitor", {}) # the irrigation controller's (until it is a server of its own) self.charts: dict[str, str] = data.get("charts", {}) # the question behind each chart sent, for its period buttons self.read: int | None = data.get("alerts_read") # the id of the last alert in the log the bot handled (AlertDelivery) + self.read_log: str | None = data.get("alerts_log") # ... and that log's identity (AlertLog.identity): ids start again in a new one def save(self): """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" write(self.path, {"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts, - **({"alerts_read": self.read} if self.read is not None else {})}) + **({"alerts_read": self.read} if self.read is not None else {}), + **({"alerts_log": self.read_log} if self.read_log is not None else {})}) def add_chat(self, chat_id: int, title: str): """A message from this chat (or the bot added to it): known from now on, and back if it was gone.""" @@ -252,19 +254,29 @@ class AlertDelivery: Notifier does, to the chats subscribed to its kind, with its link, its chart drawn from the event's chart data (and the 🔄 that replays the chart's drawn_by) or the text alone. The id of the last event handled is kept in bot_state.json (AlertState.read), so a restart resumes after it; the events that expired meanwhile are skipped (the morning's rain is not news by the afternoon). With no id - kept (the first start) it begins after the newest event: what came before is not news either.""" + kept (the first start) it begins after the newest event: what came before is not news either. So does a start on another log than the + one the id is from (alerts.sqlite removed or replaced: its ids start again at 1, and waiting for them to pass the old id would send + nothing for as long), noticed by the log's identity kept with the id, or by the id being past the log's newest.""" def __init__(self, log, notify: "Notifier", state: AlertState, tz): self.log, self.notify, self.state, self.tz = log, notify, state, tz + newest = self.log.last_id() if self.state.read is None: - self._handled(self.log.last_id()) + self._handled(newest) + elif (self.state.read_log not in (None, self.log.identity)) or self.state.read > newest: + logging.getLogger(__name__).warning( # (`log` here is the alert log) + "Alerts: the alert log is not the one the last alert delivered (%s) is from; starting after its newest (%s)", + self.state.read, newest) + self._handled(newest) + elif self.state.read_log is None: # (kept before the log had an identity: this one) + self._handled(self.state.read) @property def last(self) -> int: return self.state.read or 0 def _handled(self, event_id: int): - self.state.read = event_id + self.state.read, self.state.read_log = event_id, self.log.identity try: self.state.save() except Exception as e: # (the next one saved covers it; at worst a restart sends it again) diff --git a/lib/service/about.py b/lib/service/about.py index 4baa7c12..21c3ec3f 100644 --- a/lib/service/about.py +++ b/lib/service/about.py @@ -15,7 +15,7 @@ from datetime import datetime, tzinfo -from ..alerts.forecast import BASELINE_HOUR, RAIN_FROM_PCT, TEMP_CHANGE_C +from ..alerts.forecast import BASELINE_HOUR, DRY_BELOW_PCT, RAIN_FROM_PCT, TEMP_CHANGE_C from ..alerts.particulates import CHECK_SECONDS, MASK_PM10, MASK_PM25, SAFE_PM10, SAFE_PM25 from ..alerts.pollen_and_asthma import ALERT_FROM, WARN_FROM from ..alerts.rules import CONFIRM_READINGS @@ -184,9 +184,11 @@ def alert_rules() -> dict[str, tuple[str, dict]]: f"{_clock(*ALERT_FROM)} while it stays there, and again when it rises. October to December only.", {"from_level": LEVELS[WARN_FROM]}), "forecast": (f"Today's or tomorrow's forecast revised from the first one fetched after {_clock(BASELINE_HOUR)} that day: its highest " - f"temperature by more than {TEMP_CHANGE_C:g}°C, or the chance of at least 1 mm of rain crossing {RAIN_FROM_PCT}%. The " - "forecast alerted on is the one later forecasts are compared with.", - {"max_change_c": TEMP_CHANGE_C, "rain_crossing_pct": RAIN_FROM_PCT, "baseline_from": f"{BASELINE_HOUR:02d}:00"}), + f"temperature by more than {TEMP_CHANGE_C:g}°C, or the chance of at least 1 mm of rain rising from under {RAIN_FROM_PCT}% " + f"to {RAIN_FROM_PCT}% or more (rain likely), or falling from {RAIN_FROM_PCT}% or more to {DRY_BELOW_PCT}% or less (rain " + "unlikely). The forecast alerted on is the one later forecasts are compared with.", + {"max_change_c": TEMP_CHANGE_C, "rain_likely_from_pct": RAIN_FROM_PCT, "rain_unlikely_at_pct": DRY_BELOW_PCT, + "baseline_from": f"{BASELINE_HOUR:02d}:00"}), } diff --git a/tests/test_alert_log.py b/tests/test_alert_log.py index 86cc2d04..0bd6b1b0 100644 --- a/tests/test_alert_log.py +++ b/tests/test_alert_log.py @@ -212,6 +212,53 @@ async def test_the_first_start_begins_after_the_newest_event(tmp_path): assert telegram.sent == [] +async def test_a_removed_log_is_noticed_and_delivery_starts_again_from_the_new_one(tmp_path, caplog): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + for i in range(5): + log.append("rain", f"old {i}", "t") + await d.deliver_new() + assert state.read == 5 + log.close() + (tmp_path / "alerts.sqlite").unlink() # removed while the bot was down; bot_state.json kept + log = new_log(tmp_path) + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 0 and "not the one" in caplog.text + for i in range(3): + log.append("rain", f"new {i}", "t") + assert await restarted.deliver_new() == 3 + assert await log.wait(restarted.last - 1, timeout=0.1) + + +async def test_a_replaced_log_already_past_the_last_id_is_noticed_by_its_identity(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("rain", "old", "t") + await d.deliver_new() + log.close() + (tmp_path / "alerts.sqlite").unlink() + log = new_log(tmp_path) + for i in range(3): + log.append("rain", f"before the restart {i}", "t") # another file, its ids already past the old one + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 3 # its own newest: what came before is not news + log.append("rain", "after", "t") + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["old", "after"] + assert AlertState(state.path).read_log == log.identity == new_log(tmp_path).identity # kept, and the file's own across opens + + +async def test_a_kept_id_from_before_the_log_had_an_identity_is_resumed_from(tmp_path): + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + log.append("rain", "first", "t") + await d.deliver_new() + state.read_log = None + state.save() # as step 4 first kept it: the id alone + log.append("rain", "second", "t") + restarted = AlertDelivery(log, Notifier(telegram, AlertState(state.path)), AlertState(state.path), TZ) + assert restarted.last == 1 + await restarted.deliver_new() + assert [text for _, text, _, _ in telegram.sent] == ["first", "second"] + + async def test_the_delivery_runs_on_the_logs_notification(tmp_path): d, log, state, telegram = delivery(tmp_path, chats=(1,)) task = asyncio.create_task(d.run()) diff --git a/tests/test_forecast_alert.py b/tests/test_forecast_alert.py index 09e984c3..90605d0a 100644 --- a/tests/test_forecast_alert.py +++ b/tests/test_forecast_alert.py @@ -1,5 +1,6 @@ """The forecast alert, station-wide (docs/mcp-service.md 3.6): today's and tomorrow's forecast against the day's baseline (the first one -fetched from 6 am), an alert when the high moves by more than 2°C or the chance of rain crosses 50%, the alerted forecast the new baseline.""" +fetched from 6 am), an alert when the high moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or +less), the alerted forecast the new baseline.""" from datetime import date, datetime, time as dtime, timedelta @@ -43,11 +44,13 @@ def setup(tmp_path, days, **kw): return ForecastMonitor(forecast, store, log), forecast, Texts(log) -def test_substantial_means_rain_crossing_50_or_a_max_temperature_over_2_degrees_different(): +def test_substantial_means_rain_becoming_likely_or_unlikely_or_a_max_temperature_over_2_degrees_different(): base = day(0, max_c=20.0, pct=95) assert revised(base, day(0, max_c=20.0, pct=10)) and revised(day(0, pct=10), day(0, pct=80)) - assert revised(base, day(0, pct=49)) and revised(day(0, pct=49), day(0, pct=50)) # across 50, however little - assert not revised(base, day(0, pct=50)) and not revised(day(0, pct=20), day(0, pct=49)) # on one side of it + assert revised(day(0, pct=49), day(0, pct=50)) # likely: up past 50, however little + assert revised(base, day(0, pct=30)) and not revised(base, day(0, pct=31)) # unlikely: down to 30 or less + assert not revised(base, day(0, pct=49)) and not revised(day(0, pct=50), day(0, pct=45)) # into the band between: nothing + assert not revised(base, day(0, pct=50)) and not revised(day(0, pct=20), day(0, pct=49)) # on one side of 50 assert not revised(day(0, max_c=20.0), day(0, max_c=22.0)) and not revised(day(0, max_c=20.0), day(0, max_c=18.0)) assert revised(day(0, max_c=20.0), day(0, max_c=22.1)) and revised(day(0, max_c=20.0), day(0, max_c=17.9)) assert not revised(day(0, max_c=None, pct=None), day(0, max_c=25.0, pct=90)) # nothing to compare @@ -107,11 +110,26 @@ async def test_a_move_of_the_high_over_2_degrees_alerts_with_what_changed_and_be async def test_rain_crossing_50_alerts_each_way_and_today_and_tomorrow_are_separate_alerts(tmp_path): mon, forecast, sent = setup(tmp_path, [day(0, pct=40), day(1, pct=60), day(2)], hour=7) await mon.check() - forecast.fetch([day(0, pct=55), day(1, pct=45), day(2, pct=90)], hour=8) # both cross; the day after tomorrow is not watched + forecast.fetch([day(0, pct=55), day(1, pct=30), day(2, pct=90)], hour=8) # both cross; the day after tomorrow is not watched await mon.check() assert [t.split(":")[0] for t in sent] == ["🔄 The forecast for today has changed", "🔄 The forecast for tomorrow has changed"] - assert "rain is now likely (55%, was 40%)" in sent[0] and "rain is now unlikely (45%, was 60%)" in sent[1] - forecast.fetch([day(0, pct=60), day(1, pct=40), day(2, pct=90)], hour=9) # further, on the same side: nothing + assert "rain is now likely (55%, was 40%)" in sent[0] and "rain is now unlikely (30%, was 60%)" in sent[1] + forecast.fetch([day(0, pct=60), day(1, pct=20), day(2, pct=90)], hour=9) # further, on the same side: nothing + await mon.check() + assert len(sent) == 2 + + +async def test_a_chance_hovering_around_50_alerts_once_not_on_every_revision(tmp_path): + mon, forecast, sent = setup(tmp_path, [day(0), day(1, pct=45)], hour=6, minute=15) + await mon.check() # the baseline: tomorrow 45% + for hour, pct in zip(range(7, 12), (50, 45, 50, 45, 55)): # the ensemble's chance, rounded to 5%, between model runs + forecast.fetch([day(0), day(1, pct=pct)], hour=hour) + await mon.check() + assert len(sent) == 1 and "rain is now likely (50%, was 45%)" in sent[0] + forecast.fetch([day(0), day(1, pct=30)], hour=12) # well down: unlikely, told once + await mon.check() + assert len(sent) == 2 and "rain is now unlikely (30%, was 50%)" in sent[1] + forecast.fetch([day(0), day(1, pct=45)], hour=13) # back into the band: nothing await mon.check() assert len(sent) == 2 From 63238ced4d663da5893a5f9ba78edcf5ec87e663 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:50:07 +0000 Subject: [PATCH 060/125] The suite at any time: ECOBOT_CLOCK, pinned archives; the Wind gauge's Max counts the gust now Tests that failed just after midnight, late at night or on the 1st, each reproduced with the clock pinned: - days and relate: "this morning" at 12:05am is ahead, and is refused as in the future pointing to forecast (right). The tests now ask at a pinned 2:05pm, and a pinned 12:05am case asserts the forecast refusal. - outlook: before 3am the last 3 hours are yesterday's, which the archive holds, so a read without fetching is made from them (with the staleness warning), not refused. Pinned at 2:05pm; a pinned 12:05am case asserts that read. - current (a code bug): the Wind gauge's Max, the highest gust, counted in the live wind speed, so before today's row had a gust (every night after midnight; the month on the 1st, the year on 1 Jan) the highest gust was the speed now (14 km/h while it gusted 31), and at any time the gust now could beat it. It counts the live gust (Gauge.counted), as wind_gust's figures did. A pinned 12:05am case (and 1 Jan) covers it; the switch's dashboard hash changes for that tile alone (29 -> 31 km/h). - bench_storage: pinned at 2:05pm and 11:59pm (the KeyError fixed in 6745cbd fails there without the fix). - On the 1st or 1 Jan, and in 2027: tests that assumed a year with days in it, a wet day in every week, "this year" with a whole day, the year 2026, a fixed holiday window, at most 15 holidays a year or 146 half hours in 3 days (the 25-hour day) now pin daytime_archive or allow for it. tests/clocks.py: pin(monkeypatch, when) fixes the clock for one test; conftest's pinned_archive(when) and daytime_archive give the archive as it was then, built once for the code and kept. ECOBOT_CLOCK="2026-11-11 00:05" runs the whole suite from that time (DEVELOPMENT.md); it passes at 00:05, 23:55, 23:59, 00:05 on the 1st and on 1 Jan, and across April's clock change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 10 +++ lib/ecowitt/dashboard.py | 5 +- lib/service/current.py | 8 +- tests/clocks.py | 139 ++++++++++++++++++++++++++++++++++ tests/conftest.py | 42 ++++++++-- tests/evalworld.py | 4 +- tests/service_switch.json | 2 +- tests/test_bench_storage.py | 17 ++++- tests/test_dashboard.py | 4 +- tests/test_days.py | 9 ++- tests/test_hass_api.py | 2 +- tests/test_service_current.py | 31 ++++++-- tests/test_service_days.py | 29 +++++-- tests/test_service_outlook.py | 35 ++++++++- tests/test_service_relate.py | 9 ++- tests/test_service_scan.py | 4 +- tests/test_service_summary.py | 12 ++- tests/test_service_switch.py | 4 +- 18 files changed, 319 insertions(+), 47 deletions(-) create mode 100644 tests/clocks.py diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 8a2fc025..17c4728b 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -14,6 +14,16 @@ named for the hour and for the code that shapes it, so a change to `lib/storage` that pays about 15 s more. Tests of the archive itself use a station a few weeks old (`ecowitt_transport(history_days=...)`); the storage's reader and writer threads, and `asyncio.to_thread`, run inline in tests (the `threaded_storage` fixture puts the threads back for the tests of them). +The clock: most tests run at the real time, so some answers (just after midnight, late in the evening, on the 1st of a month or of the year) +are only tested when the suite happens to run then. To run the whole suite at such a time on purpose, set `ECOBOT_CLOCK` to a Melbourne +wall-clock time: the clock starts there and runs on, for lib/ and the tests, the archive included (`tests/clocks.py`): +``` +ECOBOT_CLOCK="2026-11-11 00:05" python -m pytest -q # also 23:55 or 23:59, and 00:05 on the 1st of a month and on 1 Jan +``` +A test whose answer depends on the time of day or the date pins its own clock instead: `daytime_archive` (2:05pm on Tue 10 Nov 2026) or +`pinned_archive(when)` with `clocks.pin(monkeypatch, when)`, the fake station's archive as it was then, built once for the code that shapes +it and kept (`ecobot-archive-pinned-*.sqlite`); a tool's answer to words alone can take `Context(clock=...)` (`clocks.yesterday_at`). + The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build the same Python into `.venv` with uv (`.claude/hooks/session-start.sh`). ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) diff --git a/lib/ecowitt/dashboard.py b/lib/ecowitt/dashboard.py index 004e5a2a..e6256c02 100644 --- a/lib/ecowitt/dashboard.py +++ b/lib/ecowitt/dashboard.py @@ -35,6 +35,8 @@ class Gauge: lowest: str | None = None # ... whose lowest is its Min (none: no Min column) decimals: int = 1 total: bool = False # rain: the Total column, the sum of the days' figures (its Max is the wettest day's) + counted: tuple[str, str] | None = None # the live reading counted into its Max and Min, when not `live` (wind: the gust, as its + # Max is the highest gust: the speed now would stand in for it before a day row has one) @property def reading(self) -> str: @@ -51,7 +53,8 @@ def reading(self) -> str: "pressure_max", "pressure_min"), Gauge("Dew point", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("outdoor", "dew_point"), "dew_point_max", "dew_point_min"), Gauge("Feels like", "°C", "thermometer", -40, 60, COLD_TO_HOT, DEGREES, ("outdoor", "feels_like"), "feels_like_max", "feels_like_min"), - Gauge("Wind", "km/h", "dial", 0, 100, WIND, (0, 20, 40, 60, 80, 100), ("wind", "wind_speed"), "wind_gust", None, 0), + Gauge("Wind", "km/h", "dial", 0, 100, WIND, (0, 20, 40, 60, 80, 100), ("wind", "wind_speed"), "wind_gust", None, 0, + counted=("wind", "wind_gust")), Gauge("Rain", "mm", "beaker", 0, 100, WATER, (100, 80, 60, 40, 20, 0), ("rainfall", "daily"), "rain", None, 1, True), Gauge("Rain rate", "mm/h", "dial", 0, 50, WATER, (0, 10, 20, 30, 40, 50), ("rainfall", "rain_rate"), "rain_rate_max"), Gauge("Solar radiation", "W/m²", "dial", 0, 1500, SUN, (0, 300, 600, 900, 1200, 1500), ("solar_and_uvi", "solar"), "solar_max", None, 0), diff --git a/lib/service/current.py b/lib/service/current.py index 08a759ba..d05a3cc9 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -283,7 +283,7 @@ def gauge_of(name: str) -> Gauge | None: """The gauge a reading's context comes from: the one whose live reading it is (rainfall.rain: the Rain gauge's "daily"); the gusts get the Wind gauge's highest, with the live gust counted in.""" if name == "wind.wind_gust": - return replace(next(g for g in GAUGES if g.live == ("wind", "wind_speed")), live=("wind", "wind_gust")) + return replace(next(g for g in GAUGES if g.live == ("wind", "wind_speed")), live=("wind", "wind_gust"), counted=None) return next((g for g in GAUGES if g.reading == name), None) @@ -367,9 +367,10 @@ def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz return {} days, unit = periods_of(today), gauge.unit now = Live(live, gauge) + counted = Live(live, replace(gauge, live=gauge.counted)) if gauge.counted else now # (wind: the gust now, not the speed) out = {} for row, key in PERIODS: - got = figures(gauge, values, days[row], None if gauge.total else now.value) + got = figures(gauge, values, days[row], None if gauge.total else counted.value) if gauge.total and row == "Daily" and now.value is not None: # today's rain is the gauge's own reading (as the gauge shows it) got = (None, now.value) entry: dict = {} @@ -385,7 +386,8 @@ def context_of(name: str, live: dict, values: dict, times: dict, today: date, tz pairs = [(high, gauge.highest, got[0])] + ([("low", gauge.lowest, got[1])] if gauge.lowest else []) for key_, figure, value in pairs: if value is not None: - entry.update(_extreme(key_, value, figure, days[row], values, times, now, gauge, unit, tz, dated=row != "Daily")) + entry.update(_extreme(key_, value, figure, days[row], values, times, counted, gauge, unit, tz, + dated=row != "Daily")) if entry: out[key] = entry return out diff --git a/tests/clocks.py b/tests/clocks.py new file mode 100644 index 00000000..80d187c4 --- /dev/null +++ b/tests/clocks.py @@ -0,0 +1,139 @@ +"""The clock in tests: pinned for one test (pin), or moved for the whole suite (ECOBOT_CLOCK). + +pin(monkeypatch, when) fixes the clock at `when` (an aware datetime) for one test, as tests/evalworld.py fixes it for the evals: every +module of lib/ is imported, then every name in a module of lib/, tests/ and scripts/ bound to datetime or date is a class whose now() and today() are `when`, +time.time() returns it, and so does the archive's epoch_now. With conftest's pinned_archive(when), the fake station's archive as it was +then: a test of something that depends on the time of day (just after midnight, the evening) runs at that time whenever it is run. + +The whole suite at another time of day: ECOBOT_CLOCK="2026-11-11 00:05" (a Melbourne wall-clock time) makes the clock start there, +and run on from it, for everything the suite and lib/ read, so a test that only fails just after midnight (or late at night, or on the +1st of a month) can be run at that time on purpose: + + ECOBOT_CLOCK="2026-11-11 00:05" python -m pytest -q + +conftest installs it before anything of lib/ is imported (install()): time.time() is moved by a fixed offset (it still ticks), and +datetime.datetime and datetime.date, in the datetime module itself, become subclasses whose now() and today() read it, so every later +`from datetime import datetime` (lib/, tests/, a default argument `clock=time.time`) gets the moved clock. The tests that fix the clock +themselves (tests/evalworld.py, tests/test_service_switch.py) still do: they rebind these classes as they would the real ones. +Without ECOBOT_CLOCK nothing is changed.""" + +import datetime as _dt +import importlib +import os +import pkgutil +import sys +import time as _time +from zoneinfo import ZoneInfo + +_REAL_TIME = _time.time +_RealDatetime, _RealDate = _dt.datetime, _dt.date +OFFSET = 0.0 +_PINNED = 0.0 +DAYTIME = _RealDatetime(2026, 11, 10, 14, 5, tzinfo=ZoneInfo("Australia/Melbourne")) # (conftest's daytime_archive) +_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +_OURS = tuple(os.path.join(_ROOT, d) + os.sep for d in ("lib", "tests", "scripts")) # (a test module too, whatever pytest names it) + + +def _now() -> float: + return _REAL_TIME() + OFFSET + + +class _DatetimeType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _RealDatetime) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _RealDatetime) + + +class SweepDatetime(_RealDatetime, metaclass=_DatetimeType): + @classmethod + def now(cls, tz=None): + return _RealDatetime.fromtimestamp(_now(), tz) + + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_now()) + + @classmethod + def utcnow(cls): + return _RealDatetime.fromtimestamp(_now(), _dt.UTC).replace(tzinfo=None) + + +class _DateType(type): + def __instancecheck__(cls, obj): + return isinstance(obj, _RealDate) + + def __subclasscheck__(cls, sub): + return issubclass(sub, _RealDate) + + +class SweepDate(_RealDate, metaclass=_DateType): + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_now()).date() + + +def install() -> str | None: + """Move the clock to ECOBOT_CLOCK (local wall-clock time, in the process's zone, Melbourne), if it is set; the text it was set to.""" + global OFFSET + text = os.environ.get("ECOBOT_CLOCK") + if not text: + return None + _time.tzset() + start = _RealDatetime.fromisoformat(text) + if start.tzinfo is None: + start = start.astimezone() # (the process's zone: conftest sets TZ first) + OFFSET = start.timestamp() - _REAL_TIME() + _time.time = _now + _dt.datetime, _dt.date = SweepDatetime, SweepDate + return text + + +class PinnedDatetime(SweepDatetime): + """datetime whose now() and today() are the pinned time (anything else, and its instances, are the real datetime's).""" + + @classmethod + def now(cls, tz=None): + return _RealDatetime.fromtimestamp(_PINNED, tz) + + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_PINNED) + + @classmethod + def utcnow(cls): + return _RealDatetime.fromtimestamp(_PINNED, _dt.UTC).replace(tzinfo=None) + + +class PinnedDate(SweepDate): + @classmethod + def today(cls): + return _RealDatetime.fromtimestamp(_PINNED).date() + + +def pin(patch, when: _RealDatetime): + """Fix the clock at `when` (aware) in every module of lib/ and tests/, with `patch` (a MonkeyPatch: its undo puts it all back).""" + import lib + for info in pkgutil.walk_packages(lib.__path__, "lib."): + importlib.import_module(info.name) + ts = when.timestamp() + patch.setattr(sys.modules[__name__], "_PINNED", ts) + patch.setattr(_time, "time", lambda: ts) + datetimes, dates = (_RealDatetime, SweepDatetime), (_RealDate, SweepDate) + for name, module in list(sys.modules.items()): + if module is None or module is sys.modules[__name__] or not str(getattr(module, "__file__", None) or "").startswith(_OURS): + continue + for attr, value in list(vars(module).items()): + if any(value is c for c in datetimes): + patch.setattr(module, attr, PinnedDatetime) + elif any(value is c for c in dates): + patch.setattr(module, attr, PinnedDate) + patch.setattr(sys.modules["lib.ecowitt.archive"], "epoch_now", lambda: ts) + + +def yesterday_at(hour: int, minute: int, tz) -> _RealDatetime: + """Yesterday at hour:minute in tz (aware): a fixed time of day that the fake station's archive, built at the real clock, always + holds the day of; for a test whose answer depends on the time of day alone (a tool's Context(clock=...)).""" + day = _RealDatetime.fromtimestamp(_time.time(), tz).date() - _dt.timedelta(days=1) + return _RealDatetime.combine(day, _dt.time(hour, minute), tz) diff --git a/tests/conftest.py b/tests/conftest.py index 0a291375..a5919c15 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) os.environ.setdefault("TZ", "Australia/Melbourne") +from tests import clocks # noqa: E402 (ECOBOT_CLOCK: the whole suite at another time; before anything of lib/ is imported) +CLOCK = clocks.install() import pytest @@ -32,10 +34,34 @@ def alert_state(tmp_path): def archived_cache(tmp_path_factory): """The bot's file (ecobot.sqlite) holding the fake station's whole archive, built once an hour and shared by every worker and run (under pytest's own temp folder, named for the hour and the code that shapes it). Tests copy it (archived_station).""" - import asyncio + from datetime import datetime + moved = "-moved" if CLOCK else "" # (built at a clock ECOBOT_CLOCK moved: never shared with a run at the real one) + return _shared_archive(tmp_path_factory, f"{datetime.now():%Y%m%d%H}{moved}", None) + + +@pytest.fixture(scope="session") +def pinned_archive(tmp_path_factory): + """pinned_archive(when) -> the file holding the fake station's whole archive as it was at `when` (an aware datetime), built with + the clock pinned there (tests/clocks.pin) once for the code that shapes it, and shared by every worker and run after. A test pins + the clock at the same time (clocks.pin) and copies it (archived_station): the station at a fixed time of day, whatever the time.""" + return lambda when: _shared_archive(tmp_path_factory, f"pinned-{when.timestamp():.0f}", when) + + +@pytest.fixture +def daytime_archive(pinned_archive, monkeypatch): + """The fake station's archive at a fixed time, 2:05pm on Tue 10 Nov 2026 (clocks.DAYTIME), the clock pinned there for the test: for + a test whose answer depends on the date or the time of day (a year so far with days in it, this morning over).""" + cache = pinned_archive(clocks.DAYTIME) + clocks.pin(monkeypatch, clocks.DAYTIME) + return cache + + +def _shared_archive(tmp_path_factory, name: str, pinned) -> Path: + """The fake station's whole archive in a file under pytest's own temp folder, named for `name` and the code that shapes it: built by + the first worker that asks (the others wait and find it), at the clock as it is, or pinned at `pinned`.""" + import concurrent.futures import fcntl import hashlib - from datetime import datetime from unittest import mock from lib.ecowitt import Archive, Ecowitt, api, archive @@ -54,14 +80,18 @@ async def build(path): base = tmp_path_factory.getbasetemp() # this run's folder under pytest-of- (a worker's is a folder under that) while not base.parent.name.startswith("pytest-of-"): base = base.parent - shared = base.parent / f"ecobot-archive-{datetime.now():%Y%m%d%H}-{digest}.sqlite" + shared = base.parent / f"ecobot-archive-{name}-{digest}.sqlite" with open(shared.with_suffix(".lock"), "w") as lock: fcntl.flock(lock, fcntl.LOCK_EX) # the first worker builds it; the others wait and find it if not shared.exists(): path = tmp_path_factory.mktemp("archive") - with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ - mock.patch.object(asyncio, "to_thread", _inline): - built = asyncio.run(build(path)) + with pytest.MonkeyPatch.context() as patch: + if pinned is not None: + clocks.pin(patch, pinned) + with mock.patch.object(api, "MIN_GAP_SECONDS", 0), mock.patch.object(archive, "PACE_SECONDS", 0), \ + mock.patch.object(asyncio, "to_thread", _inline): + with concurrent.futures.ThreadPoolExecutor(1) as pool: # (on a thread: an async test may be asking) + built = pool.submit(asyncio.run, build(path)).result() os.replace(built, shared) return shared diff --git a/tests/evalworld.py b/tests/evalworld.py index 0009331d..beb5e3fd 100644 --- a/tests/evalworld.py +++ b/tests/evalworld.py @@ -25,7 +25,7 @@ EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() -class _DatetimeType(type): +class _DatetimeType(type(_dt.datetime)): # (type, unless ECOBOT_CLOCK moved the clock: tests/sweepclock.py) def __instancecheck__(cls, obj): return isinstance(obj, _dt.datetime) @@ -43,7 +43,7 @@ def today(cls): return _dt.datetime.fromtimestamp(EVAL_NOW) -class _DateType(type): +class _DateType(type(_dt.date)): def __instancecheck__(cls, obj): return isinstance(obj, _dt.date) diff --git a/tests/service_switch.json b/tests/service_switch.json index 875f990d..c63b1438 100644 --- a/tests/service_switch.json +++ b/tests/service_switch.json @@ -1224,7 +1224,7 @@ "dashboard": { "charts": [], "gauges": [ - "2035f1d261cdf408" + "c1cb0f15c34f5e53" ], "history": "Weather station dashboard, Tue 10 Nov 2026 2:05pm", "sent": [ diff --git a/tests/test_bench_storage.py b/tests/test_bench_storage.py index cd2b62bb..272020be 100644 --- a/tests/test_bench_storage.py +++ b/tests/test_bench_storage.py @@ -1,16 +1,28 @@ """scripts/bench_storage.py: the benchmark of typical requests on a copy of the bot's file.""" import shutil import sys +from datetime import datetime from pathlib import Path +import pytest + +from tests.clocks import pin +from tests.fakes import TZ + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import bench_storage # noqa: E402 -async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_network(tmp_path, archived_cache, monkeypatch): +@pytest.mark.parametrize("when", [datetime(2026, 11, 10, 14, 5, tzinfo=TZ), datetime(2026, 11, 10, 23, 59, tzinfo=TZ)], + ids=["2:05pm", "11:59pm"]) +async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_network(tmp_path, pinned_archive, monkeypatch, when): + """At 11:59pm its "Temperature chart, 3 hours" has the day row's figures but no readings in the window: summary's chart failed on + it (a KeyError) until the reading was left out of the chart.""" + cache = pinned_archive(when) + pin(monkeypatch, when) data = tmp_path / "data" data.mkdir() - shutil.copy(archived_cache, data / "ecobot.sqlite") + shutil.copy(cache, data / "ecobot.sqlite") before = (data / "ecobot.sqlite").read_bytes() copy = tmp_path / "copy" copy.mkdir() @@ -18,7 +30,6 @@ async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_ne for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): # (the benchmark sets them where they are missing) monkeypatch.setenv(name, "t") monkeypatch.setenv("DATA_DIR", str(copy)) - from tests.fakes import TZ rows = await bench_storage.bench(copy, 1, TZ) labels = [r[0] for r in rows] assert "Temperature chart, 1Y" in labels and "/dashboard" in labels and len(rows) >= 12 diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 1bd32bee..83b6b4b4 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -78,8 +78,8 @@ async def current_of(eco, args: dict) -> dict: return json.loads(await cur.CurrentTool(Context(eco=eco)).tool().call(args, None)) -async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache(tmp_path, archived_cache): - eco, _ = await archived_station(tmp_path, archived_cache) +async def test_the_station_gives_its_gauges_from_the_live_reading_and_the_cache(tmp_path, daytime_archive): + eco, _ = await archived_station(tmp_path, daytime_archive) sheet = gauge_sheet.sheet(await current_of(eco, gauge_sheet.call())) temperature = next(t for t in sheet.tiles if t.title == "Temperature") assert temperature.value == 12.3 # the fake station's live reading diff --git a/tests/test_days.py b/tests/test_days.py index 642fa5fe..96bd8400 100644 --- a/tests/test_days.py +++ b/tests/test_days.py @@ -186,10 +186,13 @@ async def test_a_tie_is_not_reported_as_a_hotter_day(station): async def test_public_holidays_are_the_local_ones_not_the_models_guess(station): import holidays eco, _ = station - out = await ask(eco, start_date="2025-11-01", end_date="2026-02-28", only="public_holiday", sort_by="temp_max", limit=20) + today = datetime.now(TZ).date() + year = today.year - (1 if today >= today.replace(month=3, day=1) else 2) # the last November to February that is over (and held) + first, last = datetime(year, 11, 1).date(), datetime(year + 1, 2, 28).date() + out = await ask(eco, start_date=str(first), end_date=str(last), only="public_holiday", sort_by="temp_max", limit=20) vic = holidays.country_holidays("AU", subdiv="VIC") - expected = {d for d in (datetime(2025, 11, 1).date() + timedelta(days=k) for k in range(120)) if d in vic} - assert out["days_checked"] == out["matching_days"] == len(expected) and len(expected) == 5 # Cup Day, Christmas, Boxing Day, New Year, Australia Day + expected = {d for d in (first + timedelta(days=k) for k in range((last - first).days + 1)) if d in vic} + assert out["days_checked"] == out["matching_days"] == len(expected) and len(expected) >= 5 # Cup Day, Christmas, Boxing Day, New Year, Australia Day (and a day in lieu) assert {r["date"] for r in out["days"]} == {label(d) for d in expected} names = {r["holiday"] for r in out["days"]} assert {"Melbourne Cup Day", "Christmas Day", "Boxing Day", "New Year's Day", "Australia Day"} <= names diff --git a/tests/test_hass_api.py b/tests/test_hass_api.py index 2d32ab95..fe9c0463 100644 --- a/tests/test_hass_api.py +++ b/tests/test_hass_api.py @@ -85,7 +85,7 @@ async def test_a_history_is_cut_in_the_clouds_buckets_and_asks_home_assistant_a_ now = local_now() data = await api.history("x", "30min", now - timedelta(days=3), now, "outdoor,wind") stamps = [int(t) for t in data["outdoor"]["temperature"]["list"]] - assert stamps == sorted(stamps) and all(t % 1800 == 0 for t in stamps) and 140 <= len(stamps) <= 146 # three days of half hours + assert stamps == sorted(stamps) and all(t % 1800 == 0 for t in stamps) and 140 <= len(stamps) <= 148 # three days of half hours (a 25-hour day among them in April) assert {"temperature", "temperature_low", "temperature_high", "humidity", "dew_point"} <= set(data["outdoor"]) and set(data) == {"outdoor", "wind"} asked = [c for c in fake.calls if c["path"].startswith("/api/history")] assert 3 <= len(asked) <= 5 and all("sensor.ws2900_rain_rate" not in c["filter_entity_id"] for c in asked) # only the groups asked for diff --git a/tests/test_service_current.py b/tests/test_service_current.py index ca07e7f3..0c25b8e9 100644 --- a/tests/test_service_current.py +++ b/tests/test_service_current.py @@ -18,6 +18,7 @@ from lib.service.current import CurrentTool, heading from lib.service.names import AIR_DEVICE, STATION, Catalogue from lib.timeutil import clock_text, to_local +from tests.clocks import pin from tests.fakes import TZ, air_transport, archived_station, config from tests import old_tools @@ -166,8 +167,8 @@ async def test_named_readings_alone_each_once_in_the_order_named(tmp_path, archi await close(tool) -async def test_a_reading_named_that_isnt_being_read_now_is_missing(tmp_path, archived_cache): - tool, station, _ = await world(tmp_path, archived_cache, live(time.time(), **{"indoor.temperature": None})) +async def test_a_reading_named_that_isnt_being_read_now_is_missing(tmp_path, daytime_archive): + tool, station, _ = await world(tmp_path, daytime_archive, live(time.time(), **{"indoor.temperature": None})) got = await call(tool, readings=["indoor temperature", "pressure", "piezo rain"]) assert got["missing"] == ["indoor.temperature", "rainfall_piezo.rain"] and list(got["sensors"]) == ["pressure"] with_context = await call(tool, readings=["indoor temperature"], context=True) # a gauge with no reading now: its figures, dimmed @@ -258,16 +259,16 @@ async def gauge_rows(eco, data: dict) -> dict: values, _ = await eco.storage.read(day_values_on, eco.mac, names, days["Yearly"]) out = {} for g in GAUGES: - now = live_value(data, g.live) + now = live_value(data, g.counted or g.live) out[g.title] = {row: figures(g, values, days[row], None if g.total else now) for row in PERIODS} if g.total and now is not None: out[g.title]["Daily"] = (None, now) return out -async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, archived_cache): +async def test_context_is_the_gauges_figures_with_when_each_happened(tmp_path, daytime_archive): data = live(time.time(), **DAY) - tool, _, _ = await world(tmp_path, archived_cache, data) + tool, _, _ = await world(tmp_path, daytime_archive, data) # (a fixed day: a year so far with summer in it, a month of days) got = await call(tool, context=True) tiles = await gauge_rows(tool.ctx.eco, data) s = got["sensors"] @@ -332,8 +333,24 @@ async def no_air(*a, **k): await close(tool) -async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, archived_cache): - tool, station, _ = await world(tmp_path, archived_cache) +@pytest.mark.parametrize("when", [datetime(2026, 11, 11, 0, 5, tzinfo=TZ), datetime(2027, 1, 1, 0, 5, tzinfo=TZ)], + ids=["12:05am", "12:05am on 1 Jan"]) +async def test_just_after_midnight_the_highest_gust_is_the_gust_now_not_the_wind_speed(tmp_path, pinned_archive, monkeypatch, when): + """Before today's row has a gust (and on 1 Jan, before any day of the year has), the Wind gauge's Max, its highest gust, was the + live wind speed counted in (14 km/h while it gusted 31): it is the live gust, as wind_gust's own figures are.""" + cache = pinned_archive(when) + pin(monkeypatch, when) + tool, _, _ = await world(tmp_path, cache, live(time.time(), **DAY)) # (the speed now 14.0 km/h, the gust 31.0) + s = (await call(tool, readings=["wind speed", "wind gust"], context=True))["sensors"]["wind"] + rows = ("today", "month", "year") if when.month == 1 else ("today",) + for key in rows: + assert s["wind_speed"][key]["high_gust"] == s["wind_gust"][key]["high"] == 31.0, key + assert s["wind_speed"][key]["high_gust_when"] == f"at {clock_text(when, whole_hours=True)}" + await close(tool) + + +async def test_a_high_or_low_is_the_day_rows_with_its_day_or_the_live_reading_when_it_beats_them(tmp_path, daytime_archive): + tool, station, _ = await world(tmp_path, daytime_archive) got = await call(tool, readings=["outdoor temperature"], context=True) year = got["sensors"]["outdoor"]["temperature"]["year"] on = datetime.strptime(year["high_date"], "%a %d %b %Y").date() diff --git a/tests/test_service_days.py b/tests/test_service_days.py index 9040c199..0f9686f9 100644 --- a/tests/test_service_days.py +++ b/tests/test_service_days.py @@ -3,6 +3,7 @@ (which it replaces) and lib/report.py's days lookup (whose words it keeps), on the fake station's archive with an air sensor added.""" import copy +import dataclasses import json import shutil from datetime import date, datetime, time, timedelta @@ -21,6 +22,7 @@ from lib.storage.catalogue import CLOUD from lib.timeutil import day_bounds, day_text, local_epoch, now_local from lib.tools import Turn +from tests.clocks import yesterday_at from tests.fakes import TZ, archived_station, rain_day, temp from tests.test_chart_json import errors as schema_errors @@ -247,8 +249,6 @@ async def test_a_call_it_cant_use_is_refused_with_what_to_send_instead(world): hours = await ask(world, hours="dawn") assert "isn't a part of the day" in hours["error"] or "not a part of the day" in hours["error"] assert "night (22:00-06:00)" in hours["hours"] - for words in ("today", "last 5 hours", "this morning"): # whole days only: today isn't over - assert "use summary or readings" in (await ask(world, period=words))["error"], words assert "use forecast" in (await ask(world, period="next week"))["error"] forms = await ask(world, period="the other week") assert "isn't a period" in forms["error"] and "on record, all time, ever (from the first reading held)" in forms["forms"] @@ -260,6 +260,23 @@ async def test_a_call_it_cant_use_is_refused_with_what_to_send_instead(world): assert "this service has no air sensor" in refused["error"] +async def test_a_part_of_today_is_refused_pointing_to_the_tools_that_read_one(world): + """Whole days only: today isn't over. At 2:05pm each part of today asked for points to summary or readings.""" + ctx = dataclasses.replace(world, clock=yesterday_at(14, 5, TZ).timestamp) + for words in ("today", "last 5 hours", "this morning"): + assert "use summary or readings" in (await ask(ctx, period=words))["error"], words + + +async def test_just_after_midnight_this_morning_is_still_ahead_and_points_to_forecast(world): + """At 12:05am "today" and "last 5 hours" still point to summary or readings, but this morning (6am to 12pm) hasn't begun: it is + refused as in the future, pointing to forecast, with the time now.""" + ctx = dataclasses.replace(world, clock=yesterday_at(0, 5, TZ).timestamp) + for words in ("today", "last 5 hours"): + assert "use summary or readings" in (await ask(ctx, period=words))["error"], words + error = (await ask(ctx, period="this morning"))["error"] + assert "'this morning' is in the future" in error and "use forecast" in error and error.endswith("12:05am.") + + async def test_a_period_before_the_record_says_where_the_record_starts(world): first = await world.storage.read(lambda r: min(date.fromisoformat(d) for (d,) in r.db.execute("SELECT day FROM air_day"))) out = await ask(world, start=str(first - timedelta(days=30)), end=str(first - timedelta(days=1)), sort_by="pm2_5_max") @@ -273,7 +290,7 @@ async def test_the_holiday_and_weekend_filter_is_the_models_own(world): days = [datetime.strptime(r["date"], "%a %d %b %Y").date() for r in out["days"]] assert out["days_checked"] == 16 and all(d.weekday() >= 5 for d in days) holidays = await ask(world, period="past year", only="public_holiday", sort_by="rain") - assert 5 <= holidays["days_checked"] <= 15 and all(r["holiday"] for r in holidays["days"]) + assert 5 <= holidays["days_checked"] <= 18 and all(r["holiday"] for r in holidays["days"]) # (two Easters, some years) # ---------- both sensors ---------- @@ -450,8 +467,8 @@ async def test_one_figure_over_months_says_how_to_get_one_per_month_or_year(worl async def test_of_without_stat_is_refused_saying_to_send_stat_not_counted_as_days(world): """`of` with no `stat` used to count the days and drop `of` ("rain per month" answered "313 of 313 days"); it is refused, saying to send stat too, so a model corrects it in its next call.""" - out = await ask(world, of="rain", group_by="month", period="this year") + out = await ask(world, of="rain", group_by="month", period="past year") assert "error" in out and "send `stat` too" in out["error"] and "sum" in out["error"] - fixed = await ask(world, stat="sum", of="rain", group_by="month", period="this year") + fixed = await ask(world, stat="sum", of="rain", group_by="month", period="past year") assert "error" not in fixed and fixed["answer"].startswith("Total rain") - assert "error" not in await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], period="this year") # (a count: no `of`) + assert "error" not in await ask(world, where=[{"field": "rain", "op": ">=", "value": 1}], period="past year") # (a count: no `of`) diff --git a/tests/test_service_outlook.py b/tests/test_service_outlook.py index c93ab402..4acf3afe 100644 --- a/tests/test_service_outlook.py +++ b/tests/test_service_outlook.py @@ -12,6 +12,7 @@ from lib.service.common import FRESH from lib.service.context import Context from lib.service.outlook import DESCRIPTION, GROUPS, HOW_TO_READ, PARAMETERS, dew_point, read, tools +from tests.clocks import pin from tests.fakes import TZ, archived_station NOW = datetime(2026, 11, 10, 14, 5, tzinfo=TZ) # Tue 10 Nov 2026 2:05pm @@ -290,8 +291,15 @@ async def test_with_no_readings_it_is_refused_pointing_to_the_forecast(): "from. Ask forecast for today's forecast."} -async def test_on_the_fake_station_it_reads_the_last_3_hours_from_the_file_and_the_reading_now(tmp_path, archived_cache): - eco, fake = await archived_station(tmp_path, archived_cache) +async def pinned_station(when, tmp_path, pinned_archive, monkeypatch): + """(Ecowitt, fake) over the fake station's archive as it was at `when`, with the clock pinned there.""" + cache = pinned_archive(when) + pin(monkeypatch, when) + return await archived_station(tmp_path, cache) + + +async def test_on_the_fake_station_it_reads_the_last_3_hours_from_the_file_and_the_reading_now(tmp_path, pinned_archive, monkeypatch): + eco, fake = await pinned_station(NOW, tmp_path, pinned_archive, monkeypatch) # (2:05pm: the last 3 hours are all today's) try: ctx = Context(eco=eco) nothing = got(await tools(ctx)[0].call({}, {"fetch": False})) # the archive holds no 5-minute readings of today yet @@ -306,7 +314,28 @@ async def test_on_the_fake_station_it_reads_the_last_3_hours_from_the_file_and_t assert out["pressure"]["hpa"] == round(last["pressure.relative"], 1) # (the reading now has no pressure: the newest 5 minutes') assert out["moisture"]["dew_point_spread"] == 0.0 and out["moisture"]["moist"] # (the fake's dew point is its temperature) assert out["verdict"] in ("possible", "likely") - assert datetime.fromisoformat(out["as_of"]["time"]) > datetime.now(TZ) - timedelta(minutes=10) + assert datetime.fromisoformat(out["as_of"]["time"]) > NOW - timedelta(minutes=10) + finally: + await eco.close() + + +async def test_just_after_midnight_the_last_3_hours_are_yesterdays_evening_read_from_the_file(tmp_path, pinned_archive, monkeypatch): + """At 12:05am the last 3 hours are yesterday's from 9:05pm, a finished day the archive holds (up to its settled edge, 10:50pm): + without fetching, the read is made from them (nothing asked of Ecowitt), as of its newest reading and warned about when that is + over half an hour old; fetching adds the rest and the reading now. (By day the archive holds nothing of the last 3 hours: the + test above.)""" + midnight = datetime(2026, 11, 11, 0, 5, tzinfo=TZ) + eco, fake = await pinned_station(midnight, tmp_path, pinned_archive, monkeypatch) + try: + ctx = Context(eco=eco) + held = got(await tools(ctx)[0].call({}, {"fetch": False})) + assert fake.calls == [] and "error" not in held and held["verdict"] in ("unlikely", "possible", "likely") + newest = datetime.fromisoformat(held["as_of"]["time"]) + assert midnight - timedelta(hours=3) <= newest < midnight and newest.date() == midnight.date() - timedelta(days=1) + assert ("warning" in held) is (midnight - newest > timedelta(minutes=30)) + out = got(await tools(ctx)[0].call({})) + assert {(c["path"], c.get("cycle_type")) for c in fake.calls} == {("history", "5min"), ("real_time", None)} + assert midnight - timedelta(minutes=10) < datetime.fromisoformat(out["as_of"]["time"]) <= midnight and "warning" not in out finally: await eco.close() diff --git a/tests/test_service_relate.py b/tests/test_service_relate.py index f28efa38..c14a8e9f 100644 --- a/tests/test_service_relate.py +++ b/tests/test_service_relate.py @@ -1,6 +1,7 @@ """The service's `relate` tool (lib/service/relate.py): rain against one reading over whole days, with the findings of the bot's weather_link (pressure, humidity, wind) and air_link (PM2.5, PM10), and a chart that says how to draw it again.""" +import dataclasses import json import time from datetime import date, timedelta @@ -14,6 +15,7 @@ from lib.service.context import Context from lib.timeutil import local_date from lib.tools import Tools, Turn +from tests.clocks import yesterday_at from tests.fakes import TZ, archived_station from tests.test_chart_json import errors from tests.test_compose import StubAir @@ -150,9 +152,14 @@ async def test_what_it_cant_relate_is_refused_with_what_it_can(tmp_path, archive async def test_a_period_that_isnt_whole_days_points_to_the_tools_that_read_one(tmp_path, archived_cache): ctx, eco = await world(tmp_path, archived_cache) + pinned = dataclasses.replace(ctx, clock=yesterday_at(14, 5, TZ).timestamp) # (at 2:05pm: this morning is over) for period in ("today", "last 5 hours", "this morning"): - out = await ask(ctx, period=period) + out = await ask(pinned, period=period) assert "use summary or readings" in out["error"], period + midnight = dataclasses.replace(ctx, clock=yesterday_at(0, 5, TZ).timestamp) # at 12:05am this morning is still ahead + assert "use summary or readings" in (await ask(midnight, period="today"))["error"] + ahead = (await ask(midnight, period="this morning"))["error"] + assert "'this morning' is in the future" in ahead and "use forecast" in ahead and ahead.endswith("12:05am.") assert "has a time" in (await ask(ctx, start="2026-09-01 10:00"))["error"] assert "use forecast" in (await ask(ctx, period="next week"))["error"] out = await ask(ctx, period="whenever") diff --git a/tests/test_service_scan.py b/tests/test_service_scan.py index b9e22691..1377252c 100644 --- a/tests/test_service_scan.py +++ b/tests/test_service_scan.py @@ -58,8 +58,8 @@ async def test_it_takes_an_air_reading_or_all_whole_days_and_a_chart(tmp_path, a # ---------- the findings ---------- -async def test_with_nothing_named_it_scans_every_air_reading_over_the_last_90_days_as_air_scan_does(tmp_path, archived_cache): - ctx, eco = await world(tmp_path, archived_cache) +async def test_with_nothing_named_it_scans_every_air_reading_over_the_last_90_days_as_air_scan_does(tmp_path, daytime_archive): + ctx, eco = await world(tmp_path, daytime_archive) out = await ask(ctx) assert list(out)[:7] == ["period", "as_of", "fresh", "reading", "verdict", "how_to_read", "findings"] assert out["reading"] == "all" and out["period"]["asked"] == "last 90 days" and out["period"]["cut"].endswith("today isn't over") diff --git a/tests/test_service_summary.py b/tests/test_service_summary.py index a91e63c8..6a1a540b 100644 --- a/tests/test_service_summary.py +++ b/tests/test_service_summary.py @@ -3,6 +3,7 @@ chart (lib/report.py), word for word.""" import json +import re from datetime import datetime, timedelta from tests import report_words as report # (the bot's words before step 2: the oracle) @@ -14,7 +15,8 @@ from lib.service.context import Context from lib.service.daylook import FIGURES, day_look from lib.tools import Turn -from tests.fakes import TZ, air_transport, archived_station, config +from lib.timeutil import day_bounds +from tests.fakes import TZ, air_transport, archived_station, config, rain_day from tests.test_chart_json import errors as schema_errors from tests import old_tools @@ -98,7 +100,7 @@ def looked(day): assert temp["unit"] == "°C" and isinstance(temp["low"], float) and temp["low"] <= temp["high"] for want in ("low", "high"): assert temp[f"{want}_text"] == f"{temp[want]} °C" - assert temp[f"{want}_when"].startswith(("at ", "around ")) and temp[f"{want}_date"].endswith(" 2026") + assert temp[f"{want}_when"].startswith(("at ", "around ")) and re.search(r" 20\d\d$", temp[f"{want}_date"]) day = datetime.strptime(temp[f"{want}_date"], "%a %d %b %Y").date() assert temp.get(f"{want}_day_look") == looked(day) rows = temp["daily"] @@ -106,7 +108,9 @@ def looked(day): for label, row in rows.items(): day = next(d for d in (today - timedelta(days=n) for n in range(7)) if f"{d:%a} {d.day} {d:%b}" == label) assert row.get("day_look") == looked(day) and row["low"] <= row["high"] - assert any(row.get("day_look", {}).get("word") == "wet" for row in rows.values()) # the fake's every 8th day is wet + # the fake's every 8th day of the year is wet (from 2pm): a week whose finished days hold one shows it (some weeks have none) + if any(rain_day(day_bounds(today - timedelta(days=n), TZ, last_second=True)[1]) >= 5 for n in range(1, 7)): + assert any(row.get("day_look", {}).get("word") == "wet" for row in rows.values()) assert "average" not in temp await close(ctx) @@ -150,7 +154,7 @@ async def test_rain_is_the_mm_that_fell_its_total_and_its_wettest_day(tmp_path, "%Y-%m-%d %H:%M:%S"), "groups": "rainfall", "chart_field": "rain", "chart": True}, old_turn)) assert drawn["rain_total_mm"] == old["rain_total_mm"] == rain["total"] long = await ask(tool, readings=["rain"], period="3m", chart=False) - assert list(long["series"]["rainfall.rain"]["monthly"])[0].endswith(" 2026") + assert re.fullmatch(r"[A-Z][a-z]{2} 20\d\d", list(long["series"]["rainfall.rain"]["monthly"])[0]) await close(ctx) diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 5bb3d2f6..66b21e0a 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -33,7 +33,7 @@ # ---------- the clock, fixed ---------- -class _DatetimeType(type): +class _DatetimeType(type(_REAL[0])): # (type, unless ECOBOT_CLOCK moved the clock: tests/sweepclock.py) def __instancecheck__(cls, obj): return isinstance(obj, _REAL[0]) @@ -53,7 +53,7 @@ def today(cls): return _REAL[0].fromtimestamp(FROZEN) -class _DateType(type): +class _DateType(type(_REAL[1])): def __instancecheck__(cls, obj): return isinstance(obj, _REAL[1]) From f149e36d65469d5a1bc10838a2dd1debb6bae318 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 13:51:42 +0000 Subject: [PATCH 061/125] Alert delivery retries a log it can't read; about's forecast alert wording - AlertDelivery.run: an error reading the log (locked, a disk error) is logged and retried after 30 s; before, one ended the task and every alert stopped until a restart. - about: the forecast alert is today's or tomorrow's forecast changing, not 'a forecast it sent'. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/alerts/notify.py | 15 ++++++++++++--- lib/service/about.py | 2 +- tests/test_alert_log.py | 26 ++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index db3d22d9..94601654 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -282,11 +282,20 @@ def _handled(self, event_id: int): except Exception as e: # (the next one saved covers it; at worst a restart sends it again) log.warning("Couldn't save the last alert delivered (%s: %s)", type(e).__name__, e) + RETRY_SECONDS = 30 # after the log can't be read (locked, a disk error): try again, rather than stop alerts until a restart + async def run(self): - """Forever: deliver what is new, then wait for more.""" + """Forever: deliver what is new, then wait for more. A failure reading the log is logged and retried, never the end of alerts.""" while True: - await self.deliver_new() - await self.log.wait(self.last) + try: + await self.deliver_new() + await self.log.wait(self.last) + except asyncio.CancelledError: + raise + except Exception as e: + log.error("Alert delivery couldn't read the log (%s: %s); trying again in %ds", type(e).__name__, e, self.RETRY_SECONDS, + exc_info=True) + await asyncio.sleep(self.RETRY_SECONDS) async def deliver_new(self) -> int: """Send each unexpired event after the last handled, oldest first; returns how many were sent.""" diff --git a/lib/service/about.py b/lib/service/about.py index 21c3ec3f..6f6063dd 100644 --- a/lib/service/about.py +++ b/lib/service/about.py @@ -47,7 +47,7 @@ ALERT_WORDS = {"rain": "rain starting or stopping", "gusts": f"wind gusts over {GUST_ALERT_KMH} km/h", "uv": f"UV index of {UVI_ALERT} or more", "temps": "indoor/outdoor temperature crossing", "particulates": "air-quality mask alerts", "pollen_and_asthma": "pollen or thunderstorm asthma risk reaching High", - "forecast": f"a forecast it sent being revised (rain, or max temperature over {TEMP_CHANGE_C:g} degrees)"} + "forecast": f"today's or tomorrow's forecast changing (rain becoming likely or unlikely, or the high moving over {TEMP_CHANGE_C:g} degrees)"} # The alert kinds (lib/alerts/menu.py TYPES, copied, without the irrigation controller's: that is a server of its own): kind -> (its name, # the source that sends it) TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), diff --git a/tests/test_alert_log.py b/tests/test_alert_log.py index 0bd6b1b0..cff08654 100644 --- a/tests/test_alert_log.py +++ b/tests/test_alert_log.py @@ -275,6 +275,32 @@ async def test_the_delivery_runs_on_the_logs_notification(tmp_path): await asyncio.gather(task, return_exceptions=True) +async def test_a_log_that_cant_be_read_for_a_moment_is_tried_again_not_the_end_of_alerts(tmp_path): + """A locked file or a disk error reading the log is logged and retried: the delivery keeps running, and the alert written meanwhile + is sent once the log reads again (before, one error ended the task and every alert stopped until a restart).""" + import sqlite3 + d, log, state, telegram = delivery(tmp_path, chats=(1,)) + d.RETRY_SECONDS = 0.01 + real, failures = log.since, [sqlite3.OperationalError("database is locked")] + + def flaky(*a, **k): + if failures: + raise failures.pop() + return real(*a, **k) + log.since = flaky + log.append("uv", "UV 11", "t") + task = asyncio.create_task(d.run()) + try: + for _ in range(200): + if telegram.sent: + break + await asyncio.sleep(0.01) + assert [text for _, text, _, _ in telegram.sent] == ["UV 11"] and not task.done() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + # ---------- the 🔄 under a delivered alert ---------- class ChartQuery: def __init__(self, data, kind="gusts", event=None): From 9d24045c49d777c63bcac1c8748622315204314d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 14:00:37 +0000 Subject: [PATCH 062/125] outlook: the last hour ends at the newest reading; test comments name tests/clocks.py Read without fetching just after midnight, the newest readings can be over an hour old, and the last hour counted back from the clock dropped the rain in them (the verdict could flip from likely to unlikely). Rain and wind now count back from the newest reading held; as_of and the staleness warning say how old it is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/service/outlook.py | 6 ++++-- tests/evalworld.py | 2 +- tests/test_service_outlook.py | 10 ++++++++++ tests/test_service_switch.py | 2 +- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/lib/service/outlook.py b/lib/service/outlook.py index 1a7bef1d..b5979b36 100644 --- a/lib/service/outlook.py +++ b/lib/service/outlook.py @@ -76,8 +76,10 @@ def latest(*keys: str) -> list[float | None]: pressure = _pressure(points("pressure.relative")) moisture = _moisture(*latest("outdoor.temperature", "outdoor.humidity", "outdoor.dew_point")) - rain = _recent_rain(rows, live, live_ts, gauge, now_ts) - wind = _wind(points("wind.wind_speed"), now_ts) + until = newest or now_ts # "the last hour" ends at the newest reading held: stale readings (a read without fetching, just after + # midnight) still count their rain, and the result's as_of and warning say how old they are + rain = _recent_rain(rows, live, live_ts, gauge, until) + wind = _wind(points("wind.wind_speed"), until) falling = pressure is not None and pressure["tendency"] == "falling" score = 0 if not falling else 2 if -pressure["change_hpa"] > LIKELY_FALL_HPA else 1 diff --git a/tests/evalworld.py b/tests/evalworld.py index beb5e3fd..9c005f33 100644 --- a/tests/evalworld.py +++ b/tests/evalworld.py @@ -25,7 +25,7 @@ EVAL_NOW = evalkit.NOW.replace(tzinfo=ZoneInfo(evalkit.NOW_TZ)).timestamp() -class _DatetimeType(type(_dt.datetime)): # (type, unless ECOBOT_CLOCK moved the clock: tests/sweepclock.py) +class _DatetimeType(type(_dt.datetime)): # (type, unless ECOBOT_CLOCK moved the clock: tests/clocks.py) def __instancecheck__(cls, obj): return isinstance(obj, _dt.datetime) diff --git a/tests/test_service_outlook.py b/tests/test_service_outlook.py index 4acf3afe..c40a1260 100644 --- a/tests/test_service_outlook.py +++ b/tests/test_service_outlook.py @@ -347,3 +347,13 @@ def test_it_is_offered_only_with_a_station_and_its_description_carries_the_rules "wind picking up", "rain rate above 0 now", "forecast", "summary", "relate"): assert rule in DESCRIPTION, rule assert set(GROUPS) == {"outdoor", "pressure", "rainfall", "rainfall_piezo", "wind"} # (the prefetch's groups) + + +def test_the_last_hour_ends_at_the_newest_reading_so_stale_readings_still_count_their_rain(): + """Read without fetching just after midnight, the newest readings can be over an hour old: their last hour's rain (and wind) is + counted from the newest reading, not from the clock, so the rain in them isn't dropped and the verdict doesn't flip to unlikely.""" + stale = NOW_TS - 75 * 60 # the newest reading 75 minutes before the time asked + rows = station(daily=lambda i: 0.0 if i < STEPS - 6 else 0.4 * (i - STEPS + 6), rate=lambda i: 0.0, now_ts=stale) + out = read(rows, None, NOW_TS) + assert out["recent_rain"]["rained"] and out["recent_rain"]["last_hour_mm"] == 2.4 and out["verdict"] != "unlikely" + assert out["newest"] == stale diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index f5838415..05595912 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -33,7 +33,7 @@ # ---------- the clock, fixed ---------- -class _DatetimeType(type(_REAL[0])): # (type, unless ECOBOT_CLOCK moved the clock: tests/sweepclock.py) +class _DatetimeType(type(_REAL[0])): # (type, unless ECOBOT_CLOCK moved the clock: tests/clocks.py) def __instancecheck__(cls, obj): return isinstance(obj, _REAL[0]) From 45d61c712852049795a7bd91fc610d7c909479fc Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 22:23:32 +0000 Subject: [PATCH 063/125] Step 5, service side: the MCP server, python -m ecobot_service, the stdio bridge - lib/mcp_server.py: the SDK's low-level Server over the ten tools (hand-written schemas, readOnly/openWorld hints, request _meta passed to ServiceTool.call, complete results with a user-audience reply and _meta ecobot/complete), the resources of 3.4 and the alerts{?since,expired} template, the prompts of 3.5, the instructions, subscriptions/listen (ResourceUpdated on change, repeats not sent; ToolsListChanged when the catalogue gains a reading), and http_app: Streamable HTTP with allowed hosts and a constant-time TokenVerifier over MCP_TOKENS. - ecobot_service/: core.py is the service's startup (sources, alert log, tools, alert rules, keep-warm, warm-up, health), shared with ecobot.py, whose behaviour is unchanged; __main__.py runs it under uvicorn; bridge.py is the supervised stdio bridge. - Config: MCP_TOKENS, MCP_BIND, MCP_ALLOWED_HOSTS; from_env(bot=False) needs no Telegram token. Tasks moves to lib/warm.py. - Packaging: mcp==2.3.0, uvicorn==0.54.0; the image ships ecobot_service/ and schemas/; compose has ecobot-service under the "service" profile. - Tests: tests/test_mcp_server.py (in memory), tests/test_mcp_listen.py (uvicorn on localhost: lost listen and re-read, auth, hosts, stdio bridge, the service started with fakes). Docs: DEVELOPMENT.md, configuration.md, mcp-service.md step 5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- .dockerignore | 2 + DEVELOPMENT.md | 21 ++ Dockerfile | 9 +- compose.yaml | 25 +++ docs/configuration.md | 14 +- docs/mcp-service.md | 26 ++- ecobot.py | 210 +++--------------- ecobot_service/__init__.py | 10 + ecobot_service/__main__.py | 115 ++++++++++ ecobot_service/bridge.py | 234 ++++++++++++++++++++ ecobot_service/core.py | 298 ++++++++++++++++++++++++++ lib/bot.py | 25 +-- lib/config.py | 49 ++++- lib/mcp_server.py | 425 +++++++++++++++++++++++++++++++++++++ lib/service/current.py | 9 +- lib/warm.py | 26 ++- requirements.txt | 2 + tests/test_mcp_listen.py | 227 ++++++++++++++++++++ tests/test_mcp_server.py | 334 +++++++++++++++++++++++++++++ 19 files changed, 1849 insertions(+), 212 deletions(-) create mode 100644 ecobot_service/__init__.py create mode 100644 ecobot_service/__main__.py create mode 100644 ecobot_service/bridge.py create mode 100644 ecobot_service/core.py create mode 100644 lib/mcp_server.py create mode 100644 tests/test_mcp_listen.py create mode 100644 tests/test_mcp_server.py diff --git a/.dockerignore b/.dockerignore index c4f0d639..cc5365f9 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,7 +2,9 @@ # in the container: docker compose exec ecobot python scripts/...) * !ecobot.py +!ecobot_service/ !lib/ +!schemas/ !scripts/ !requirements.txt # the commit the log says it is running is read from these (a clone; the files are a few hundred bytes) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 17c4728b..cf12cdf8 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -26,6 +26,27 @@ it and kept (`ecobot-archive-pinned-*.sqlite`); a tool's answer to words alone c The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build the same Python into `.venv` with uv (`.claude/hooks/session-start.sh`). +## The MCP service +The service on its own ([docs/mcp-service.md](docs/mcp-service.md) 3.8, step 5): the sources and their syncers, the alert rules writing the +alert log, and the MCP server (`lib/mcp_server.py`) at `http://MCP_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). +It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) less the bot's own, and `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`: +``` +set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them +MCP_TOKENS=me:$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp +python -m ecobot_service.bridge # the same on stdio (WEATHER_MCP_URL, WEATHER_MCP_TOKEN), for a desktop client +sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 +``` +Don't run it beside the bot on the same data folder yet: until the bot is its client, the bot runs the sources and the alert rules itself, and +both would fetch twice and write each alert twice. A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with +`WEATHER_MCP_TOKEN` in its environment, e.g. `claude mcp add ecobot -e WEATHER_MCP_TOKEN=... -- python -m ecobot_service.bridge` from the clone. +To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. + +Its tests: `tests/test_mcp_server.py` (the SDK's in-memory transport: every tool listed and answering as the ServiceTool does, each resource, +the alerts' template, the prompts, the publishing, the tokens, the bridge in-process) and `tests/test_mcp_listen.py` (the real app under uvicorn +on a free localhost port: a client that listens loses its listen when the service stops and reads what it missed when it is back; the +token and Host checks over HTTP; the bridge as a subprocess on stdio; `python -m ecobot_service` with the fake sources, a tool call through +a proxy's Host name). + ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) | Job | When | What | |---|---|---| diff --git a/Dockerfile b/Dockerfile index 3a1aa967..17963879 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# The bot as a small image: python:3.13-slim with the runtime packages in a venv that has no pip, no pip cache and no test suites, +# The bot (and the MCP service, python -m ecobot_service) as a small image: python:3.13-slim with the runtime packages in a venv that has no pip, no pip cache and no test suites, # and bytecode for only what the bot imports at start (bytecode for everything is 48 MB more; none adds ~2 s to every start). # docker build -t ecobot . # docker compose up -d --build (compose.yaml) @@ -25,17 +25,20 @@ RUN groupadd --system --gid 10001 ecobot \ && mkdir /data && chown 10001:10001 /data WORKDIR /app COPY ecobot.py ./ +COPY ecobot_service ecobot_service COPY lib lib +COPY schemas schemas COPY scripts scripts ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 # The bot reads the running commit for its start-up log line from .git (HEAD, the branch's ref, packed-refs: .dockerignore lets only these # through), so building from a clone needs nothing more; COMMIT, if given, is used instead (a build from files that are not a clone). -# Importing the bot once writes the bytecode of every module it loads at start, and only those. +# Importing the bot and the service once writes the bytecode of every module they load at start, and only those. COPY .git* .git/ ARG COMMIT= RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi \ - && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot" \ + && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot, ecobot_service.__main__, ecobot_service.bridge, lib.mcp_server" \ && rm -rf /tmp/build ENV DATA_DIR=/data USER 10001:10001 +# The bot; the same image runs the MCP service with `python -m ecobot_service` (compose.yaml's ecobot-service) CMD ["python", "ecobot.py"] diff --git a/compose.yaml b/compose.yaml index c30e7307..daef3736 100644 --- a/compose.yaml +++ b/compose.yaml @@ -19,3 +19,28 @@ services: options: max-size: 10m max-file: "5" + + # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, + # at http://127.0.0.1:8765/mcp on the host (put TLS in front of it, e.g. Caddy, to reach it from elsewhere). Off unless asked for + # (`sudo docker compose --profile service up -d ecobot-service`): until the bot is its client, the bot runs the sources and the alert + # rules itself, and both on one data folder would fetch twice and write each alert twice. It needs MCP_TOKENS (name:token,..., in + # /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. MCP_ALLOWED_HOSTS: add + # the name a proxy or a LAN client uses for it. + ecobot-service: + image: ecobot + container_name: ecobot-service + profiles: [service] + command: ["python", "-m", "ecobot_service"] + restart: unless-stopped + env_file: /etc/ecobot.env + environment: + MCP_BIND: 0.0.0.0:8765 + ports: + - 127.0.0.1:8765:8765 + volumes: + - /var/lib/private/ecobot:/data + logging: + driver: local + options: + max-size: 10m + max-file: "5" diff --git a/docs/configuration.md b/docs/configuration.md index 4bad7926..d9256f7c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -21,7 +21,7 @@ One `NAME=value` per line, no `export`; a line starting with `#` is a comment (n | Variable | Default | Description | |---|---|---| -| `TELEGRAM_BOT_TOKEN` | – | Required. Bot token (@BotFather) | +| `TELEGRAM_BOT_TOKEN` | – | Required by the bot (not the MCP service). Bot token (@BotFather) | | `OPENROUTER_API_KEY` | – | [OpenRouter](https://openrouter.ai/keys) API key. Unset → no model: `/report`, chart commands, plain lookups ("how hot is it?", "rain chart 7d", "forecast") and all alerts work; anything needing the model gets a "no model" reply | | `OPENROUTER_MODEL` | `deepseek/deepseek-v4.1-flash-1017` | Model, by its OpenRouter name | | `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | API endpoint | @@ -79,3 +79,15 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `DATA_DIR` | `$STATE_DIRECTORY`, else app dir | State (`bot_state.json`) and SQLite caches. Relative paths from the working dir. Created if missing. | | `LOG_WIDTH` | `24` | Characters of a chat message kept in the log, then `…`; `0` keeps all. No other line is cut | | `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. `DEBUG` adds the bot's own lines (chart timings) | + +### The MCP service + +`python -m ecobot_service` ([mcp-service.md](mcp-service.md) 3.8, `DEVELOPMENT.md`) reads every setting above that is not the bot's own (it needs no `TELEGRAM_BOT_TOKEN`, model or chat setting), and these: + +| Variable | Default | Description | +|---|---|---| +| `MCP_TOKENS` | none | `name:token,name:token`: the bearer token each client sends (`Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart). Compared in constant time; a token is never logged, only its name. Unset → no auth, which the service allows only on a loopback `MCP_BIND` | +| `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | +| `MCP_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | + +The stdio bridge (`python -m ecobot_service.bridge`, for a desktop client) reads `WEATHER_MCP_URL` (default `http://127.0.0.1:8765/mcp`) and `WEATHER_MCP_TOKEN` (one of `MCP_TOKENS`' tokens). diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 80adf086..e6f6f395 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -294,9 +294,9 @@ For applications that keep an eye on the station rather than ask about it; a mod | URI | Holds | Pushed | |---|---|---| -| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds, what each means and its threshold; the AirGradient dashboard link | on change | -| `ecobot://now/weather` | the live reading: `{as_of, group: {field: {value, unit, text, time}}}` | each new reading (5 s with HA, 60 s cloud only) | -| `ecobot://now/air` | the latest air reading, its time, ratings and AQI | each new reading | +| `ecobot://station` | name, time zone, latitude and longitude, created; the sensors, their readings with labels, units and the words people use for them; each source's mode (HA, cloud, local) and retention; the alert kinds, what each means and its threshold; the AirGradient dashboard link | when the catalogue gains a reading | +| `ecobot://now/weather` | the live reading as kept, in the service's names (`current`'s, nothing fetched for it): `{as_of, sensors: {sensor: {reading: {value, unit, text, [emoji], [compass]}}}, lines, heading, [unavailable]}` | each new reading (5 s with HA, 60 s cloud only) | +| `ecobot://now/air` | the latest air reading, the same shape: its time, each reading's rating, PM2.5's AQI and band | each new reading | | `ecobot://alerts` (in the resource list) and `ecobot://alerts{?since,expired}` (a template) | the alerts, newest last, kept 30 days; `since` an alert id: those after it; unexpired ones only unless `expired=true` (3.6) | each new alert, on the bare URI | | `ecobot://forecast` | the forecast days, structured (min and max, rain chance, chance of at least 1 mm, summary), with `fetched_at` and `place` | each new forecast | | `ecobot://pollen` | grass and asthma levels with their days, `fetched_at`, `in_season` | each new page | @@ -560,6 +560,26 @@ Each step ships on its own, with the tests and evals green and the bot working t repository against it, the bot connects to both, and `lib/irrigation` goes from here. The service's scripts (`edit_readings`, `cache_status`, `refill_airgradient`, `check_rain`, `bench_storage`, `conditions`, `ecowitt_metrics`, `dump_specs`) stay; `show_request` and `report_inputs` become MCP clients. + - **The service side (done).** `lib/mcp_server.py` (`EcobotServer`): the SDK's low-level `Server` with the ten tools (their + hand-written schemas, `readOnlyHint` and `openWorldHint` from each ServiceTool, the list built from the current catalogue; a call + runs the ServiceTool with the request's `_meta` and answers its JSON unchanged as one text block, `isError` for a refusal, a + complete answer with its `reply` as a second block for `audience: ["user"]` and result `_meta` `{"ecobot/complete": true}`), + 3.4's resources and the alerts' template, 3.5's prompts, the instructions, and `subscriptions/listen` (`InMemorySubscriptionBus`, + `ListenHandler`): `ResourceUpdated` for the live resources when what the sources keep changes (compared every 2 s, nothing fetched + for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`AlertLog.wait`), the station and + `ToolsListChanged` when the file's catalogue gains a reading (read every minute; the tools and instructions are then built again). + `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_ALLOWED_HOSTS` and the `TokenCheck` verifier over + `MCP_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_service/`: `core.py` is the service's startup + (`start_sources`, `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch, the weather + rules, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for + `ecobot://health`), which `ecobot.py` now calls in-process, its behaviour unchanged; `__main__.py` runs it with the server under + uvicorn (`MCP_BIND`, refusing a non-loopback address without `MCP_TOKENS`); `bridge.py` is the stdio bridge, one supervised upstream + client pinned to 2026-07-28 that discovers by hand, listens and re-listens after a backoff. The image ships `ecobot_service/` and + `schemas/`; compose has `ecobot-service`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and + `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the bridge + on stdio, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs + no Telegram token. Left: the bot as a client (the switch, the supervisor, `charts` from results, delivery from the listen), its + `warm_up` cut to its charts drawn ahead, the poke going, the irrigation server and the scripts as clients. 6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. ## 7. Testing diff --git a/ecobot.py b/ecobot.py index 1f49543d..dea23b0b 100644 --- a/ecobot.py +++ b/ecobot.py @@ -1,49 +1,39 @@ """Telegram bot for a personal weather station (Ecowitt) and air-quality sensor (AirGradient), answered by a model through OpenRouter, with proactive alerts. Settings come from environment variables (see lib/config.py); run it under systemd with the unit's EnvironmentFile set. + +The service's half (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and +Home Assistant's imports) is ecobot_service/core.py, which the service (python -m ecobot_service) runs the same way: the bot runs it +in-process, beside its own half (Telegram, the model, delivering the alerts, the irrigation controller, its charts drawn ahead). """ import asyncio import contextlib -import dataclasses import logging -import os import signal -import time -from lib.config import ROOT, Config +from lib.config import Config from telegram import Update from telegram.error import InvalidToken, NetworkError from telegram.ext import Application, Defaults +from ecobot_service.core import Core, commit_in, configure, start_sources, version # noqa: F401 (commit_in, start_sources: named here for the tests) from lib import charts -from lib.airgradient import AirGradient -from lib.airgradient import metrics as air_metrics -from lib.alert_log import AlertLog +from lib.airgradient import AirGradient # noqa: F401 (the sources, named here for the startup tests) from lib.alerts.irrigation import IrrigationMonitor -from lib.alerts.menu import LABELS, available_kinds from lib.alerts.notify import AlertDelivery, AlertState, Notifier -from lib.alerts.store import AlertStore -from lib.alerts.weather import WeatherMonitor # (the weather rules, started by AlertRules; named here for the startup tests) +from lib.alerts.weather import WeatherMonitor # noqa: F401 (the weather rules, started by AlertRules; named here for the startup tests) from lib.bot import AHEAD_SECONDS, TURN_SECONDS, Bot, Tasks, polling_error -from lib.ecowitt import Archive, Ecowitt -from lib.ecowitt.source import HA_IMPORT_SECONDS -from lib.forecast import Forecast +from lib.ecowitt import Ecowitt # noqa: F401 +from lib.forecast import Forecast # noqa: F401 from lib.irrigation import Tuya from lib.irrigation.watchdog import CHECK_SECONDS as VALVE_CHECK_SECONDS from lib.llm import Agent -from lib.logs import BUGS, LogFormat, on_journal, stream_handlers -from lib.pollen import Pollen -from lib.service import Service -from lib.service import about as service_about -from lib.service import names as service_names +from lib.logs import LogFormat, on_journal, stream_handlers +from lib.pollen import Pollen # noqa: F401 from lib.service.alerts import AlertRules -from lib.service.context import Context -from lib.compose import Composer -from lib.sources import Source -from lib.storage import Storage from lib import model_tools from lib.warm import every, safely @@ -55,149 +45,30 @@ log = logging.getLogger("ecobot") -async def start_sources(cfg: Config) -> tuple[list[Source], Config]: - """Every configured data source that starts, and the settings in the time zone they run in. The weather station starts - first: it names its own time zone, which wins over TZ, so the air sensor and the optional website sources (pollen, - forecast, off unless switched on), and everything built after, use the station's; those three start side by side (each - waits on its own server). The forecast uses the station's location unless one is configured.""" - sources: list[Source] = [] - took: dict[str, float] = {} - - async def start(kind: type[Source], *args, **kwargs) -> Source | None: - """A source made and started; one that fails either way is logged and left out (None).""" - source, started = None, time.monotonic() - try: - source = kind(*args, **kwargs) - await source.start() - return source - except Exception as e: - log.error("%s couldn't start (%s: %s) - continuing without it", kind.name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) - if source is not None: - await safely(source.close) - return None - finally: - took[kind.name] = time.monotonic() - started - storage = None - if cfg.ecowitt or cfg.airgradient: - try: # (in a thread: opening makes or upgrades its tables) - storage = await asyncio.to_thread(Storage, cfg.storage_path, cfg.tz) - except Exception as e: - log.error("The history file %s couldn't be opened (%s: %s) - continuing without the weather station and the air sensor", - cfg.storage_path, type(e).__name__, e, exc_info=isinstance(e, BUGS)) - if cfg.ecowitt and storage is not None and (eco := await start(Ecowitt, cfg, storage=storage)): - sources.append(eco) - eco = sources[0] if sources else None - if eco and str(eco.tz) != str(cfg.tz): - if os.getenv("TZ"): - log.warning("TZ=%s is not the weather station's time zone; using the station's, %s", os.getenv("TZ"), eco.tz) - cfg = dataclasses.replace(cfg, tz=eco.tz) - if not getattr(cfg.tz, "key", None): - log.warning("The time zone has no name, only an offset (%s), so daylight saving will put the times out: set TZ, " - "e.g. TZ=Australia/Melbourne", cfg.tz) - starts = [] - if cfg.airgradient and storage is not None: # (one file and one Home Assistant client for both; the file is the station's to close, else the sensor's) - starts.append(start(AirGradient, cfg, storage=storage, owned=eco is None, **({"ha": eco.ha} if eco and eco.ha else {}))) - if cfg.pollen: - starts.append(start(Pollen, cfg)) - if cfg.forecast: - starts.append(start(Forecast, cfg, (eco.latitude, eco.longitude) if eco and None not in (eco.latitude, eco.longitude) else None)) - sources += [s for s in await asyncio.gather(*starts) if s is not None] # (in this order, whichever answers first) - if storage is not None and not sources: - storage.close() - if took: - log.debug("Sources started in %.1fs: %s", sum(took.values()), ", ".join(f"{name} {seconds:.1f}" for name, seconds in took.items())) - return sources, cfg - - -def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, alert_log: AlertLog) -> tuple[list[str], AlertRules]: - """Hook up the service's alert rules over every source that started (lib/service/alerts.py: they append to the alert log, which the +def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Core) -> tuple[list[str], AlertRules]: + """Hook up the service's alert rules over every source that started (core.start_alerts: they append to the alert log, which the bot delivers from, AlertDelivery) and the irrigation controller's (sent by the bot itself until it is a server of its own). The weather rules start in warm_up, once the station has been read. Returns the alert types now running, and the rules.""" - store = AlertStore(cfg.alert_state_path, moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) - rules = AlertRules(bot.by_name, store, alert_log, cfg.alert_cooldown_minutes * 60, cfg.rain_quiet_hours, bot.service) - tasks.start(AlertDelivery(alert_log, notify, bot.state, cfg.tz).run()) - running = rules.start(tasks) + running = core.start_alerts(moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) + tasks.start(AlertDelivery(core.alert_log, notify, bot.state, cfg.tz).run()) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, bot.by_name.get("Ecowitt"), bot.by_name.get("Forecast")).run()) tasks.start(every(VALVE_CHECK_SECONDS, bot.watchdog.check)) running += IrrigationMonitor.KINDS - return running, rules - - -async def warm_up(bot: Bot, rules: AlertRules | None, running: list[str], tasks: Tasks, tg_bot=None): - """Fetch everything once, together, and log one summary line; then start what waited for it: the weather alerts, the - archives (copying each source's history into its cache), the keyboard's charts drawn ahead every few minutes.""" - eco, air = bot.by_name.get("Ecowitt"), bot.by_name.get("AirGradient") - - async def ecowitt_part(): - # One request at a time (Ecowitt rate-limits): warm first, so the alerts' own look at the last 3 hours is answered - # from what was just fetched. A failed first refresh must not stop the alerts or the archive: safely() logs it - await safely(eco.warm, True) - try: - if rules is not None: - await rules.start_weather(running) - except Exception as e: - log.error("Weather alerts couldn't start (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - if eco.fast is not None: - tasks.start(eco.watch_live()) - # The full history is copied into the cache in the background (a few minutes the first time), so questions rarely - # need Ecowitt inline - tasks.start(Archive(eco, eco.archive_pace).loop()) - if eco.ranges_from_ha: # the cloud's readings get their 5-minute bands from what Home Assistant kept, the days the bot was not watching too - tasks.start(every(HA_IMPORT_SECONDS, eco.import_ranges)) + return running, core.rules - async def air_part(): - await safely(air.warm, True) - tasks.start(air_history()) # even if the sensor was unreachable just now - async def air_history(): - """What Home Assistant kept of the monitor (the readings the bot lacks, their bands, the minutes), then the days the cache lacks, then - Home Assistant again every HA_IMPORT_SECONDS.""" - if air.ha: # (first: it is quick, and holds the last days; the backfill can take minutes the first time) - await safely(air.import_history) - if air.cloud: - await safely(air_backfill) - if air.ha: - await every(HA_IMPORT_SECONDS, air.import_history) - - async def air_backfill(): - started = time.monotonic() - fetched, failed, total = await air.backfill() - log.info("Backfill AirGradient: %d days fetched, %d failed, %d days held, %.0fs", fetched, failed, total, time.monotonic() - started) - - try: - await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else [])) - except Exception as e: - log.error("Startup fetch failed (%s: %s); the regular refreshes will catch up", type(e).__name__, e, exc_info=isinstance(e, BUGS)) - if missing := [LABELS[k] for k in available_kinds(bot.by_name, bot.irrigation is not None) if k not in running]: +async def warm_up(bot: Bot, core: Core, running: list[str], tasks: Tasks, tg_bot=None): + """The service's warm-up (core.warm_up: everything fetched once, together; then the weather alerts and the archives), then what + the bot waited for: the alerts not running named, the keyboard's charts drawn ahead every few minutes.""" + await core.warm_up(running) + if missing := core.missing_alerts(running, bot.irrigation is not None): log.warning("Alerts NOT running: %s (see the error above)", ", ".join(missing)) if tg_bot is not None: tasks.start(every(AHEAD_SECONDS, lambda: bot.draw_buttons_ahead(tg_bot))) -def version() -> str: - """The checked-out commit, so the log shows which code is running.""" - return commit_in(ROOT / ".git") - - -def commit_in(git_dir) -> str: - """The short hash HEAD points at, read from the repository's files rather than by running git (which refuses a folder owned by - another user, as when the service runs as its own user). "unknown" when it cannot be read.""" - try: - head = (git_dir / "HEAD").read_text().strip() - if head.startswith("ref:"): - ref = head.split(None, 1)[1] - try: - head = (git_dir / ref).read_text().strip() - except FileNotFoundError: # after `git pack-refs` or gc the branch is a line in packed-refs - head = next(line.split()[0] for line in (git_dir / "packed-refs").read_text().splitlines() - if line.endswith(f" {ref}")) - return head[:7] if len(head) >= 7 and all(c in "0123456789abcdef" for c in head.lower()) else "unknown" - except Exception: - return "unknown" - - AsyncOpenAI = Timeout = None # openai's, imported when the model's client is made (_client): the import takes half a second, more than all of lib @@ -217,11 +88,7 @@ async def main(): _format.width = cfg.log_width # a chat message in the log is cut to it from here on for name in ("ecobot", "lib"): # the bot's own lines: the libraries keep theirs logging.getLogger(name).setLevel(cfg.log_level) - air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive - service_names.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like # "all" (and "weather all week") draws these too - service_names.VPD_IN_ALL = cfg.chart_all_vpd - service_about.RAIN_QUIET_HOURS = cfg.rain_quiet_hours # what `about` says of the rain alert's quiet hours ... - service_about.ALERT_COOLDOWN_MINUTES = cfg.alert_cooldown_minutes # ... and of the alerts' cooldown + configure(cfg) # Whatever starts is closed on the way out, the last started first, however the bot stops (a failure part-way included) async with contextlib.AsyncExitStack() as stack: app = (Application.builder().token(cfg.telegram_token).concurrent_updates(True) @@ -239,32 +106,26 @@ async def main(): if not sources: handshake.cancel() raise SystemExit("No data source is working - nothing to talk about") - by_name = {s.name: s for s in sources} - eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") charts.configure(cfg.dark_mode, cfg.tz) # DARKMODE (in the station's time zone, as everything from here on) - composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources client = _client(cfg) if cfg.openrouter_api_key else None # without a key the bot answers only what it works out in code if client: stack.push_async_callback(safely, client.close) else: log.warning("OPENROUTER_API_KEY is not set: running without the model, so answers are limited") state = AlertState(cfg.state_path) - alert_log = AlertLog(cfg.alert_log_path, cfg.tz) # the alerts the rules decide, which the bot delivers - stack.callback(alert_log.close) if cfg.admin_only and not cfg.admin_chat_ids and not any(chat < 0 for chat in state.chats): log.warning("Admin only is on but no group is known yet and ADMIN_CHAT_IDS is empty, so nobody can use the bot: " "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") + tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) + # The service in-process (ecobot_service/core.py): the alert log the rules write and the bot delivers from, and the ten tools + # over the sources that started (lib/service): the model is offered them (lib/model_tools.py), and the bot's own code paths call + # them (its shortcuts, report, gauges, alert charts and period buttons) + core = await Core.open(cfg, sources, stack, tasks) irrigation = Tuya(cfg) if cfg.irrigation else None if irrigation: stack.push_async_callback(safely, irrigation.close) - tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) - # The service's ten tools over the sources that started (lib/service): the model is offered them (lib/model_tools.py), and the - # bot's own code paths call them (its shortcuts, report, gauges, alert charts and period buttons) - service = Service.of(await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), - pollen=by_name.get("Pollen"), tz=cfg.tz)) - log.info("Service tools: %s", ", ".join(t.name for t in service)) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(service)), sources, state, irrigation, tasks, service=service, - alert_log=alert_log) + bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(core.service)), sources, state, irrigation, tasks, + service=core.service, alert_log=core.alert_log) bot.register(app) stop = asyncio.Event() @@ -287,15 +148,12 @@ async def main(): stack.push_async_callback(source.warmer.stop) log.info("Telegram: @%s, Model: %s", app.bot.username, cfg.openrouter_model if client else "none") - for source in sources: # what each is reading, in the order they are listed - for line in source.startup_lines(): - log.info("%s", line) + core.log_startup() # what each source is reading, in the order they are listed notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's await bot.publish_commands(app.bot) # the / menu - running, rules = start_alerts(cfg, bot, notify, tasks, alert_log) - for source in sources: # keeping warm: everything questions need, refreshed before they arrive - tasks.start(source.warmer.run()) - tasks.start(warm_up(bot, rules, running, tasks, app.bot)) + running, rules = start_alerts(cfg, bot, notify, tasks, core) + core.start_warmers() # keeping warm: everything questions need, refreshed before they arrive + tasks.start(warm_up(bot, core, running, tasks, app.bot)) await stop.wait() diff --git a/ecobot_service/__init__.py b/ecobot_service/__init__.py new file mode 100644 index 00000000..6df966ad --- /dev/null +++ b/ecobot_service/__init__.py @@ -0,0 +1,10 @@ +"""The weather and air service on its own (docs/mcp-service.md 3.8, step 5): the readings file, the sources and syncers that fill it, the +alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). + + - `python -m ecobot_service` (__main__.py): the service, Streamable HTTP at http://MCP_BIND/mcp; + - `python -m ecobot_service.bridge` (bridge.py): a stdio bridge to a running service, for a desktop client; + - core.py: the service's startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, + the backfills and Home Assistant's imports), the one function the service and the bot (ecobot.py, while it runs everything + in-process) both call. + +Nothing is imported here, so the bridge starts without the sources' code.""" diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py new file mode 100644 index 00000000..b57e61b3 --- /dev/null +++ b/ecobot_service/__main__.py @@ -0,0 +1,115 @@ +"""python -m ecobot_service: the weather and air service on its own (docs/mcp-service.md 3.8). It runs the sources and their syncers +(ecobot_service/core.py: the keep-warm, the first fetch, the archive, the backfills, Home Assistant's imports), the alert rules writing +the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a +reverse proxy such as Caddy) to reach it from elsewhere. + +Settings come from the environment, as the bot reads them (lib/config.py, docs/configuration.md), less the bot's own (no Telegram token +is needed), with MCP_TOKENS (name:token,..., one per client), MCP_BIND (host:port, default 127.0.0.1:8765) and MCP_ALLOWED_HOSTS (the +Host names it answers, default 127.0.0.1 and localhost). Without MCP_TOKENS it serves without auth, and then only on a loopback address.""" + +import asyncio +import contextlib +import ipaddress +import logging +import signal + +import uvicorn + +from lib.config import Config +from lib.logs import LogFormat, on_journal, stream_handlers + +from .core import Core, configure, start_sources, version + +log = logging.getLogger("ecobot.service") +SHUTDOWN_SECONDS = 3 # how long uvicorn waits for open connections (a listen stream) to end when the service stops + + +class Uvicorn(uvicorn.Server): + """uvicorn's server, leaving SIGINT and SIGTERM to the service (which closes everything in order: uvicorn's own handling raises the + signal again once it has stopped, ending the process before the sources are closed).""" + + @contextlib.contextmanager + def capture_signals(self): + yield + + +def loopback(host: str) -> bool: + if host == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def server_config(app, host: str, port: int) -> uvicorn.Config: + """uvicorn's settings for the app: its lifespan on (the MCP session manager runs in it), its own access log off, and an open + listen stream given SHUTDOWN_SECONDS to end when it stops (else it would wait for the client to hang up).""" + return uvicorn.Config(app, host=host, port=port, lifespan="on", log_level="warning", access_log=False, proxy_headers=True, + timeout_graceful_shutdown=SHUTDOWN_SECONDS) + + +async def main(): + from lib.mcp_server import EcobotServer, http_app + log.info("Starting the ecobot service %s", version()) + cfg = Config.from_env(bot=False) + for name in ("ecobot", "lib"): + logging.getLogger(name).setLevel(cfg.log_level) + host, port = cfg.mcp_bind + if not cfg.mcp_tokens and not loopback(host): + raise SystemExit(f"MCP_BIND is {host}:{port}, which other machines can reach, and MCP_TOKENS is empty: set MCP_TOKENS " + "(name:token,...) or bind to 127.0.0.1") + configure(cfg) + async with contextlib.AsyncExitStack() as stack: + sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on + for source in sources: + stack.push_async_callback(source.close) + if not sources: + raise SystemExit("No data source is working - nothing to serve") + from lib.warm import Tasks + tasks = Tasks() + core = await Core.open(cfg, sources, stack, tasks) + stack.push_async_callback(tasks.close) + for source in sources: + stack.push_async_callback(source.warmer.stop) + server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) + app = http_app(server, tokens=cfg.mcp_tokens, allowed_hosts=cfg.mcp_allowed_hosts, issuer_url=f"http://{host}:{port}") + core.log_startup() + running = core.start_alerts() + core.start_warmers() + tasks.start(server.run()) + + async def warm_up(): + await core.warm_up(running) + if missing := core.missing_alerts(running): + log.warning("Alerts NOT running: %s (see the error above)", ", ".join(missing)) + tasks.start(warm_up()) + + stop = asyncio.Event() + for sig in (signal.SIGINT, signal.SIGTERM): + asyncio.get_running_loop().add_signal_handler(sig, stop.set) + web = Uvicorn(server_config(app, host, port)) + serving = asyncio.create_task(web.serve()) + log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", host if ":" not in host else f"[{host}]", port, + f"tokens for {', '.join(name for name, _ in cfg.mcp_tokens)}" if cfg.mcp_tokens else "no auth (loopback only)", + ", ".join(cfg.mcp_allowed_hosts)) + waiting = asyncio.create_task(stop.wait()) + await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) + server.listen.close() # (the listen streams end gracefully: their clients know to listen again) + web.should_exit = True + await serving + waiting.cancel() + if not stop.is_set(): + raise SystemExit(f"The MCP server stopped: is {host}:{port} free?") + + +def run(): + _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) + logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) + logging.getLogger("httpx").setLevel(logging.WARNING) + with contextlib.suppress(KeyboardInterrupt): + asyncio.run(main()) + + +if __name__ == "__main__": + run() diff --git a/ecobot_service/bridge.py b/ecobot_service/bridge.py new file mode 100644 index 00000000..06cdce16 --- /dev/null +++ b/ecobot_service/bridge.py @@ -0,0 +1,234 @@ +"""python -m ecobot_service.bridge: the service on stdio, for a desktop client that starts its servers as commands (docs/mcp-service.md +3.8). It is a thin bridge: an SDK client of the running service (WEATHER_MCP_URL, default http://127.0.0.1:8765/mcp, with the bearer +token WEATHER_MCP_TOKEN), re-exposed as an MCP server on stdin and stdout: the tools, resources, resource templates and prompts are +forwarded as they are (a tool call's request _meta too), the server's instructions are the service's, and the service's listen stream +is forwarded to the client's listens. No sources, no rules, no file of its own: a second process on the readings file would fetch and +alert twice, and its in-memory bus would hear nothing. + +The upstream connection is supervised (Upstream): the protocol revision is pinned (2026-07-28, so a proxy's 502 during a restart +can't land it on the older revision, which can't listen) and discovered once by hand for the instructions; when the connection fails +or the listen is lost, the client is dropped and a new one built after a backoff, which listens again, and the bridge's own listeners +are told everything changed (there is no replay). A request while it is down is refused with an error that says so. + + python -m ecobot_service.bridge [--url URL] + +Logs go to stderr: stdout is the protocol.""" + +import argparse +import asyncio +import contextlib +import logging +import os +import sys + +import mcp_types as types +from mcp import Client +from mcp.server.lowlevel import Server +from mcp.server.subscriptions import (InMemorySubscriptionBus, ListenHandler, PromptsListChanged, ResourcesListChanged, ResourceUpdated, + ToolsListChanged) +from mcp.shared.exceptions import MCPError + +log = logging.getLogger("ecobot.bridge") + +URL_ENV, TOKEN_ENV = "WEATHER_MCP_URL", "WEATHER_MCP_TOKEN" +DEFAULT_URL = "http://127.0.0.1:8765/mcp" +VERSION = "2026-07-28" # the protocol revision pinned: the one that can listen +READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed +CONNECT_WAIT = 10.0 # how long a request waits for the service to be reached before it is refused +BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated +OWN_META = "io.modelcontextprotocol/" # the SDK's own _meta keys, stamped by each side itself: never forwarded + + +def _forwarded(meta) -> dict | None: + """A _meta as passed on: the SDK's own keys and the progress token left out (each side stamps its own).""" + out = {k: v for k, v in dict(meta or {}).items() if not k.startswith(OWN_META) and k not in ("progressToken", "progress_token")} + return out or None + + +def http_transport(url: str, token: str | None = None): + """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS.""" + import httpx2 + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + + @contextlib.asynccontextmanager + async def connect(): + headers = {"Authorization": f"Bearer {token}"} if token else None + async with create_mcp_http_client(headers=headers, timeout=httpx2.Timeout(30.0, read=READ_SECONDS)) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + return connect() + + +class Upstream: + """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or + its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" + + def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None): + """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is + acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async.""" + self.target, self.token = target, token + self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening + self.client: Client | None = None + self.connected = asyncio.Event() + self.attempts = 0 + + def _client(self) -> Client: + server = http_transport(self.target, self.token) if isinstance(self.target, str) else self.target + return Client(server, mode=VERSION, cache=None) + + async def run(self): + """Keep a connection, until cancelled.""" + while True: + try: + async with self._client() as client: + raw = await client.session.send_discover(VERSION) + discovered = types.DiscoverResult.model_validate(raw) + client.session.adopt(discovered) + if self.on_discover: + await self.on_discover(discovered) + self.client, self.attempts = client, 0 + self.connected.set() + log.info("Bridge: connected to %s", self.target if isinstance(self.target, str) else "the service") + await self._listen(client) + log.warning("Bridge: the service ended the listen; connecting again") + except asyncio.CancelledError: + raise + except BaseException as e: # (a transport failure ends the whole client, as an exception group too) + if isinstance(e, (KeyboardInterrupt, SystemExit)): + raise + log.warning("Bridge: the service at %s isn't reachable (%s: %s); trying again", self.target, type(e).__name__, e) + finally: + self.client = None + self.connected.clear() + await asyncio.sleep(BACKOFF[min(self.attempts, len(BACKOFF) - 1)]) + self.attempts += 1 + + async def _listen(self, client: Client): + """Listen to every resource the service lists and its lists' changes, passing each event on, until the stream ends.""" + uris = [r.uri for r in (await client.list_resources()).resources] + async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, + resource_subscriptions=uris) as sub: + if self.on_listening: + await self.on_listening() + async for event in sub: + if self.on_event: + await self.on_event(event) + + async def get(self) -> Client: + """The connected client; refused (MCPError) when the service can't be reached within CONNECT_WAIT.""" + if self.client is None: + try: + await asyncio.wait_for(self.connected.wait(), CONNECT_WAIT) + except TimeoutError: + pass + if self.client is None: + raise MCPError(types.INTERNAL_ERROR, f"The weather service isn't reachable ({self.target}): try again shortly.") + return self.client + + +class Bridge: + """The stdio server (`server`) forwarding to the service through `upstream`.""" + + def __init__(self, target=DEFAULT_URL, token: str | None = None): + self.bus = InMemorySubscriptionBus() + self.upstream = Upstream(target, token, on_event=self.bus.publish, on_discover=self._discovered, on_listening=self._listening) + self._first = True + self.server = Server("ecobot-bridge", title="Ecobot weather and air service (bridge)", + on_list_tools=self._list_tools, on_call_tool=self._call_tool, + on_list_resources=self._list_resources, on_list_resource_templates=self._list_templates, + on_read_resource=self._read_resource, on_list_prompts=self._list_prompts, on_get_prompt=self._get_prompt, + on_subscriptions_listen=ListenHandler(self.bus)) + + async def _discovered(self, discovered: types.DiscoverResult): + """A new connection: the service's instructions are the bridge's.""" + self.server.instructions = discovered.instructions + + async def _listening(self): + """Listening again: after the first time, every listener is told everything changed, since what happened while the link was + down is not replayed.""" + if self._first: + self._first = False + return + client = self.upstream.client + await self.bus.publish(ToolsListChanged()) + await self.bus.publish(PromptsListChanged()) + await self.bus.publish(ResourcesListChanged()) + if client is not None: + for r in (await client.list_resources()).resources: + await self.bus.publish(ResourceUpdated(str(r.uri))) + + async def _call(self, fn): + """fn(client) against the service: its error (MCPError) passed on as it is; a failed connection refused with one that says so.""" + client = await self.upstream.get() + try: + return await fn(client) + except MCPError: + raise + except Exception as e: + raise MCPError(types.INTERNAL_ERROR, f"The weather service didn't answer ({type(e).__name__}: {e}).") from e + + async def _list_tools(self, ctx, params) -> types.ListToolsResult: + r = await self._call(lambda c: c.list_tools()) + return types.ListToolsResult(tools=r.tools) + + async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.CallToolResult: + r = await self._call(lambda c: c.call_tool(params.name, params.arguments, meta=_forwarded(ctx.meta))) + return types.CallToolResult(content=r.content, structured_content=r.structured_content, is_error=r.is_error, + _meta=_forwarded(r.meta)) + + async def _list_resources(self, ctx, params) -> types.ListResourcesResult: + r = await self._call(lambda c: c.list_resources()) + return types.ListResourcesResult(resources=r.resources) + + async def _list_templates(self, ctx, params) -> types.ListResourceTemplatesResult: + r = await self._call(lambda c: c.list_resource_templates()) + return types.ListResourceTemplatesResult(resource_templates=r.resource_templates) + + async def _read_resource(self, ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: + r = await self._call(lambda c: c.read_resource(str(params.uri))) + return types.ReadResourceResult(contents=r.contents) + + async def _list_prompts(self, ctx, params) -> types.ListPromptsResult: + r = await self._call(lambda c: c.list_prompts()) + return types.ListPromptsResult(prompts=r.prompts) + + async def _get_prompt(self, ctx, params: types.GetPromptRequestParams) -> types.GetPromptResult: + r = await self._call(lambda c: c.get_prompt(params.name, params.arguments)) + return types.GetPromptResult(description=r.description, messages=r.messages) + + @contextlib.asynccontextmanager + async def running(self, wait: float = CONNECT_WAIT): + """The upstream supervisor running (the first connection waited for, up to `wait` seconds, so the instructions are there for the + client's first request), cancelled on leaving.""" + task = asyncio.create_task(self.upstream.run()) + try: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(self.upstream.connected.wait(), wait) + yield self + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +async def main(argv: list[str] | None = None): + from mcp.server.stdio import stdio_server + parser = argparse.ArgumentParser(prog="python -m ecobot_service.bridge", description=__doc__.split("\n\n")[0]) + parser.add_argument("--url", default=os.getenv(URL_ENV) or DEFAULT_URL, help=f"the service's MCP endpoint (${URL_ENV}, default {DEFAULT_URL})") + args = parser.parse_args(argv) + bridge = Bridge(args.url, os.getenv(TOKEN_ENV) or None) + async with bridge.running(): + async with stdio_server() as (read, write): + await bridge.server.run(read, write, bridge.server.create_initialization_options()) + + +def run(): + logging.basicConfig(level=logging.INFO, stream=sys.stderr, format="%(levelname)s %(message)s") + logging.getLogger("httpx2").setLevel(logging.WARNING) + logging.getLogger("httpx").setLevel(logging.WARNING) + with contextlib.suppress(KeyboardInterrupt): + asyncio.run(main()) + + +if __name__ == "__main__": + run() diff --git a/ecobot_service/core.py b/ecobot_service/core.py new file mode 100644 index 00000000..15a73445 --- /dev/null +++ b/ecobot_service/core.py @@ -0,0 +1,298 @@ +"""The service's startup (docs/mcp-service.md step 5: "ecobot.py's warm_up() is split"), shared by the service (python -m +ecobot_service) and the bot (ecobot.py), which runs it in-process until it is a client of the service: + + 1. `configure(cfg)`: the settings the engines read as module values (the anti-spike rule, what "all" draws, what `about` says); + 2. `start_sources(cfg)`: every configured source that starts, the weather station first (its time zone wins); + 3. `Core.open(cfg, sources, stack, tasks)`: the alert log, the tools' Context and the ten tools (lib/service); + 4. `core.log_startup()`: each source's startup line; + 5. `core.start_alerts()`: the alert rules (lib/service/alerts.py), writing the alert log; `core.start_warmers()`: the keep-warm; + 6. `core.warm_up(running)`: the first fetch, then the weather alerts, the live poll, the archive, Home Assistant's imports, the air + sensor's history and backfill. + +`Health` records each loop's last success and failure (ecobot://health).""" + +import asyncio +import dataclasses +import functools +import logging +import os +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, field +from datetime import datetime + +from lib.airgradient import AirGradient +from lib.airgradient import metrics as air_metrics +from lib.alert_log import AlertLog +from lib.alerts.menu import LABELS, available_kinds +from lib.alerts.store import AlertStore +from lib.compose import Composer +from lib.config import ROOT, Config +from lib.ecowitt import Archive, Ecowitt +from lib.ecowitt.source import HA_IMPORT_SECONDS +from lib.forecast import Forecast +from lib.logs import BUGS +from lib.pollen import Pollen +from lib.service import Service +from lib.service import about as service_about +from lib.service import names as service_names +from lib.service.alerts import AlertRules +from lib.service.context import Context +from lib.sources import Source +from lib.storage import Storage +from lib.warm import Tasks, every, safely + +log = logging.getLogger("ecobot.service") # (under the bot's own logger: LOG_LEVEL reaches it) + + +def configure(cfg: Config): + """The settings the engines read as module values: the anti-spike rule, what "all" draws, what `about` says of the alerts.""" + air_metrics.REQUIRE_CONSECUTIVE = cfg.antispike_require_consecutive + service_names.FEELS_LIKE_IN_ALL = cfg.chart_all_feels_like # "all" (and "weather all week") draws these too + service_names.VPD_IN_ALL = cfg.chart_all_vpd + service_about.RAIN_QUIET_HOURS = cfg.rain_quiet_hours # what `about` says of the rain alert's quiet hours ... + service_about.ALERT_COOLDOWN_MINUTES = cfg.alert_cooldown_minutes # ... and of the alerts' cooldown + + +async def start_sources(cfg: Config) -> tuple[list[Source], Config]: + """Every configured data source that starts, and the settings in the time zone they run in. The weather station starts + first: it names its own time zone, which wins over TZ, so the air sensor and the optional website sources (pollen, + forecast, off unless switched on), and everything built after, use the station's; those three start side by side (each + waits on its own server). The forecast uses the station's location unless one is configured.""" + sources: list[Source] = [] + took: dict[str, float] = {} + + async def start(kind: type[Source], *args, **kwargs) -> Source | None: + """A source made and started; one that fails either way is logged and left out (None).""" + source, started = None, time.monotonic() + try: + source = kind(*args, **kwargs) + await source.start() + return source + except Exception as e: + log.error("%s couldn't start (%s: %s) - continuing without it", kind.name, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + if source is not None: + await safely(source.close) + return None + finally: + took[kind.name] = time.monotonic() - started + storage = None + if cfg.ecowitt or cfg.airgradient: + try: # (in a thread: opening makes or upgrades its tables) + storage = await asyncio.to_thread(Storage, cfg.storage_path, cfg.tz) + except Exception as e: + log.error("The history file %s couldn't be opened (%s: %s) - continuing without the weather station and the air sensor", + cfg.storage_path, type(e).__name__, e, exc_info=isinstance(e, BUGS)) + if cfg.ecowitt and storage is not None and (eco := await start(Ecowitt, cfg, storage=storage)): + sources.append(eco) + eco = sources[0] if sources else None + if eco and str(eco.tz) != str(cfg.tz): + if os.getenv("TZ"): + log.warning("TZ=%s is not the weather station's time zone; using the station's, %s", os.getenv("TZ"), eco.tz) + cfg = dataclasses.replace(cfg, tz=eco.tz) + if not getattr(cfg.tz, "key", None): + log.warning("The time zone has no name, only an offset (%s), so daylight saving will put the times out: set TZ, " + "e.g. TZ=Australia/Melbourne", cfg.tz) + starts = [] + if cfg.airgradient and storage is not None: # (one file and one Home Assistant client for both; the file is the station's to close, else the sensor's) + starts.append(start(AirGradient, cfg, storage=storage, owned=eco is None, **({"ha": eco.ha} if eco and eco.ha else {}))) + if cfg.pollen: + starts.append(start(Pollen, cfg)) + if cfg.forecast: + starts.append(start(Forecast, cfg, (eco.latitude, eco.longitude) if eco and None not in (eco.latitude, eco.longitude) else None)) + sources += [s for s in await asyncio.gather(*starts) if s is not None] # (in this order, whichever answers first) + if storage is not None and not sources: + storage.close() + if took: + log.debug("Sources started in %.1fs: %s", sum(took.values()), ", ".join(f"{name} {seconds:.1f}" for name, seconds in took.items())) + return sources, cfg + + +# ---------- health ---------- +class Health: + """Each loop's last success and failure (`track`), and the archive's last run (`archived`), for ecobot://health.""" + + def __init__(self, tz=None): + self.tz = tz + self.loops: dict[str, dict] = {} + self.archive: dict = {} + self.extra: dict[str, Callable[[], dict]] = {} # name -> figures read when asked (the live poll's last answer) + + def track(self, name: str, fn: Callable[..., Awaitable]) -> Callable[..., Awaitable]: + """fn, its every run recorded under `name`: when it last succeeded, when it last failed and why. It raises as before, and keeps + its name (safely() logs a failure by it).""" + @functools.wraps(fn) + async def run(*args, **kwargs): + entry = self.loops.setdefault(name, {}) + try: + out = await fn(*args, **kwargs) + except Exception as e: + entry.update(last_failure=time.time(), error=f"{type(e).__name__}: {e}") + raise + entry["last_ok"] = time.time() + return out + return run + + def _time(self, t: float | None) -> str | None: + return None if not t else datetime.fromtimestamp(t, self.tz).isoformat(timespec="seconds") + + def report(self) -> dict: + loops = {name: {k: self._time(v) if k.startswith("last_") else v for k, v in entry.items()} for name, entry in self.loops.items()} + for name, read in self.extra.items(): + try: + loops[name] = {k: self._time(v) if k.startswith("last_") else v for k, v in read().items()} + except Exception as e: # (only a figure) + loops[name] = {"error": f"{type(e).__name__}: {e}"} + archive = {k: self._time(v) if k.startswith("last_") else v for k, v in self.archive.items()} + return {"loops": loops, **({"archive": archive} if archive else {})} + + +# ---------- the service ---------- +@dataclass +class Core: + """The service as it runs: its settings, sources, alert log, tools and their Context, the alert rules once started.""" + cfg: Config + sources: list[Source] + alert_log: AlertLog + ctx: Context + service: Service + tasks: Tasks + health: Health + rules: AlertRules | None = None + running: list[str] = field(default_factory=list) # the alert types running (the weather's go first once they start) + + @property + def by_name(self) -> dict[str, Source]: + return {s.name: s for s in self.sources} + + @classmethod + async def open(cls, cfg: Config, sources: list[Source], stack, tasks: Tasks) -> "Core": + """The alert log (closed by `stack`) and the ten tools over the sources that started.""" + by_name = {s.name: s for s in sources} + eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") + composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources + alert_log = AlertLog(cfg.alert_log_path, cfg.tz) # the alerts the rules decide, which clients deliver + stack.callback(alert_log.close) + ctx = await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), pollen=by_name.get("Pollen"), + tz=cfg.tz) + service = Service.of(ctx) + log.info("Service tools: %s", ", ".join(t.name for t in service)) + health = Health(cfg.tz) + for source in sources: # (the keep-warm's refreshes, recorded) + source.warmer.refresh = health.track(f"{source.name} refresh", source.warmer.refresh) + if eco is not None and eco.fast is not None: + health.extra["Ecowitt live poll"] = lambda: {"last_ok": eco._polled or None} + return cls(cfg, sources, alert_log, ctx, service, tasks, health) + + def log_startup(self): + """Each source's startup line, in the order they are listed.""" + for source in self.sources: + for line in source.startup_lines(): + log.info("%s", line) + + def start_alerts(self, moved_from=None) -> list[str]: + """The alert rules over every source that started (lib/service/alerts.py), writing the alert log; the weather's start in + warm_up, once the station has been read. moved_from: the bot's state, whose rules' state the first start moves (AlertStore). + Returns the alert types now running (a list warm_up adds the weather's to).""" + store = AlertStore(self.cfg.alert_state_path, moved_from=moved_from) + self.rules = AlertRules(self.by_name, store, self.alert_log, self.cfg.alert_cooldown_minutes * 60, self.cfg.rain_quiet_hours, + self.service) + self.running = self.rules.start(self.tasks) + return self.running + + def start_warmers(self): + """Keeping warm: everything questions need, refreshed before they arrive.""" + for source in self.sources: + self.tasks.start(source.warmer.run()) + + async def warm_up(self, running: list[str] | None = None): + """Fetch everything once, together; then start what waited for it: the weather alerts, the live poll, the archives (copying each + source's history into its file), Home Assistant's imports.""" + running = self.running if running is None else running + eco, air, tasks, health = self.by_name.get("Ecowitt"), self.by_name.get("AirGradient"), self.tasks, self.health + + async def ecowitt_part(): + # One request at a time (Ecowitt rate-limits): warm first, so the alerts' own look at the last 3 hours is answered + # from what was just fetched. A failed first refresh must not stop the alerts or the archive: safely() logs it + await safely(health.track("Ecowitt refresh", eco.warm), True) + try: + if self.rules is not None: + await self.rules.start_weather(running) + except Exception as e: + log.error("Weather alerts couldn't start (%s: %s)", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + if eco.fast is not None: + tasks.start(eco.watch_live()) + # The full history is copied into the cache in the background (a few minutes the first time), so questions rarely + # need Ecowitt inline + archive = Archive(eco, eco.archive_pace) + archive.run_once = self._archived(archive, archive.run_once) + tasks.start(archive.loop()) + if eco.ranges_from_ha: # the cloud's readings get their 5-minute bands from what Home Assistant kept, the days the bot was not watching too + tasks.start(every(HA_IMPORT_SECONDS, health.track("Ecowitt Home Assistant import", eco.import_ranges))) + + async def air_part(): + await safely(health.track("AirGradient refresh", air.warm), True) + tasks.start(air_history()) # even if the sensor was unreachable just now + + async def air_history(): + """What Home Assistant kept of the monitor (the readings the service lacks, their bands, the minutes), then the days the cache + lacks, then Home Assistant again every HA_IMPORT_SECONDS.""" + imported = health.track("AirGradient Home Assistant import", air.import_history) + if air.ha: # (first: it is quick, and holds the last days; the backfill can take minutes the first time) + await safely(imported) + if air.cloud: + await safely(health.track("AirGradient backfill", air_backfill)) + if air.ha: + await every(HA_IMPORT_SECONDS, imported) + + async def air_backfill(): + started = time.monotonic() + fetched, failed, total = await air.backfill() + log.info("Backfill AirGradient: %d days fetched, %d failed, %d days held, %.0fs", fetched, failed, total, time.monotonic() - started) + + try: + await asyncio.gather(*([ecowitt_part()] if eco else []), *([air_part()] if air else [])) + except Exception as e: + log.error("Startup fetch failed (%s: %s); the regular refreshes will catch up", type(e).__name__, e, exc_info=isinstance(e, BUGS)) + + def _archived(self, archive: Archive, run_once): + """The archive's run, its outcome recorded (Health.archive): when it last ran, what it fetched and failed, and what is held.""" + tracked = self.health.track("Ecowitt archive", run_once) + + @functools.wraps(run_once) + async def run(): + fetched, failed = await tracked() + self.health.archive = {"last_run": time.time(), "fetched": fetched, "failed": failed, "held": archive.held()} + return fetched, failed + return run + + def missing_alerts(self, running: list[str] | None = None, irrigation: bool = False) -> list[str]: + """The alert types the sources have that are not running (their labels): a rule that could not start.""" + running = self.running if running is None else running + return [LABELS[k] for k in available_kinds(self.by_name, irrigation) if k not in running] + + +# ---------- the running code ---------- +def version() -> str: + """The checked-out commit, so the log shows which code is running.""" + return commit_in(ROOT / ".git") + + +def commit_in(git_dir) -> str: + """The short hash HEAD points at, read from the repository's files rather than by running git (which refuses a folder owned by + another user, as when the service runs as its own user). "unknown" when it cannot be read.""" + try: + head = (git_dir / "HEAD").read_text().strip() + if head.startswith("ref:"): + ref = head.split(None, 1)[1] + try: + head = (git_dir / ref).read_text().strip() + except FileNotFoundError: # after `git pack-refs` or gc the branch is a line in packed-refs + head = next(line.split()[0] for line in (git_dir / "packed-refs").read_text().splitlines() + if line.endswith(f" {ref}")) + return head[:7] if len(head) >= 7 and all(c in "0123456789abcdef" for c in head.lower()) else "unknown" + except Exception: + return "unknown" + + +__all__ = ["Core", "Health", "commit_in", "configure", "start_sources", "version"] diff --git a/lib/bot.py b/lib/bot.py index 168332a1..3c72b45c 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -12,7 +12,6 @@ import re import time from collections import defaultdict -from collections.abc import Coroutine from dataclasses import dataclass, field from datetime import datetime, UTC from typing import NamedTuple @@ -43,6 +42,7 @@ from .timeutil import clock_text, day_text, now_local from .llm import Agent, shorten_old, strip_tool_turns, trim_history from .logs import BUGS, QUOTES, fit +from .warm import Tasks # (the service's too: ecobot_service) log = logging.getLogger(__name__) @@ -387,29 +387,6 @@ async def deliver(msg: Message, text: str, photos: list[bytes], link: tuple[str, return Delivered(on_text and bool(text), sent) -class Tasks: - """The tasks the bot runs in the background: one that stops with an error is logged as it does, and close() cancels them.""" - - def __init__(self): - self.running: set[asyncio.Task] = set() - - def start(self, work: Coroutine) -> asyncio.Task: - task = asyncio.create_task(work, name=getattr(work, "__qualname__", None)) - self.running.add(task) - task.add_done_callback(self._ended) - return task - - def _ended(self, task: asyncio.Task): - self.running.discard(task) - if not task.cancelled() and (error := task.exception()): - log.error("%s stopped: %s: %s", task.get_name(), type(error).__name__, error, exc_info=error if isinstance(error, BUGS) else None) - - async def close(self): - for task in self.running: - task.cancel() - await asyncio.gather(*self.running, return_exceptions=True) - - class Bot: def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None, service: Service | None = None, alert_log=None): diff --git a/lib/config.py b/lib/config.py index a33b23b9..a01fe396 100644 --- a/lib/config.py +++ b/lib/config.py @@ -62,6 +62,42 @@ def _required(value: str, default: str, name: str) -> str: raise SystemExit(f"{name} is not set: the bot can't start without it (see docs/configuration.md)") +REQUIRED_BY_BOT = ("telegram_token",) # read only by the bot: the service (python -m ecobot_service) runs without them + + +def _tokens(value: str, default: tuple, name: str) -> tuple[tuple[str, str], ...]: + """"bot:s3cret, phone:t0ken" -> (("bot", "s3cret"), ("phone", "t0ken")): one token per client, each named, so one can be revoked + alone. An entry without a name or a token is ignored (and logged by its name, never its token); a name given twice keeps the last.""" + found, bad = {}, [] + for part in filter(None, (p.strip() for p in value.split(","))): + who, _, token = part.partition(":") + if who.strip() and token.strip(): + found[who.strip()] = token.strip() + else: + bad.append(who.strip() if token.strip() == "" and who.strip() else "(no name)") + if bad: + log.warning("%s: ignoring %s (each entry is name:token)", name, ", ".join(bad)) + return tuple(found.items()) or default + + +def _bind(value: str, default: tuple[str, int], name: str) -> tuple[str, int]: + """"0.0.0.0:8765" -> ("0.0.0.0", 8765), "[::1]:8765" -> ("::1", 8765), "8765" -> (the default host, 8765); anything unreadable + keeps the default, with a warning.""" + if not value: + return default + host, sep, port = value.rpartition(":") + host = host.strip().strip("[]") if sep else default[0] + if port.strip().isdecimal() and 0 < int(port) < 65536 and host: + return host, int(port) + log.warning("%s: %r is not host:port; keeping %s:%d", name, value, *default) + return default + + +def _names(value: str, default: tuple[str, ...], name: str) -> tuple[str, ...]: + """"ecobot.lan, 192.168.1.5:8765" -> ("ecobot.lan", "192.168.1.5:8765"); unset or empty is the default.""" + return tuple(filter(None, (p.strip() for p in value.split(",")))) or default + + def _url(value: str, default: str, name: str) -> str: return (value or default).rstrip("/") @@ -211,7 +247,7 @@ class Config: tz: tzinfo state_path: Path storage_path: Path # the bot's one file of readings, the pollen page and the forecast (lib/storage) - telegram_token: str = _setting("TELEGRAM_BOT_TOKEN", "", _required) + telegram_token: str = _setting("TELEGRAM_BOT_TOKEN", "") # the bot's (REQUIRED_BY_BOT: it stops without it) openrouter_api_key: str = _setting("OPENROUTER_API_KEY", "") # unset: the bot runs without the model, answering only what it works out in code openrouter_base_url: str = _setting("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1") openrouter_model: str = _setting("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") @@ -247,6 +283,10 @@ class Config: antispike_require_consecutive: int = _setting("ANTISPIKE_REQUIRE_CONSECUTIVE", 2, _readings_in_a_row) # readings in a row a rise of the particles needs to be the air, not a glitch of the sensor (1: off) log_width: int = _setting("LOG_WIDTH", 24, _whole) # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the bot's own debug lines; the libraries keep theirs + # The MCP service (python -m ecobot_service: docs/mcp-service.md 3.8) + mcp_tokens: tuple[tuple[str, str], ...] = _setting("MCP_TOKENS", (), _tokens) # "name:token,...", one per client; none: no auth, loopback only + mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind) # host:port the service listens on + mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) @property def alert_state_path(self) -> Path: @@ -302,9 +342,9 @@ def airgradient(self) -> bool: return self.airgradient_cloud or self.airgradient_local or self.airgradient_homeassistant @classmethod - def from_env(cls) -> "Config": + def from_env(cls, bot: bool = True) -> "Config": """Every setting from its variable, the files in the data folder. Stops, saying why, when one the bot can't run without is - missing or the folder can't be written.""" + missing or the folder can't be written. bot: False for the service (python -m ecobot_service), which has no Telegram token.""" data = data_dir() try: data.mkdir(parents=True, exist_ok=True) @@ -316,6 +356,9 @@ def from_env(cls) -> "Config": "(under systemd with StateDirectory=ecobot that is /var/lib/ecobot)") cfg = cls(tz=local_tz(), state_path=data / "bot_state.json", storage_path=data / "ecobot.sqlite", **{f.name: _from_env(f) for f in fields(cls) if "env" in f.metadata}) + for f in fields(cls): + if bot and f.name in REQUIRED_BY_BOT: + _required(getattr(cfg, f.name), f.default, f.metadata["env"]) if not (cfg.ecowitt or cfg.airgradient): raise SystemExit("Set ECOWITT_API_KEY + ECOWITT_APP_KEY and/or HOMEASSISTANT_URL + HOMEASSISTANT_TOKEN and/or AIRGRADIENT_API_TOKEN + " "AIRGRADIENT_LOCATION_ID and/or AIRGRADIENT_LOCAL_URL") diff --git a/lib/mcp_server.py b/lib/mcp_server.py new file mode 100644 index 00000000..d8613c8e --- /dev/null +++ b/lib/mcp_server.py @@ -0,0 +1,425 @@ +"""The service over MCP (docs/mcp-service.md 3.4-3.8): the SDK's low-level Server serving the ten tools (lib/service), the resources and +prompts, the server's instructions (lib/service/instructions.py) and the `subscriptions/listen` stream, as Streamable HTTP behind a bearer +token check. + + - **Tools**: each ServiceTool as it is, its hand-written input schema and description, `readOnlyHint` and `openWorldHint` from it. The + list is built when asked, from the catalogue of readings the file holds: when that gains a reading (`refresh_catalogue`, every + CATALOGUE_SECONDS) the tools are built again and ToolsListChanged is published. A call runs the ServiceTool with the request's + `_meta` (`chart_points`, `fetch`, `priority`: common.request_meta) and answers its JSON as one text block, unchanged: its charts are + the full chart JSON (3.7), sized by `chart_points`. A refusal is `isError`. A complete answer (3.7: `chart_answers_it` and a chart) + also carries its `reply` as a second text block for the person (`audience: ["user"]`) and result `_meta` {"ecobot/complete": true}. + - **Resources** (3.4): RESOURCES, and the alerts with `since` and `expired` (the ALERTS_TEMPLATE). Each is JSON. The live ones are + published as ResourceUpdated when they change (`publish_changes`, every PUBLISH_SECONDS, from what the sources keep: no request is + made for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`watch_alerts`, lib/alert_log.py + `wait`), the station when the catalogue gains a reading. + - **Prompts** (3.5): PROMPTS, each a question in words with its period an argument; no logic. + - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against the allowed hosts + (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_ALLOWED_HOSTS says), each request's bearer token against + MCP_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). + +`EcobotServer(ctx, alert_log)` builds it over the service's Context; `run()` is its publishing, for as long as it runs. Nothing here +fetches, alerts or writes: ecobot_service runs the sources and the rules.""" + +import asyncio +import hmac +import json +import logging +import os +from collections.abc import Callable +from datetime import date, datetime +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +import mcp_types as types +from mcp.server.auth.provider import AccessToken +from mcp.server.auth.settings import AuthSettings +from mcp.server.lowlevel import Server +from mcp.server.subscriptions import InMemorySubscriptionBus, ListenHandler, ResourceUpdated, ToolsListChanged +from mcp.server.transport_security import TransportSecuritySettings +from mcp.shared.exceptions import MCPError + +from .config import ROOT +from .service import Service +from .service.about import AboutTool, alerts as alert_kinds +from .service.common import iso +from .service.current import CurrentTool +from .service.instructions import instructions +from .service.names import AIR_DEVICE, STATION, Catalogue + +log = logging.getLogger(__name__) + +NAME = "ecobot" +COMPLETE = "ecobot/complete" # result _meta of a complete answer (3.7) +RESOURCE_NOT_FOUND = -32002 # MCP's error for a resource there is none of +PUBLISH_SECONDS = 2.0 # how often the live resources are compared with what was last published +CATALOGUE_SECONDS = 60.0 # how often the file's catalogue of readings is read again +SCHEMA_PATH = ROOT / "schemas" / "chart.json" +JSON = "application/json" + +# ---------- resources (3.4) ---------- +STATION_URI, WEATHER_URI, AIR_URI = "ecobot://station", "ecobot://now/weather", "ecobot://now/air" +ALERTS_URI, FORECAST_URI, POLLEN_URI = "ecobot://alerts", "ecobot://forecast", "ecobot://pollen" +HEALTH_URI, SCHEMA_URI = "ecobot://health", "ecobot://schema/chart" +ALERTS_TEMPLATE = "ecobot://alerts{?since,expired}" +RESOURCES = { # uri: (name, title, description, the source it needs: None for always) + STATION_URI: ("station", "The station", "Its name, time zone, location and when it was set up; the sensors with their readings (name, " + "label, unit) and the words people use for them; each source's mode and how far back its history goes; the alert " + "kinds, each with its rule and thresholds; the AirGradient dashboard link. Pushed when the readings change.", None), + WEATHER_URI: ("now/weather", "The weather now", "The weather station's live reading: {as_of, sensors: {sensor: {reading: {value, " + "unit, text, [emoji], [compass]}}}, lines, heading}. Pushed on each new reading (every 5 s with Home Assistant, 60 s " + "from the cloud).", "eco"), + AIR_URI: ("now/air", "The air now", "The air sensor's latest reading, with each reading's rating, PM2.5's US AQI and band: {as_of, " + "sensors: {air: {reading: {value, unit, text, [rating], [aqi_us, band]}}}, lines, heading}. Pushed on each new reading.", + "air"), + ALERTS_URI: ("alerts", "Alerts", "The alerts the service has decided, newest last, kept 30 days: {alerts: [{id, kind, time, expires, " + "title, text, data, [link], [chart]}], last_id, identity}; only those not yet expired (the template: since an id, and " + "expired=true for all). Pushed on each new alert.", None), + FORECAST_URI: ("forecast", "The forecast", "The forecast days, structured: {place, fetched_at, days: [{date, min_c, max_c, " + "rain_chance_pct, rain_1mm_pct, summary, text}]}. Pushed on each new forecast.", "forecast"), + POLLEN_URI: ("pollen", "Pollen and thunderstorm asthma", "Grass pollen and thunderstorm asthma levels: {in_season, fetched_at, " + "grass: {level, emoji, date}, asthma: {level, emoji, updated}, lines}. Pushed on each new page.", "pollen"), + HEALTH_URI: ("health", "Health", "Each loop's last success and failure, the archive's progress, the readings file's size and the " + "alert log's newest id. Not pushed.", None), + SCHEMA_URI: ("schema/chart", "Chart JSON Schema", "The JSON Schema of the charts in the tools' results and the alerts " + "(schemas/chart.json, versioned). Not pushed.", None), +} +PUSHED = (WEATHER_URI, AIR_URI, FORECAST_URI, POLLEN_URI) # compared every PUBLISH_SECONDS (the alerts and the station have their own) + +# ---------- prompts (3.5) ---------- +PERIOD = types.PromptArgument(name="period", description="The period in your own words (\"this week\", \"last 3 months\", \"yesterday\")", + required=False) +PROMPTS = { # name: (description, arguments, the question: a format string over the arguments, with their defaults) + "now": ("The weather and the air now.", [], "How is it outside now?"), + "report": ("A report: the readings now, today's forecast and the pollen.", [], + "Give me a report: the readings now, today's forecast and the pollen."), + "will_it_rain": ("Will it rain in the next few hours: the station's read and the forecast.", [], "Will it rain in the next few hours?"), + "weather": ("Every reading of the weather station over a period, a panel each.", [PERIOD], + "Chart every weather reading, a panel each, over {period}."), + "chart": ("A chart of a reading over a period.", + [types.PromptArgument(name="reading", description="The reading (\"temperature\", \"pressure\", \"pm2.5\")", required=True), + PERIOD], "Chart {reading} over {period}."), + "rain": ("How much rain fell over a period, and when.", [PERIOD], "How much rain fell over {period}?"), + "air": ("The air quality, now or over a period.", [PERIOD], "How was the air quality over {period}?"), +} +PROMPT_DEFAULTS = {"weather": {"period": "the last 7 days"}, "chart": {"period": "the last 24 hours"}, "rain": {"period": "today"}} +WITHOUT_ARGUMENTS = {"air": "How is the air quality now?"} # the question when no argument is sent + + +def _json(data) -> str: + return json.dumps(data, ensure_ascii=False, default=_plain) + + +def _plain(x): + """What JSON lacks: a date or a time as ISO.""" + if isinstance(x, (date, datetime)): + return x.isoformat() + raise TypeError(f"{type(x).__name__} is not JSON") + + +# ---------- a tool's answer as MCP's ---------- +def tool_entry(tool) -> types.Tool: + """A ServiceTool as tools/list gives it: its name, description, hand-written input schema and annotations.""" + return types.Tool(name=tool.name, description=tool.description, input_schema=tool.parameters, + annotations=types.ToolAnnotations(read_only_hint=tool.read_only, open_world_hint=tool.open_world)) + + +def tool_result(text: str) -> types.CallToolResult: + """A ServiceTool's answer as tools/call gives it: the JSON as one text block, unchanged; `isError` for a refusal; a complete answer + (3.7) with its reply for the person as a second block (audience user) and result _meta {COMPLETE: true}.""" + try: + data = json.loads(text) + except ValueError: + data = None + content: list = [types.TextContent(text=text)] + meta = None + if isinstance(data, dict) and data.get("complete") is True and isinstance(data.get("reply"), str) and "error" not in data: + content.append(types.TextContent(text=data["reply"], annotations=types.Annotations(audience=["user"]))) + meta = {COMPLETE: True} + return types.CallToolResult(content=content, is_error=isinstance(data, dict) and "error" in data, _meta=meta) + + +# ---------- auth ---------- +class TokenCheck: + """The service's TokenVerifier (3.8): a bearer token is one of MCP_TOKENS', compared in constant time against every one of them; + the client it names is the AccessToken's client_id. `revoke(name)` takes one out while the service runs (MCP_TOKENS without it does + the same at the next start).""" + + def __init__(self, tokens: dict[str, str] | tuple[tuple[str, str], ...]): + self.tokens = dict(tokens) + + def revoke(self, name: str): + self.tokens.pop(name, None) + + async def verify_token(self, token: str) -> AccessToken | None: + found = None + sent = (token or "").encode() + for name, known in list(self.tokens.items()): # (every one compared: the time says nothing of which matched) + if hmac.compare_digest(sent, known.encode()): + found = name + return AccessToken(token=token, client_id=found, scopes=[]) if found else None + + +def host_settings(allowed: tuple[str, ...] | list[str]) -> TransportSecuritySettings: + """The Host (and Origin) headers the service answers: each name allowed with any port, unless it names one.""" + hosts, origins = [], [] + for name in allowed: + bare = name.startswith("[") and name.endswith("]") or ":" not in name.rsplit("]", 1)[-1] + hosts += [name, f"{name}:*"] if bare else [name] + origins += [f"{scheme}://{h}" for scheme in ("http", "https") for h in ([name, f"{name}:*"] if bare else [name])] + return TransportSecuritySettings(enable_dns_rebinding_protection=True, allowed_hosts=hosts, allowed_origins=origins) + + +# ---------- the server ---------- +class EcobotServer: + """The service's MCP server over a Context (lib/service/context.py) and the alert log. health: a callable giving the service's own + health figures (ecobot_service's loops), merged into ecobot://health.""" + + def __init__(self, ctx, alert_log=None, *, health: Callable[[], dict] | None = None, version: str = "", bus=None): + self.ctx, self.alert_log, self.health_of = ctx, alert_log, health + self.bus = bus or InMemorySubscriptionBus() + self.listen = ListenHandler(self.bus) + self._service = Service.of(ctx) + self._seen: dict[str, str | None] = {uri: self._fingerprint(uri) for uri in PUSHED} + self.server = Server(NAME, version=version, title="Ecobot weather and air service", instructions=instructions(ctx), + get_tool_input_schema=self._schema, + on_list_tools=self._list_tools, on_call_tool=self._call_tool, + on_list_resources=self._list_resources, on_list_resource_templates=self._list_templates, + on_read_resource=self._read_resource, + on_list_prompts=self._list_prompts, on_get_prompt=self._get_prompt, + on_subscriptions_listen=self.listen) + + @property + def service(self) -> Service: + return self._service + + # ---------- tools ---------- + def _schema(self, name: str): + tool = self._service.get(name) + return tool.parameters if tool else None + + async def _list_tools(self, ctx, params) -> types.ListToolsResult: + return types.ListToolsResult(tools=[tool_entry(t) for t in self._service]) + + async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.CallToolResult: + tool = self._service.get(params.name) + if tool is None: + raise MCPError(types.INVALID_PARAMS, f"No tool {params.name!r}: the tools are {', '.join(t.name for t in self._service)}.") + return tool_result(await tool.call(params.arguments or {}, dict(ctx.meta or {}))) + + async def refresh_catalogue(self) -> bool: + """Read the file's catalogue of readings again; when it gained a reading (a sensor sent a field it never sent), build the tools + and the instructions again and publish ToolsListChanged and the station. True when it did.""" + if self.ctx.eco is None and self.ctx.air is None: + return False + new = await Catalogue.open(self.ctx.eco, self.ctx.air) + if not (gained := [n for n in new.names if n not in set(self.ctx.readings().names)]): + return False + self.ctx.catalogue = new + self._service = Service.of(self.ctx) + self.server.instructions = instructions(self.ctx) + log.info("MCP: the readings now include %s: the tools are built again", ", ".join(gained)) + await self.bus.publish(ToolsListChanged()) + await self.bus.publish(ResourceUpdated(STATION_URI)) + return True + + # ---------- resources ---------- + def _there(self, need: str | None) -> bool: + return need is None or (need == "eco" and self.ctx.eco is not None) or (need == "air" and self.ctx.air is not None) or \ + (need == "forecast" and self.ctx.forecast is not None) or (need == "pollen" and self.ctx.pollen is not None) + + async def _list_resources(self, ctx, params) -> types.ListResourcesResult: + return types.ListResourcesResult(resources=[ + types.Resource(uri=uri, name=name, title=title, description=what, mime_type=JSON) + for uri, (name, title, what, need) in RESOURCES.items() if self._there(need) and (uri != ALERTS_URI or self.alert_log)]) + + async def _list_templates(self, ctx, params) -> types.ListResourceTemplatesResult: + if self.alert_log is None: + return types.ListResourceTemplatesResult(resource_templates=[]) + return types.ListResourceTemplatesResult(resource_templates=[types.ResourceTemplate( + uri_template=ALERTS_TEMPLATE, name="alerts since", title="Alerts since an id", + description="The alerts after the id `since` (a client's last handled), only those not yet expired unless `expired=true`.", + mime_type=JSON)]) + + async def _read_resource(self, ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: + uri = str(params.uri) + return types.ReadResourceResult(contents=[types.TextResourceContents(uri=uri, mime_type=JSON, text=_json(await self.read(uri)))]) + + async def read(self, uri: str) -> dict: + """A resource's content (a dict, sent as JSON). Raises MCPError (RESOURCE_NOT_FOUND) for one there is none of.""" + parts = urlsplit(uri) + key = f"{parts.scheme}://{parts.netloc}{parts.path}" + query = parse_qs(parts.query) + if key == ALERTS_URI and self.alert_log is not None: + return self.alerts(query) + entry = RESOURCES.get(key) + if entry is None or parts.query or key == ALERTS_URI or not self._there(entry[3]): + raise MCPError(RESOURCE_NOT_FOUND, f"No resource {uri!r}: there are " + f"{', '.join(u for u, e in RESOURCES.items() if self._there(e[3]))}, and {ALERTS_TEMPLATE}.") + return await {STATION_URI: self.station, WEATHER_URI: lambda: self.now(STATION), AIR_URI: lambda: self.now(AIR_DEVICE), + FORECAST_URI: self.forecast, POLLEN_URI: self.pollen, HEALTH_URI: self.health, SCHEMA_URI: self.schema}[key]() + + def alerts(self, query: dict | None = None) -> dict: + """{alerts, last_id, identity}: the alerts after `since` (0), only the unexpired unless `expired` is true.""" + query = query or {} + since = (query.get("since") or ["0"])[-1].strip() + expired = (query.get("expired") or ["false"])[-1].strip().lower() in ("true", "1", "yes", "on") + if since and not since.isdecimal(): + raise MCPError(types.INVALID_PARAMS, f"`since` is an alert's id, a whole number, not {since!r}.") + log_ = self.alert_log + return {"alerts": log_.since(int(since or 0), expired=expired), "last_id": log_.last_id(), "identity": log_.identity} + + async def station(self) -> dict: + """ecobot://station: what the station is and has (3.4).""" + c, tz = self.ctx, self.ctx.zone + catalogue = c.readings() + about = AboutTool(c) + sensors = {} + for device, there in ((STATION, c.eco), (AIR_DEVICE, c.air)): + if there: + sensors[device] = {"readings": [{"name": r.name, "label": r.label, "unit": r.unit} for r in catalogue if r.device == device]} + sources = {} + if c.eco: + sources["Ecowitt"] = {"mode": c.eco.via, "station": c.eco.station_name} + if c.air: + sources["AirGradient"] = {"mode": "/".join(m for m, on in (("local", c.air.local), ("homeassistant", c.air.ha), + ("cloud", c.air.cloud)) if on) or "none"} + if c.forecast: + sources["Forecast"] = {"mode": "Open-Meteo", "place": c.forecast.place} + if c.pollen: + sources["Pollen"] = {"mode": "Melbourne Pollen", "district": c.pollen.district} + eco = c.eco + return {"name": eco.station_name if eco else None, "time_zone": str(tz), + "latitude": eco.latitude if eco else None, "longitude": eco.longitude if eco else None, + "created": iso(eco.created) if eco and eco.created else None, + "sensors": sensors, "words": catalogue.words(), "sources": sources, "history": await about.history(), + "alerts": alert_kinds(about.sources), + "airgradient_dashboard": c.air.link[1] if c.air and c.air.link else None} + + async def now(self, device: str) -> dict: + """ecobot://now/weather, ecobot://now/air: the device's reading as kept (nothing is fetched for it).""" + part = await CurrentTool(self.ctx).now_of(device, {"fetch": False}) + out = {"as_of": iso(part.at) if part.at else None, "sensors": {}, "lines": part.lines, "heading": part.heading} + for r, entry in part.entries: + out["sensors"].setdefault(r.sensor, {})[r.reading] = entry + if part.unavailable: + out["unavailable"] = part.unavailable + return out + + async def forecast(self) -> dict: + from .forecast.source import describe_day + f = self.ctx.forecast + return {"place": f.place, "fetched_at": iso(f.fetched_at, self.ctx.zone) if f.fetched_at else None, + "days": [{**d, "text": describe_day(d)} for d in (f.days or [])]} + + async def pollen(self) -> dict: + p = self.ctx.pollen + now = p.current() + return {"in_season": p.in_season(), "fetched_at": iso(now["fetched_at"], self.ctx.zone) if now["fetched_at"] else None, + "grass": now["grass"], "asthma": now["asthma"], "lines": p.lines()} + + async def health(self) -> dict: + out = {} + storage = self.ctx.storage + if storage is not None: + path = Path(storage.path) + out["file"] = {"path": str(path), "bytes": os.path.getsize(path) if path.exists() else 0} + if self.alert_log is not None: + out["alert_log"] = {"last_id": self.alert_log.last_id()} + if self.health_of is not None: + out.update(self.health_of()) + return out + + async def schema(self) -> dict: + return json.loads(SCHEMA_PATH.read_text()) + + # ---------- prompts ---------- + async def _list_prompts(self, ctx, params) -> types.ListPromptsResult: + return types.ListPromptsResult(prompts=[types.Prompt(name=name, description=what, arguments=args or None) + for name, (what, args, _) in PROMPTS.items()]) + + async def _get_prompt(self, ctx, params: types.GetPromptRequestParams) -> types.GetPromptResult: + return prompt(params.name, params.arguments) + + # ---------- publishing (3.4) ---------- + def _fingerprint(self, uri: str) -> str | None: + """What a pushed resource's change is told by, from what the sources keep (nothing fetched): the live reading itself (its + values and times), the forecast's days, the pollen page's levels. None while there is none.""" + c = self.ctx + try: + if uri == WEATHER_URI: + kept = getattr(c.eco, "_live", None) + return _json(kept[1]) if kept else None + if uri == AIR_URI: + kept = getattr(c.air, "_current", None) + return _json(kept[0]) if kept else None + if uri == FORECAST_URI: + return _json(c.forecast.days) if c.forecast and c.forecast.days else None + if uri == POLLEN_URI: + return _json({k: v for k, v in c.pollen.current().items() if k != "fetched_at"}) if c.pollen else None + except Exception as e: # (only what is told: never stops the publishing) + log.warning("MCP: couldn't compare %s: %s: %s", uri, type(e).__name__, e) + return None + + async def publish_changes(self) -> list[str]: + """Publish ResourceUpdated for each pushed resource whose content changed since the last look; the URIs published.""" + changed = [] + for uri in PUSHED: + now = self._fingerprint(uri) + if now is not None and now != self._seen.get(uri): + changed.append(uri) + if now is not None: + self._seen[uri] = now + for uri in changed: + await self.bus.publish(ResourceUpdated(uri)) + return changed + + async def watch_alerts(self): + """Publish the alerts' URI on each new alert, until cancelled.""" + if self.alert_log is None: + return + last = self.alert_log.last_id() + while True: + await self.alert_log.wait(last) + last = self.alert_log.last_id() + await self.bus.publish(ResourceUpdated(ALERTS_URI)) + + async def run(self, publish_every: float = PUBLISH_SECONDS, catalogue_every: float = CATALOGUE_SECONDS): + """The publishing, until cancelled: the alerts as they come, the live resources every `publish_every` s, the catalogue every + `catalogue_every` s. A failure is logged and the next round tries again.""" + async def every(seconds: float, fn): + while True: + await asyncio.sleep(seconds) + try: + await fn() + except Exception as e: + log.warning("MCP: %s failed: %s: %s", fn.__name__, type(e).__name__, e) + await asyncio.gather(self.watch_alerts(), every(publish_every, self.publish_changes), every(catalogue_every, self.refresh_catalogue)) + + +def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: + """A prompt's question in words, its arguments filled in (their defaults where not sent).""" + if name not in PROMPTS: + raise MCPError(types.INVALID_PARAMS, f"No prompt {name!r}: the prompts are {', '.join(PROMPTS)}.") + what, args, text = PROMPTS[name] + given = {**PROMPT_DEFAULTS.get(name, {}), **{k: str(v).strip() for k, v in (arguments or {}).items() if v is not None and str(v).strip()}} + if missing := [a.name for a in args if a.required and a.name not in given]: + raise MCPError(types.INVALID_PARAMS, f"The prompt {name!r} needs {', '.join(missing)}.") + question = WITHOUT_ARGUMENTS[name] if name in WITHOUT_ARGUMENTS and not given else text.format(**given) + return types.GetPromptResult(description=what, messages=[types.PromptMessage(role="user", content=types.TextContent(text=question))]) + + +def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", + path: str = "/mcp"): + """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (MCP_TOKENS: + name -> token), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth + metadata is published (resource_server_url=None).""" + check = TokenCheck(tokens) if tokens else None + app = server.server.streamable_http_app( + streamable_http_path=path, transport_security=host_settings(allowed_hosts), + auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None) if check else None, token_verifier=check) + app.state.tokens = check + return app + + +__all__ = ["ALERTS_TEMPLATE", "ALERTS_URI", "COMPLETE", "EcobotServer", "PROMPTS", "RESOURCES", "TokenCheck", "host_settings", "http_app", + "prompt", "tool_entry", "tool_result"] diff --git a/lib/service/current.py b/lib/service/current.py index d05a3cc9..f0e95870 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -38,7 +38,7 @@ from ..storage.catalogue import BY_NAME, column_of, kind_of, text as written from ..storage.read import Reader from ..timeutil import clock_text, day_text, to_local -from .common import BACKGROUND, Refusal, ServiceTool, answer +from .common import BACKGROUND, Refusal, ServiceTool, answer, request_meta from .context import Context from .names import AIR_DEVICE, CATALOGUE, STATION, Catalogue, Reading, _split @@ -448,6 +448,13 @@ async def handle(self, args: dict, meta: dict) -> str: times = [p.at for p in parts if p.at] return answer(period=None, as_of=max(times) if times else self.ctx.now() if sensors else None, **fields) + async def now_of(self, device: str, meta: dict | None = None) -> "Part": + """One device's part as `current` with no readings named gives it (its every reading now, its lines and heading), for the + service's resources (ecobot://now/weather, ecobot://now/air: lib/mcp_server.py). meta: the request's (request_meta).""" + readings = [r for r in self.ctx.readings() if r.device == device] + meta = request_meta(meta) + return await (self._station(readings, False, False, meta) if device == STATION else self._air(readings, False, meta)) + async def _station(self, station: list[Reading], named: bool, context: bool, meta: dict) -> "Part": """The weather station's part: each reading asked for now (with the gauges' figures beside it, with `context`), its lines and heading. A reading named that it isn't reading is missing; so is a gauge's, with `context`, shown with its figures alone.""" diff --git a/lib/warm.py b/lib/warm.py index d70cccbc..3dd37b8b 100644 --- a/lib/warm.py +++ b/lib/warm.py @@ -7,7 +7,7 @@ import asyncio import logging -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Coroutine from datetime import datetime from .logs import BUGS @@ -40,6 +40,30 @@ async def every(delay: float | Callable[[], float], fn: Callable[[], Awaitable]) await asyncio.sleep(delay() if callable(delay) else delay) +class Tasks: + """The tasks run in the background (the bot's, the service's): one that stops with an error is logged as it does, and close() + cancels them.""" + + def __init__(self): + self.running: set[asyncio.Task] = set() + + def start(self, work: Coroutine) -> asyncio.Task: + task = asyncio.create_task(work, name=getattr(work, "__qualname__", None)) + self.running.add(task) + task.add_done_callback(self._ended) + return task + + def _ended(self, task: asyncio.Task): + self.running.discard(task) + if not task.cancelled() and (error := task.exception()): + log.error("%s stopped: %s: %s", task.get_name(), type(error).__name__, error, exc_info=error if isinstance(error, BUGS) else None) + + async def close(self): + for task in self.running: + task.cancel() + await asyncio.gather(*self.running, return_exceptions=True) + + class Warmer: def __init__(self, refresh: Callable[[bool], Awaitable], interval: float = REFRESH_SECONDS): self.refresh, self.interval = refresh, interval diff --git a/requirements.txt b/requirements.txt index 4dcfb9bc..2690e49f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,8 @@ holidays httpx +mcp==2.3.0 openai python-telegram-bot>=22.8 pillow==13.0.0 +uvicorn==0.54.0 zeroconf diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py new file mode 100644 index 00000000..4acb9b36 --- /dev/null +++ b/tests/test_mcp_listen.py @@ -0,0 +1,227 @@ +"""The service over the network (docs/mcp-service.md 7, "a client that listens", "a deploy check"): the real Streamable HTTP app under +uvicorn on a localhost port each test starts and stops, not the in-memory transport (a connection can't fail there, and it buffers a +listen stream). A client that listens hears a new alert, loses its listen when the service stops, listens again once it is back and +reads the alerts after its last id, once; a request without the token, with a wrong or revoked one, or to a Host not allowed is +refused; and `python -m ecobot_service` runs the sources and answers a tool call through the name a proxy uses.""" + +import asyncio +import json +import os +import signal +import socket +import time +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo + +import httpx +import pytest +from mcp import Client + +from ecobot_service import bridge +from ecobot_service.__main__ import Uvicorn, server_config +from ecobot_service.bridge import Upstream, http_transport +from lib.alert_log import AlertLog +from lib.mcp_server import ALERTS_URI, EcobotServer, http_app +from lib.service.context import Context + +TZ = ZoneInfo("Australia/Melbourne") +TOKENS = {"bot": "bot-s3cret", "phone": "phone-s3cret"} + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +async def until(check, seconds: float = 10.0, what: str = "it"): + """Wait until check() is true (polled), failing after `seconds`.""" + deadline = time.monotonic() + seconds + while not check(): + if time.monotonic() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.02) + + +class Serving: + """The app under uvicorn on 127.0.0.1:port, started and stopped by the test.""" + + def __init__(self, app, port: int): + self.web = Uvicorn(server_config(app, "127.0.0.1", port)) + self.task: asyncio.Task | None = None + + async def __aenter__(self): + self.task = asyncio.create_task(self.web.serve()) + await until(lambda: self.web.started or self.task.done(), what="uvicorn to start") + return self + + async def stop(self): + self.web.should_exit = True + await self.task + + async def __aexit__(self, *exc): + if not self.task.done(): + await self.stop() + + +@pytest.fixture +def service(tmp_path): + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + yield server + alerts.close() + + +async def test_a_client_that_listens_hears_an_alert_and_after_a_lost_listen_listens_again_and_reads_what_it_missed(service, monkeypatch): + monkeypatch.setattr(bridge, "BACKOFF", (0.1,)) + alerts, port = service.alert_log, free_port() + url = f"http://127.0.0.1:{port}/mcp" + publishing = asyncio.create_task(service.watch_alerts()) + handled, connections = [], [] + + async def read_new(*_): + """The client's delivery: the alerts after the last id it handled, each once.""" + after = handled[-1] if handled else 0 + got = json.loads((await up.client.read_resource(f"{ALERTS_URI}?since={after}")).contents[0].text) + handled.extend(a["id"] for a in got["alerts"] if a["id"] > (handled[-1] if handled else 0)) + + async def listening(): + connections.append(True) + await read_new() + up = Upstream(url, TOKENS["bot"], on_event=read_new, on_listening=listening) + supervisor = asyncio.create_task(up.run()) + try: + async with Serving(http_app(service, tokens=TOKENS), port) as first: + await until(lambda: connections and service.listen._streams, what="the listen") + alerts.append("rain", "🌧️ It's started raining", "Rain started", expires=time.time() + 3600) + await until(lambda: handled == [1], what="alert 1") + await first.stop() # the service goes away: the listen is lost + await until(lambda: not up.connected.is_set(), what="the client to notice") + alerts.append("gusts", "💨 A gust of 72 km/h", "Gusts", expires=time.time() + 3600) # missed while it was down + alerts.append("uv", "UV 9", "UV", expires=time.time() - 1) # ... and already expired: never news + async with Serving(http_app(service, tokens=TOKENS), port): + await until(lambda: len(connections) == 2, what="the client to listen again") + await until(lambda: handled == [1, 2], what="alert 2, read after its last id") + alerts.append("temps", "Warmer outside", "Temperatures", expires=time.time() + 3600) + await until(lambda: handled == [1, 2, 4], what="alert 4 on the new listen") + finally: + supervisor.cancel() + publishing.cancel() + await asyncio.gather(supervisor, publishing, return_exceptions=True) + assert handled == [1, 2, 4] + + +async def test_a_request_without_the_token_with_a_wrong_or_revoked_one_or_to_a_host_not_allowed_is_refused(service): + port = free_port() + url = f"http://127.0.0.1:{port}/mcp" + app = http_app(service, tokens=TOKENS, allowed_hosts=("127.0.0.1", "weather.lan")) + body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": { + "io.modelcontextprotocol/protocolVersion": "2026-07-28"}}} + + async def post(token=None, host=None) -> int: + headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "Mcp-Protocol-Version": "2026-07-28", "Mcp-Method": "server/discover"} + if token: + headers["Authorization"] = f"Bearer {token}" + if host: + headers["Host"] = host + async with httpx.AsyncClient() as http: + return (await http.post(url, headers=headers, json=body)).status_code + async with Serving(app, port): + assert await post() == 401 and await post("nope") == 401 and await post(TOKENS["bot"].upper()) == 401 + assert await post(TOKENS["phone"], host="evil.example") == 421 # DNS rebinding: a Host not allowed + async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + app.state.tokens.revoke("phone") # one client's token revoked alone + assert await post(TOKENS["phone"]) == 401 + with pytest.raises(BaseException): + async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: + await client.call_tool("about", {}) + async with Client(http_transport(url, TOKENS["bot"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + + +async def test_the_stdio_bridge_as_a_desktop_client_starts_it_forwards_a_tool_call_to_the_running_service(service): + import sys + from mcp import StdioServerParameters + from lib.config import ROOT + port = free_port() + async with Serving(http_app(service, tokens=TOKENS), port): + params = StdioServerParameters(command=sys.executable, args=["-m", "ecobot_service.bridge"], cwd=str(ROOT), + env={**os.environ, "WEATHER_MCP_URL": f"http://127.0.0.1:{port}/mcp", + "WEATHER_MCP_TOKEN": TOKENS["bot"]}) + async with Client(params) as client: + assert client.instructions == service.server.instructions + got = await client.call_tool("about", {}) + assert not got.is_error and got.content[0].text == await service.service["about"].call({}) + assert [r.uri for r in (await client.list_resources()).resources][0] == "ecobot://station" + + +async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name(tmp_path, monkeypatch, caplog): + """A deploy check: `python -m ecobot_service` (main) with the fake sources, MCP_ALLOWED_HOSTS the name a reverse proxy sends, a + tool call with a token through that name answered, the archives run, then SIGTERM closes it all.""" + import ecobot_service.__main__ as service_main + from ecobot_service import core + from lib.config import Config + from lib.ecowitt import archive + from lib.airgradient import source as air_source + from tests.fakes import air_transport, config, ecowitt_transport + caplog.set_level("INFO") + port = free_port() + cfg = config(tmp_path, telegram_token="", mcp_tokens=(("proxy", "pr0xy"),), mcp_bind=("127.0.0.1", port), + mcp_allowed_hosts=("weather.lan",)) + eco_t, _ = ecowitt_transport(history_days=10) + air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) + for cls, transport in ((core.Ecowitt, eco_t), (core.AirGradient, air_t)): + monkeypatch.setattr(cls, "__init__", lambda self, c, transport=None, orig=cls.__init__, t=transport, **kw: orig(self, c, t, **kw)) + monkeypatch.setattr(archive, "PACE_SECONDS", 0) + monkeypatch.setattr(air_source, "BACKFILL_PACE", 0) + monkeypatch.setattr(air_source, "BACKFILL_EMPTY_STOP", 3) + answered = {} + + async def ask_then_stop(): + await until(lambda: "MCP: http://127.0.0.1:" in caplog.text, 30, "the service to listen") + url = f"http://127.0.0.1:{port}/mcp" + from mcp.shared._httpx_utils import create_mcp_http_client + import contextlib + from mcp.client.streamable_http import streamable_http_client + + @contextlib.asynccontextmanager + async def through_the_proxy(): + headers = {"Authorization": "Bearer pr0xy", "Host": "weather.lan"} + async with create_mcp_http_client(headers=headers) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + async with Client(through_the_proxy(), mode="2026-07-28") as client: + answered["tools"] = [t.name for t in (await client.list_tools()).tools] + answered["current"] = json.loads((await client.call_tool("current", {"readings": ["temperature"]})).content[0].text) + answered["health"] = json.loads((await client.read_resource("ecobot://health")).contents[0].text) + answered["direct"] = await post_status(url) # 127.0.0.1 is not among the allowed hosts here + await until(lambda: any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) + and "Backfill AirGradient:" in caplog.text, 60, "the archives") + os.kill(os.getpid(), signal.SIGTERM) + + async def post_status(url) -> int: + async with httpx.AsyncClient() as http: + return (await http.post(url, headers={"Authorization": "Bearer pr0xy", "Content-Type": "application/json"}, json={})).status_code + asker = asyncio.create_task(ask_then_stop()) + await service_main.main() + await asker + log = caplog.text + assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "tokens for proxy" in log + assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) + assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] + assert answered["direct"] == 421 + assert "Ecowitt refresh" in answered["health"]["loops"] and answered["health"]["file"]["bytes"] > 0 + assert "Alerts NOT running" not in log and "Telegram" not in log + + +async def test_the_service_will_not_serve_without_tokens_on_an_address_others_can_reach(tmp_path, monkeypatch): + import ecobot_service.__main__ as service_main + from lib.config import Config + from tests.fakes import config + cfg = config(tmp_path, telegram_token="", mcp_bind=("0.0.0.0", free_port())) + monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) + with pytest.raises(SystemExit, match="MCP_TOKENS"): + await service_main.main() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py new file mode 100644 index 00000000..5b97833e --- /dev/null +++ b/tests/test_mcp_server.py @@ -0,0 +1,334 @@ +"""The service over MCP (lib/mcp_server.py, docs/mcp-service.md 3.4-3.8): the ten tools listed and called over the SDK's in-memory +transport with the same answers as the ServiceTools themselves, the resources and the alerts' template, the prompts, the publishing of +changes, the auth and the allowed hosts, and the stdio bridge. The listen over the network is tests/test_mcp_listen.py's (under uvicorn, +as docs 7 asks).""" + +import asyncio +import json +import time +from types import SimpleNamespace as NS +from zoneinfo import ZoneInfo + +import mcp_types as types +import pytest +from mcp import Client +from mcp.server.subscriptions import ResourceUpdated, ToolsListChanged +from mcp.shared.exceptions import MCPError + +from lib import mcp_server +from lib.alert_log import AlertLog +from lib.mcp_server import (ALERTS_TEMPLATE, ALERTS_URI, COMPLETE, PROMPTS, EcobotServer, TokenCheck, host_settings, prompt, + tool_result) +from lib.service.common import CHART_POINTS +from lib.service.context import Context +from lib.service.names import Catalogue +from tests import evalkit, evalworld + +TZ = ZoneInfo("Australia/Melbourne") +EXPECT = evalkit.load_service_cases() + + +def at_eval_now(patch: pytest.MonkeyPatch): + evalworld.at_eval_now(patch, __name__) + + +@pytest.fixture(scope="module") +def eval_archive(tmp_path_factory): + """The fake station's whole archive built at the evals' NOW, once for the module (as tests/test_service_evals.py's).""" + path = tmp_path_factory.mktemp("mcp-eval-now") + with pytest.MonkeyPatch.context() as patch: + at_eval_now(patch) + return asyncio.run(evalworld.build_archive(path)) + + +@pytest.fixture +async def world(tmp_path, eval_archive, monkeypatch): + """The four sources (faked, the clock at the evals' NOW), an alert log, and the server over them.""" + at_eval_now(monkeypatch) + ctx = await evalworld.real_context(tmp_path, eval_archive) + alerts = AlertLog(tmp_path / "alerts.sqlite", ctx.zone) + server = EcobotServer(ctx, alerts, health=lambda: {"loops": {"Ecowitt refresh": {"last_ok": "now"}}}) + yield server + alerts.close() + await evalworld.close(ctx) + + +def first_call(tool: str) -> dict: + """An argument set the evals expect of this tool (any accepted call will do).""" + return next((args for expect in EXPECT.values() for name, args in evalkit.example_calls(expect) if name == tool), {}) + + +# ---------- tools ---------- +async def test_every_tool_is_listed_with_its_schema_and_hints_and_answers_as_the_service_tool_does(world): + async with Client(world.server) as client: + listed = {t.name: t for t in (await client.list_tools()).tools} + assert list(listed) == [t.name for t in world.service] and len(listed) == 10 + for tool in world.service: + entry = listed[tool.name] + assert entry.description == tool.description and entry.input_schema == tool.parameters + assert entry.annotations.read_only_hint is True and entry.annotations.open_world_hint is tool.open_world + args = first_call(tool.name) + for _ in range(10): # (what a call fetches inline, fetched first: the answers are then the same each time) + if await tool.call(args) == await tool.call(args): + break + got = await client.call_tool(tool.name, args) + assert got.content[0].text == await tool.call(args), tool.name + assert got.is_error is ("error" in json.loads(got.content[0].text)) + + +async def test_a_refusal_is_an_error_result_with_what_teaches_the_right_call_and_an_unknown_tool_a_protocol_error(world): + async with Client(world.server) as client: + got = await client.call_tool("summary", {"period": "the age of the dinosaurs"}) + assert got.is_error and "forms" in json.loads(got.content[0].text) + with pytest.raises(MCPError, match="No tool 'weather_now'"): + await client.call_tool("weather_now", {}) + + +async def test_the_requests_meta_reaches_the_tool_charts_come_whole_and_sized_by_chart_points(world): + args = {"readings": ["temperature"], "period": "last 7 days", "chart": True} + async with Client(world.server) as client: + default = json.loads((await client.call_tool("summary", args)).content[0].text) + small = json.loads((await client.call_tool("summary", args, meta={"chart_points": 40})).content[0].text) + (chart,) = default["charts"] + assert {"title", "period", "source", "drawn_by", "panels"} <= set(chart) # the full chart JSON (3.7) + longest = lambda c: max(len(s["points"]) for p in c["panels"] for s in p["series"]) + assert 40 < longest(chart) <= CHART_POINTS and longest(small["charts"][0]) <= 40 + assert default == json.loads(await world.service["summary"].call(args)) + + +async def test_a_complete_answer_carries_its_reply_for_the_person_and_the_complete_mark(world): + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + async with Client(world.server) as client: + got = await client.call_tool("summary", args) + plain = await client.call_tool("summary", {"readings": ["pressure"], "period": "this week"}) + data = json.loads(got.content[0].text) + assert data["complete"] is True and len(got.content) == 2 + reply = got.content[1] + assert reply.text == data["reply"] and reply.annotations.audience == ["user"] + assert got.meta[COMPLETE] is True + assert len(plain.content) == 1 and COMPLETE not in (plain.meta or {}) + + +def test_a_result_is_complete_only_with_a_reply_and_no_error(): + assert tool_result('{"complete": true, "reply": "Pressure ...", "charts": []}').meta == {COMPLETE: True} + assert tool_result('{"complete": true}').meta is None and len(tool_result('{"complete": true}').content) == 1 + assert tool_result('{"error": "no"}').is_error and tool_result("not json").content[0].text == "not json" + + +async def test_the_tools_are_built_again_when_the_catalogue_gains_a_reading_and_listeners_are_told(world, monkeypatch): + seen = [] + world.bus.subscribe(seen.append) + assert await world.refresh_catalogue() is False and seen == [] # (nothing gained: nothing sent) + held = world.ctx.readings() + new = "outdoor.dew_point" # (as if the station had just sent it for the first time) + assert new in held.names + world.ctx.catalogue = Catalogue([r for r in held if r.name != new]) + world._service = world.service.of(world.ctx) + described = lambda: world.service["readings"].parameters["properties"]["reading"]["description"] + assert new not in described() + assert await world.refresh_catalogue() is True + assert seen == [ToolsListChanged(), ResourceUpdated("ecobot://station")] + assert new in described() and new in world.server.instructions or new.split(".")[1] in world.server.instructions + + +# ---------- the instructions ---------- +async def test_the_instructions_are_the_services_and_come_with_discover(world): + from lib.service.instructions import instructions + async with Client(world.server) as client: + assert client.instructions == instructions(world.ctx) and "Australia/Melbourne" in client.instructions + + +# ---------- resources ---------- +async def test_each_resource_is_listed_and_readable_as_json(world): + world.alert_log.append("rain", "🌧️ It's started raining", "Rain started", data={"mm": 0.4}, expires=None) + async with Client(world.server) as client: + assert json.loads((await client.read_resource("ecobot://now/weather")).contents[0].text)["unavailable"] # (none kept yet) + for name in ("current", "forecast"): # (the station's live reading and the forecast asked for, and kept: a resource fetches nothing) + await world.service[name].call({}) + listed = [r.uri for r in (await client.list_resources()).resources] + assert listed == list(mcp_server.RESOURCES) + read = {} + for uri in listed: + (content,) = (await client.read_resource(uri)).contents + assert content.mime_type == "application/json" and content.uri == uri + read[uri] = json.loads(content.text) + station = read["ecobot://station"] + assert station["name"] == world.ctx.eco.station_name and station["time_zone"] == "Australia/Melbourne" + assert {"station", "air"} == set(station["sensors"]) and "temperature" in station["words"] + assert {r["name"] for r in station["sensors"]["station"]["readings"]} >= {"outdoor.temperature", "pressure.relative"} + assert set(station["sources"]) == {"Ecowitt", "AirGradient", "Forecast", "Pollen"} and station["history"]["station"]["held"] + assert {a["kind"] for a in station["alerts"]} >= {"rain", "gusts", "particulates", "forecast", "pollen_and_asthma"} + weather = read["ecobot://now/weather"] + assert weather["sensors"]["outdoor"]["temperature"]["unit"] and weather["lines"] and weather["as_of"] + air = read["ecobot://now/air"] + assert air["sensors"]["air"]["pm2_5"]["rating"] and "aqi_us" in air["sensors"]["air"]["pm2_5"] + assert [a["kind"] for a in read[ALERTS_URI]["alerts"]] == ["rain"] and read[ALERTS_URI]["last_id"] == 1 + forecast = read["ecobot://forecast"] + assert forecast["place"] == "Melbourne" and forecast["days"] and {"date", "min_c", "max_c", "text"} <= set(forecast["days"][0]) + assert {"in_season", "grass", "asthma", "fetched_at"} <= set(read["ecobot://pollen"]) + health = read["ecobot://health"] + assert health["file"]["bytes"] > 0 and health["alert_log"] == {"last_id": 1} and "Ecowitt refresh" in health["loops"] + assert read["ecobot://schema/chart"]["$id"] == "ecobot://schema/chart" + + +async def test_a_resource_there_is_none_of_is_refused_naming_those_there_are(tmp_path): + server = EcobotServer(Context(tz=TZ), AlertLog(tmp_path / "a.sqlite", TZ)) + async with Client(server.server) as client: + listed = [r.uri for r in (await client.list_resources()).resources] + assert listed == ["ecobot://station", ALERTS_URI, "ecobot://health", "ecobot://schema/chart"] # (no sensor, no forecast, no pollen) + for uri in ("ecobot://now/weather", "ecobot://nowhere", "ecobot://health?x=1"): + with pytest.raises(MCPError, match="No resource") as e: + await client.read_resource(uri) + assert e.value.error.code == mcp_server.RESOURCE_NOT_FOUND + + +async def test_the_alerts_template_reads_after_an_id_and_leaves_the_expired_out_unless_asked(tmp_path): + alerts = AlertLog(tmp_path / "a.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + now = time.time() + alerts.append("rain", "It rained", "Rain", expires=now - 60) # 1: expired + alerts.append("gusts", "Gusty", "Gusts", expires=now + 3600) # 2 + alerts.append("uv", "UV high", "UV", expires=None) # 3: never expires + async with Client(server.server) as client: + (template,) = (await client.list_resource_templates()).resource_templates + assert template.uri_template == ALERTS_TEMPLATE + + async def ids(uri): + return [a["id"] for a in json.loads((await client.read_resource(uri)).contents[0].text)["alerts"]] + assert await ids(ALERTS_URI) == [2, 3] + assert await ids(f"{ALERTS_URI}?since=2") == [3] + assert await ids(f"{ALERTS_URI}?expired=true") == [1, 2, 3] + assert await ids(f"{ALERTS_URI}?since=1&expired=true") == [2, 3] + assert await ids(f"{ALERTS_URI}?since=3") == [] + with pytest.raises(MCPError, match="whole number"): + await ids(f"{ALERTS_URI}?since=last") + whole = json.loads((await client.read_resource(ALERTS_URI)).contents[0].text) + assert whole["last_id"] == 3 and whole["identity"] == alerts.identity + alerts.close() + + +# ---------- publishing ---------- +async def test_a_live_resource_is_published_when_its_reading_changes_and_not_when_it_repeats(tmp_path): + eco = NS(_live=None, storage=None, tz=TZ) + ctx = Context(eco=eco, tz=TZ) + ctx.catalogue = Catalogue([]) + server = EcobotServer(ctx, None) + seen = [] + server.bus.subscribe(seen.append) + assert await server.publish_changes() == [] # nothing kept yet + eco._live = (time.time(), {"outdoor": {"temperature": {"value": "12.3", "unit": "℃", "time": "1000"}}}) + assert await server.publish_changes() == ["ecobot://now/weather"] + eco._live = (time.time() + 5, {"outdoor": {"temperature": {"value": "12.3", "unit": "℃", "time": "1000"}}}) # the same reading again + assert await server.publish_changes() == [] + eco._live = (time.time() + 10, {"outdoor": {"temperature": {"value": "12.4", "unit": "℃", "time": "1060"}}}) + assert await server.publish_changes() == ["ecobot://now/weather"] + assert seen == [ResourceUpdated("ecobot://now/weather")] * 2 + + +async def test_a_new_alert_is_published_to_a_listener(tmp_path): + alerts = AlertLog(tmp_path / "a.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) + publishing = asyncio.create_task(server.watch_alerts()) + try: + async with Client(server.server) as client: + async with client.listen(resource_subscriptions=[ALERTS_URI, "ecobot://now/weather"]) as sub: + alerts.append("gusts", "💨 A gust of 72 km/h", "Gusts", expires=time.time() + 3600) + event = await asyncio.wait_for(sub.__anext__(), 5) + assert event == ResourceUpdated(ALERTS_URI) + got = json.loads((await client.read_resource(f"{ALERTS_URI}?since=0")).contents[0].text) + assert [a["text"] for a in got["alerts"]] == ["💨 A gust of 72 km/h"] + finally: + publishing.cancel() + alerts.close() + + +# ---------- prompts ---------- +async def test_the_prompts_are_questions_in_words_with_their_period_an_argument(world): + async with Client(world.server) as client: + listed = {p.name: p for p in (await client.list_prompts()).prompts} + assert list(listed) == ["now", "report", "will_it_rain", "weather", "chart", "rain", "air"] == list(PROMPTS) + assert [a.name for a in listed["chart"].arguments] == ["reading", "period"] and listed["chart"].arguments[0].required + got = await client.get_prompt("chart", {"reading": "pressure", "period": "this week"}) + assert got.messages[0].role == "user" and got.messages[0].content.text == "Chart pressure over this week." + with pytest.raises(MCPError, match="needs reading"): + await client.get_prompt("chart", {}) + assert prompt("rain").messages[0].content.text == "How much rain fell over today?" + assert prompt("air").messages[0].content.text == "How is the air quality now?" + assert prompt("air", {"period": "last week"}).messages[0].content.text == "How was the air quality over last week?" + assert prompt("weather").messages[0].content.text == "Chart every weather reading, a panel each, over the last 7 days." + with pytest.raises(MCPError, match="No prompt"): + prompt("lightning") + + +# ---------- auth and hosts ---------- +async def test_a_token_is_one_of_mcp_tokens_named_by_its_client_and_one_can_be_revoked_alone(): + check = TokenCheck((("bot", "s3cret-bot"), ("phone", "s3cret-phone"))) + assert (await check.verify_token("s3cret-bot")).client_id == "bot" + assert (await check.verify_token("s3cret-phone")).client_id == "phone" + for wrong in ("", "s3cret", "s3cret-bot ", "S3CRET-BOT"): + assert await check.verify_token(wrong) is None + check.revoke("phone") + assert await check.verify_token("s3cret-phone") is None and (await check.verify_token("s3cret-bot")).client_id == "bot" + + +def test_the_allowed_hosts_take_any_port_unless_one_is_named(): + settings = host_settings(("127.0.0.1", "weather.lan:443")) + assert settings.enable_dns_rebinding_protection + assert settings.allowed_hosts == ["127.0.0.1", "127.0.0.1:*", "weather.lan:443"] + assert "https://weather.lan:443" in settings.allowed_origins and "http://127.0.0.1:*" in settings.allowed_origins + + +# ---------- the bridge ---------- +async def test_the_bridge_forwards_a_tool_call_its_meta_and_its_complete_mark_and_the_instructions(world): + from ecobot_service.bridge import Bridge + bridge = Bridge(world.server) # (the service in-process, as the bridge's upstream) + async with bridge.running(5): + assert bridge.upstream.client is not None + async with Client(bridge.server) as client: + assert client.instructions == world.server.instructions + assert [t.name for t in (await client.list_tools()).tools] == [t.name for t in world.service] + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + got = await client.call_tool("summary", args, meta={"chart_points": 30}) + direct = await world.service["summary"].call(args, {"chart_points": 30}) + assert got.content[0].text == direct and got.meta[COMPLETE] is True and got.content[1].annotations.audience == ["user"] + refused = await client.call_tool("summary", {"period": "whenever"}) + assert refused.is_error + assert json.loads((await client.read_resource("ecobot://health")).contents[0].text)["alert_log"] == {"last_id": 0} + assert (await client.get_prompt("now")).messages[0].content.text == "How is it outside now?" + with pytest.raises(MCPError, match="No resource"): + await client.read_resource("ecobot://nowhere") + + +def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, tmp_path, caplog): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + for key, value in {"ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b", "TELEGRAM_BOT_TOKEN": ""}.items(): + monkeypatch.setenv(key, value) + for key in ("MCP_TOKENS", "MCP_BIND", "MCP_ALLOWED_HOSTS"): + monkeypatch.delenv(key, raising=False) + with pytest.raises(SystemExit, match="TELEGRAM_BOT_TOKEN is not set"): + Config.from_env() # the bot can't start without it ... + cfg = Config.from_env(bot=False) # ... the service can + assert cfg.mcp_tokens == () and cfg.mcp_bind == ("127.0.0.1", 8765) and cfg.mcp_allowed_hosts == ("127.0.0.1", "localhost") + monkeypatch.setenv("MCP_TOKENS", " bot:s3cret , phone:t0k:en, broken, :nameless") + monkeypatch.setenv("MCP_BIND", "0.0.0.0:9000") + monkeypatch.setenv("MCP_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") + cfg = Config.from_env(bot=False) + assert cfg.mcp_tokens == (("bot", "s3cret"), ("phone", "t0k:en")) + assert "MCP_TOKENS: ignoring broken, (no name)" in caplog.text and "s3cret" not in caplog.text and "nameless" not in caplog.text + assert cfg.mcp_bind == ("0.0.0.0", 9000) and cfg.mcp_allowed_hosts == ("weather.lan", "192.168.1.5:9000") + for value, want in (("[::1]:8800", ("::1", 8800)), ("9001", ("127.0.0.1", 9001)), ("host:port", ("127.0.0.1", 8765)), + ("h:70000", ("127.0.0.1", 8765))): + monkeypatch.setenv("MCP_BIND", value) + assert Config.from_env(bot=False).mcp_bind == want, value + + +async def test_the_bridge_refuses_a_request_while_the_service_cant_be_reached(monkeypatch): + from ecobot_service import bridge as bridge_module + monkeypatch.setattr(bridge_module, "CONNECT_WAIT", 0.2) + monkeypatch.setattr(bridge_module, "BACKOFF", (0.1,)) + bridge = bridge_module.Bridge("http://127.0.0.1:9/mcp") # (nothing listens there) + async with bridge.running(0.2): + async with Client(bridge.server) as client: + with pytest.raises(MCPError, match="isn't reachable"): + await client.call_tool("current", {}) From eee2460dd3b03faa14c2acec4229205fe918086b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 23:39:39 +0000 Subject: [PATCH 064/125] Step 5, bot side: the bot as the service's client over MCP (WEATHER_MCP_URL) - lib/weather.py: one interface for everything the bot asks of the service. LocalWeather (unset: the service in-process, as before) and RemoteWeather (set: the bridge's supervised Upstream, pinned to 2026-07-28, discover for the instructions, listening to the station, the alerts and the forecast; tools and station read again on each connection and on ToolsListChanged/ResourceUpdated). Calls wait up to 5 s while it reconnects (background ones not at all), then ServiceUnreachable. - The bot: tools, names, catalogue (Catalogue.listed from ecobot://station), instructions, AirGradient link and alerts through it; a question while the service is unreachable is told so without the model. The model's tools follow the service's list (model_tools.ServiceTools). - AlertDelivery reads the log in process or over MCP (RemoteAlerts: since the last id, woken by the listen). - Irrigation: with the service remote, the daily check reads the rain from summary and the forecast from ecobot://forecast (ServiceRain, ServiceForecast; the last forecast read stands while unreachable). - ecobot.py: with WEATHER_MCP_URL no sources, rules or warm-up; only the charts drawn ahead. Config gains WEATHER_MCP_URL and WEATHER_MCP_TOKEN (no source setting needed with it). - bridge.Upstream: stops when cancelled even if the SDK wrapped the cancellation; can listen to some URIs only. - tests/test_bot_remote.py; conftest restores the loggers' levels after each test (a main() left them at INFO). - Docs: README, DEVELOPMENT.md, docs/configuration.md, docs/mcp-service.md step 5, compose.yaml. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 24 ++- README.md | 1 + compose.yaml | 9 +- docs/configuration.md | 11 ++ docs/mcp-service.md | 29 ++- ecobot.py | 92 ++++++--- ecobot_service/bridge.py | 11 +- lib/alerts/irrigation.py | 17 +- lib/alerts/notify.py | 22 ++- lib/bot.py | 83 ++++---- lib/config.py | 5 +- lib/model_tools.py | 34 +++- lib/service/names.py | 11 +- lib/weather.py | 414 +++++++++++++++++++++++++++++++++++++++ tests/conftest.py | 11 ++ tests/test_bot_remote.py | 330 +++++++++++++++++++++++++++++++ 16 files changed, 1018 insertions(+), 86 deletions(-) create mode 100644 lib/weather.py create mode 100644 tests/test_bot_remote.py diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index cf12cdf8..c83e3479 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -36,8 +36,8 @@ MCP_TOKENS=me:$(openssl rand -hex 16) python -m ecobot_service # http://127 python -m ecobot_service.bridge # the same on stdio (WEATHER_MCP_URL, WEATHER_MCP_TOKEN), for a desktop client sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 ``` -Don't run it beside the bot on the same data folder yet: until the bot is its client, the bot runs the sources and the alert rules itself, and -both would fetch twice and write each alert twice. A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with +Don't run it beside a bot that runs the service itself (`WEATHER_MCP_URL` unset) on the same data folder: both would fetch twice and write +each alert twice; make the bot its client (below). A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with `WEATHER_MCP_TOKEN` in its environment, e.g. `claude mcp add ecobot -e WEATHER_MCP_TOKEN=... -- python -m ecobot_service.bridge` from the clone. To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. @@ -47,6 +47,26 @@ on a free localhost port: a client that listens loses its listen when the servic token and Host checks over HTTP; the bridge as a subprocess on stdio; `python -m ecobot_service` with the fake sources, a tool call through a proxy's Host name). +### The bot as the service's client +With `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`, one of the service's `MCP_TOKENS`) set, the bot runs no sources, syncers or alert rules of +its own and reaches the service over MCP (`lib/weather.RemoteWeather`, [docs/mcp-service.md](docs/mcp-service.md) 3.8): one client pinned +to protocol 2026-07-28, kept by one supervisor task (the bridge's `Upstream`), which discovers by hand for the instructions and listens to +`ecobot://alerts`, `ecobot://station` and `ecobot://forecast`; when the connection fails or the listen is lost it builds a new client after +a backoff, listens again and reads the alerts after the last id it handled. Unset, the bot runs the service in-process as before +(`lib/weather.LocalWeather`). Both are one interface, `lib/weather.py`, which everything the bot asks of the service goes through: +the model's tools and instructions, its shortcuts, report, gauges, charts drawn ahead and period buttons, Help and `/usage`, the alerts +(lib/alerts/notify.AlertDelivery reads either log) and the irrigation check's rain and forecast (`ServiceRain`, `ServiceForecast`). +``` +set -a; . <(sudo cat /etc/ecobot.env); set +a +MCP_TOKENS=bot:$TOKEN python -m ecobot_service & # the service, with the sources' settings +WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN=$TOKEN python ecobot.py # the bot, its client +``` +In Docker (compose.yaml): start `ecobot-service` (its profile), add `ecobot-service` to its `MCP_ALLOWED_HOSTS` and set the bot's +`WEATHER_MCP_URL=http://ecobot-service:8765/mcp`. Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a +question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through +the listen, the irrigation check's inputs; under uvicorn: a dropped connection rebuilt and the alerts after the last id read once, the +service down, `ecobot.main()` as a client). + ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) | Job | When | What | |---|---|---| diff --git a/README.md b/README.md index d5c00c56..2fa60439 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ Settings are environment variables in `/etc/ecobot.env`. The ones you're most li | `AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | | `AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | | `POLLEN`, `FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | +| `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN` | Optional. The bot as a client of the weather service running on its own (`python -m ecobot_service`, e.g. `http://127.0.0.1:8765/mcp`, and one of its `MCP_TOKENS`): the bot then fetches nothing and runs no alert rules itself, and needs none of the source settings above. Unset (the default), the bot runs everything itself, as before. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-the-services-client). | After editing the file, restart: `sudo systemctl restart ecobot`, or for Docker `sudo docker compose up -d --force-recreate` (`docker restart` keeps the old settings). diff --git a/compose.yaml b/compose.yaml index daef3736..6fa48d51 100644 --- a/compose.yaml +++ b/compose.yaml @@ -22,10 +22,11 @@ services: # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, # at http://127.0.0.1:8765/mcp on the host (put TLS in front of it, e.g. Caddy, to reach it from elsewhere). Off unless asked for - # (`sudo docker compose --profile service up -d ecobot-service`): until the bot is its client, the bot runs the sources and the alert - # rules itself, and both on one data folder would fetch twice and write each alert twice. It needs MCP_TOKENS (name:token,..., in - # /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. MCP_ALLOWED_HOSTS: add - # the name a proxy or a LAN client uses for it. + # (`sudo docker compose --profile service up -d ecobot-service`). Run it only with the bot as its client (WEATHER_MCP_URL= + # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_ALLOWED_HOSTS): a bot that runs + # the sources and the alert rules itself, on the same data folder, would fetch twice and write each alert twice. It needs MCP_TOKENS + # (name:token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. + # MCP_ALLOWED_HOSTS: add the name a proxy or a LAN client uses for it. ecobot-service: image: ecobot container_name: ecobot-service diff --git a/docs/configuration.md b/docs/configuration.md index d9256f7c..90a6c2db 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -91,3 +91,14 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `MCP_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | The stdio bridge (`python -m ecobot_service.bridge`, for a desktop client) reads `WEATHER_MCP_URL` (default `http://127.0.0.1:8765/mcp`) and `WEATHER_MCP_TOKEN` (one of `MCP_TOKENS`' tokens). + +### The bot as the service's client + +| Variable | Default | Description | +|---|---|---| +| `WEATHER_MCP_URL` | none | The service's MCP endpoint (`http://127.0.0.1:8765/mcp`, or its TLS address behind a proxy). Set: the bot is a client of the service ([mcp-service.md](mcp-service.md) step 5): it starts no sources, syncers or alert rules of its own, so the source settings (`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `POLLEN`, `FORECAST` …) are the service's and the bot needs none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are) and the alerts come from the service. Unset: the bot runs the service inside itself, as before | +| `WEATHER_MCP_TOKEN` | none | The bearer token the bot sends: one of the service's `MCP_TOKENS` (give the bot its own, e.g. `bot:`) | + +While the service can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the +alerts sent meanwhile that are still news are delivered once it is back. The irrigation controller (`TUYA_*`) stays the bot's: its daily +check asks the service for the rain measured and the forecast. diff --git a/docs/mcp-service.md b/docs/mcp-service.md index e6f6f395..6e3fc419 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -578,8 +578,33 @@ Each step ships on its own, with the tests and evals green and the bot working t `schemas/`; compose has `ecobot-service`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the bridge on stdio, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs - no Telegram token. Left: the bot as a client (the switch, the supervisor, `charts` from results, delivery from the listen), its - `warm_up` cut to its charts drawn ahead, the poke going, the irrigation server and the scripts as clients. + no Telegram token. + - **The bot as a client (done).** `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`) set: the bot starts no sources, syncers or alert rules + (`ecobot.connect`); unset: it runs the service in-process, unchanged. Both go through one interface, `lib/weather.py` + (`LocalWeather` over lib/service and the sources; `RemoteWeather` over MCP): the tools as `Service` lists them (each `call(args, + meta)` answering the tool's JSON), the sources there are (`names`), the catalogue, the instructions, the AirGradient link, the + alert feed and one alert by id, a resource, and whether it can be reached. `RemoteWeather` is 3.8's client: the bridge's `Upstream` + (pinned to 2026-07-28, `send_discover` and `adopt` for the instructions, one supervisor task that drops the client on a transport + error or a lost or ended listen and builds another after a backoff, the 45-second read timeout), listening to the station, the + alerts and the forecast; each connection reads the tool list and the station again (`ToolsListChanged` and the station's + `ResourceUpdated` too). The station gives the time zone, the sources (`names`: the alert menu, the report's calls, the gauges, Help + and `/usage`), the catalogue the shortcuts read their words against (`Catalogue.listed`) and the AirGradient dashboard. The model's + tools follow the service's list (`model_tools.ServiceTools`), charts stripped for the model as before; the shortcuts, report, + gauges, period buttons and 🔄 replays, charts drawn ahead and preloads call the same tools. Alert delivery + (`AlertDelivery`) reads `ecobot://alerts?since=`, woken by the listen's `ResourceUpdated` for `ecobot://alerts` + and by each new connection (nothing is replayed), resuming from the id kept in `bot_state.json` as before; the 🔄 under an alert + finds its event with the template (`since` the id before it, `expired=true`). A question's call waits up to 5 seconds while the + client is being built again, a background one not at all; a question while the service can't be reached is answered that it can't + (`bot.SERVICE_DOWN`), without the model. The bot's `warm_up` is its charts drawn ahead, every 5 minutes, quietly nothing while the + service is away; the poke of the sources is gone (there are none). Irrigation stays in the bot until 5b: its daily check reads the + measured rain from `summary {readings: ["rain"], period: "last 24 hours"}` (`ServiceRain`) and the forecast from `ecobot://forecast` + (`ServiceForecast`, read again at each check and on each `ResourceUpdated`; the one last read stands when the service can't be + reached). Tests: `tests/test_bot_remote.py` (the bot against the real server, in memory and under uvicorn: a question answered with + the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through the listen, a + dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client); the path + with the setting unset is the rest of the suite, unchanged. + - **Left: 5b**, the irrigation server in its own repository (3.9: its tools, the watchdog and the daily check, `irrigation://alerts`), + the bot connecting to both and `lib/irrigation` going from here; and `show_request` and `report_inputs` as MCP clients. 6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. ## 7. Testing diff --git a/ecobot.py b/ecobot.py index dea23b0b..c1c4d7c2 100644 --- a/ecobot.py +++ b/ecobot.py @@ -3,12 +3,16 @@ (see lib/config.py); run it under systemd with the unit's EnvironmentFile set. The service's half (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and -Home Assistant's imports) is ecobot_service/core.py, which the service (python -m ecobot_service) runs the same way: the bot runs it -in-process, beside its own half (Telegram, the model, delivering the alerts, the irrigation controller, its charts drawn ahead). +Home Assistant's imports) is ecobot_service/core.py, which the service (python -m ecobot_service) runs the same way. With WEATHER_MCP_URL +unset the bot runs it in-process, beside its own half (Telegram, the model, delivering the alerts, the irrigation controller, its charts +drawn ahead). With it set the bot is the service's client over MCP (lib/weather.RemoteWeather, docs/mcp-service.md 3.8 and step 5): it +runs no sources, syncers or alert rules of its own; its tools, instructions, station and alerts come from the service. Either way the bot +reaches the service through one interface (lib/weather.py). """ import asyncio import contextlib +import dataclasses import logging import signal @@ -36,6 +40,7 @@ from lib.service.alerts import AlertRules from lib import model_tools from lib.warm import every, safely +from lib.weather import RemoteWeather, ServiceRain _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) # DEBUG and INFO to stdout, WARN and ERROR to stderr @@ -44,19 +49,48 @@ logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING) # "Application started" etc. log = logging.getLogger("ecobot") - -def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Core) -> tuple[list[str], AlertRules]: - """Hook up the service's alert rules over every source that started (core.start_alerts: they append to the alert log, which the - bot delivers from, AlertDelivery) and the irrigation controller's (sent by the bot itself until it is a server of its own). The - weather rules start in warm_up, once the station has been read. Returns the alert types now running, and the rules.""" - running = core.start_alerts(moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) - tasks.start(AlertDelivery(core.alert_log, notify, bot.state, cfg.tz).run()) +STARTUP_WAIT = 30.0 # seconds the bot waits for a remote service at start (its station names the time zone) before it carries on without + + +def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Core | None, + weather: RemoteWeather | None = None) -> tuple[list[str], AlertRules | None]: + """In-process (`core`): hook up the service's alert rules over every source that started (core.start_alerts: they append to the + alert log); the weather rules start in warm_up, once the station has been read. Remote (`weather`): the rules are the service's, and + its alert log is read over MCP. Either way the bot delivers from the log (AlertDelivery), and runs the irrigation controller's check + and watchdog (sent by the bot itself until it is a server of its own, step 5b; remote, its rain and forecast are asked of the + service). Returns the alert types now running here, and the rules (None when remote).""" + if core is not None: + running = core.start_alerts(moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) + feed, station, forecast = core.alert_log, bot.by_name.get("Ecowitt"), bot.by_name.get("Forecast") + else: + running, feed, station, forecast = [], weather.alerts, ServiceRain(weather), weather.forecast + tasks.start(AlertDelivery(feed, notify, bot.state, cfg.tz).run()) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run - tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, bot.by_name.get("Ecowitt"), - bot.by_name.get("Forecast")).run()) + tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, station, forecast).run()) tasks.start(every(VALVE_CHECK_SECONDS, bot.watchdog.check)) running += IrrigationMonitor.KINDS - return running, core.rules + return running, core.rules if core is not None else None + + +async def connect(cfg: Config, stack: contextlib.AsyncExitStack) -> tuple[RemoteWeather, Config]: + """The bot as the service's client (WEATHER_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to + STARTUP_WAIT seconds; the settings in the station's time zone once it has been read (else TZ's, with a warning).""" + weather = RemoteWeather(cfg.weather_mcp_url, cfg.weather_mcp_token or None, cfg.tz) + supervisor = asyncio.create_task(weather.run()) + + async def stop(): + supervisor.cancel() + await asyncio.gather(supervisor, return_exceptions=True) + await weather.close() + stack.push_async_callback(stop) + try: + await asyncio.wait_for(weather.listening.wait(), STARTUP_WAIT) + except TimeoutError: + log.warning("The weather service at %s isn't reachable yet: questions are told so until it is (the time zone is TZ's, %s)", + cfg.weather_mcp_url, cfg.tz) + if weather.station_tz is not None and str(weather.station_tz) != str(cfg.tz): + cfg = dataclasses.replace(cfg, tz=weather.station_tz) + return weather, cfg async def warm_up(bot: Bot, core: Core, running: list[str], tasks: Tasks, tg_bot=None): @@ -96,14 +130,19 @@ async def main(): .connect_timeout(10).read_timeout(15).write_timeout(15) # default 5s is tight .build()) handshake = asyncio.create_task(app.initialize()) # Telegram is asked who the bot is while the sources start + weather = None # (WEATHER_MCP_URL: the service, reached over MCP) try: - sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on + if cfg.weather_mcp_url: # a client of the service: no sources of its own + sources = [] + weather, cfg = await connect(cfg, stack) + else: + sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on except BaseException: handshake.cancel() raise for source in sources: stack.push_async_callback(safely, source.close) - if not sources: + if not sources and weather is None: handshake.cancel() raise SystemExit("No data source is working - nothing to talk about") charts.configure(cfg.dark_mode, cfg.tz) # DARKMODE (in the station's time zone, as everything from here on) @@ -118,14 +157,15 @@ async def main(): "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) # The service in-process (ecobot_service/core.py): the alert log the rules write and the bot delivers from, and the ten tools - # over the sources that started (lib/service): the model is offered them (lib/model_tools.py), and the bot's own code paths call - # them (its shortcuts, report, gauges, alert charts and period buttons) - core = await Core.open(cfg, sources, stack, tasks) + # over the sources that started (lib/service); or, remote, the same over MCP (lib/weather.py). The model is offered the tools + # (lib/model_tools.py), and the bot's own code paths call them (its shortcuts, report, gauges, alert charts and period buttons) + core = await Core.open(cfg, sources, stack, tasks) if weather is None else None irrigation = Tuya(cfg) if cfg.irrigation else None if irrigation: stack.push_async_callback(safely, irrigation.close) - bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(core.service)), sources, state, irrigation, tasks, - service=core.service, alert_log=core.alert_log) + service = weather if weather is not None else core.service + bot = Bot(cfg, Agent(client, cfg.openrouter_model, model_tools.tools(service)), sources, state, irrigation, tasks, + service=service, alert_log=core.alert_log if core else None) bot.register(app) stop = asyncio.Event() @@ -148,12 +188,18 @@ async def main(): stack.push_async_callback(source.warmer.stop) log.info("Telegram: @%s, Model: %s", app.bot.username, cfg.openrouter_model if client else "none") - core.log_startup() # what each source is reading, in the order they are listed + if core is not None: + core.log_startup() # what each source is reading, in the order they are listed + else: + log.info("Weather service: %s (%s)", cfg.weather_mcp_url, ", ".join(sorted(weather.names)) or "not reached yet") notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's await bot.publish_commands(app.bot) # the / menu - running, rules = start_alerts(cfg, bot, notify, tasks, core) - core.start_warmers() # keeping warm: everything questions need, refreshed before they arrive - tasks.start(warm_up(bot, core, running, tasks, app.bot)) + running, rules = start_alerts(cfg, bot, notify, tasks, core, weather) + if core is not None: + core.start_warmers() # keeping warm: everything questions need, refreshed before they arrive + tasks.start(warm_up(bot, core, running, tasks, app.bot)) + else: # the service keeps itself warm: the bot only draws its keyboard's charts ahead (quietly nothing while it can't be reached) + tasks.start(every(AHEAD_SECONDS, lambda: bot.draw_buttons_ahead(app.bot))) await stop.wait() diff --git a/ecobot_service/bridge.py b/ecobot_service/bridge.py index 06cdce16..e3516c32 100644 --- a/ecobot_service/bridge.py +++ b/ecobot_service/bridge.py @@ -64,10 +64,11 @@ class Upstream: """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" - def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None): + def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None, resources=None): """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is - acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async.""" - self.target, self.token = target, token + acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. + resources: the URIs listened to, of those the service lists (None: every one).""" + self.target, self.token, self.resources = target, token, resources self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening self.client: Client | None = None self.connected = asyncio.Event() @@ -97,6 +98,8 @@ async def run(self): except BaseException as e: # (a transport failure ends the whole client, as an exception group too) if isinstance(e, (KeyboardInterrupt, SystemExit)): raise + if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have + raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same log.warning("Bridge: the service at %s isn't reachable (%s: %s); trying again", self.target, type(e).__name__, e) finally: self.client = None @@ -106,7 +109,7 @@ async def run(self): async def _listen(self, client: Client): """Listen to every resource the service lists and its lists' changes, passing each event on, until the stream ends.""" - uris = [r.uri for r in (await client.list_resources()).resources] + uris = [r.uri for r in (await client.list_resources()).resources if self.resources is None or str(r.uri) in self.resources] async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, resource_subscriptions=uris) as sub: if self.on_listening: diff --git a/lib/alerts/irrigation.py b/lib/alerts/irrigation.py index cf59dbf5..1ca9b815 100644 --- a/lib/alerts/irrigation.py +++ b/lib/alerts/irrigation.py @@ -33,7 +33,9 @@ class IrrigationMonitor: KINDS = kinds_of("Irrigation") def __init__(self, device, state, notify, tz, hour: int = 18, station=None, forecast=None): - """station: the Ecowitt source (its recent() gives the measured rain); forecast: the Forecast source. Either may be None.""" + """station: the Ecowitt source (its recent() gives the measured rain), or, with the weather service remote, what asks it for the + measured rain (lib/weather.ServiceRain: rain_mm()); forecast: the Forecast source, or the forecast read from the service + (lib/weather.ServiceForecast: read again at each check, the one last read standing when it can't be). Either may be None.""" self.device, self.state, self.notify, self.tz, self.hour = device, state, notify, tz, hour self.station, self.forecast = station, forecast @@ -95,13 +97,22 @@ async def rain_reason(self, now: datetime) -> str | None: """Why the irrigation should be delayed (what rained or will), or None. `now` is local.""" if self.station is not None: try: - rows = await self.station.recent(MEASURED_HOURS) - fell = rain_amount(rows, rows[0][0], rows[-1][0]) if rows else None + if (asked := getattr(self.station, "rain_mm", None)) is not None: # the weather service's summary of the rain + fell = await asked(MEASURED_HOURS) + else: + rows = await self.station.recent(MEASURED_HOURS) + fell = rain_amount(rows, rows[0][0], rows[-1][0]) if rows else None except Exception as e: # the forecast can still decide log.warning("Irrigation: the measured rain is unavailable (%s: %s)", type(e).__name__, e) fell = None if fell is not None and fell > MEASURED_MM: return f"{fell:g} mm of rain in the last 24 hours" + if (refresh := getattr(self.forecast, "refresh", None)) is not None: # the weather service's forecast, read again + try: + await refresh() + except Exception as e: + log.warning("Irrigation: the forecast couldn't be read (%s: %s); %s", type(e).__name__, e, + "using the one last read" if self.forecast.days else "there is none to go on") if self.forecast is not None and self.forecast.days: if local_epoch(now, self.tz) - self.forecast.fetched_at > FORECAST_TRUSTED_SECONDS: log.info("Irrigation: the forecast is from %s, over a day old: only the measured rain decides", diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 94601654..8b96f100 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -24,6 +24,7 @@ from .menu import ALL, LABELS, alert_keyboard from .pictures import CHARTS, AlertCharts, Picture, picture_of from .store import load, write +from ..weather import value log = logging.getLogger(__name__) @@ -259,8 +260,20 @@ class AlertDelivery: nothing for as long), noticed by the log's identity kept with the id, or by the id being past the log's newest.""" def __init__(self, log, notify: "Notifier", state: AlertState, tz): + """log: the alert log in this process (lib/alert_log.py), or the remote service's read over MCP (lib/weather.RemoteAlerts, whose + reads are coroutines: it is looked at when `run` starts).""" self.log, self.notify, self.state, self.tz = log, notify, state, tz - newest = self.log.last_id() + self.begun = False + if not getattr(log, "remote", False): + self._begin(self.log.last_id()) + + async def begin(self): + """Where delivery starts (the log looked at), if it hasn't yet.""" + if not self.begun: + self._begin(await value(self.log.last_id())) + + def _begin(self, newest: int): + self.begun = True if self.state.read is None: self._handled(newest) elif (self.state.read_log not in (None, self.log.identity)) or self.state.read > newest: @@ -288,8 +301,9 @@ async def run(self): """Forever: deliver what is new, then wait for more. A failure reading the log is logged and retried, never the end of alerts.""" while True: try: + await self.begin() await self.deliver_new() - await self.log.wait(self.last) + await value(self.log.wait(self.last)) except asyncio.CancelledError: raise except Exception as e: @@ -299,9 +313,9 @@ async def run(self): async def deliver_new(self) -> int: """Send each unexpired event after the last handled, oldest first; returns how many were sent.""" - newest = self.log.last_id() + newest = await value(self.log.last_id()) sent = 0 - for event in self.log.since(self.last): + for event in await value(self.log.since(self.last)): try: await self.deliver(event) sent += 1 diff --git a/lib/bot.py b/lib/bot.py index 3c72b45c..d491e20a 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -31,8 +31,6 @@ from .charts import render_data from .service import Service from .service.common import AS_DRAWN, BACKGROUND -from .service.context import Context -from .service.instructions import instructions from .specs import from_json from . import gauge_sheet from .tools import Turn @@ -43,6 +41,7 @@ from .llm import Agent, shorten_old, strip_tool_turns, trim_history from .logs import BUGS, QUOTES, fit from .warm import Tasks # (the service's too: ecobot_service) +from .weather import UNREACHABLE, LocalWeather, ServiceUnreachable log = logging.getLogger(__name__) @@ -74,6 +73,7 @@ "/particulates, /wind), \"weather now\" and a reading's chart over a period like \"rain chart 7d\" or \"humidity 30d\", " "as well as all the alerts.") OUT_OF_DATE = "That chart is out of date, please ask again" +SERVICE_DOWN = "Sorry, I can't reach the weather service right now. Please try again in a minute." # (WEATHER_MCP_URL: it is another program) @dataclass @@ -392,13 +392,15 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler service: Service | None = None, alert_log=None): """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); - its own when none is given. service: the service's tools (lib/service), which the bot's own code paths call (its shortcuts, - report, gauges, alert charts and period buttons); built over `sources` when none is given. The model is offered the same tools - (agent.tools: lib/model_tools.py), with the server's instructions (instructions(service.ctx)) after the bot's persona. alert_log: - the service's alert log (lib/alert_log.py), whose events the 🔄 under an alert's chart finds its chart's drawn_by in.""" + its own when none is given. service: the weather service as the bot reaches it (lib/weather.py: RemoteWeather over MCP, with + WEATHER_MCP_URL; `sources` is then empty), or the service's tools in this process (lib/service), which the bot's own code paths + call (its shortcuts, report, gauges, alert charts and period buttons), built over `sources` when none is given (LocalWeather). + The model is offered the same tools (agent.tools: lib/model_tools.py), with the server's instructions after the bot's persona. + alert_log: the service's alert log in this process (lib/alert_log.py), whose events the 🔄 under an alert's chart finds its + chart's drawn_by in.""" self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation - self.alert_log = alert_log - self._service = service + self.weather = service if getattr(service, "is_weather", False) else \ + LocalWeather(sources, service, alert_log, tz=getattr(cfg, "tz", None)) self.tasks = tasks or Tasks() self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends self.keyboard_version = templates.version(irrigation is not None) @@ -417,12 +419,14 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler @property def service(self) -> Service: - """The service's tools over the bot's sources (built on first use when none was given).""" - if self._service is None: - get = self.by_name.get - self._service = Service.of(Context(eco=get("Ecowitt"), air=get("AirGradient"), forecast=get("Forecast"), pollen=get("Pollen"), - tz=getattr(self.cfg, "tz", None))) - return self._service + """The service's tools (lib/weather.py: in this process, built over the bot's sources on first use when none was given; or the + remote service's list).""" + return self.weather.service + + @property + def names(self) -> set[str]: + """The sources the service has ("Ecowitt", "AirGradient", "Forecast", "Pollen").""" + return self.weather.names # ---------- the service's tools, as the bot calls them ---------- async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dict: @@ -435,23 +439,21 @@ async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dic log.debug("Service call %s %s", tool, json.dumps(args, ensure_ascii=False), extra=QUOTES) try: out = json.loads(await found.call(args, meta)) + except ServiceUnreachable as e: # (a remote service while it is being reached again: said once the person asks, _answer) + (log.debug if ahead else log.warning)("Service tool %s: %s", tool, e) + return {"error": str(e)} except Exception as e: log.error("Service tool %s failed: %s: %s", tool, type(e).__name__, e, exc_info=isinstance(e, BUGS)) return {"error": f"{type(e).__name__}: {e}"} return out if isinstance(out, dict) else {"error": "not an answer"} def _catalogue(self): - """The readings the service holds (the words of a shortcut are read against them): its Context's, else those of the sources the - bot has.""" - ctx = getattr(self.service, "ctx", None) - if ctx is not None: - return ctx.readings() - from .service.names import Catalogue - return Catalogue.of(station="Ecowitt" in self.by_name, air="AirGradient" in self.by_name) + """The readings the service holds (the words of a shortcut are read against them).""" + return self.weather.catalogue() def _instructions(self) -> str: - """The server's instructions (lib/service/instructions.py) over the service's Context.""" - return instructions(getattr(self.service, "ctx", None)) + """The server's instructions (lib/service/instructions.py; from server/discover when the service is remote).""" + return self.weather.instructions() def _sentence_call(self, text: str, now: datetime) -> tuple[str, dict] | None: """The call a keyboard sentence ("Wind chart 1d") is: a named reading's chart and a period (intent.chart_call); None for any other.""" @@ -603,7 +605,7 @@ async def on_membership(self, update: Update, context: ContextTypes.DEFAULT_TYPE self.state.mark_gone(change.chat.id, f"bot {status}") def _alert_kinds(self) -> list[str]: - return menu.available_kinds(self.by_name, bool(self.irrigation)) + return menu.available_kinds(self.names, bool(self.irrigation)) async def on_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """/alerts: the alert settings, as buttons (🔔 Alerts and 🔊 Sound). /alerts on and /alerts off still subscribe or @@ -627,7 +629,7 @@ async def on_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): async def _help_and_alerts(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """What the bot can do, then the alert settings: the Help & Alerts button and /usage.""" about = await self._service_call("about", {}) - await update.effective_message.reply_text("\n".join(about.get("lines") or []) or templates.capabilities_text(self.by_name)) + await update.effective_message.reply_text("\n".join(about.get("lines") or []) or templates.capabilities_text(self.names)) await self.on_alerts(update, context) async def on_usage(self, update: Update, context: ContextTypes.DEFAULT_TYPE): @@ -717,10 +719,10 @@ def _alert_event(message) -> int | None: return int(parts[3]) return None - def _alert_call(self, kind: str, event: int | None) -> tuple[str, dict] | None: + async def _alert_call(self, kind: str, event: int | None) -> tuple[str, dict] | None: """The call that draws an alert's chart again: its chart's drawn_by, from the alert log (`event`: its id); None without one (an alert sent before the log, or one dropped from it), when the type's own chart is drawn.""" - found = self.alert_log.get(event) if event is not None and self.alert_log is not None else None + found = await self.weather.alert(event) if event is not None else None drawn_by = (found or {}).get("chart", {}).get("drawn_by") if found and found.get("kind") == kind else None return (drawn_by["tool"], drawn_by["arguments"]) if drawn_by else None @@ -730,18 +732,19 @@ async def _redraw_alert(self, query, kind: str, event: int | None = None): drawn_by replayed, found in the alert log by its id `event`; the type's chart for an alert from before the log) and kept. The alert's text (what happened, as it was sent) and its buttons stay as they are.""" message = query.message - source = self.by_name.get(menu.TYPES[kind][1]) if kind in menu.TYPES else None - if source is None or not self._redrawable(message, kind): # an alert of a type, or from a source, the bot no longer has + there = kind in menu.TYPES and menu.TYPES[kind][1] in self.names + if not there or not self._redrawable(message, kind): # an alert of a type, or from a source, the bot no longer has await answer_query(query, STALE_BUTTON) return photo, drawn = self.alert_charts.newer_than(kind, message), False if photo is None: try: - if call := self._alert_call(kind, event): + if call := await self._alert_call(kind, event): made = await asyncio.wait_for(self._draw_call(*call, ahead=False), TURN_SECONDS) picture = pictures.Picture(made[0], made[1], made[3], made[4]) if made else None else: - picture = await asyncio.wait_for(pictures.chart(source, pictures.CHARTS[kind], source.tz, self.service), TURN_SECONDS) + picture = await asyncio.wait_for(pictures.chart(self.by_name.get(menu.TYPES[kind][1]), pictures.CHARTS[kind], self.cfg.tz, + self.service), TURN_SECONDS) except TimeoutError: picture = None if picture is None: # (pictures.chart has said why) the message stays as it was @@ -893,8 +896,7 @@ async def on_report_button(self, update: Update, context: ContextTypes.DEFAULT_T async def _redraw_dashboard(self, query): """A press on 🔄 under the dashboard: its gauges drawn again with the latest readings, and the time in its title, in the same message. When the station doesn't answer, the message stays as it was.""" - eco = self.by_name.get("Ecowitt") - if eco is None or not getattr(getattr(query, "message", None), "photo", None): # no station any more, or not the dashboard's picture + if "Ecowitt" not in self.names or not getattr(getattr(query, "message", None), "photo", None): # no station any more, or not the dashboard's picture await answer_query(query, STALE_BUTTON) return try: @@ -1147,7 +1149,7 @@ def _content(self, msg: Message, text: str, bot_id: int) -> str: async def _written_in_code(self, report: bool, ahead: bool = False) -> str: """The report, or "weather now", in the service's words: the readings now (current: each device's heading and lines), then the pollen's and the forecast's own text, the calls made together (intent.report_calls; "weather now": current {}).""" - calls = intent.report_calls(self.by_name) if report else [intent.WEATHER_NOW_CALL] + calls = intent.report_calls(self.names) if report else [intent.WEATHER_NOW_CALL] results = await asyncio.gather(*(self._service_call(name, args, ahead=ahead) for name, args in calls)) by_tool = {name: out for (name, _), out in zip(calls, results)} now = by_tool.get("current") or {"error": "none"} @@ -1171,7 +1173,7 @@ async def _report(self, report: bool, gauges: bool) -> tuple[str, bytes | None]: async def _status_gauges(self) -> bytes | None: """The report's picture: the weather station's temperature, humidity and rain gauges (gauge_sheet.STATUS), from the service's current with context. None without the station, or when they can't be drawn (the report then goes as text alone).""" - if "Ecowitt" not in self.by_name: + if "Ecowitt" not in self.names: return None try: sheet = await self._gauge_sheet(gauge_sheet.STATUS) @@ -1342,10 +1344,10 @@ async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text typing = asyncio.create_task(keep_typing(context.bot, msg.chat_id, self._thread(msg), stop_typing)) await asyncio.sleep(0) now = now_local(self.cfg.tz) - read = intent.read(text, now, self.by_name, self.cfg.tz, self._catalogue()) + read = intent.read(text, now, self.names, self.cfg.tz, self._catalogue()) log.info("%s%s: %s", describe_source(update), f" (reasoning: {read.effort})" if read.effort != intent.EFFORT_DEFAULT else "", text, extra=QUOTES) - for source in self.sources: # fetch recent readings while the model thinks + for source in self.sources: # fetch recent readings while the model thinks (in-process: a remote service keeps its own warm) if source.wants(text) and not read.chart: # a chart made in code reads just what it needs, first in line source.poke() if read.chart: @@ -1389,6 +1391,9 @@ async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], dra key = periods.call_key(*read.chart) if read.chart else None # the call the chart is (its cache key) if read.chart and (ready := self.images.ready(key)): # drawn ahead, or for someone's same call answer = Answer(ready.caption, [ready.photo], [ready.title], silent=True, ready=ready, drawn_by=[ready.drawn_by], key=key) + elif not await self.weather.ready(): # a remote service that can't be reached (in-process: always there) + log.warning("%s: %s", chat_tag(msg.chat_id), UNREACHABLE) + answer = Answer(SERVICE_DOWN, ok=False) elif read.chart: # drawn by the service; the chart goes out with just its title (the text is kept for the history) began = time.monotonic() made = await asyncio.wait_for(self._chart_in_code(read.chart), TURN_SECONDS) @@ -1428,7 +1433,7 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added time.monotonic() - started, len(used), len(photos), len(reply)) catalogue = self._catalogue() used_air = answer.ok and any(r and reads_air(*r, catalogue) for r in turn.results) # (an error reply gets no link) - air = self.by_name.get("AirGradient") + air_link = self.weather.air_link() if used_air else None markup = templates.keyboard(self.irrigation is not None) if self._keyboard_stale(msg) else None refresh = answer.ok and read.report and 0 < len(reply) <= TG_LIMIT and not markup # the report, to be refreshed in place single = len(photos) == 1 and not (read.dashboard or read.report) # a single chart: its period buttons go under it @@ -1446,7 +1451,7 @@ async def _send(self, msg: Message, bot, read, turn: Turn, answer: Answer, added self.images.alias(kept, periods.call_key(drawn_by["tool"], periods.with_period(drawn_by, own))) try: began = time.monotonic() - sent = await deliver(msg, reply, photos, link=air.link if air and used_air else None, + sent = await deliver(msg, reply, photos, link=air_link, markup=markup or (report_menu.keyboard() if refresh else report_menu.dashboard_keyboard() if answer.ok and read.dashboard and photos else None), titles=titles, period_row=row, bold_headings=answer.ok and read.report, photos_first=read.report) diff --git a/lib/config.py b/lib/config.py index a01fe396..e7793f01 100644 --- a/lib/config.py +++ b/lib/config.py @@ -287,6 +287,9 @@ class Config: mcp_tokens: tuple[tuple[str, str], ...] = _setting("MCP_TOKENS", (), _tokens) # "name:token,...", one per client; none: no auth, loopback only mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind) # host:port the service listens on mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) + # The bot as the service's client (docs/mcp-service.md step 5): set, the bot runs no sources, syncers or alert rules of its own + weather_mcp_url: str = _setting("WEATHER_MCP_URL", "", _url) # the service's MCP endpoint, e.g. http://127.0.0.1:8765/mcp; unset: the service runs inside the bot + weather_mcp_token: str = _setting("WEATHER_MCP_TOKEN", "") # the bearer token the bot sends it (one of the service's MCP_TOKENS) @property def alert_state_path(self) -> Path: @@ -359,7 +362,7 @@ def from_env(cls, bot: bool = True) -> "Config": for f in fields(cls): if bot and f.name in REQUIRED_BY_BOT: _required(getattr(cfg, f.name), f.default, f.metadata["env"]) - if not (cfg.ecowitt or cfg.airgradient): + if not (cfg.ecowitt or cfg.airgradient) and not (bot and cfg.weather_mcp_url): # (a client of the service needs no source) raise SystemExit("Set ECOWITT_API_KEY + ECOWITT_APP_KEY and/or HOMEASSISTANT_URL + HOMEASSISTANT_TOKEN and/or AIRGRADIENT_API_TOKEN + " "AIRGRADIENT_LOCATION_ID and/or AIRGRADIENT_LOCAL_URL") return cfg diff --git a/lib/model_tools.py b/lib/model_tools.py index 09f280fe..dc613793 100644 --- a/lib/model_tools.py +++ b/lib/model_tools.py @@ -44,9 +44,37 @@ async def handle(args: dict, turn: Turn) -> str: return Tool(service_tool.name, service_tool.description, service_tool.parameters, handle) +class ServiceTools(Tools): + """The service's tools as the model is offered them, following the service's list: read again whenever it is another list (a remote + service's, read on each connection and when the service says its tools changed; none while it has not been reached).""" + + def __init__(self, service): + self.service = service + self._seen: list[int] | None = None + self._by_name: dict[str, Tool] = {} + self._schemas: list[dict] = [] + + def _current(self): + listed = list(self.service) + if (seen := [id(t) for t in listed]) != self._seen: + wrapped = [tool(t) for t in listed] + self._by_name, self._schemas, self._seen = {t.name: t for t in wrapped}, [t.schema() for t in wrapped], seen + + @property + def by_name(self) -> dict[str, Tool]: + self._current() + return self._by_name + + @property + def schemas(self) -> list[dict]: + self._current() + return self._schemas + + def tools(service) -> Tools: - """The service's tools (a lib.service.Service, or any list of ServiceTools), in its order, as the model is offered them.""" - return Tools([tool(t) for t in service]) + """The service's tools (a lib.service.Service, a remote service's list (lib/weather.py), or any list of ServiceTools), in its order, + as the model is offered them.""" + return ServiceTools(service) -__all__ = ["BOT_CHART_NOTE", "for_model", "tool", "tools"] +__all__ = ["BOT_CHART_NOTE", "ServiceTools", "for_model", "tool", "tools"] diff --git a/lib/service/names.py b/lib/service/names.py index 6caa53d3..248c663f 100644 --- a/lib/service/names.py +++ b/lib/service/names.py @@ -19,7 +19,7 @@ import re from collections.abc import Iterable -from dataclasses import dataclass +from dataclasses import dataclass, replace from ..history import AIR_SENSOR, RAIN, Metric, air_metrics, station_fields, station_metrics from ..series import AIR, AIR_EXTRA, INDOOR_READINGS, WEATHER @@ -201,6 +201,15 @@ async def open(cls, eco=None, air=None) -> "Catalogue": """The readings the file holds for these sources (Ecowitt, AirGradient; either may be None), as the readings tool reads them.""" return cls.of(await station_fields(eco) if eco else None, station=eco is not None, air=air is not None) + @classmethod + def listed(cls, entries: Iterable[dict]) -> "Catalogue": + """The catalogue another process holds, from the readings it lists ({name, label, unit}, as ecobot://station's sensors give + them: a client's, docs/mcp-service.md step 5): each reading as this catalogue makes it, with the label and unit listed.""" + wanted = {e["name"]: e for e in entries if isinstance(e, dict) and e.get("name")} + made = (_reading(m, set(wanted)) for m in [*station_metrics(None), *air_metrics(extra=True)]) + return cls(replace(r, label=wanted[r.name].get("label") or r.label, unit=wanted[r.name].get("unit", r.unit)) + for r in made if r.name in wanted) + @property def names(self) -> list[str]: return list(self.readings) diff --git a/lib/weather.py b/lib/weather.py new file mode 100644 index 00000000..6309bee6 --- /dev/null +++ b/lib/weather.py @@ -0,0 +1,414 @@ +"""The weather service as the bot reaches it (docs/mcp-service.md section 4 and step 5): one interface, whether the service runs in this +process (LocalWeather: lib/service's tools over the bot's own sources, the alert log in this process; WEATHER_MCP_URL unset, as before) +or is another program reached over MCP (RemoteWeather: WEATHER_MCP_URL, a client pinned to protocol 2026-07-28 that one supervisor +task keeps connected). Everything the bot asks of the service goes through it, so the bot doesn't branch on where the service runs: + + - `service`: the tools, as lib.service.Service gives them: iterated in order, `get(name)` or `service[name]`, each with its name, + description, parameters and `call(args, meta)`, which returns the tool's JSON text (lib/model_tools.py offers them to the model; the + bot's shortcuts, report, gauges, charts drawn ahead and period buttons call them); + - `names`: the sources the service has ("Ecowitt", "AirGradient", "Forecast", "Pollen"): which alerts, report sections and gauges + there are; + - `catalogue()`: the readings it holds (a shortcut's words are read against them); `instructions()`: the server's instructions (from + `server/discover` when remote); `air_link()`: the AirGradient dashboard (the live-chart link under an answer about the air); + - `alerts`: the alert feed lib/alerts/notify.AlertDelivery reads (`last_id`, `identity`, `since`, `wait`), and `alert(id)` one event + (the 🔄 under an alert replays its chart's drawn_by); + - `resource(uri)`: a resource's content (ecobot://station, ecobot://forecast ...); + - `ready(wait)`: whether it can be reached (in-process, always; remote, once connected, waiting up to `wait` seconds for it). + +For the irrigation check while it is still the bot's (step 5b moves it to its own server): `ServiceRain` (the measured rain, from +`summary {readings: ["rain"], period: "last 24 hours"}`) and `ServiceForecast` (ecobot://forecast, the last read kept when the service +can't be reached), docs 3.9.""" + +import asyncio +import json +import logging +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from .service.instructions import instructions as service_instructions +from .timeutil import now_local + +log = logging.getLogger(__name__) + +STATION_URI, ALERTS_URI, FORECAST_URI = "ecobot://station", "ecobot://alerts", "ecobot://forecast" # (as lib/mcp_server.py's) +LISTENED = (STATION_URI, ALERTS_URI, FORECAST_URI) # what the bot listens to (not the live readings, pushed every few seconds) +CALL_WAIT = 5.0 # how long a question's call waits for the service while it is being reached again, before it is refused +BACKGROUND = "background" # request _meta priority of a call nobody waits for (lib/service/common.py): refused at once while down +AIR_LINK_LABEL = "live chart" # the AirGradient dashboard link's words (lib/airgradient/source.py) +AS_A_CALL = object() # a wait of CALL_WAIT seconds (read when called) +UNREACHABLE = "The weather service isn't reachable right now: try again in a minute." + + +class ServiceUnreachable(RuntimeError): + """The remote service can't be reached (it is down, or the connection is being made again).""" + + def __init__(self, message: str = UNREACHABLE): + super().__init__(message) + + +async def value(x): + """x, awaited when it is awaitable: the alert feed's methods are plain in-process and coroutines when remote.""" + return await x if asyncio.iscoroutine(x) or isinstance(x, asyncio.Future) else x + + +# ---------- in-process ---------- +class LocalWeather: + """The service in this process: its tools (a lib.service.Service, built over `sources` on first use when none is given), the sources + it runs over, the alert log.""" + is_weather, remote = True, False + + def __init__(self, sources=(), service=None, alert_log=None, tz=None): + self.sources, self.alert_log, self.tz = list(sources), alert_log, tz + self.by_name = {s.name: s for s in self.sources} + self._service = service + + @property + def service(self): + if self._service is None: + from .service import Service + from .service.context import Context + get = self.by_name.get + self._service = Service.of(Context(eco=get("Ecowitt"), air=get("AirGradient"), forecast=get("Forecast"), pollen=get("Pollen"), + tz=self.tz)) + return self._service + + def __iter__(self): # (the tools, as the service lists them: lib/model_tools.py follows the list) + return iter(self.service) + + @property + def names(self) -> set[str]: + return set(self.by_name) + + @property + def ctx(self): + return getattr(self.service, "ctx", None) + + def catalogue(self): + if (ctx := self.ctx) is not None: + return ctx.readings() + from .service.names import Catalogue + return Catalogue.of(station="Ecowitt" in self.by_name, air="AirGradient" in self.by_name) + + def instructions(self) -> str: + return service_instructions(self.ctx) + + def air_link(self) -> tuple[str, str] | None: + return getattr(self.by_name.get("AirGradient"), "link", None) + + @property + def alerts(self): + return self.alert_log + + async def alert(self, event_id: int) -> dict | None: + return self.alert_log.get(event_id) if self.alert_log is not None else None + + async def resource(self, uri: str) -> dict: + from .mcp_server import EcobotServer + return await EcobotServer(self.ctx, self.alert_log).read(uri) + + async def ready(self, wait: float = 0) -> bool: + return True + + +# ---------- over MCP ---------- +class RemoteTool: + """One of the service's tools as tools/list gave it, called over MCP.""" + + def __init__(self, weather: "RemoteWeather", entry): + self.weather, self.name = weather, entry.name + self.description, self.parameters = entry.description or "", entry.input_schema + hints = entry.annotations + self.read_only = bool(getattr(hints, "read_only_hint", True)) + self.open_world = bool(getattr(hints, "open_world_hint", False)) + + async def call(self, args: dict | None = None, meta: dict | None = None) -> str: + return await self.weather.call_text(self.name, args, meta) + + +class RemoteTools: + """The service's tool list, as lib.service.Service is used: in order, by name.""" + + def __init__(self, tools=()): + self.tools = list(tools) + self.by_name = {t.name: t for t in self.tools} + + def __iter__(self): + return iter(self.tools) + + def __len__(self): + return len(self.tools) + + def __contains__(self, name) -> bool: + return name in self.by_name + + def get(self, name: str): + return self.by_name.get(name) + + def __getitem__(self, name: str): + return self.by_name[name] + + +class RemoteAlerts: + """The service's alert log read over MCP (ecobot://alerts and its template with `since`), as AlertDelivery reads the log in process. + A read waits for the service while it can't be reached; `wait` returns when the listen says the alerts changed (ResourceUpdated) or a + new connection listens (nothing is replayed, so what was missed is read after the last id handled).""" + remote = True + + def __init__(self, weather: "RemoteWeather"): + self.weather = weather + self.identity: str | None = None + self.newest = 0 + self._changed = asyncio.Event() + + def changed(self): + self._changed.set() + + async def read(self, since: int = 0, expired: bool = False) -> dict: + """ecobot://alerts?since=… as {alerts, last_id, identity}, waiting for the service as long as it takes; a refusal (MCPError) is + raised.""" + from mcp.shared.exceptions import MCPError + uri = f"{ALERTS_URI}?since={int(since)}" + ("&expired=true" if expired else "") + while True: + try: + data = await self.weather.resource(uri, wait=None) + except MCPError: + raise + except asyncio.CancelledError: + raise + except Exception as e: # (the connection lost mid-read: the supervisor builds another) + log.debug("The alerts couldn't be read (%s: %s); trying again", type(e).__name__, e) + await asyncio.sleep(1) + continue + self.identity, self.newest = data.get("identity"), int(data.get("last_id") or 0) + return data + + async def last_id(self) -> int: + await self.read(self.newest) + return self.newest + + async def since(self, after: int = 0, expired: bool = False) -> list[dict]: + self._changed.clear() # (before the read: a change while it runs wakes the next wait) + return (await self.read(after, expired))["alerts"] + + async def get(self, event_id: int) -> dict | None: + found = await self.read(max(int(event_id) - 1, 0), expired=True) + return next((a for a in found["alerts"] if a.get("id") == event_id), None) + + async def wait(self, after: int, timeout: float | None = None) -> bool: + try: + async with asyncio.timeout(timeout): + await self._changed.wait() + return True + except TimeoutError: + return False + + +class RemoteWeather: + """The service at `target` (its MCP URL; in tests, a Server in-process), as the bot's interface. `run()` is the supervisor (the + bridge's Upstream: one client, discovered by hand for the instructions, listening; on a transport error or a lost or ended listen it + is dropped and built again after a backoff, which discovers and listens again). Each new connection reads the tool list and the + station; the listen's events keep them current (ToolsListChanged, the station's and the forecast's ResourceUpdated) and wake the + alert delivery (the alerts'). A call while it is being reached waits up to CALL_WAIT seconds (a background one not at all) and is + then refused with ServiceUnreachable.""" + is_weather, remote = True, True + + def __init__(self, target, token: str | None = None, tz=None): + from ecobot_service.bridge import Upstream + self.target, self.fallback_tz, self.station_tz = target, tz, None + self.upstream = Upstream(target, token, on_event=self._event, on_discover=self._discovered, on_listening=self._listening, + resources=LISTENED) + self.service = RemoteTools() + self.station: dict = {} + self._instructions = "" + self._catalogue = None + self.alerts = RemoteAlerts(self) + self.forecast = ServiceForecast(self) + self.listening = asyncio.Event() # the first connection's listen is up, its tools and station read + self._background: set[asyncio.Task] = set() + + def __iter__(self): # (the tools, as the service lists them now: lib/model_tools.py follows the list) + return iter(self.service) + + @property + def url(self) -> str: + return self.target if isinstance(self.target, str) else "the service" + + async def run(self): + await self.upstream.run() + + # ---------- the connection ---------- + async def _discovered(self, discovered): + self._instructions = discovered.instructions or "" + + async def _listening(self): + """A new connection listens: the tools and the station read again, the alerts looked at (what came while it was down is not + replayed), the forecast read again.""" + for refresh in (self._read_tools, self._read_station): + try: + await refresh() + except Exception as e: # (the connection is still good: the listen's events refresh them later) + log.warning("Weather service: couldn't read %s (%s: %s)", refresh.__name__.removeprefix("_read_"), type(e).__name__, e) + self.alerts.changed() + self._soon(self.forecast.refresh) + self.listening.set() + + async def _event(self, event): + from mcp.shared.subscriptions import ResourceUpdated, ToolsListChanged + if isinstance(event, ToolsListChanged): + self._soon(self._read_tools) + elif isinstance(event, ResourceUpdated): + uri = str(event.uri) + if uri == ALERTS_URI: + self.alerts.changed() + elif uri == STATION_URI: + self._soon(self._read_station) + elif uri == FORECAST_URI: + self._soon(self.forecast.refresh) + + def _soon(self, fn): + """fn() in the background (a listen event is not held up by the reads it causes), its failure only logged.""" + async def run(): + try: + await fn() + except Exception as e: + log.debug("Weather service: %s failed (%s: %s)", getattr(fn, "__name__", fn), type(e).__name__, e) + task = asyncio.create_task(run()) + self._background.add(task) + task.add_done_callback(self._background.discard) + + async def _read_tools(self): + client = await self._client(0) + self.service = RemoteTools(RemoteTool(self, t) for t in (await client.list_tools()).tools) + + async def _read_station(self): + station = await self.resource(STATION_URI, wait=0) + self.station, self._catalogue = station, None + if zone := station.get("time_zone"): + try: + self.station_tz = ZoneInfo(zone) + except Exception: # (an offset only: TZ stands) + pass + + @property + def tz(self): + """The station's time zone (ecobot://station's), TZ until it has been read.""" + return self.station_tz or self.fallback_tz + + async def _client(self, wait: float | None): + """The connected client, waiting up to `wait` seconds for one (None: as long as it takes); ServiceUnreachable after.""" + up = self.upstream + if up.client is None and wait != 0: + try: + async with asyncio.timeout(wait): + while up.client is None: + await up.connected.wait() + if up.client is None: + await asyncio.sleep(0.05) + except TimeoutError: + pass + if up.client is None: + raise ServiceUnreachable() + return up.client + + async def ready(self, wait=AS_A_CALL) -> bool: + try: + await self._client(CALL_WAIT if wait is AS_A_CALL else wait) + return True + except ServiceUnreachable: + return False + + # ---------- what the bot asks ---------- + async def call_text(self, name: str, args: dict | None = None, meta: dict | None = None) -> str: + """A tool's answer as its JSON text (the first text block: the tool's JSON, a refusal's too). A background request (nobody + waiting) doesn't wait for the service.""" + meta = dict(meta or {}) + client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) + result = await client.call_tool(name, args or {}, meta=meta or None) + for block in result.content: + if getattr(block, "type", None) == "text": + return block.text + return json.dumps({"error": f"The service's {name} gave no answer."}) + + async def resource(self, uri: str, wait=AS_A_CALL) -> dict: + """A resource's content; `wait`: how long to wait for the service (CALL_WAIT; None as long as it takes).""" + client = await self._client(CALL_WAIT if wait is AS_A_CALL else wait) + read = await client.read_resource(uri) + return json.loads(read.contents[0].text) + + @property + def names(self) -> set[str]: + return set(self.station.get("sources") or {}) + + def catalogue(self): + if self._catalogue is None: + from .service.names import Catalogue + sensors = self.station.get("sensors") or {} + self._catalogue = Catalogue.listed([r for s in sensors.values() for r in s.get("readings") or []]) + return self._catalogue + + def instructions(self) -> str: + return self._instructions + + def air_link(self) -> tuple[str, str] | None: + url = self.station.get("airgradient_dashboard") + return (AIR_LINK_LABEL, url) if url else None + + async def alert(self, event_id: int) -> dict | None: + try: + return await asyncio.wait_for(self.alerts.get(event_id), CALL_WAIT) + except Exception as e: # (not reached in time, or refused: the alert's type's own chart is drawn instead) + log.debug("Weather service: alert %s couldn't be read (%s: %s)", event_id, type(e).__name__, e) + return None + + async def close(self): + for task in list(self._background): + task.cancel() + await asyncio.gather(*self._background, return_exceptions=True) + + +# ---------- the irrigation check's inputs (docs 3.9) ---------- +class ServiceRain: + """The measured rain as the irrigation check asks the service for it: summary {readings: ["rain"], period: "last N hours"}'s total.""" + + def __init__(self, weather): + self.weather = weather + + async def rain_mm(self, hours: int = 24) -> float | None: + out = json.loads(await self.weather.call_text("summary", {"readings": ["rain"], "period": f"last {hours} hours"})) + if "error" in out: + raise ValueError(out["error"]) + return out.get("rain_total_mm") + + +class ServiceForecast: + """The forecast as the irrigation check reads it, from ecobot://forecast (its days, each with its chance of at least 1 mm, and when it + was fetched), as lib/forecast's source gives them (`days`, `fetched_at`, `now()`, `upcoming()`). `refresh()` reads it again; when the + service can't be reached the forecast last read stands.""" + + def __init__(self, weather): + self.weather = weather + self.days: list[dict] | None = None + self.fetched_at: float = 0 + self.place: str | None = None + + async def refresh(self): + data = await self.weather.resource(FORECAST_URI) + days = [] + for d in data.get("days") or []: + try: + days.append({**d, "date": date.fromisoformat(str(d["date"])[:10])}) + except (KeyError, ValueError): + continue + fetched = data.get("fetched_at") + self.days, self.place = days, data.get("place") + self.fetched_at = datetime.fromisoformat(fetched).timestamp() if fetched else 0 + + def now(self) -> datetime: + return now_local(self.weather.tz) + + def upcoming(self, count: int = 2) -> list[dict]: + today = self.now().date() + return [d for d in (self.days or []) if d["date"] >= today][:count] + + +__all__ = ["LocalWeather", "RemoteWeather", "ServiceForecast", "ServiceRain", "ServiceUnreachable", "UNREACHABLE", "value"] diff --git a/tests/conftest.py b/tests/conftest.py index a5919c15..f7dd0dba 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,6 +23,17 @@ def pytest_collection_modifyitems(items): items.sort(key=lambda item: (item.path.name not in HEAVY, HEAVY.index(item.path.name) if item.path.name in HEAVY else 0)) +@pytest.fixture(autouse=True) +def the_log_levels_as_they_were(): + """The programs' main() (ecobot.py, ecobot_service) set the "ecobot" and "lib" loggers' levels from LOG_LEVEL: put back after every + test, so a test that reads the debug lines doesn't depend on which ran before it on its worker.""" + import logging + levels = {name: logging.getLogger(name).level for name in ("ecobot", "lib")} + yield + for name, level in levels.items(): + logging.getLogger(name).setLevel(level) + + @pytest.fixture def alert_state(tmp_path): """The bot's chats and settings (an AlertState) in a file of the test's own: what a Bot is given, as in the running bot.""" diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py new file mode 100644 index 00000000..0bfacb94 --- /dev/null +++ b/tests/test_bot_remote.py @@ -0,0 +1,330 @@ +"""The bot as the service's client over MCP (WEATHER_MCP_URL: lib/weather.RemoteWeather, docs/mcp-service.md 3.8 and step 5), against the +real server (lib/mcp_server.EcobotServer): over the SDK's in-memory transport for a question answered with the remote tools, a chart drawn +from a remote result with its buttons, an alert delivered through the listen and the irrigation check's inputs; under uvicorn on a localhost +port (a connection can fail there) for a dropped connection rebuilt with the alerts after the last id read once, the service down (the bot +says so), and ecobot.main() as a client. The path with WEATHER_MCP_URL unset is the rest of the suite's.""" + +import asyncio +import json +import time +from types import SimpleNamespace as NS + +import pytest + +from ecobot_service import bridge +from lib import model_tools, weather as weather_module +from lib.alert_log import AlertLog +from lib.alerts.notify import AlertDelivery, AlertState, Notifier +from lib.bot import SERVICE_DOWN, Bot +from lib.llm import Agent +from lib.mcp_server import EcobotServer, http_app +from lib.service.context import Context +from lib.weather import RemoteWeather, ServiceForecast, ServiceRain, ServiceUnreachable +from tests import evalworld +from tests.fakes import TZ +from tests.test_mcp_listen import Serving, free_port, until + +TOKEN = "s3cret" + + +def at_eval_now(patch: pytest.MonkeyPatch): + evalworld.at_eval_now(patch, __name__) + + +@pytest.fixture(scope="module") +def eval_archive(tmp_path_factory): + path = tmp_path_factory.mktemp("remote-eval-now") + with pytest.MonkeyPatch.context() as patch: + at_eval_now(patch) + return asyncio.run(evalworld.build_archive(path)) + + +@pytest.fixture +async def world(tmp_path, eval_archive, monkeypatch): + """The real server over the four sources (faked, the clock at the evals' NOW) and an alert log.""" + at_eval_now(monkeypatch) + ctx = await evalworld.real_context(tmp_path, eval_archive) + alerts = AlertLog(tmp_path / "alerts.sqlite", ctx.zone) + server = EcobotServer(ctx, alerts) + yield server + alerts.close() + await evalworld.close(ctx) + + +@pytest.fixture(autouse=True) +def quick(monkeypatch): + """Reconnections and waits in tenths of a second, not seconds.""" + monkeypatch.setattr(bridge, "BACKOFF", (0.1,)) + monkeypatch.setattr(weather_module, "CALL_WAIT", 0.3) + + +@pytest.fixture +async def connected(world): + """A RemoteWeather over the server in memory, its supervisor running and listening.""" + remote = RemoteWeather(world.server, tz=None) + task = asyncio.create_task(remote.run()) + await asyncio.wait_for(remote.listening.wait(), 10) + yield remote + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await remote.close() + + +class Telegram: + """What the bot sends, kept.""" + def __init__(self): + self.sent = [] + + async def send_message(self, chat_id, text, **kw): + self.sent.append((chat_id, text)) + return NS(photo=None) + + async def send_photo(self, chat_id, photo, **kw): + self.sent.append((chat_id, kw.get("caption"))) + return NS(photo=(NS(file_id="small"), NS(file_id="big"))) + + +def a_chat(kind="private"): + """A message in a chat, its replies kept (text, or (caption, buttons) for a photo).""" + replies = [] + + async def reply_text(body, **kw): + replies.append(body) + return NS(message_id=8) + + async def reply_photo(photo, caption=None, reply_markup=None, **kw): + replies.append((caption, reply_markup)) + return NS(message_id=9) + + async def nothing(*a, **k): + pass + msg = NS(chat_id=1, message_thread_id=None, is_topic_message=False, reply_text=reply_text, reply_photo=reply_photo, + chat=NS(type=kind, title="g" if kind != "private" else None), from_user=NS(full_name="Rob"), reply_to_message=None) + update = NS(effective_message=msg, effective_chat=msg.chat, effective_user=NS(username="rob", full_name="Rob")) + context = NS(bot=NS(send_chat_action=nothing, send_message_draft=nothing, id=99)) + return update, context, replies + + +class Model: + """A model that makes `calls` (name, arguments) in its first step, then answers `answer`; what it was sent is kept.""" + + def __init__(self, calls, answer="It's 14.2 °C."): + self.calls, self.answer, self.seen = calls, answer, [] + self.chat = NS(completions=self) + + async def create(self, **kw): + self.seen.append(kw) + if len(self.seen) == 1 and self.calls: + made = [NS(id=str(i), function=NS(name=name, arguments=json.dumps(args))) for i, (name, args) in enumerate(self.calls)] + return NS(choices=[NS(message=NS(content="", tool_calls=made))], usage=None) + return NS(choices=[NS(message=NS(content=self.answer, tool_calls=None))], usage=None) + + +# ---------- in memory ---------- +async def test_a_question_is_answered_with_the_remote_tools_and_the_instructions_from_discover(connected, world, alert_state): + model = Model([("current", {"readings": ["temperature"]})]) + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(connected)), [], alert_state, service=connected) + update, context, replies = a_chat("group") # (no draft streamed: the model's answer comes whole) + await bot.respond(update, context, "how warm is it outside?") + first = model.seen[0] + assert [t["function"]["name"] for t in first["tools"]] == [t.name for t in world.service] # the service's ten, as listed + assert world.server.instructions and world.server.instructions in first["messages"][0]["content"] # discover's instructions + told = json.loads(model.seen[1]["messages"][-1]["content"]) + assert told == json.loads(await world.service["current"].call({"readings": ["temperature"]})) # the remote tool's own answer + assert replies == ["It's 14.2 °C."] + assert bot.names == {"Ecowitt", "AirGradient", "Forecast", "Pollen"} and bot.sources == [] # (from ecobot://station; no sources here) + assert bot._catalogue().names == world.ctx.readings().names + + +async def test_a_chart_is_drawn_from_a_remote_result_with_its_period_buttons(connected, alert_state, monkeypatch): + drawn = [] + monkeypatch.setattr("lib.bot.Bot._draw", lambda self, c, times=None: drawn.append(c) or (b"png", c["title"], 0)) + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), [], alert_state, service=connected) + update, context, replies = a_chat("group") + await bot.respond(update, context, "Humidity chart 7d") # (a shortcut: a fixed summary call, no model) + (caption, markup), = replies + (chart,) = drawn + assert chart["drawn_by"]["tool"] == "summary" and chart["drawn_by"]["arguments"]["period"] == "7d" + assert len(max((s["points"] for p in chart["panels"] for s in p["series"]), key=len)) > 150 # (asked as drawn, not 150 points) + assert [b.callback_data for b in markup.inline_keyboard[0]] == ["pd:1d", "pd:7d", "pd:1m", "pd:3m", "pd:1y"] + assert bot.charted.get(1, 9)["drawn_by"] == chart["drawn_by"] + + +async def test_an_alert_reaches_the_subscribed_chats_through_the_listen(connected, world, tmp_path): + publishing = asyncio.create_task(world.watch_alerts()) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + delivery = asyncio.create_task(AlertDelivery(connected.alerts, Notifier(telegram, state), state, TZ).run()) + try: + await until(lambda: state.read is not None, what="the delivery to begin") + world.alert_log.append("rain", "🌧️ It's started raining: 0.4 mm so far", "Rain started") # (no expiry: the clock here is the evals') + await until(lambda: telegram.sent, what="the alert") + finally: + for task in (publishing, delivery): + task.cancel() + await asyncio.gather(publishing, delivery, return_exceptions=True) + assert telegram.sent == [(1, "🌧️ It's started raining: 0.4 mm so far")] and state.read == 1 + + +async def test_the_irrigation_check_reads_the_measured_rain_and_the_forecast_from_the_service(connected, world): + rain = await ServiceRain(connected).rain_mm(24) + summary = json.loads(await world.service["summary"].call({"readings": ["rain"], "period": "last 24 hours"})) + assert rain == summary["rain_total_mm"] + await world.ctx.forecast.warm() # (the service fetches its forecast) + forecast = connected.forecast + await forecast.refresh() # (as the check does; the listen's ResourceUpdated does it too) + assert forecast.days + assert [d["date"] for d in forecast.days] == [d["date"] for d in world.ctx.forecast.days] + assert forecast.fetched_at == pytest.approx(world.ctx.forecast.fetched_at, abs=1) + + +async def test_the_irrigation_check_runs_on_the_forecast_last_read_when_the_service_cant_be_reached(caplog): + from datetime import date, datetime + from lib.alerts.irrigation import IrrigationMonitor + + class Down: + tz = TZ + + async def call_text(self, *a, **k): + raise ServiceUnreachable() + + async def resource(self, uri, wait=None): + raise ServiceUnreachable() + forecast = ServiceForecast(Down()) + now = datetime(2026, 11, 10, 18, 0, tzinfo=TZ) + forecast.days, forecast.fetched_at = [{"date": date(2026, 11, 11), "rain_1mm_pct": 70}], now.timestamp() - 3600 # (read an hour ago) + forecast.now = lambda: now + monitor = IrrigationMonitor(None, NS(monitor={}), None, TZ, station=ServiceRain(Down()), forecast=forecast) + assert await monitor.rain_reason(now) == "70% chance of at least 1 mm tomorrow" + assert "the measured rain is unavailable" in caplog.text and "using the one last read" in caplog.text + + +# ---------- under uvicorn ---------- +@pytest.fixture +def bare(tmp_path): + """A server with no sources (the alerts and their listen are what matter) and its alert log.""" + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + yield EcobotServer(Context(tz=TZ), alerts) + alerts.close() + + +async def test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_are_read_once(bare, tmp_path): + port = free_port() + remote = RemoteWeather(f"http://127.0.0.1:{port}/mcp", TOKEN, TZ) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + publishing = asyncio.create_task(bare.watch_alerts()) + supervisor = asyncio.create_task(remote.run()) + delivery = asyncio.create_task(AlertDelivery(remote.alerts, Notifier(telegram, state), state, TZ).run()) + texts = lambda: [text for _, text in telegram.sent] + alerts = bare.alert_log + try: + async with Serving(http_app(bare, tokens={"bot": TOKEN}), port) as first: + await until(lambda: state.read is not None and bare.listen._streams, what="the listen") + alerts.append("rain", "first", "Rain started", expires=time.time() + 3600) + await until(lambda: texts() == ["first"], what="alert 1") + await first.stop() # the service goes away: the listen is lost + await until(lambda: not remote.upstream.connected.is_set(), what="the bot to notice") + assert not await remote.ready(0.1) + alerts.append("gusts", "missed", "Gusts", expires=time.time() + 3600) # sent while it was down + alerts.append("uv", "stale", "UV", expires=time.time() - 1) # ... and expired already: not news + async with Serving(http_app(bare, tokens={"bot": TOKEN}), port): + await until(lambda: texts() == ["first", "missed"], what="the alert missed, read after the last id") + await until(lambda: bare.listen._streams, what="the listen again") + alerts.append("temps", "after", "Temperatures", expires=time.time() + 3600) + await until(lambda: texts() == ["first", "missed", "after"], what="alert 4 on the new listen") + await asyncio.sleep(0.3) + finally: + for task in (delivery, supervisor, publishing): + task.cancel() + await asyncio.gather(delivery, supervisor, publishing, return_exceptions=True) + assert texts() == ["first", "missed", "after"] and state.read == 4 # each once, the expired one skipped + + +async def test_with_the_service_down_the_bot_says_so_and_carries_on(alert_state, caplog): + remote = RemoteWeather(f"http://127.0.0.1:{free_port()}/mcp", TOKEN, TZ) # (nothing listens there) + supervisor = asyncio.create_task(remote.run()) + try: + model = Model([("current", {})]) + bot = Bot(NS(tz=TZ), Agent(model, "m", model_tools.tools(remote)), [], alert_state, service=remote) + for text in ("how warm is it?", "weather now", "Humidity chart 7d"): + update, context, replies = a_chat() + await bot.respond(update, context, text) + assert replies == [SERVICE_DOWN], text + assert model.seen == [] # (no model call for an answer it couldn't get) + assert model_tools.tools(remote).schemas == [] # (no tools listed while it has not been reached) + with pytest.raises(ServiceUnreachable): + await remote.call_text("current", {}, {"priority": "background"}) # (a call nobody waits for is refused at once) + assert "isn't reachable" in caplog.text + finally: + supervisor.cancel() + await asyncio.gather(supervisor, return_exceptions=True) + + +async def test_main_as_a_client_runs_no_sources_and_answers_from_the_service(bare, tmp_path, monkeypatch, caplog): + """ecobot.main() with WEATHER_MCP_URL: no source is started (no keys are set), the service's station names the time zone, the + bot draws its keyboard's charts ahead, and an alert the service logs reaches a chat.""" + import os + import signal + import ecobot + from tests.fakes import config + from tests.test_startup import FakeApp, FakeBuilder + caplog.set_level("INFO") + port = free_port() + cfg = config(tmp_path, weather_mcp_url=f"http://127.0.0.1:{port}/mcp", weather_mcp_token=TOKEN, ecowitt_api_key="", + ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") + (tmp_path / "bot").mkdir() + AlertState(cfg.state_path).add_chat(5, "private") + app = FakeApp() + monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) # (main sets LOG_WIDTH's: put back after; the levels: conftest) + drawn = [] + + async def note(self, tg_bot): + drawn.append(tg_bot) + monkeypatch.setattr(ecobot.Bot, "draw_buttons_ahead", note) + monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(app))) + started = [] + monkeypatch.setattr(ecobot, "start_sources", lambda *a: started.append(a)) + publishing = asyncio.create_task(bare.watch_alerts()) + + async def alert_then_stop(): + try: + await alert() + finally: # (main() runs until it is stopped, whatever happened) + os.kill(os.getpid(), signal.SIGTERM) + + async def alert(): + await until(lambda: bare.listen._streams and cfg.state_path.exists() and "alerts_read" in cfg.state_path.read_text(), + what="the bot to listen and its delivery to begin") + bare.alert_log.append("rain", "🌧️ Raining", "Rain started", expires=time.time() + 3600) + await until(lambda: app.sent, what="the alert sent") + try: + async with Serving(http_app(bare, tokens={"bot": TOKEN}), port): + stopper = asyncio.create_task(alert_then_stop()) + await ecobot.main() + await stopper + finally: + publishing.cancel() + await asyncio.gather(publishing, return_exceptions=True) + assert started == [] and "Ecowitt: " not in caplog.text and "Telegram: @testbot" in caplog.text + assert f"Weather service: {cfg.weather_mcp_url}" in caplog.text + assert [(chat, text) for chat, text, _ in app.sent] == [(5, "🌧️ Raining")] + assert drawn == [app.bot] + + +def test_a_client_of_the_service_needs_no_source_settings(monkeypatch, tmp_path): + from lib.config import Config + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1:x") + for name in ("ECOWITT_API_KEY", "ECOWITT_APP_KEY", "HOMEASSISTANT_URL", "HOMEASSISTANT_TOKEN", "AIRGRADIENT_API_TOKEN", + "AIRGRADIENT_LOCATION_ID", "AIRGRADIENT_LOCAL_URL", "WEATHER_MCP_URL"): + monkeypatch.delenv(name, raising=False) + with pytest.raises(SystemExit, match="ECOWITT_API_KEY"): + Config.from_env() + monkeypatch.setenv("WEATHER_MCP_URL", "http://127.0.0.1:8765/mcp/") + monkeypatch.setenv("WEATHER_MCP_TOKEN", "t0ken") + cfg = Config.from_env() + assert (cfg.weather_mcp_url, cfg.weather_mcp_token) == ("http://127.0.0.1:8765/mcp", "t0ken") and not cfg.ecowitt From 18ce9c49ac49ce1de3c64aad08c07fe5dd955045 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:09:33 +0000 Subject: [PATCH 065/125] Step 5a review: a log replaced while the bot runs; the station's zone read late - AlertDelivery checks the alert log's identity (and its newest id) on every pass, not only at the start: the service back on another alerts.sqlite while the bot runs is noticed at once, with a warning, and delivery goes on in the new log with its events from after the old one was last read (one logged while the bot was reconnecting included), not after the old last id. - The station's time zone is followed whenever it is read (RemoteWeather.on_zone, ecobot.follow_zone): a start before the service could be reached moves into it later (the bot's settings, the charts, the alerts' charts, AlertDelivery, IrrigationMonitor, whose wait for the check time is timed again). It is kept in bot_state.json (station_zone): a start while the service is down runs in the zone last read, TZ only before any. - Tests: the service back on a fresh alert log while the bot runs; main() started without the service, then reached; the irrigation check timed again in a zone read later. Docs: mcp-service.md, configuration.md (TZ). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/configuration.md | 2 +- docs/mcp-service.md | 7 +- ecobot.py | 72 +++++++++++++++---- lib/alerts/irrigation.py | 26 ++++++- lib/alerts/notify.py | 66 +++++++++++++---- lib/weather.py | 8 ++- tests/test_bot_remote.py | 150 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 298 insertions(+), 33 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 90a6c2db..31708d62 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -38,7 +38,7 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `AIRGRADIENT_LOCAL_URL` | – | Sensor's local server, e.g. `http://airgradient_.local` or an IP. Live reading polled every 60 s, recorded as 5-min means (`pm02Compensated` over `pm02`). Cloud, if configured, only fills gaps. Without cloud vars: sensor + SQLite only, no cloud requests. `.local` resolved in-process (mDNS); in Docker needs the host network (README: Docker networking) or an IP. Sensor down → cloud fallback, retry after 5 min | | `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the bot reads the readings back to shade the recent charts between each 5 minutes' lowest and highest, for the days it was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from the bot's own readings | | `AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | -| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne` | +| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne`. With `WEATHER_MCP_URL`, the service's station's zone wins once read (and is kept for a start while the service is down); `TZ` only until it has ever been read | | `PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | | `POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | | `POLLEN_DISTRICT` | `Central` | East Gippsland, Mallee, North Central, North East, Northern Country, South West, West and South Gippsland, Wimmera. Case-insensitive; unknown → warning | diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 6e3fc419..30f70b9e 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -593,7 +593,12 @@ Each step ships on its own, with the tests and evals green and the bot working t gauges, period buttons and 🔄 replays, charts drawn ahead and preloads call the same tools. Alert delivery (`AlertDelivery`) reads `ecobot://alerts?since=`, woken by the listen's `ResourceUpdated` for `ecobot://alerts` and by each new connection (nothing is replayed), resuming from the id kept in `bot_state.json` as before; the 🔄 under an alert - finds its event with the template (`since` the id before it, `expired=true`). A question's call waits up to 5 seconds while the + finds its event with the template (`since` the id before it, `expired=true`). Each read is checked against the log's identity, so + the service back on another `alerts.sqlite` while the bot runs (removed, moved, redeployed) is noticed at once: delivery goes on in + the new log with its events from after the old one was last read, with a warning. The station's time zone is the bot's whenever + it is read: one read after the start (the service not up within 30 seconds) moves the bot's settings, the charts, the alert + delivery and the irrigation check (its wait for the check time timed again) into it; it is kept in `bot_state.json` + (`station_zone`), and a start while the service can't be reached runs in the zone last read, `TZ` only before any. A question's call waits up to 5 seconds while the client is being built again, a background one not at all; a question while the service can't be reached is answered that it can't (`bot.SERVICE_DOWN`), without the model. The bot's `warm_up` is its charts drawn ahead, every 5 minutes, quietly nothing while the service is away; the poke of the sources is gone (there are none). Irrigation stays in the bot until 5b: its daily check reads the diff --git a/ecobot.py b/ecobot.py index c1c4d7c2..badeb393 100644 --- a/ecobot.py +++ b/ecobot.py @@ -15,6 +15,7 @@ import dataclasses import logging import signal +from zoneinfo import ZoneInfo from lib.config import Config @@ -53,29 +54,68 @@ def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Core | None, - weather: RemoteWeather | None = None) -> tuple[list[str], AlertRules | None]: + weather: RemoteWeather | None = None) -> tuple[list[str], AlertRules | None, list]: """In-process (`core`): hook up the service's alert rules over every source that started (core.start_alerts: they append to the alert log); the weather rules start in warm_up, once the station has been read. Remote (`weather`): the rules are the service's, and its alert log is read over MCP. Either way the bot delivers from the log (AlertDelivery), and runs the irrigation controller's check and watchdog (sent by the bot itself until it is a server of its own, step 5b; remote, its rain and forecast are asked of the - service). Returns the alert types now running here, and the rules (None when remote).""" + service). Returns the alert types now running here, the rules (None when remote), and what keeps the time zone (the delivery, the + irrigation check: follow_zone).""" if core is not None: running = core.start_alerts(moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) feed, station, forecast = core.alert_log, bot.by_name.get("Ecowitt"), bot.by_name.get("Forecast") else: running, feed, station, forecast = [], weather.alerts, ServiceRain(weather), weather.forecast - tasks.start(AlertDelivery(feed, notify, bot.state, cfg.tz).run()) + delivery = AlertDelivery(feed, notify, bot.state, cfg.tz) + zoned: list = [delivery] + tasks.start(delivery.run()) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run - tasks.start(IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, station, forecast).run()) + monitor = IrrigationMonitor(bot.irrigation, bot.state, notify, cfg.tz, cfg.irrigation_check_hour, station, forecast) + zoned.append(monitor) + tasks.start(monitor.run()) tasks.start(every(VALVE_CHECK_SECONDS, bot.watchdog.check)) running += IrrigationMonitor.KINDS - return running, core.rules if core is not None else None + return running, core.rules if core is not None else None, zoned -async def connect(cfg: Config, stack: contextlib.AsyncExitStack) -> tuple[RemoteWeather, Config]: +def _zone(name: str | None): + try: + return ZoneInfo(name) if name else None + except Exception: + return None + + +def follow_zone(weather: RemoteWeather, bot: Bot, state: AlertState, zoned: list): + """Remote: the bot in the station's time zone whenever it is read (the first read, if the service couldn't be reached at start, or + another zone later): the bot's settings, the charts, the alerts' charts, and what start_alerts started (`zoned`: AlertDelivery, + IrrigationMonitor, whose wait for the check time is timed again). The zone is kept in bot_state.json, for a start while the service + can't be reached (connect).""" + def apply(zone): + if state.zone != str(zone): + state.zone = str(zone) + try: + state.save() + except Exception as e: + log.warning("Couldn't save the station's time zone (%s: %s)", type(e).__name__, e) + if str(zone) == str(bot.cfg.tz): + return + log.info("The weather station's time zone is %s: the bot runs in it from now on (it was %s)", zone, bot.cfg.tz) + bot.cfg = dataclasses.replace(bot.cfg, tz=zone) + bot.alert_charts.tz = zone + charts.configure(bot.cfg.dark_mode, zone) + for keeper in zoned: + keeper.tz = zone + weather.on_zone = apply + if weather.station_tz is not None: # (read before this was hooked up) + apply(weather.station_tz) + + +async def connect(cfg: Config, stack: contextlib.AsyncExitStack, state: AlertState) -> tuple[RemoteWeather, Config]: """The bot as the service's client (WEATHER_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to - STARTUP_WAIT seconds; the settings in the station's time zone once it has been read (else TZ's, with a warning).""" - weather = RemoteWeather(cfg.weather_mcp_url, cfg.weather_mcp_token or None, cfg.tz) + STARTUP_WAIT seconds; the settings in the station's time zone once it has been read, else in the one last read (kept in + bot_state.json), else in TZ's, with a warning. Read later, it is followed then (follow_zone).""" + kept = _zone(state.zone) + weather = RemoteWeather(cfg.weather_mcp_url, cfg.weather_mcp_token or None, kept or cfg.tz) supervisor = asyncio.create_task(weather.run()) async def stop(): @@ -86,10 +126,10 @@ async def stop(): try: await asyncio.wait_for(weather.listening.wait(), STARTUP_WAIT) except TimeoutError: - log.warning("The weather service at %s isn't reachable yet: questions are told so until it is (the time zone is TZ's, %s)", - cfg.weather_mcp_url, cfg.tz) - if weather.station_tz is not None and str(weather.station_tz) != str(cfg.tz): - cfg = dataclasses.replace(cfg, tz=weather.station_tz) + log.warning("The weather service at %s isn't reachable yet: questions are told so until it is (the time zone is %s, %s, " + "until its station is read)", cfg.weather_mcp_url, "the station's last read" if kept else "TZ's", weather.tz) + if str(weather.tz) != str(cfg.tz): + cfg = dataclasses.replace(cfg, tz=weather.tz) return weather, cfg @@ -131,10 +171,11 @@ async def main(): .build()) handshake = asyncio.create_task(app.initialize()) # Telegram is asked who the bot is while the sources start weather = None # (WEATHER_MCP_URL: the service, reached over MCP) + state = AlertState(cfg.state_path) try: if cfg.weather_mcp_url: # a client of the service: no sources of its own sources = [] - weather, cfg = await connect(cfg, stack) + weather, cfg = await connect(cfg, stack, state) else: sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on except BaseException: @@ -151,7 +192,6 @@ async def main(): stack.push_async_callback(safely, client.close) else: log.warning("OPENROUTER_API_KEY is not set: running without the model, so answers are limited") - state = AlertState(cfg.state_path) if cfg.admin_only and not cfg.admin_chat_ids and not any(chat < 0 for chat in state.chats): log.warning("Admin only is on but no group is known yet and ADMIN_CHAT_IDS is empty, so nobody can use the bot: " "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") @@ -194,7 +234,9 @@ async def main(): log.info("Weather service: %s (%s)", cfg.weather_mcp_url, ", ".join(sorted(weather.names)) or "not reached yet") notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's await bot.publish_commands(app.bot) # the / menu - running, rules = start_alerts(cfg, bot, notify, tasks, core, weather) + running, rules, zoned = start_alerts(cfg, bot, notify, tasks, core, weather) + if weather is not None: + follow_zone(weather, bot, state, zoned) if core is not None: core.start_warmers() # keeping warm: everything questions need, refreshed before they arrive tasks.start(warm_up(bot, core, running, tasks, app.bot)) diff --git a/lib/alerts/irrigation.py b/lib/alerts/irrigation.py index 1ca9b815..5ec7a818 100644 --- a/lib/alerts/irrigation.py +++ b/lib/alerts/irrigation.py @@ -36,9 +36,33 @@ def __init__(self, device, state, notify, tz, hour: int = 18, station=None, fore """station: the Ecowitt source (its recent() gives the measured rain), or, with the weather service remote, what asks it for the measured rain (lib/weather.ServiceRain: rain_mm()); forecast: the Forecast source, or the forecast read from the service (lib/weather.ServiceForecast: read again at each check, the one last read standing when it can't be). Either may be None.""" + self._rezoned = asyncio.Event() self.device, self.state, self.notify, self.tz, self.hour = device, state, notify, tz, hour self.station, self.forecast = station, forecast + @property + def tz(self): + return self._tz + + @tz.setter + def tz(self, zone): + """The station's zone; another one (the remote service's station read late) wakes the wait for the check time, timed again in it.""" + self._tz = zone + self._rezoned.set() + + async def _sleep(self, seconds: float): + """Until the check time (`seconds`), or until the zone changes.""" + self._rezoned.clear() + sleeper, woken = asyncio.ensure_future(asyncio.sleep(seconds)), asyncio.ensure_future(self._rezoned.wait()) + try: + await asyncio.wait((sleeper, woken), return_when=asyncio.FIRST_COMPLETED) + slept = sleeper.done() + finally: + for task in (sleeper, woken): + task.cancel() + if slept: + sleeper.result() # (its own failure or cancellation, raised here) + def _memory(self) -> dict: return self.state.monitor.setdefault("irrigation_monitor", {}) @@ -61,7 +85,7 @@ async def run(self): await asyncio.sleep(min(RETRY_SECONDS, self.seconds_until_next(now))) continue now = now_local(self.tz) - await asyncio.sleep(self.seconds_until_next(now)) + await self._sleep(self.seconds_until_next(now)) async def check(self, now: datetime | None = None): """One check: the battery, then the rain. Raises when the controller can't be reached (nothing is recorded then).""" diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 8b96f100..8c3a50ae 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -15,7 +15,7 @@ import logging import time from collections.abc import Awaitable, Callable, Collection -from datetime import timedelta +from datetime import datetime, timedelta from telegram.error import BadRequest, ChatMigrated, Forbidden, NetworkError, RetryAfter, TelegramError, TimedOut @@ -32,6 +32,14 @@ FLOOD_WAIT_MAX = 60 # Telegram's flood limit asks to wait: a longer wait is not waited out (that chat misses the alert) +def _epoch(iso: str | None) -> float: + """An event's time (ISO, with its offset) as an epoch; 0 when it has none.""" + try: + return datetime.fromisoformat(iso).timestamp() if iso else 0.0 + except ValueError: + return 0.0 + + def _flood_wait(e: RetryAfter) -> float: """The seconds Telegram asks to wait (python-telegram-bot gives a number, or a timedelta once PTB_TIMEDELTA is set).""" wait = e.retry_after @@ -50,12 +58,15 @@ def __init__(self, path): self.charts: dict[str, str] = data.get("charts", {}) # the question behind each chart sent, for its period buttons self.read: int | None = data.get("alerts_read") # the id of the last alert in the log the bot handled (AlertDelivery) self.read_log: str | None = data.get("alerts_log") # ... and that log's identity (AlertLog.identity): ids start again in a new one + self.zone: str | None = data.get("station_zone") # the remote service's station's time zone, last read (ecobot.py: a start + # while the service can't be reached runs in it, not in TZ's) def save(self): """Written in full to a new file that then replaces the old one, on disk first, so a crash leaves one or the other whole.""" write(self.path, {"chats": {str(k): v for k, v in self.chats.items()}, "monitor": self.monitor, "charts": self.charts, **({"alerts_read": self.read} if self.read is not None else {}), - **({"alerts_log": self.read_log} if self.read_log is not None else {})}) + **({"alerts_log": self.read_log} if self.read_log is not None else {}), + **({"station_zone": self.zone} if self.zone is not None else {})}) def add_chat(self, chat_id: int, title: str): """A message from this chat (or the bot added to it): known from now on, and back if it was gone.""" @@ -257,13 +268,16 @@ class AlertDelivery: restart resumes after it; the events that expired meanwhile are skipped (the morning's rain is not news by the afternoon). With no id kept (the first start) it begins after the newest event: what came before is not news either. So does a start on another log than the one the id is from (alerts.sqlite removed or replaced: its ids start again at 1, and waiting for them to pass the old id would send - nothing for as long), noticed by the log's identity kept with the id, or by the id being past the log's newest.""" + nothing for as long), noticed by the log's identity kept with the id, or by the id being past the log's newest. With the service remote + the log can also be replaced while the bot runs (the service back on another alerts.sqlite): that is looked for on every pass, and + delivery goes on in the new log with what came since the old one was last read (_switched).""" - def __init__(self, log, notify: "Notifier", state: AlertState, tz): + def __init__(self, log, notify: "Notifier", state: AlertState, tz, now: Callable[[], float] = time.time): """log: the alert log in this process (lib/alert_log.py), or the remote service's read over MCP (lib/weather.RemoteAlerts, whose - reads are coroutines: it is looked at when `run` starts).""" - self.log, self.notify, self.state, self.tz = log, notify, state, tz + reads are coroutines: it is looked at when `run` starts). now: the epoch clock (the events' times are compared with it).""" + self.log, self.notify, self.state, self.tz, self.now = log, notify, state, tz, now self.begun = False + self.seen_at: float | None = None # when the log was last read through (a pass of deliver_new began): see _switched if not getattr(log, "remote", False): self._begin(self.log.last_id()) @@ -276,14 +290,30 @@ def _begin(self, newest: int): self.begun = True if self.state.read is None: self._handled(newest) - elif (self.state.read_log not in (None, self.log.identity)) or self.state.read > newest: - logging.getLogger(__name__).warning( # (`log` here is the alert log) - "Alerts: the alert log is not the one the last alert delivered (%s) is from; starting after its newest (%s)", - self.state.read, newest) + elif self._other_log(newest): + log.warning("Alerts: the alert log is not the one the last alert delivered (%s) is from; starting after its newest (%s)", + self.state.read, newest) self._handled(newest) elif self.state.read_log is None: # (kept before the log had an identity: this one) self._handled(self.state.read) + def _other_log(self, newest: int) -> bool: + """Is the log read now another than the one the last id handled is from (its identity, or its newest id behind that id)?""" + return self.state.read is not None and (self.state.read_log not in (None, self.log.identity) or self.state.read > newest) + + async def _switched(self, newest: int): + """The log was replaced while the bot runs (remote: the service came back on another alerts.sqlite, deleted, moved or + redeployed; its ids start again at 1). Delivery goes on in the new log after the events from before the bot last read the old + one through (`seen_at`): the new log began after that, so those that came since are news, and they are sent; none known (the + first pass), after its newest, as at a start.""" + start = newest + if self.seen_at is not None: + fresh = [e for e in await value(self.log.since(0)) if _epoch(e.get("time")) >= self.seen_at] + start = fresh[0]["id"] - 1 if fresh else newest + log.warning("Alerts: the service's alert log is another than the one the last alert delivered (%s) is from; " + "going on in it after %s", self.state.read, start) + self._handled(start) + @property def last(self) -> int: return self.state.read or 0 @@ -312,10 +342,19 @@ async def run(self): await asyncio.sleep(self.RETRY_SECONDS) async def deliver_new(self) -> int: - """Send each unexpired event after the last handled, oldest first; returns how many were sent.""" - newest = await value(self.log.last_id()) + """Send each unexpired event after the last handled, oldest first; returns how many were sent. A log replaced since the last + pass (its identity another) is noticed here, while the bot runs, not only when it starts (_switched).""" + started = self.now() + while True: + newest = await value(self.log.last_id()) + if self._other_log(newest): + await self._switched(newest) + identity = self.log.identity + events = await value(self.log.since(self.last)) + if self.log.identity == identity: # (else replaced again between the reads: looked at once more) + break sent = 0 - for event in await value(self.log.since(self.last)): + for event in events: try: await self.deliver(event) sent += 1 @@ -324,6 +363,7 @@ async def deliver_new(self) -> int: self._handled(event["id"]) if newest > self.last: # (only expired events after the last handled: skipped) self._handled(newest) + self.seen_at = started return sent async def deliver(self, event: dict) -> int: diff --git a/lib/weather.py b/lib/weather.py index 6309bee6..1c87b294 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -224,6 +224,7 @@ def __init__(self, target, token: str | None = None, tz=None): self.alerts = RemoteAlerts(self) self.forecast = ServiceForecast(self) self.listening = asyncio.Event() # the first connection's listen is up, its tools and station read + self.on_zone = None # on_zone(zone): the station's time zone, called when it is first read and when it changes (ecobot.py) self._background: set[asyncio.Task] = set() def __iter__(self): # (the tools, as the service lists them now: lib/model_tools.py follows the list) @@ -285,9 +286,12 @@ async def _read_station(self): self.station, self._catalogue = station, None if zone := station.get("time_zone"): try: - self.station_tz = ZoneInfo(zone) + read = ZoneInfo(zone) except Exception: # (an offset only: TZ stands) - pass + return + first_or_new, self.station_tz = str(read) != str(self.station_tz), read + if first_or_new and self.on_zone: + self.on_zone(read) @property def tz(self): diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py index 0bfacb94..f3284c2e 100644 --- a/tests/test_bot_remote.py +++ b/tests/test_bot_remote.py @@ -243,6 +243,57 @@ async def test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_ assert texts() == ["first", "missed", "after"] and state.read == 4 # each once, the expired one skipped +async def test_the_service_back_on_a_fresh_alert_log_while_the_bot_runs_has_its_new_alerts_delivered(tmp_path, caplog): + """The service stops and comes back on a new alerts.sqlite (deleted, moved, redeployed: its ids start again at 1) while the bot runs: + delivery goes on in the new log with what came after the old one was last read (one logged while it was down included), not after + the old last id (3, which the new ids would take weeks to pass). An event of the new log from before then is not news.""" + port = free_port() + path = tmp_path / "service" / "alerts.sqlite" + path.parent.mkdir() + old = AlertLog(path, TZ) + remote = RemoteWeather(f"http://127.0.0.1:{port}/mcp", TOKEN, TZ) + state = AlertState(tmp_path / "bot_state.json") + state.add_chat(1, "private") + telegram = Telegram() + supervisor = asyncio.create_task(remote.run()) + delivery = asyncio.create_task(AlertDelivery(remote.alerts, Notifier(telegram, state), state, TZ).run()) + texts = lambda: [text for _, text in telegram.sent] + tasks = [delivery, supervisor] + try: + first = EcobotServer(Context(tz=TZ), old) + tasks.append(asyncio.create_task(first.watch_alerts())) + async with Serving(http_app(first, tokens={"bot": TOKEN}), port): + await until(lambda: state.read is not None and first.listen._streams, what="the listen") + for text in ("one", "two", "three"): + old.append("rain", text, "Rain", expires=time.time() + 3600) + await until(lambda: texts() == ["one", "two", "three"] and state.read == 3, what="the old log's alerts") + old_identity = old.identity + old.close() + for leftover in path.parent.iterdir(): # (alerts.sqlite and its -wal, -shm) + leftover.unlink() + new = AlertLog(path, TZ) + assert new.identity != old_identity + new.append("uv", "old news", "UV", expires=time.time() + 3600, time=time.time() - 3600) # (from before the bot last read) + new.append("gusts", "while down", "Gusts", expires=time.time() + 3600) + second = EcobotServer(Context(tz=TZ), new) + tasks.append(asyncio.create_task(second.watch_alerts())) + async with Serving(http_app(second, tokens={"bot": TOKEN}), port): + await until(lambda: texts()[3:] == ["while down"], what="the new log's alert logged while it was down") + await until(lambda: second.listen._streams, what="the listen again") + new.append("temps", "after", "Temperatures", expires=time.time() + 3600) + await until(lambda: texts()[3:] == ["while down", "after"], what="the new log's next alert") + await asyncio.sleep(0.3) + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await remote.close() + assert texts() == ["one", "two", "three", "while down", "after"] + assert (state.read, state.read_log) == (3, new.identity) and AlertState(state.path).read_log == new.identity + assert "is another than the one the last alert delivered (3) is from" in caplog.text + new.close() + + async def test_with_the_service_down_the_bot_says_so_and_carries_on(alert_state, caplog): remote = RemoteWeather(f"http://127.0.0.1:{free_port()}/mcp", TOKEN, TZ) # (nothing listens there) supervisor = asyncio.create_task(remote.run()) @@ -315,6 +366,105 @@ async def alert(): assert drawn == [app.bot] +async def test_a_start_while_the_service_cant_be_reached_follows_the_station_s_zone_once_read_and_keeps_it(tmp_path, monkeypatch, caplog): + """ecobot.main() with WEATHER_MCP_URL and the service not up within STARTUP_WAIT starts in TZ's zone (UTC here, as a container's); once + the service is reached, its station's zone (Melbourne) is the bot's, the charts', the alert delivery's and the irrigation check's, + and it is kept in bot_state.json: the next start with the service down runs in it, not in UTC.""" + import os + import signal + from zoneinfo import ZoneInfo + import ecobot + from lib import charts + from tests.fakes import config + from tests.test_startup import FakeApp, FakeBuilder + caplog.set_level("INFO") + utc = ZoneInfo("Etc/UTC") + port = free_port() + cfg = config(tmp_path, tz=utc, weather_mcp_url=f"http://127.0.0.1:{port}/mcp", weather_mcp_token=TOKEN, ecowitt_api_key="", + ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") + (tmp_path / "bot").mkdir() + monkeypatch.setattr(ecobot, "STARTUP_WAIT", 0.3) + monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) + monkeypatch.setattr(ecobot.Config, "from_env", classmethod(lambda cls: cfg)) + monkeypatch.setattr(ecobot, "start_sources", lambda *a: pytest.fail("no sources when remote")) + monkeypatch.setattr(charts, "ZONE", charts.ZONE) # (put back after) + made = {} + + class Kept(ecobot.Bot): + def __init__(self, *a, **k): + super().__init__(*a, **k) + made["bot"] = self + + class Delivery(ecobot.AlertDelivery): + def __init__(self, *a, **k): + super().__init__(*a, **k) + made["delivery"] = self + monkeypatch.setattr(ecobot, "Bot", Kept) + monkeypatch.setattr(ecobot, "AlertDelivery", Delivery) + + async def until_then_stop(check, what): + try: + await until(check, what=what) + finally: + os.kill(os.getpid(), signal.SIGTERM) + + alerts = AlertLog(tmp_path / "alerts.sqlite", TZ) + server = EcobotServer(Context(tz=TZ), alerts) # (its station: Australia/Melbourne) + try: + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(FakeApp()))) + bot_up = lambda: "delivery" in made and made["bot"].cfg.tz is not None + + async def serve_late(): + await until(bot_up, what="the bot started without the service") + assert str(made["bot"].cfg.tz) == "Etc/UTC" and str(made["delivery"].tz) == "Etc/UTC" # (TZ's, while unread) + async with Serving(http_app(server, tokens={"bot": TOKEN}), port): + await until_then_stop(lambda: str(made["bot"].cfg.tz) == "Australia/Melbourne", "the station's zone") + late = asyncio.create_task(serve_late()) + await ecobot.main() + await late + bot, delivery = made["bot"], made["delivery"] + assert str(bot.cfg.tz) == str(delivery.tz) == str(bot.alert_charts.tz) == str(charts.ZONE) == "Australia/Melbourne" + assert json.loads(cfg.state_path.read_text())["station_zone"] == "Australia/Melbourne" + assert "isn't reachable yet" in caplog.text and "TZ's, Etc/UTC" in caplog.text + + made.clear() # the next start, the service down: the zone last read, not UTC + caplog.clear() + monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(FakeApp()))) + stopper = asyncio.create_task(until_then_stop(bot_up, "the bot to start again")) + await ecobot.main() + await stopper + assert str(made["bot"].cfg.tz) == str(made["delivery"].tz) == str(charts.ZONE) == "Australia/Melbourne" + assert "the station's last read, Australia/Melbourne" in caplog.text + finally: + alerts.close() + + +async def test_the_irrigation_check_is_timed_again_in_a_zone_read_later(tmp_path, monkeypatch): + """The irrigation check's wait for 18:00 is cut short when the station's zone arrives, and timed again in it.""" + from datetime import datetime + from zoneinfo import ZoneInfo + from lib.alerts import irrigation as monitor_module + from lib.alerts.irrigation import IrrigationMonitor + utc = ZoneInfo("Etc/UTC") + monitor = IrrigationMonitor(None, NS(monitor={"irrigation_monitor": {}}), None, utc, 18) + waits = [] + + def now_local(tz): + return datetime(2026, 11, 10, 6, 0) if str(tz) == "Etc/UTC" else datetime(2026, 11, 10, 17, 0) # (06:00 UTC: 17:00 there) + monkeypatch.setattr(monitor_module, "now_local", now_local) + timed = monitor.seconds_until_next + monitor.seconds_until_next = lambda now: waits.append(timed(now)) or waits[-1] # (the waits themselves are real) + task = asyncio.create_task(monitor.run()) + try: + await until(lambda: waits, what="the first wait") + monitor.tz = TZ + await until(lambda: len(waits) == 2, what="the wait timed again") + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert waits == [12 * 3600, 3600] # 12 hours to 18:00 UTC; then the hour to 18:00 in Melbourne + + def test_a_client_of_the_service_needs_no_source_settings(monkeypatch, tmp_path): from lib.config import Config monkeypatch.setenv("DATA_DIR", str(tmp_path)) From 59763878c5ce4d88534189fab26a3bd3e5b95ce7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:14:14 +0000 Subject: [PATCH 066/125] Step 5a minor fixes: one service per data folder (service.lock), no token text in the log, IPv6 bind with tokens, quieter MCP client log - Core.open holds DATA_DIR/service.lock, so the in-process bot and python -m ecobot_service can't both fetch and write alerts on one folder; the docs switch the bot to a client first - MCP_TOKENS entries that don't parse are logged by position only - issuer_url brackets an IPv6 bind host - httpx2 at WARNING; the bridge's reconnect warning names the real error inside the exception group Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 11 +++++++---- compose.yaml | 4 ++-- ecobot.py | 1 + ecobot_service/__main__.py | 3 ++- ecobot_service/bridge.py | 10 +++++++++- ecobot_service/core.py | 18 ++++++++++++++++++ lib/config.py | 11 ++++++----- tests/test_mcp_server.py | 17 ++++++++++++++++- 8 files changed, 61 insertions(+), 14 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index c83e3479..2a9e24a0 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -36,8 +36,9 @@ MCP_TOKENS=me:$(openssl rand -hex 16) python -m ecobot_service # http://127 python -m ecobot_service.bridge # the same on stdio (WEATHER_MCP_URL, WEATHER_MCP_TOKEN), for a desktop client sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 ``` -Don't run it beside a bot that runs the service itself (`WEATHER_MCP_URL` unset) on the same data folder: both would fetch twice and write -each alert twice; make the bot its client (below). A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with +Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside +a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set +`WEATHER_MCP_URL` and restart the bot, then start the service; the bot waits for it and connects when it is up. A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with `WEATHER_MCP_TOKEN` in its environment, e.g. `claude mcp add ecobot -e WEATHER_MCP_TOKEN=... -- python -m ecobot_service.bridge` from the clone. To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. @@ -61,8 +62,10 @@ set -a; . <(sudo cat /etc/ecobot.env); set +a MCP_TOKENS=bot:$TOKEN python -m ecobot_service & # the service, with the sources' settings WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN=$TOKEN python ecobot.py # the bot, its client ``` -In Docker (compose.yaml): start `ecobot-service` (its profile), add `ecobot-service` to its `MCP_ALLOWED_HOSTS` and set the bot's -`WEATHER_MCP_URL=http://ecobot-service:8765/mcp`. Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a +In Docker (compose.yaml): in /etc/ecobot.env set `MCP_TOKENS=bot:`, `WEATHER_MCP_URL=http://ecobot-service:8765/mcp`, +`WEATHER_MCP_TOKEN=` and `MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service`; then recreate the bot first +(`sudo docker compose up -d --force-recreate ecobot`, which frees the data folder) and start the service +(`sudo docker compose --profile service up -d ecobot-service`). Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through the listen, the irrigation check's inputs; under uvicorn: a dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client). diff --git a/compose.yaml b/compose.yaml index 6fa48d51..af36702d 100644 --- a/compose.yaml +++ b/compose.yaml @@ -23,8 +23,8 @@ services: # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, # at http://127.0.0.1:8765/mcp on the host (put TLS in front of it, e.g. Caddy, to reach it from elsewhere). Off unless asked for # (`sudo docker compose --profile service up -d ecobot-service`). Run it only with the bot as its client (WEATHER_MCP_URL= - # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_ALLOWED_HOSTS): a bot that runs - # the sources and the alert rules itself, on the same data folder, would fetch twice and write each alert twice. It needs MCP_TOKENS + # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_ALLOWED_HOSTS), recreating the + # bot first: one process runs the service per data folder (service.lock), so it won't start beside a bot running it. It needs MCP_TOKENS # (name:token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. # MCP_ALLOWED_HOSTS: add the name a proxy or a LAN client uses for it. ecobot-service: diff --git a/ecobot.py b/ecobot.py index badeb393..846fe45f 100644 --- a/ecobot.py +++ b/ecobot.py @@ -47,6 +47,7 @@ _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) # DEBUG and INFO to stdout, WARN and ERROR to stderr logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) logging.getLogger("httpx").setLevel(logging.WARNING) +logging.getLogger("httpx2").setLevel(logging.WARNING) # the MCP client's: a line per request otherwise logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING) # "Application started" etc. log = logging.getLogger("ecobot") diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py index b57e61b3..fee81158 100644 --- a/ecobot_service/__main__.py +++ b/ecobot_service/__main__.py @@ -73,7 +73,7 @@ async def main(): for source in sources: stack.push_async_callback(source.warmer.stop) server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) - app = http_app(server, tokens=cfg.mcp_tokens, allowed_hosts=cfg.mcp_allowed_hosts, issuer_url=f"http://{host}:{port}") + app = http_app(server, tokens=cfg.mcp_tokens, allowed_hosts=cfg.mcp_allowed_hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") core.log_startup() running = core.start_alerts() core.start_warmers() @@ -107,6 +107,7 @@ def run(): _format = LogFormat("%(levelname)s %(message)s", priority=on_journal()) logging.basicConfig(level=logging.INFO, handlers=stream_handlers(_format)) logging.getLogger("httpx").setLevel(logging.WARNING) + logging.getLogger("httpx2").setLevel(logging.WARNING) with contextlib.suppress(KeyboardInterrupt): asyncio.run(main()) diff --git a/ecobot_service/bridge.py b/ecobot_service/bridge.py index e3516c32..228c69a2 100644 --- a/ecobot_service/bridge.py +++ b/ecobot_service/bridge.py @@ -60,6 +60,13 @@ async def connect(): return connect() +def _leaf(e: BaseException) -> BaseException: + """The first real error inside an exception group (a refused connection, a 401, a 421), not the group's "unhandled errors".""" + while isinstance(e, BaseExceptionGroup) and e.exceptions: + e = e.exceptions[0] + return e + + class Upstream: """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" @@ -100,7 +107,8 @@ async def run(self): raise if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same - log.warning("Bridge: the service at %s isn't reachable (%s: %s); trying again", self.target, type(e).__name__, e) + cause = _leaf(e) + log.warning("Bridge: the service at %s isn't reachable (%s: %s); trying again", self.target, type(cause).__name__, cause) finally: self.client = None self.connected.clear() diff --git a/ecobot_service/core.py b/ecobot_service/core.py index 15a73445..a08138b2 100644 --- a/ecobot_service/core.py +++ b/ecobot_service/core.py @@ -148,6 +148,23 @@ def report(self) -> dict: # ---------- the service ---------- +def hold_data_folder(cfg: Config, stack): + """One service per data folder: the bot running it in-process and `python -m ecobot_service` on the same folder would both fetch + and both write each alert (sent twice). The lock is the kernel's, so it goes with the process, however that ends.""" + import fcntl + path = cfg.state_path.parent / "service.lock" + path.parent.mkdir(parents=True, exist_ok=True) + held = open(path, "w") + try: + fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + held.close() + raise SystemExit(f"Another process already runs the weather service on {path.parent} (the bot without WEATHER_MCP_URL, or " + f"python -m ecobot_service). Stop it first, or set WEATHER_MCP_URL to use it.") + stack.callback(held.close) + + + @dataclass class Core: """The service as it runs: its settings, sources, alert log, tools and their Context, the alert rules once started.""" @@ -168,6 +185,7 @@ def by_name(self) -> dict[str, Source]: @classmethod async def open(cls, cfg: Config, sources: list[Source], stack, tasks: Tasks) -> "Core": """The alert log (closed by `stack`) and the ten tools over the sources that started.""" + hold_data_folder(cfg, stack) by_name = {s.name: s for s in sources} eco, air = by_name.get("Ecowitt"), by_name.get("AirGradient") composer = Composer(eco, air) if eco and air else None # charts and comparisons across the two sources diff --git a/lib/config.py b/lib/config.py index e7793f01..f4c02833 100644 --- a/lib/config.py +++ b/lib/config.py @@ -67,14 +67,15 @@ def _required(value: str, default: str, name: str) -> str: def _tokens(value: str, default: tuple, name: str) -> tuple[tuple[str, str], ...]: """"bot:s3cret, phone:t0ken" -> (("bot", "s3cret"), ("phone", "t0ken")): one token per client, each named, so one can be revoked - alone. An entry without a name or a token is ignored (and logged by its name, never its token); a name given twice keeps the last.""" + alone. An entry without a name or a token is ignored and logged by its place in the list, never its text (an entry without a colon + may be a bare token); a name given twice keeps the last.""" found, bad = {}, [] - for part in filter(None, (p.strip() for p in value.split(","))): - who, _, token = part.partition(":") - if who.strip() and token.strip(): + for n, part in enumerate(filter(None, (p.strip() for p in value.split(","))), 1): + who, colon, token = part.partition(":") + if colon and who.strip() and token.strip(): found[who.strip()] = token.strip() else: - bad.append(who.strip() if token.strip() == "" and who.strip() else "(no name)") + bad.append(f"entry {n}") if bad: log.warning("%s: ignoring %s (each entry is name:token)", name, ", ".join(bad)) return tuple(found.items()) or default diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 5b97833e..e64f9a38 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -315,7 +315,7 @@ def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, monkeypatch.setenv("MCP_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") cfg = Config.from_env(bot=False) assert cfg.mcp_tokens == (("bot", "s3cret"), ("phone", "t0k:en")) - assert "MCP_TOKENS: ignoring broken, (no name)" in caplog.text and "s3cret" not in caplog.text and "nameless" not in caplog.text + assert "MCP_TOKENS: ignoring entry 3, entry 4" in caplog.text and "broken" not in caplog.text and "nameless" not in caplog.text assert cfg.mcp_bind == ("0.0.0.0", 9000) and cfg.mcp_allowed_hosts == ("weather.lan", "192.168.1.5:9000") for value, want in (("[::1]:8800", ("::1", 8800)), ("9001", ("127.0.0.1", 9001)), ("host:port", ("127.0.0.1", 8765)), ("h:70000", ("127.0.0.1", 8765))): @@ -332,3 +332,18 @@ async def test_the_bridge_refuses_a_request_while_the_service_cant_be_reached(mo async with Client(bridge.server) as client: with pytest.raises(MCPError, match="isn't reachable"): await client.call_tool("current", {}) + + +def test_one_service_per_data_folder(tmp_path): + """The bot running the service in-process and python -m ecobot_service on one folder would both fetch and both write each alert.""" + import contextlib + from types import SimpleNamespace + + from ecobot_service.core import hold_data_folder + cfg = SimpleNamespace(state_path=tmp_path / "bot_state.json") + with contextlib.ExitStack() as first: + hold_data_folder(cfg, first) + with contextlib.ExitStack() as second, pytest.raises(SystemExit, match="already runs the weather service"): + hold_data_folder(cfg, second) + with contextlib.ExitStack() as again: # free once the first has closed + hold_data_folder(cfg, again) From 6ada0ba47c3a341dd298ebcaebf9792ac28de854 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:27:38 +0000 Subject: [PATCH 067/125] ecobot-mcp.service: the weather service under systemd, beside the bot Same checkout, venv, sandbox and data folder as ecobot.service; User=ecobot shares the bot's dynamic user so neither takes the folder from the other. The bot's own secrets are unset for it. README: back up, make the bot a client, start the service, check the owner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 20 ++++++++++++ ecobot-mcp.service | 78 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 ecobot-mcp.service diff --git a/README.md b/README.md index 2fa60439..89eda52f 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,26 @@ journalctl -fu ecobot Warnings and errors alone: `journalctl -p warning -u ecobot`. +#### The weather service on its own (optional) + +Not needed: without it the bot runs everything itself, as before. `ecobot-mcp.service` runs the weather service as its own program +(`python -m ecobot_service`, an MCP server at `http://127.0.0.1:8765/mcp`) for other MCP clients, with the bot as one of them. It uses the +bot's data folder, so back that up first: `sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`. Then: + +1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`): + ``` + MCP_TOKENS=bot: + WEATHER_MCP_URL=http://127.0.0.1:8765/mcp + WEATHER_MCP_TOKEN= + ``` +2. Restart the bot, now the service's client (it waits for the service): `sudo systemctl restart ecobot` +3. Start the service: `sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable --now ecobot-mcp` +4. Check that both run as the same user and the folder's owner is unchanged (the three numbers match): + `systemctl show -p UID --value ecobot ecobot-mcp; stat -c %u /var/lib/private/ecobot` + +Logs: `journalctl -fu ecobot-mcp`. To go back: `sudo systemctl disable --now ecobot-mcp`, remove the three lines, `sudo systemctl restart ecobot`. +Only one process runs the service on the data folder: started beside a bot without `WEATHER_MCP_URL`, it stops, saying so in its log. + Then message `/report` to your Telegram bot. The service runs sandboxed as its own user, and keeps its data in `/var/lib/private/ecobot`. diff --git a/ecobot-mcp.service b/ecobot-mcp.service new file mode 100644 index 00000000..a125a37e --- /dev/null +++ b/ecobot-mcp.service @@ -0,0 +1,78 @@ +# The weather service on its own (python -m ecobot_service, docs/mcp-service.md step 5): the sources and their syncers, the alert rules +# and the MCP server at http://127.0.0.1:8765/mcp. Install it beside ecobot.service, from the same checkout and venv (see that file): +# sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload +# Only one process runs the service on a data folder (service.lock): before enabling this, make the bot its client (WEATHER_MCP_URL +# and WEATHER_MCP_TOKEN in /etc/ecobot.env, with the token in MCP_TOKENS) and restart it; otherwise this one stops at start, saying so. +# The data folder is the bot's own, /var/lib/private/ecobot (StateDirectory=ecobot): User=ecobot gives this unit the same dynamic user +# as ecobot.service, so the two share the folder's owner and neither takes it from the other when it starts. +# It reads /etc/ecobot.env as the bot does, less the bot's own secrets (UnsetEnvironment=). MCP_BIND defaults to 127.0.0.1:8765; to +# reach it from other machines set MCP_BIND=0.0.0.0:8765 (refused without MCP_TOKENS) and put TLS in front of it. +[Unit] +Description=ecobot weather service (MCP) +After=network-online.target +Wants=network-online.target +Before=ecobot.service + +[Service] +DynamicUser=yes +User=ecobot +Group=ecobot +WorkingDirectory=/opt/ecobot +EnvironmentFile=/etc/ecobot.env +UnsetEnvironment=TELEGRAM_BOT_TOKEN OPENROUTER_API_KEY WEATHER_MCP_TOKEN TUYA_CLIENT_ID TUYA_CLIENT_SECRET +Environment=PYTHONUNBUFFERED=1 +Environment=PYTHONPYCACHEPREFIX=/var/cache/ecobot/pycache +StateDirectory=ecobot +CacheDirectory=ecobot +ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_service +Restart=on-failure +RestartSec=10 +TimeoutStopSec=30 +StandardOutput=journal +StandardError=journal +SyslogIdentifier=ecobot-mcp + +# Filesystem isolation +ProtectSystem=strict +ProtectHome=yes +PrivateTmp=yes +PrivateDevices=yes +InaccessiblePaths=/boot /media /mnt +UMask=0077 + +# Privilege restrictions +AmbientCapabilities= +CapabilityBoundingSet= +LockPersonality=yes +MemoryDenyWriteExecute=yes +NoNewPrivileges=yes +RestrictRealtime=yes +RestrictSUIDSGID=yes +SystemCallArchitectures=native +SystemCallErrorNumber=EPERM +SystemCallFilter=@system-service + +# Kernel and system protection +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +ProtectClock=yes +ProtectHostname=yes + +# Process isolation +ProtectProc=invisible +RestrictNamespaces=yes + +# Network: HTTPS to the weather, air, pollen and forecast APIs and Home Assistant, and its own MCP port (AF_UNIX: the local name +# resolver; AF_NETLINK: listing the network interfaces, which finding the air sensor by its .local name needs) +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK + +# Resource limits +TasksMax=64 +MemoryAccounting=yes +MemoryHigh=300M +MemoryMax=450M + +[Install] +WantedBy=multi-user.target From 46f3dbf42b12a3b8fdbad527d1c0b38f20fefc5e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:36:31 +0000 Subject: [PATCH 068/125] Remove the stdio bridge; the bot's reconnecting client moves to lib/upstream.py Nothing here needs a stdio client: the bot and Claude Code connect over HTTP. Upstream (pinned protocol, discover, listen, backoff) is unchanged apart from its module and log prefix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 11 +- Dockerfile | 2 +- docs/configuration.md | 1 - docs/mcp-service.md | 17 ++- ecobot_service/__init__.py | 5 +- ecobot_service/bridge.py | 245 ------------------------------------- lib/upstream.py | 113 +++++++++++++++++ lib/weather.py | 4 +- tests/test_bot_remote.py | 4 +- tests/test_mcp_listen.py | 22 +--- tests/test_mcp_server.py | 34 +---- 11 files changed, 135 insertions(+), 323 deletions(-) delete mode 100644 ecobot_service/bridge.py create mode 100644 lib/upstream.py diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 2a9e24a0..9f3f7672 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -33,25 +33,24 @@ It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) les ``` set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them MCP_TOKENS=me:$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp -python -m ecobot_service.bridge # the same on stdio (WEATHER_MCP_URL, WEATHER_MCP_TOKEN), for a desktop client sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 ``` Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set -`WEATHER_MCP_URL` and restart the bot, then start the service; the bot waits for it and connects when it is up. A desktop client (Claude Desktop, Claude Code) starts the bridge as its command, with -`WEATHER_MCP_TOKEN` in its environment, e.g. `claude mcp add ecobot -e WEATHER_MCP_TOKEN=... -- python -m ecobot_service.bridge` from the clone. +`WEATHER_MCP_URL` and restart the bot, then start the service; the bot waits for it and connects when it is up. +Claude Code connects over HTTP: `claude mcp add --transport http ecobot http://127.0.0.1:8765/mcp --header "Authorization: Bearer "`. To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. Its tests: `tests/test_mcp_server.py` (the SDK's in-memory transport: every tool listed and answering as the ServiceTool does, each resource, -the alerts' template, the prompts, the publishing, the tokens, the bridge in-process) and `tests/test_mcp_listen.py` (the real app under uvicorn +the alerts' template, the prompts, the publishing, the tokens) and `tests/test_mcp_listen.py` (the real app under uvicorn on a free localhost port: a client that listens loses its listen when the service stops and reads what it missed when it is back; the -token and Host checks over HTTP; the bridge as a subprocess on stdio; `python -m ecobot_service` with the fake sources, a tool call through +token and Host checks over HTTP; `python -m ecobot_service` with the fake sources, a tool call through a proxy's Host name). ### The bot as the service's client With `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`, one of the service's `MCP_TOKENS`) set, the bot runs no sources, syncers or alert rules of its own and reaches the service over MCP (`lib/weather.RemoteWeather`, [docs/mcp-service.md](docs/mcp-service.md) 3.8): one client pinned -to protocol 2026-07-28, kept by one supervisor task (the bridge's `Upstream`), which discovers by hand for the instructions and listens to +to protocol 2026-07-28, kept by one supervisor task (`lib/upstream.Upstream`), which discovers by hand for the instructions and listens to `ecobot://alerts`, `ecobot://station` and `ecobot://forecast`; when the connection fails or the listen is lost it builds a new client after a backoff, listens again and reads the alerts after the last id it handled. Unset, the bot runs the service in-process as before (`lib/weather.LocalWeather`). Both are one interface, `lib/weather.py`, which everything the bot asks of the service goes through: diff --git a/Dockerfile b/Dockerfile index 17963879..3e58a0ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -36,7 +36,7 @@ ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 COPY .git* .git/ ARG COMMIT= RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi \ - && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot, ecobot_service.__main__, ecobot_service.bridge, lib.mcp_server" \ + && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot, ecobot_service.__main__, lib.upstream, lib.mcp_server" \ && rm -rf /tmp/build ENV DATA_DIR=/data USER 10001:10001 diff --git a/docs/configuration.md b/docs/configuration.md index 31708d62..02ab09cd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -90,7 +90,6 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | | `MCP_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | -The stdio bridge (`python -m ecobot_service.bridge`, for a desktop client) reads `WEATHER_MCP_URL` (default `http://127.0.0.1:8765/mcp`) and `WEATHER_MCP_TOKEN` (one of `MCP_TOKENS`' tokens). ### The bot as the service's client diff --git a/docs/mcp-service.md b/docs/mcp-service.md index 30f70b9e..cda9e460 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -385,9 +385,8 @@ Charts are data: the client draws them, or its model does from the numbers. server is the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built when asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by default it answers only `Host: 127.0.0.1` or `localhost`, and refuses the name a proxy or a LAN client uses. -- **Stdio, for a desktop client:** `python -m ecobot_service.bridge` is a thin bridge, an SDK client to the running service re-exposed - on stdio (tools, resources, prompts and the listen stream forwarded), with no syncers, no rules and no file of its own. A second - process on the readings file would duplicate the fetching and the alerts, and its in-memory bus would hear nothing. +- **No stdio:** clients connect over HTTP (Claude Code: `claude mcp add --transport http ...` with the bearer header). A stdio bridge + for clients that can only start a local command was built in step 5 and removed: nothing here needs it. - **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` (`name:token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://", resource_server_url=None)` (`issuer_url` is required but unused without an OAuth provider; no OAuth metadata is published). Bind to @@ -551,8 +550,7 @@ Each step ships on its own, with the tests and evals green and the bot working t - Tests: the rules' tests assert events appended (`tests/test_alerts.py`), the log and the delivery (`tests/test_alert_log.py`), the forecast baseline (`tests/test_forecast_alert.py`). 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the - transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file) with the - stdio bridge; the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the + transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file); the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). `ecobot.py`'s `warm_up()` is split: the first fetch, the archive, the backfill, the Home Assistant imports and the startup line go to the service; the bot keeps only its charts drawn ahead, as `summary` calls at background priority, failing quietly until the service has warmed. The bot's poke of the sources @@ -573,17 +571,16 @@ Each step ships on its own, with the tests and evals green and the bot working t (`start_sources`, `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch, the weather rules, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for `ecobot://health`), which `ecobot.py` now calls in-process, its behaviour unchanged; `__main__.py` runs it with the server under - uvicorn (`MCP_BIND`, refusing a non-loopback address without `MCP_TOKENS`); `bridge.py` is the stdio bridge, one supervised upstream - client pinned to 2026-07-28 that discovers by hand, listens and re-listens after a backoff. The image ships `ecobot_service/` and + uvicorn (`MCP_BIND`, refusing a non-loopback address without `MCP_TOKENS`); `lib/upstream.py` is the bot's one supervised + client, pinned to 2026-07-28, that discovers by hand, listens and re-listens after a backoff (a stdio bridge was built on it and later removed). The image ships `ecobot_service/` and `schemas/`; compose has `ecobot-service`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and - `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the bridge - on stdio, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs + `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs no Telegram token. - **The bot as a client (done).** `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`) set: the bot starts no sources, syncers or alert rules (`ecobot.connect`); unset: it runs the service in-process, unchanged. Both go through one interface, `lib/weather.py` (`LocalWeather` over lib/service and the sources; `RemoteWeather` over MCP): the tools as `Service` lists them (each `call(args, meta)` answering the tool's JSON), the sources there are (`names`), the catalogue, the instructions, the AirGradient link, the - alert feed and one alert by id, a resource, and whether it can be reached. `RemoteWeather` is 3.8's client: the bridge's `Upstream` + alert feed and one alert by id, a resource, and whether it can be reached. `RemoteWeather` is 3.8's client: `lib/upstream.Upstream` (pinned to 2026-07-28, `send_discover` and `adopt` for the instructions, one supervisor task that drops the client on a transport error or a lost or ended listen and builds another after a backoff, the 45-second read timeout), listening to the station, the alerts and the forecast; each connection reads the tool list and the station again (`ToolsListChanged` and the station's diff --git a/ecobot_service/__init__.py b/ecobot_service/__init__.py index 6df966ad..e1685e41 100644 --- a/ecobot_service/__init__.py +++ b/ecobot_service/__init__.py @@ -2,9 +2,6 @@ alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). - `python -m ecobot_service` (__main__.py): the service, Streamable HTTP at http://MCP_BIND/mcp; - - `python -m ecobot_service.bridge` (bridge.py): a stdio bridge to a running service, for a desktop client; - core.py: the service's startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and Home Assistant's imports), the one function the service and the bot (ecobot.py, while it runs everything - in-process) both call. - -Nothing is imported here, so the bridge starts without the sources' code.""" + in-process) both call.""" diff --git a/ecobot_service/bridge.py b/ecobot_service/bridge.py deleted file mode 100644 index 228c69a2..00000000 --- a/ecobot_service/bridge.py +++ /dev/null @@ -1,245 +0,0 @@ -"""python -m ecobot_service.bridge: the service on stdio, for a desktop client that starts its servers as commands (docs/mcp-service.md -3.8). It is a thin bridge: an SDK client of the running service (WEATHER_MCP_URL, default http://127.0.0.1:8765/mcp, with the bearer -token WEATHER_MCP_TOKEN), re-exposed as an MCP server on stdin and stdout: the tools, resources, resource templates and prompts are -forwarded as they are (a tool call's request _meta too), the server's instructions are the service's, and the service's listen stream -is forwarded to the client's listens. No sources, no rules, no file of its own: a second process on the readings file would fetch and -alert twice, and its in-memory bus would hear nothing. - -The upstream connection is supervised (Upstream): the protocol revision is pinned (2026-07-28, so a proxy's 502 during a restart -can't land it on the older revision, which can't listen) and discovered once by hand for the instructions; when the connection fails -or the listen is lost, the client is dropped and a new one built after a backoff, which listens again, and the bridge's own listeners -are told everything changed (there is no replay). A request while it is down is refused with an error that says so. - - python -m ecobot_service.bridge [--url URL] - -Logs go to stderr: stdout is the protocol.""" - -import argparse -import asyncio -import contextlib -import logging -import os -import sys - -import mcp_types as types -from mcp import Client -from mcp.server.lowlevel import Server -from mcp.server.subscriptions import (InMemorySubscriptionBus, ListenHandler, PromptsListChanged, ResourcesListChanged, ResourceUpdated, - ToolsListChanged) -from mcp.shared.exceptions import MCPError - -log = logging.getLogger("ecobot.bridge") - -URL_ENV, TOKEN_ENV = "WEATHER_MCP_URL", "WEATHER_MCP_TOKEN" -DEFAULT_URL = "http://127.0.0.1:8765/mcp" -VERSION = "2026-07-28" # the protocol revision pinned: the one that can listen -READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed -CONNECT_WAIT = 10.0 # how long a request waits for the service to be reached before it is refused -BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated -OWN_META = "io.modelcontextprotocol/" # the SDK's own _meta keys, stamped by each side itself: never forwarded - - -def _forwarded(meta) -> dict | None: - """A _meta as passed on: the SDK's own keys and the progress token left out (each side stamps its own).""" - out = {k: v for k, v in dict(meta or {}).items() if not k.startswith(OWN_META) and k not in ("progressToken", "progress_token")} - return out or None - - -def http_transport(url: str, token: str | None = None): - """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS.""" - import httpx2 - from mcp.client.streamable_http import streamable_http_client - from mcp.shared._httpx_utils import create_mcp_http_client - - @contextlib.asynccontextmanager - async def connect(): - headers = {"Authorization": f"Bearer {token}"} if token else None - async with create_mcp_http_client(headers=headers, timeout=httpx2.Timeout(30.0, read=READ_SECONDS)) as http: - async with streamable_http_client(url, http_client=http) as streams: - yield streams - return connect() - - -def _leaf(e: BaseException) -> BaseException: - """The first real error inside an exception group (a refused connection, a 401, a 421), not the group's "unhandled errors".""" - while isinstance(e, BaseExceptionGroup) and e.exceptions: - e = e.exceptions[0] - return e - - -class Upstream: - """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or - its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" - - def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None, resources=None): - """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is - acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. - resources: the URIs listened to, of those the service lists (None: every one).""" - self.target, self.token, self.resources = target, token, resources - self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening - self.client: Client | None = None - self.connected = asyncio.Event() - self.attempts = 0 - - def _client(self) -> Client: - server = http_transport(self.target, self.token) if isinstance(self.target, str) else self.target - return Client(server, mode=VERSION, cache=None) - - async def run(self): - """Keep a connection, until cancelled.""" - while True: - try: - async with self._client() as client: - raw = await client.session.send_discover(VERSION) - discovered = types.DiscoverResult.model_validate(raw) - client.session.adopt(discovered) - if self.on_discover: - await self.on_discover(discovered) - self.client, self.attempts = client, 0 - self.connected.set() - log.info("Bridge: connected to %s", self.target if isinstance(self.target, str) else "the service") - await self._listen(client) - log.warning("Bridge: the service ended the listen; connecting again") - except asyncio.CancelledError: - raise - except BaseException as e: # (a transport failure ends the whole client, as an exception group too) - if isinstance(e, (KeyboardInterrupt, SystemExit)): - raise - if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have - raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same - cause = _leaf(e) - log.warning("Bridge: the service at %s isn't reachable (%s: %s); trying again", self.target, type(cause).__name__, cause) - finally: - self.client = None - self.connected.clear() - await asyncio.sleep(BACKOFF[min(self.attempts, len(BACKOFF) - 1)]) - self.attempts += 1 - - async def _listen(self, client: Client): - """Listen to every resource the service lists and its lists' changes, passing each event on, until the stream ends.""" - uris = [r.uri for r in (await client.list_resources()).resources if self.resources is None or str(r.uri) in self.resources] - async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, - resource_subscriptions=uris) as sub: - if self.on_listening: - await self.on_listening() - async for event in sub: - if self.on_event: - await self.on_event(event) - - async def get(self) -> Client: - """The connected client; refused (MCPError) when the service can't be reached within CONNECT_WAIT.""" - if self.client is None: - try: - await asyncio.wait_for(self.connected.wait(), CONNECT_WAIT) - except TimeoutError: - pass - if self.client is None: - raise MCPError(types.INTERNAL_ERROR, f"The weather service isn't reachable ({self.target}): try again shortly.") - return self.client - - -class Bridge: - """The stdio server (`server`) forwarding to the service through `upstream`.""" - - def __init__(self, target=DEFAULT_URL, token: str | None = None): - self.bus = InMemorySubscriptionBus() - self.upstream = Upstream(target, token, on_event=self.bus.publish, on_discover=self._discovered, on_listening=self._listening) - self._first = True - self.server = Server("ecobot-bridge", title="Ecobot weather and air service (bridge)", - on_list_tools=self._list_tools, on_call_tool=self._call_tool, - on_list_resources=self._list_resources, on_list_resource_templates=self._list_templates, - on_read_resource=self._read_resource, on_list_prompts=self._list_prompts, on_get_prompt=self._get_prompt, - on_subscriptions_listen=ListenHandler(self.bus)) - - async def _discovered(self, discovered: types.DiscoverResult): - """A new connection: the service's instructions are the bridge's.""" - self.server.instructions = discovered.instructions - - async def _listening(self): - """Listening again: after the first time, every listener is told everything changed, since what happened while the link was - down is not replayed.""" - if self._first: - self._first = False - return - client = self.upstream.client - await self.bus.publish(ToolsListChanged()) - await self.bus.publish(PromptsListChanged()) - await self.bus.publish(ResourcesListChanged()) - if client is not None: - for r in (await client.list_resources()).resources: - await self.bus.publish(ResourceUpdated(str(r.uri))) - - async def _call(self, fn): - """fn(client) against the service: its error (MCPError) passed on as it is; a failed connection refused with one that says so.""" - client = await self.upstream.get() - try: - return await fn(client) - except MCPError: - raise - except Exception as e: - raise MCPError(types.INTERNAL_ERROR, f"The weather service didn't answer ({type(e).__name__}: {e}).") from e - - async def _list_tools(self, ctx, params) -> types.ListToolsResult: - r = await self._call(lambda c: c.list_tools()) - return types.ListToolsResult(tools=r.tools) - - async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.CallToolResult: - r = await self._call(lambda c: c.call_tool(params.name, params.arguments, meta=_forwarded(ctx.meta))) - return types.CallToolResult(content=r.content, structured_content=r.structured_content, is_error=r.is_error, - _meta=_forwarded(r.meta)) - - async def _list_resources(self, ctx, params) -> types.ListResourcesResult: - r = await self._call(lambda c: c.list_resources()) - return types.ListResourcesResult(resources=r.resources) - - async def _list_templates(self, ctx, params) -> types.ListResourceTemplatesResult: - r = await self._call(lambda c: c.list_resource_templates()) - return types.ListResourceTemplatesResult(resource_templates=r.resource_templates) - - async def _read_resource(self, ctx, params: types.ReadResourceRequestParams) -> types.ReadResourceResult: - r = await self._call(lambda c: c.read_resource(str(params.uri))) - return types.ReadResourceResult(contents=r.contents) - - async def _list_prompts(self, ctx, params) -> types.ListPromptsResult: - r = await self._call(lambda c: c.list_prompts()) - return types.ListPromptsResult(prompts=r.prompts) - - async def _get_prompt(self, ctx, params: types.GetPromptRequestParams) -> types.GetPromptResult: - r = await self._call(lambda c: c.get_prompt(params.name, params.arguments)) - return types.GetPromptResult(description=r.description, messages=r.messages) - - @contextlib.asynccontextmanager - async def running(self, wait: float = CONNECT_WAIT): - """The upstream supervisor running (the first connection waited for, up to `wait` seconds, so the instructions are there for the - client's first request), cancelled on leaving.""" - task = asyncio.create_task(self.upstream.run()) - try: - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(self.upstream.connected.wait(), wait) - yield self - finally: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - - -async def main(argv: list[str] | None = None): - from mcp.server.stdio import stdio_server - parser = argparse.ArgumentParser(prog="python -m ecobot_service.bridge", description=__doc__.split("\n\n")[0]) - parser.add_argument("--url", default=os.getenv(URL_ENV) or DEFAULT_URL, help=f"the service's MCP endpoint (${URL_ENV}, default {DEFAULT_URL})") - args = parser.parse_args(argv) - bridge = Bridge(args.url, os.getenv(TOKEN_ENV) or None) - async with bridge.running(): - async with stdio_server() as (read, write): - await bridge.server.run(read, write, bridge.server.create_initialization_options()) - - -def run(): - logging.basicConfig(level=logging.INFO, stream=sys.stderr, format="%(levelname)s %(message)s") - logging.getLogger("httpx2").setLevel(logging.WARNING) - logging.getLogger("httpx").setLevel(logging.WARNING) - with contextlib.suppress(KeyboardInterrupt): - asyncio.run(main()) - - -if __name__ == "__main__": - run() diff --git a/lib/upstream.py b/lib/upstream.py new file mode 100644 index 00000000..c8260f94 --- /dev/null +++ b/lib/upstream.py @@ -0,0 +1,113 @@ +"""The bot's one connection to the weather service (WEATHER_MCP_URL, docs/mcp-service.md 3.8), kept by one supervisor task (Upstream): +the protocol revision is pinned (2026-07-28, so a proxy's 502 during a restart can't land it on the older revision, which can't listen) +and discovered by hand for the instructions; when the connection fails or the listen is lost, the client is dropped and a new one built +after a backoff, which listens again (there is no replay: the caller reads what it missed). A request while it is down is refused with +an error that says so.""" + +import asyncio +import contextlib +import logging + +import mcp_types as types +from mcp import Client +from mcp.shared.exceptions import MCPError + +log = logging.getLogger("lib.upstream") + +VERSION = "2026-07-28" # the protocol revision pinned: the one that can listen +READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed +CONNECT_WAIT = 10.0 # how long a request waits for the service to be reached before it is refused +BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated + + +def http_transport(url: str, token: str | None = None): + """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS.""" + import httpx2 + from mcp.client.streamable_http import streamable_http_client + from mcp.shared._httpx_utils import create_mcp_http_client + + @contextlib.asynccontextmanager + async def connect(): + headers = {"Authorization": f"Bearer {token}"} if token else None + async with create_mcp_http_client(headers=headers, timeout=httpx2.Timeout(30.0, read=READ_SECONDS)) as http: + async with streamable_http_client(url, http_client=http) as streams: + yield streams + return connect() + + +def _leaf(e: BaseException) -> BaseException: + """The first real error inside an exception group (a refused connection, a 401, a 421), not the group's "unhandled errors".""" + while isinstance(e, BaseExceptionGroup) and e.exceptions: + e = e.exceptions[0] + return e + + +class Upstream: + """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or + its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" + + def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None, resources=None): + """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is + acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. + resources: the URIs listened to, of those the service lists (None: every one).""" + self.target, self.token, self.resources = target, token, resources + self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening + self.client: Client | None = None + self.connected = asyncio.Event() + self.attempts = 0 + + def _client(self) -> Client: + server = http_transport(self.target, self.token) if isinstance(self.target, str) else self.target + return Client(server, mode=VERSION, cache=None) + + async def run(self): + """Keep a connection, until cancelled.""" + while True: + try: + async with self._client() as client: + raw = await client.session.send_discover(VERSION) + discovered = types.DiscoverResult.model_validate(raw) + client.session.adopt(discovered) + if self.on_discover: + await self.on_discover(discovered) + self.client, self.attempts = client, 0 + self.connected.set() + log.info("Weather service: connected to %s", self.target if isinstance(self.target, str) else "the service") + await self._listen(client) + log.warning("Weather service: the service ended the listen; connecting again") + except asyncio.CancelledError: + raise + except BaseException as e: # (a transport failure ends the whole client, as an exception group too) + if isinstance(e, (KeyboardInterrupt, SystemExit)): + raise + if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have + raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same + cause = _leaf(e) + log.warning("Weather service: the service at %s isn't reachable (%s: %s); trying again", self.target, type(cause).__name__, cause) + finally: + self.client = None + self.connected.clear() + await asyncio.sleep(BACKOFF[min(self.attempts, len(BACKOFF) - 1)]) + self.attempts += 1 + + async def _listen(self, client: Client): + """Listen to every resource the service lists and its lists' changes, passing each event on, until the stream ends.""" + uris = [r.uri for r in (await client.list_resources()).resources if self.resources is None or str(r.uri) in self.resources] + async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, + resource_subscriptions=uris) as sub: + if self.on_listening: + await self.on_listening() + async for event in sub: + if self.on_event: + await self.on_event(event) + + async def get(self) -> Client: + """The connected client; refused (MCPError) when the service can't be reached within CONNECT_WAIT.""" + if self.client is None: + try: + await asyncio.wait_for(self.connected.wait(), CONNECT_WAIT) + except TimeoutError: + pass + if self.client is None: + raise MCPError(types.INTERNAL_ERROR, f"The weather service isn't reachable ({self.target}): try again shortly.") + return self.client diff --git a/lib/weather.py b/lib/weather.py index 1c87b294..c8387158 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -205,7 +205,7 @@ async def wait(self, after: int, timeout: float | None = None) -> bool: class RemoteWeather: """The service at `target` (its MCP URL; in tests, a Server in-process), as the bot's interface. `run()` is the supervisor (the - bridge's Upstream: one client, discovered by hand for the instructions, listening; on a transport error or a lost or ended listen it + lib/upstream.py's Upstream: one client, discovered by hand for the instructions, listening; on a transport error or a lost or ended listen it is dropped and built again after a backoff, which discovers and listens again). Each new connection reads the tool list and the station; the listen's events keep them current (ToolsListChanged, the station's and the forecast's ResourceUpdated) and wake the alert delivery (the alerts'). A call while it is being reached waits up to CALL_WAIT seconds (a background one not at all) and is @@ -213,7 +213,7 @@ class RemoteWeather: is_weather, remote = True, True def __init__(self, target, token: str | None = None, tz=None): - from ecobot_service.bridge import Upstream + from lib.upstream import Upstream self.target, self.fallback_tz, self.station_tz = target, tz, None self.upstream = Upstream(target, token, on_event=self._event, on_discover=self._discovered, on_listening=self._listening, resources=LISTENED) diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py index f3284c2e..51d45a8c 100644 --- a/tests/test_bot_remote.py +++ b/tests/test_bot_remote.py @@ -11,7 +11,7 @@ import pytest -from ecobot_service import bridge +from lib import upstream from lib import model_tools, weather as weather_module from lib.alert_log import AlertLog from lib.alerts.notify import AlertDelivery, AlertState, Notifier @@ -54,7 +54,7 @@ async def world(tmp_path, eval_archive, monkeypatch): @pytest.fixture(autouse=True) def quick(monkeypatch): """Reconnections and waits in tenths of a second, not seconds.""" - monkeypatch.setattr(bridge, "BACKOFF", (0.1,)) + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) monkeypatch.setattr(weather_module, "CALL_WAIT", 0.3) diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 4acb9b36..03bb0a33 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -17,9 +17,9 @@ import pytest from mcp import Client -from ecobot_service import bridge +from lib import upstream from ecobot_service.__main__ import Uvicorn, server_config -from ecobot_service.bridge import Upstream, http_transport +from lib.upstream import Upstream, http_transport from lib.alert_log import AlertLog from lib.mcp_server import ALERTS_URI, EcobotServer, http_app from lib.service.context import Context @@ -73,7 +73,7 @@ def service(tmp_path): async def test_a_client_that_listens_hears_an_alert_and_after_a_lost_listen_listens_again_and_reads_what_it_missed(service, monkeypatch): - monkeypatch.setattr(bridge, "BACKOFF", (0.1,)) + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) alerts, port = service.alert_log, free_port() url = f"http://127.0.0.1:{port}/mcp" publishing = asyncio.create_task(service.watch_alerts()) @@ -141,22 +141,6 @@ async def post(token=None, host=None) -> int: assert not (await client.call_tool("about", {})).is_error -async def test_the_stdio_bridge_as_a_desktop_client_starts_it_forwards_a_tool_call_to_the_running_service(service): - import sys - from mcp import StdioServerParameters - from lib.config import ROOT - port = free_port() - async with Serving(http_app(service, tokens=TOKENS), port): - params = StdioServerParameters(command=sys.executable, args=["-m", "ecobot_service.bridge"], cwd=str(ROOT), - env={**os.environ, "WEATHER_MCP_URL": f"http://127.0.0.1:{port}/mcp", - "WEATHER_MCP_TOKEN": TOKENS["bot"]}) - async with Client(params) as client: - assert client.instructions == service.server.instructions - got = await client.call_tool("about", {}) - assert not got.is_error and got.content[0].text == await service.service["about"].call({}) - assert [r.uri for r in (await client.list_resources()).resources][0] == "ecobot://station" - - async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name(tmp_path, monkeypatch, caplog): """A deploy check: `python -m ecobot_service` (main) with the fake sources, MCP_ALLOWED_HOSTS the name a reverse proxy sends, a tool call with a token through that name answered, the archives run, then SIGTERM closes it all.""" diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index e64f9a38..1e03ace1 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1,6 +1,6 @@ """The service over MCP (lib/mcp_server.py, docs/mcp-service.md 3.4-3.8): the ten tools listed and called over the SDK's in-memory transport with the same answers as the ServiceTools themselves, the resources and the alerts' template, the prompts, the publishing of -changes, the auth and the allowed hosts, and the stdio bridge. The listen over the network is tests/test_mcp_listen.py's (under uvicorn, +changes, the auth and the allowed hosts. The listen over the network is tests/test_mcp_listen.py's (under uvicorn, as docs 7 asks).""" import asyncio @@ -278,27 +278,6 @@ def test_the_allowed_hosts_take_any_port_unless_one_is_named(): assert "https://weather.lan:443" in settings.allowed_origins and "http://127.0.0.1:*" in settings.allowed_origins -# ---------- the bridge ---------- -async def test_the_bridge_forwards_a_tool_call_its_meta_and_its_complete_mark_and_the_instructions(world): - from ecobot_service.bridge import Bridge - bridge = Bridge(world.server) # (the service in-process, as the bridge's upstream) - async with bridge.running(5): - assert bridge.upstream.client is not None - async with Client(bridge.server) as client: - assert client.instructions == world.server.instructions - assert [t.name for t in (await client.list_tools()).tools] == [t.name for t in world.service] - args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} - got = await client.call_tool("summary", args, meta={"chart_points": 30}) - direct = await world.service["summary"].call(args, {"chart_points": 30}) - assert got.content[0].text == direct and got.meta[COMPLETE] is True and got.content[1].annotations.audience == ["user"] - refused = await client.call_tool("summary", {"period": "whenever"}) - assert refused.is_error - assert json.loads((await client.read_resource("ecobot://health")).contents[0].text)["alert_log"] == {"last_id": 0} - assert (await client.get_prompt("now")).messages[0].content.text == "How is it outside now?" - with pytest.raises(MCPError, match="No resource"): - await client.read_resource("ecobot://nowhere") - - def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, tmp_path, caplog): from lib.config import Config monkeypatch.setenv("DATA_DIR", str(tmp_path)) @@ -323,17 +302,6 @@ def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, assert Config.from_env(bot=False).mcp_bind == want, value -async def test_the_bridge_refuses_a_request_while_the_service_cant_be_reached(monkeypatch): - from ecobot_service import bridge as bridge_module - monkeypatch.setattr(bridge_module, "CONNECT_WAIT", 0.2) - monkeypatch.setattr(bridge_module, "BACKOFF", (0.1,)) - bridge = bridge_module.Bridge("http://127.0.0.1:9/mcp") # (nothing listens there) - async with bridge.running(0.2): - async with Client(bridge.server) as client: - with pytest.raises(MCPError, match="isn't reachable"): - await client.call_tool("current", {}) - - def test_one_service_per_data_folder(tmp_path): """The bot running the service in-process and python -m ecobot_service on one folder would both fetch and both write each alert.""" import contextlib From 4828f3eb35e95d5851fe5517a0a20003d02c56af Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:38:46 +0000 Subject: [PATCH 069/125] Docker: the service container on the host network and in the journal too; README steps to run it beside the bot compose.host-network.yaml puts ecobot-service on the host's network bound to its loopback (no published port), so .local sources work and the bot reaches it at 127.0.0.1; compose.journald.yaml covers it too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 25 +++++++++++++++++++++++++ compose.host-network.yaml | 7 +++++++ compose.journald.yaml | 3 +++ 3 files changed, 35 insertions(+) diff --git a/README.md b/README.md index 89eda52f..bc341ab0 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,31 @@ Then message `/report` to your Telegram bot. Docker uses the same data folder as the systemd service, so you can switch between them, one at a time. To go back to systemd: `sudo docker rm -f ecobot && sudo systemctl start ecobot`. +#### The weather service on its own in Docker (optional) + +Not needed: without it the bot runs everything itself, as before. The `ecobot-service` container runs the weather service from the same +image (an MCP server for other clients, with the bot as one of them) on the bot's data folder, so back that up first: +`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`. Then: + +1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`), and the `WEATHER_MCP_URL` line that matches your network: + ``` + MCP_TOKENS=bot: + WEATHER_MCP_TOKEN= + # Docker's own network (the default): + WEATHER_MCP_URL=http://ecobot-service:8765/mcp + MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service + # or, with compose.host-network.yaml in COMPOSE_FILE: + WEATHER_MCP_URL=http://127.0.0.1:8765/mcp + ``` +2. Recreate the bot, now the service's client (it waits for the service): `sudo docker compose up -d --force-recreate ecobot` +3. Start the service: `sudo docker compose --profile service up -d ecobot-service` +4. Watch both: `sudo docker logs -tf ecobot-service` should show `MCP: http://.../mcp`, and `sudo docker logs -tf ecobot` with + `Weather service: connected`. Then message `/report` to the bot. + +From then on, `sudo docker compose --profile service up -d --build` updates both. To go back: `sudo docker compose --profile service down` +(it stops both), remove the lines from step 1, then `sudo docker compose up -d`. +Only one process runs the service on the data folder: started beside a bot without `WEATHER_MCP_URL`, it stops, saying so in its log. + #### Docker logging Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot`): diff --git a/compose.host-network.yaml b/compose.host-network.yaml index ae673a2e..ec093e08 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -1,3 +1,10 @@ services: ecobot: network_mode: host + # On the host's network too (its sources may be .local names), listening on the host's loopback only: the bot reaches it at + # http://127.0.0.1:8765/mcp, and nothing else on the network can. + ecobot-service: + network_mode: host + environment: + MCP_BIND: 127.0.0.1:8765 + ports: !reset [] diff --git a/compose.journald.yaml b/compose.journald.yaml index a6962faf..806c05eb 100644 --- a/compose.journald.yaml +++ b/compose.journald.yaml @@ -2,3 +2,6 @@ services: ecobot: logging: !override driver: journald + ecobot-service: + logging: !override + driver: journald From b54c95b9ff65c8999334807a3727d4f45417a4fc Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:50:52 +0000 Subject: [PATCH 070/125] Service settings named MCP_SERVICE_*; MCP_SERVICE_TOKENS is a plain token list MCP_TOKENS, MCP_BIND and MCP_ALLOWED_HOSTS become MCP_SERVICE_TOKENS, MCP_SERVICE_BIND and MCP_SERVICE_ALLOWED_HOSTS, apart from the bot's WEATHER_MCP_URL and WEATHER_MCP_TOKEN. Tokens no longer take a name: prefix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 14 +++++++------- README.md | 8 ++++---- compose.host-network.yaml | 2 +- compose.yaml | 10 +++++----- docs/configuration.md | 8 ++++---- docs/mcp-service.md | 16 ++++++++-------- ecobot-mcp.service | 6 +++--- ecobot_service/__init__.py | 2 +- ecobot_service/__main__.py | 20 ++++++++++---------- lib/config.py | 26 ++++++++------------------ lib/mcp_server.py | 30 ++++++++++++++---------------- tests/test_bot_remote.py | 12 ++++++------ tests/test_mcp_listen.py | 20 ++++++++++---------- tests/test_mcp_server.py | 30 ++++++++++++++---------------- 14 files changed, 95 insertions(+), 109 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 9f3f7672..600a1706 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -28,11 +28,11 @@ The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build t ## The MCP service The service on its own ([docs/mcp-service.md](docs/mcp-service.md) 3.8, step 5): the sources and their syncers, the alert rules writing the -alert log, and the MCP server (`lib/mcp_server.py`) at `http://MCP_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). -It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) less the bot's own, and `MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`: +alert log, and the MCP server (`lib/mcp_server.py`) at `http://MCP_SERVICE_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). +It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) less the bot's own, and `MCP_SERVICE_TOKENS`, `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS`: ``` set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them -MCP_TOKENS=me:$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp +MCP_SERVICE_TOKENS=$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 ``` Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside @@ -48,7 +48,7 @@ token and Host checks over HTTP; `python -m ecobot_service` with the fake source a proxy's Host name). ### The bot as the service's client -With `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`, one of the service's `MCP_TOKENS`) set, the bot runs no sources, syncers or alert rules of +With `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`, one of the service's `MCP_SERVICE_TOKENS`) set, the bot runs no sources, syncers or alert rules of its own and reaches the service over MCP (`lib/weather.RemoteWeather`, [docs/mcp-service.md](docs/mcp-service.md) 3.8): one client pinned to protocol 2026-07-28, kept by one supervisor task (`lib/upstream.Upstream`), which discovers by hand for the instructions and listens to `ecobot://alerts`, `ecobot://station` and `ecobot://forecast`; when the connection fails or the listen is lost it builds a new client after @@ -58,11 +58,11 @@ the model's tools and instructions, its shortcuts, report, gauges, charts drawn (lib/alerts/notify.AlertDelivery reads either log) and the irrigation check's rain and forecast (`ServiceRain`, `ServiceForecast`). ``` set -a; . <(sudo cat /etc/ecobot.env); set +a -MCP_TOKENS=bot:$TOKEN python -m ecobot_service & # the service, with the sources' settings +MCP_SERVICE_TOKENS=$TOKEN python -m ecobot_service & # the service, with the sources' settings WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN=$TOKEN python ecobot.py # the bot, its client ``` -In Docker (compose.yaml): in /etc/ecobot.env set `MCP_TOKENS=bot:`, `WEATHER_MCP_URL=http://ecobot-service:8765/mcp`, -`WEATHER_MCP_TOKEN=` and `MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service`; then recreate the bot first +In Docker (compose.yaml): in /etc/ecobot.env set `MCP_SERVICE_TOKENS=`, `WEATHER_MCP_URL=http://ecobot-service:8765/mcp`, +`WEATHER_MCP_TOKEN=` and `MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service`; then recreate the bot first (`sudo docker compose up -d --force-recreate ecobot`, which frees the data folder) and start the service (`sudo docker compose --profile service up -d ecobot-service`). Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through diff --git a/README.md b/README.md index bc341ab0..fe6e4bdf 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ bot's data folder, so back that up first: `sudo cp -a /var/lib/private/ecobot /v 1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`): ``` - MCP_TOKENS=bot: + MCP_SERVICE_TOKENS= WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN= ``` @@ -158,11 +158,11 @@ image (an MCP server for other clients, with the bot as one of them) on the bot' 1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`), and the `WEATHER_MCP_URL` line that matches your network: ``` - MCP_TOKENS=bot: + MCP_SERVICE_TOKENS= WEATHER_MCP_TOKEN= # Docker's own network (the default): WEATHER_MCP_URL=http://ecobot-service:8765/mcp - MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service + MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service # or, with compose.host-network.yaml in COMPOSE_FILE: WEATHER_MCP_URL=http://127.0.0.1:8765/mcp ``` @@ -246,7 +246,7 @@ Settings are environment variables in `/etc/ecobot.env`. The ones you're most li | `AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | | `AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | | `POLLEN`, `FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | -| `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN` | Optional. The bot as a client of the weather service running on its own (`python -m ecobot_service`, e.g. `http://127.0.0.1:8765/mcp`, and one of its `MCP_TOKENS`): the bot then fetches nothing and runs no alert rules itself, and needs none of the source settings above. Unset (the default), the bot runs everything itself, as before. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-the-services-client). | +| `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN` | Optional. The bot as a client of the weather service running on its own (`python -m ecobot_service`, e.g. `http://127.0.0.1:8765/mcp`, and one of its `MCP_SERVICE_TOKENS`): the bot then fetches nothing and runs no alert rules itself, and needs none of the source settings above. Unset (the default), the bot runs everything itself, as before. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-the-services-client). | After editing the file, restart: `sudo systemctl restart ecobot`, or for Docker `sudo docker compose up -d --force-recreate` (`docker restart` keeps the old settings). diff --git a/compose.host-network.yaml b/compose.host-network.yaml index ec093e08..331b3682 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -6,5 +6,5 @@ services: ecobot-service: network_mode: host environment: - MCP_BIND: 127.0.0.1:8765 + MCP_SERVICE_BIND: 127.0.0.1:8765 ports: !reset [] diff --git a/compose.yaml b/compose.yaml index af36702d..d0eaa4e9 100644 --- a/compose.yaml +++ b/compose.yaml @@ -23,10 +23,10 @@ services: # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, # at http://127.0.0.1:8765/mcp on the host (put TLS in front of it, e.g. Caddy, to reach it from elsewhere). Off unless asked for # (`sudo docker compose --profile service up -d ecobot-service`). Run it only with the bot as its client (WEATHER_MCP_URL= - # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_ALLOWED_HOSTS), recreating the - # bot first: one process runs the service per data folder (service.lock), so it won't start beside a bot running it. It needs MCP_TOKENS - # (name:token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. - # MCP_ALLOWED_HOSTS: add the name a proxy or a LAN client uses for it. + # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_SERVICE_ALLOWED_HOSTS), recreating the + # bot first: one process runs the service per data folder (service.lock), so it won't start beside a bot running it. It needs MCP_SERVICE_TOKENS + # (token,token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. + # MCP_SERVICE_ALLOWED_HOSTS: add the name a proxy or a LAN client uses for it. ecobot-service: image: ecobot container_name: ecobot-service @@ -35,7 +35,7 @@ services: restart: unless-stopped env_file: /etc/ecobot.env environment: - MCP_BIND: 0.0.0.0:8765 + MCP_SERVICE_BIND: 0.0.0.0:8765 ports: - 127.0.0.1:8765:8765 volumes: diff --git a/docs/configuration.md b/docs/configuration.md index 02ab09cd..c8337bb1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -86,9 +86,9 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | Variable | Default | Description | |---|---|---| -| `MCP_TOKENS` | none | `name:token,name:token`: the bearer token each client sends (`Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart). Compared in constant time; a token is never logged, only its name. Unset → no auth, which the service allows only on a loopback `MCP_BIND` | -| `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | -| `MCP_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | +| `MCP_SERVICE_TOKENS` | none | `token,token`: the bearer tokens the service accepts (each client sends one as `Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart). Compared in constant time; a token is never logged, only its name. Unset → no auth, which the service allows only on a loopback `MCP_SERVICE_BIND` | +| `MCP_SERVICE_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | +| `MCP_SERVICE_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | ### The bot as the service's client @@ -96,7 +96,7 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | Variable | Default | Description | |---|---|---| | `WEATHER_MCP_URL` | none | The service's MCP endpoint (`http://127.0.0.1:8765/mcp`, or its TLS address behind a proxy). Set: the bot is a client of the service ([mcp-service.md](mcp-service.md) step 5): it starts no sources, syncers or alert rules of its own, so the source settings (`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `POLLEN`, `FORECAST` …) are the service's and the bot needs none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are) and the alerts come from the service. Unset: the bot runs the service inside itself, as before | -| `WEATHER_MCP_TOKEN` | none | The bearer token the bot sends: one of the service's `MCP_TOKENS` (give the bot its own, e.g. `bot:`) | +| `WEATHER_MCP_TOKEN` | none | The bearer token the bot sends: one of the service's `MCP_SERVICE_TOKENS` (give the bot its own) | While the service can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the alerts sent meanwhile that are still news are delivered once it is back. The irrigation controller (`TUYA_*`) stays the bot's: its daily diff --git a/docs/mcp-service.md b/docs/mcp-service.md index cda9e460..a82da227 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -383,12 +383,12 @@ Charts are data: the client draws them, or its model does from the numbers. - **One program:** `python -m ecobot_service` runs the syncers, the alert rules and the server, at `https:///mcp` (Streamable HTTP, `streamable_http_app`, under uvicorn behind TLS: a reverse proxy such as Caddy, or uvicorn's own certificate). The server is the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built when - asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by + asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_SERVICE_ALLOWED_HOSTS)`: by default it answers only `Host: 127.0.0.1` or `localhost`, and refuses the name a proxy or a LAN client uses. - **No stdio:** clients connect over HTTP (Claude Code: `claude mcp add --transport http ...` with the bearer header). A stdio bridge for clients that can only start a local command was built in step 5 and removed: nothing here needs it. -- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_TOKENS` - (`name:token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://", +- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_SERVICE_TOKENS` + (`token,token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://", resource_server_url=None)` (`issuer_url` is required but unused without an OAuth provider; no OAuth metadata is published). Bind to the LAN or a tailnet; nothing needs the internet to reach it. - **A client that listens** (our bot, an alert forwarder): `Client(…, mode="2026-07-28")`, pinning the protocol revision (the default @@ -417,8 +417,8 @@ on its own (step 5). `ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `CHART_ALL_FEELS_LIKE`, `CHART_ALL_VPD`, -`MCP_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, -its own `MCP_TOKENS`. +`MCP_SERVICE_TOKENS`, `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, +its own `MCP_SERVICE_TOKENS`. ## 4. The bot until it is retired @@ -566,12 +566,12 @@ Each step ships on its own, with the tests and evals green and the bot working t `ListenHandler`): `ResourceUpdated` for the live resources when what the sources keep changes (compared every 2 s, nothing fetched for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`AlertLog.wait`), the station and `ToolsListChanged` when the file's catalogue gains a reading (read every minute; the tools and instructions are then built again). - `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_ALLOWED_HOSTS` and the `TokenCheck` verifier over - `MCP_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_service/`: `core.py` is the service's startup + `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_SERVICE_ALLOWED_HOSTS` and the `TokenCheck` verifier over + `MCP_SERVICE_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_service/`: `core.py` is the service's startup (`start_sources`, `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch, the weather rules, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for `ecobot://health`), which `ecobot.py` now calls in-process, its behaviour unchanged; `__main__.py` runs it with the server under - uvicorn (`MCP_BIND`, refusing a non-loopback address without `MCP_TOKENS`); `lib/upstream.py` is the bot's one supervised + uvicorn (`MCP_SERVICE_BIND`, refusing a non-loopback address without `MCP_SERVICE_TOKENS`); `lib/upstream.py` is the bot's one supervised client, pinned to 2026-07-28, that discovers by hand, listens and re-listens after a backoff (a stdio bridge was built on it and later removed). The image ships `ecobot_service/` and `schemas/`; compose has `ecobot-service`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs diff --git a/ecobot-mcp.service b/ecobot-mcp.service index a125a37e..594d1bc7 100644 --- a/ecobot-mcp.service +++ b/ecobot-mcp.service @@ -2,11 +2,11 @@ # and the MCP server at http://127.0.0.1:8765/mcp. Install it beside ecobot.service, from the same checkout and venv (see that file): # sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload # Only one process runs the service on a data folder (service.lock): before enabling this, make the bot its client (WEATHER_MCP_URL -# and WEATHER_MCP_TOKEN in /etc/ecobot.env, with the token in MCP_TOKENS) and restart it; otherwise this one stops at start, saying so. +# and WEATHER_MCP_TOKEN in /etc/ecobot.env, with the token in MCP_SERVICE_TOKENS) and restart it; otherwise this one stops at start, saying so. # The data folder is the bot's own, /var/lib/private/ecobot (StateDirectory=ecobot): User=ecobot gives this unit the same dynamic user # as ecobot.service, so the two share the folder's owner and neither takes it from the other when it starts. -# It reads /etc/ecobot.env as the bot does, less the bot's own secrets (UnsetEnvironment=). MCP_BIND defaults to 127.0.0.1:8765; to -# reach it from other machines set MCP_BIND=0.0.0.0:8765 (refused without MCP_TOKENS) and put TLS in front of it. +# It reads /etc/ecobot.env as the bot does, less the bot's own secrets (UnsetEnvironment=). MCP_SERVICE_BIND defaults to 127.0.0.1:8765; to +# reach it from other machines set MCP_SERVICE_BIND=0.0.0.0:8765 (refused without MCP_SERVICE_TOKENS) and put TLS in front of it. [Unit] Description=ecobot weather service (MCP) After=network-online.target diff --git a/ecobot_service/__init__.py b/ecobot_service/__init__.py index e1685e41..45ad69b9 100644 --- a/ecobot_service/__init__.py +++ b/ecobot_service/__init__.py @@ -1,7 +1,7 @@ """The weather and air service on its own (docs/mcp-service.md 3.8, step 5): the readings file, the sources and syncers that fill it, the alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). - - `python -m ecobot_service` (__main__.py): the service, Streamable HTTP at http://MCP_BIND/mcp; + - `python -m ecobot_service` (__main__.py): the service, Streamable HTTP at http://MCP_SERVICE_BIND/mcp; - core.py: the service's startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and Home Assistant's imports), the one function the service and the bot (ecobot.py, while it runs everything in-process) both call.""" diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py index fee81158..7d874d7f 100644 --- a/ecobot_service/__main__.py +++ b/ecobot_service/__main__.py @@ -1,11 +1,11 @@ """python -m ecobot_service: the weather and air service on its own (docs/mcp-service.md 3.8). It runs the sources and their syncers (ecobot_service/core.py: the keep-warm, the first fetch, the archive, the backfills, Home Assistant's imports), the alert rules writing -the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a +the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_SERVICE_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a reverse proxy such as Caddy) to reach it from elsewhere. Settings come from the environment, as the bot reads them (lib/config.py, docs/configuration.md), less the bot's own (no Telegram token -is needed), with MCP_TOKENS (name:token,..., one per client), MCP_BIND (host:port, default 127.0.0.1:8765) and MCP_ALLOWED_HOSTS (the -Host names it answers, default 127.0.0.1 and localhost). Without MCP_TOKENS it serves without auth, and then only on a loopback address.""" +is needed), with MCP_SERVICE_TOKENS (token,token,..., one per client), MCP_SERVICE_BIND (host:port, default 127.0.0.1:8765) and MCP_SERVICE_ALLOWED_HOSTS (the +Host names it answers, default 127.0.0.1 and localhost). Without MCP_SERVICE_TOKENS it serves without auth, and then only on a loopback address.""" import asyncio import contextlib @@ -55,10 +55,10 @@ async def main(): cfg = Config.from_env(bot=False) for name in ("ecobot", "lib"): logging.getLogger(name).setLevel(cfg.log_level) - host, port = cfg.mcp_bind - if not cfg.mcp_tokens and not loopback(host): - raise SystemExit(f"MCP_BIND is {host}:{port}, which other machines can reach, and MCP_TOKENS is empty: set MCP_TOKENS " - "(name:token,...) or bind to 127.0.0.1") + host, port = cfg.mcp_service_bind + if not cfg.mcp_service_tokens and not loopback(host): + raise SystemExit(f"MCP_SERVICE_BIND is {host}:{port}, which other machines can reach, and MCP_SERVICE_TOKENS is empty: set MCP_SERVICE_TOKENS " + "(token,token,...) or bind to 127.0.0.1") configure(cfg) async with contextlib.AsyncExitStack() as stack: sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on @@ -73,7 +73,7 @@ async def main(): for source in sources: stack.push_async_callback(source.warmer.stop) server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) - app = http_app(server, tokens=cfg.mcp_tokens, allowed_hosts=cfg.mcp_allowed_hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") + app = http_app(server, tokens=cfg.mcp_service_tokens, allowed_hosts=cfg.mcp_service_allowed_hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") core.log_startup() running = core.start_alerts() core.start_warmers() @@ -91,8 +91,8 @@ async def warm_up(): web = Uvicorn(server_config(app, host, port)) serving = asyncio.create_task(web.serve()) log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", host if ":" not in host else f"[{host}]", port, - f"tokens for {', '.join(name for name, _ in cfg.mcp_tokens)}" if cfg.mcp_tokens else "no auth (loopback only)", - ", ".join(cfg.mcp_allowed_hosts)) + f"{len(cfg.mcp_service_tokens)} token(s)" if cfg.mcp_service_tokens else "no auth (loopback only)", + ", ".join(cfg.mcp_service_allowed_hosts)) waiting = asyncio.create_task(stop.wait()) await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) server.listen.close() # (the listen streams end gracefully: their clients know to listen again) diff --git a/lib/config.py b/lib/config.py index f4c02833..758da6a1 100644 --- a/lib/config.py +++ b/lib/config.py @@ -65,20 +65,10 @@ def _required(value: str, default: str, name: str) -> str: REQUIRED_BY_BOT = ("telegram_token",) # read only by the bot: the service (python -m ecobot_service) runs without them -def _tokens(value: str, default: tuple, name: str) -> tuple[tuple[str, str], ...]: - """"bot:s3cret, phone:t0ken" -> (("bot", "s3cret"), ("phone", "t0ken")): one token per client, each named, so one can be revoked - alone. An entry without a name or a token is ignored and logged by its place in the list, never its text (an entry without a colon - may be a bare token); a name given twice keeps the last.""" - found, bad = {}, [] - for n, part in enumerate(filter(None, (p.strip() for p in value.split(","))), 1): - who, colon, token = part.partition(":") - if colon and who.strip() and token.strip(): - found[who.strip()] = token.strip() - else: - bad.append(f"entry {n}") - if bad: - log.warning("%s: ignoring %s (each entry is name:token)", name, ", ".join(bad)) - return tuple(found.items()) or default +def _tokens(value: str, default: tuple, name: str) -> tuple[str, ...]: + """"s3cret, t0ken" -> ("s3cret", "t0ken"): the bearer tokens the service accepts, one per client, so one can be revoked alone (take + it out and restart). Blank entries are skipped; a token given twice counts once.""" + return tuple(dict.fromkeys(filter(None, (p.strip() for p in value.split(","))))) or default def _bind(value: str, default: tuple[str, int], name: str) -> tuple[str, int]: @@ -285,12 +275,12 @@ class Config: log_width: int = _setting("LOG_WIDTH", 24, _whole) # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the bot's own debug lines; the libraries keep theirs # The MCP service (python -m ecobot_service: docs/mcp-service.md 3.8) - mcp_tokens: tuple[tuple[str, str], ...] = _setting("MCP_TOKENS", (), _tokens) # "name:token,...", one per client; none: no auth, loopback only - mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind) # host:port the service listens on - mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) + mcp_service_tokens: tuple[str, ...] = _setting("MCP_SERVICE_TOKENS", (), _tokens) # "token,token,...", one per client; none: no auth, loopback only + mcp_service_bind: tuple[str, int] = _setting("MCP_SERVICE_BIND", ("127.0.0.1", 8765), _bind) # host:port the service listens on + mcp_service_allowed_hosts: tuple[str, ...] = _setting("MCP_SERVICE_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) # The bot as the service's client (docs/mcp-service.md step 5): set, the bot runs no sources, syncers or alert rules of its own weather_mcp_url: str = _setting("WEATHER_MCP_URL", "", _url) # the service's MCP endpoint, e.g. http://127.0.0.1:8765/mcp; unset: the service runs inside the bot - weather_mcp_token: str = _setting("WEATHER_MCP_TOKEN", "") # the bearer token the bot sends it (one of the service's MCP_TOKENS) + weather_mcp_token: str = _setting("WEATHER_MCP_TOKEN", "") # the bearer token the bot sends it (one of the service's MCP_SERVICE_TOKENS) @property def alert_state_path(self) -> Path: diff --git a/lib/mcp_server.py b/lib/mcp_server.py index d8613c8e..411695af 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -14,8 +14,8 @@ `wait`), the station when the catalogue gains a reading. - **Prompts** (3.5): PROMPTS, each a question in words with its period an argument; no logic. - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against the allowed hosts - (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_ALLOWED_HOSTS says), each request's bearer token against - MCP_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). + (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_SERVICE_ALLOWED_HOSTS says), each request's bearer token against + MCP_SERVICE_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). `EcobotServer(ctx, alert_log)` builds it over the service's Context; `run()` is its publishing, for as long as it runs. Nothing here fetches, alerts or writes: ecobot_service runs the sources and the rules.""" @@ -140,23 +140,22 @@ def tool_result(text: str) -> types.CallToolResult: # ---------- auth ---------- class TokenCheck: - """The service's TokenVerifier (3.8): a bearer token is one of MCP_TOKENS', compared in constant time against every one of them; - the client it names is the AccessToken's client_id. `revoke(name)` takes one out while the service runs (MCP_TOKENS without it does - the same at the next start).""" + """The service's TokenVerifier (3.8): a bearer token is one of MCP_SERVICE_TOKENS, compared in constant time against every one of + them. `revoke(token)` takes one out while the service runs (MCP_SERVICE_TOKENS without it does the same at the next start).""" - def __init__(self, tokens: dict[str, str] | tuple[tuple[str, str], ...]): - self.tokens = dict(tokens) + def __init__(self, tokens): + self.tokens = list(dict.fromkeys(tokens)) - def revoke(self, name: str): - self.tokens.pop(name, None) + def revoke(self, token: str): + if token in self.tokens: + self.tokens.remove(token) async def verify_token(self, token: str) -> AccessToken | None: - found = None + found = False sent = (token or "").encode() - for name, known in list(self.tokens.items()): # (every one compared: the time says nothing of which matched) - if hmac.compare_digest(sent, known.encode()): - found = name - return AccessToken(token=token, client_id=found, scopes=[]) if found else None + for known in list(self.tokens): # (every one compared: the time says nothing of which matched) + found |= hmac.compare_digest(sent, known.encode()) + return AccessToken(token=token, client_id="client", scopes=[]) if found else None def host_settings(allowed: tuple[str, ...] | list[str]) -> TransportSecuritySettings: @@ -410,8 +409,7 @@ def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", path: str = "/mcp"): - """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (MCP_TOKENS: - name -> token), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth + """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (MCP_SERVICE_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth metadata is published (resource_server_url=None).""" check = TokenCheck(tokens) if tokens else None app = server.server.streamable_http_app( diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py index 51d45a8c..0d53f5aa 100644 --- a/tests/test_bot_remote.py +++ b/tests/test_bot_remote.py @@ -221,7 +221,7 @@ async def test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_ texts = lambda: [text for _, text in telegram.sent] alerts = bare.alert_log try: - async with Serving(http_app(bare, tokens={"bot": TOKEN}), port) as first: + async with Serving(http_app(bare, tokens=(TOKEN,)), port) as first: await until(lambda: state.read is not None and bare.listen._streams, what="the listen") alerts.append("rain", "first", "Rain started", expires=time.time() + 3600) await until(lambda: texts() == ["first"], what="alert 1") @@ -230,7 +230,7 @@ async def test_a_dropped_connection_is_rebuilt_and_the_alerts_after_the_last_id_ assert not await remote.ready(0.1) alerts.append("gusts", "missed", "Gusts", expires=time.time() + 3600) # sent while it was down alerts.append("uv", "stale", "UV", expires=time.time() - 1) # ... and expired already: not news - async with Serving(http_app(bare, tokens={"bot": TOKEN}), port): + async with Serving(http_app(bare, tokens=(TOKEN,)), port): await until(lambda: texts() == ["first", "missed"], what="the alert missed, read after the last id") await until(lambda: bare.listen._streams, what="the listen again") alerts.append("temps", "after", "Temperatures", expires=time.time() + 3600) @@ -262,7 +262,7 @@ async def test_the_service_back_on_a_fresh_alert_log_while_the_bot_runs_has_its_ try: first = EcobotServer(Context(tz=TZ), old) tasks.append(asyncio.create_task(first.watch_alerts())) - async with Serving(http_app(first, tokens={"bot": TOKEN}), port): + async with Serving(http_app(first, tokens=(TOKEN,)), port): await until(lambda: state.read is not None and first.listen._streams, what="the listen") for text in ("one", "two", "three"): old.append("rain", text, "Rain", expires=time.time() + 3600) @@ -277,7 +277,7 @@ async def test_the_service_back_on_a_fresh_alert_log_while_the_bot_runs_has_its_ new.append("gusts", "while down", "Gusts", expires=time.time() + 3600) second = EcobotServer(Context(tz=TZ), new) tasks.append(asyncio.create_task(second.watch_alerts())) - async with Serving(http_app(second, tokens={"bot": TOKEN}), port): + async with Serving(http_app(second, tokens=(TOKEN,)), port): await until(lambda: texts()[3:] == ["while down"], what="the new log's alert logged while it was down") await until(lambda: second.listen._streams, what="the listen again") new.append("temps", "after", "Temperatures", expires=time.time() + 3600) @@ -353,7 +353,7 @@ async def alert(): bare.alert_log.append("rain", "🌧️ Raining", "Rain started", expires=time.time() + 3600) await until(lambda: app.sent, what="the alert sent") try: - async with Serving(http_app(bare, tokens={"bot": TOKEN}), port): + async with Serving(http_app(bare, tokens=(TOKEN,)), port): stopper = asyncio.create_task(alert_then_stop()) await ecobot.main() await stopper @@ -417,7 +417,7 @@ async def until_then_stop(check, what): async def serve_late(): await until(bot_up, what="the bot started without the service") assert str(made["bot"].cfg.tz) == "Etc/UTC" and str(made["delivery"].tz) == "Etc/UTC" # (TZ's, while unread) - async with Serving(http_app(server, tokens={"bot": TOKEN}), port): + async with Serving(http_app(server, tokens=(TOKEN,)), port): await until_then_stop(lambda: str(made["bot"].cfg.tz) == "Australia/Melbourne", "the station's zone") late = asyncio.create_task(serve_late()) await ecobot.main() diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 03bb0a33..4da0f209 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -91,7 +91,7 @@ async def listening(): up = Upstream(url, TOKENS["bot"], on_event=read_new, on_listening=listening) supervisor = asyncio.create_task(up.run()) try: - async with Serving(http_app(service, tokens=TOKENS), port) as first: + async with Serving(http_app(service, tokens=TOKENS.values()), port) as first: await until(lambda: connections and service.listen._streams, what="the listen") alerts.append("rain", "🌧️ It's started raining", "Rain started", expires=time.time() + 3600) await until(lambda: handled == [1], what="alert 1") @@ -99,7 +99,7 @@ async def listening(): await until(lambda: not up.connected.is_set(), what="the client to notice") alerts.append("gusts", "💨 A gust of 72 km/h", "Gusts", expires=time.time() + 3600) # missed while it was down alerts.append("uv", "UV 9", "UV", expires=time.time() - 1) # ... and already expired: never news - async with Serving(http_app(service, tokens=TOKENS), port): + async with Serving(http_app(service, tokens=TOKENS.values()), port): await until(lambda: len(connections) == 2, what="the client to listen again") await until(lambda: handled == [1, 2], what="alert 2, read after its last id") alerts.append("temps", "Warmer outside", "Temperatures", expires=time.time() + 3600) @@ -114,7 +114,7 @@ async def listening(): async def test_a_request_without_the_token_with_a_wrong_or_revoked_one_or_to_a_host_not_allowed_is_refused(service): port = free_port() url = f"http://127.0.0.1:{port}/mcp" - app = http_app(service, tokens=TOKENS, allowed_hosts=("127.0.0.1", "weather.lan")) + app = http_app(service, tokens=TOKENS.values(), allowed_hosts=("127.0.0.1", "weather.lan")) body = {"jsonrpc": "2.0", "id": 1, "method": "server/discover", "params": {"_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28"}}} @@ -132,7 +132,7 @@ async def post(token=None, host=None) -> int: assert await post(TOKENS["phone"], host="evil.example") == 421 # DNS rebinding: a Host not allowed async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: assert not (await client.call_tool("about", {})).is_error - app.state.tokens.revoke("phone") # one client's token revoked alone + app.state.tokens.revoke(TOKENS["phone"]) # one client's token revoked alone assert await post(TOKENS["phone"]) == 401 with pytest.raises(BaseException): async with Client(http_transport(url, TOKENS["phone"]), mode="2026-07-28") as client: @@ -142,7 +142,7 @@ async def post(token=None, host=None) -> int: async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name(tmp_path, monkeypatch, caplog): - """A deploy check: `python -m ecobot_service` (main) with the fake sources, MCP_ALLOWED_HOSTS the name a reverse proxy sends, a + """A deploy check: `python -m ecobot_service` (main) with the fake sources, MCP_SERVICE_ALLOWED_HOSTS the name a reverse proxy sends, a tool call with a token through that name answered, the archives run, then SIGTERM closes it all.""" import ecobot_service.__main__ as service_main from ecobot_service import core @@ -152,8 +152,8 @@ async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_ from tests.fakes import air_transport, config, ecowitt_transport caplog.set_level("INFO") port = free_port() - cfg = config(tmp_path, telegram_token="", mcp_tokens=(("proxy", "pr0xy"),), mcp_bind=("127.0.0.1", port), - mcp_allowed_hosts=("weather.lan",)) + cfg = config(tmp_path, telegram_token="", mcp_service_tokens=("pr0xy",), mcp_service_bind=("127.0.0.1", port), + mcp_service_allowed_hosts=("weather.lan",)) eco_t, _ = ecowitt_transport(history_days=10) air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) @@ -193,7 +193,7 @@ async def post_status(url) -> int: await service_main.main() await asker log = caplog.text - assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "tokens for proxy" in log + assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "1 token(s)" in log assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] assert answered["direct"] == 421 @@ -205,7 +205,7 @@ async def test_the_service_will_not_serve_without_tokens_on_an_address_others_ca import ecobot_service.__main__ as service_main from lib.config import Config from tests.fakes import config - cfg = config(tmp_path, telegram_token="", mcp_bind=("0.0.0.0", free_port())) + cfg = config(tmp_path, telegram_token="", mcp_service_bind=("0.0.0.0", free_port())) monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) - with pytest.raises(SystemExit, match="MCP_TOKENS"): + with pytest.raises(SystemExit, match="MCP_SERVICE_TOKENS"): await service_main.main() diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 1e03ace1..9f2cc367 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -261,14 +261,13 @@ async def test_the_prompts_are_questions_in_words_with_their_period_an_argument( # ---------- auth and hosts ---------- -async def test_a_token_is_one_of_mcp_tokens_named_by_its_client_and_one_can_be_revoked_alone(): - check = TokenCheck((("bot", "s3cret-bot"), ("phone", "s3cret-phone"))) - assert (await check.verify_token("s3cret-bot")).client_id == "bot" - assert (await check.verify_token("s3cret-phone")).client_id == "phone" +async def test_a_token_is_one_of_mcp_service_tokens_and_one_can_be_revoked_alone(): + check = TokenCheck(("s3cret-bot", "s3cret-phone")) + assert await check.verify_token("s3cret-bot") and await check.verify_token("s3cret-phone") for wrong in ("", "s3cret", "s3cret-bot ", "S3CRET-BOT"): assert await check.verify_token(wrong) is None - check.revoke("phone") - assert await check.verify_token("s3cret-phone") is None and (await check.verify_token("s3cret-bot")).client_id == "bot" + check.revoke("s3cret-phone") + assert await check.verify_token("s3cret-phone") is None and await check.verify_token("s3cret-bot") def test_the_allowed_hosts_take_any_port_unless_one_is_named(): @@ -283,23 +282,22 @@ def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, monkeypatch.setenv("DATA_DIR", str(tmp_path)) for key, value in {"ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b", "TELEGRAM_BOT_TOKEN": ""}.items(): monkeypatch.setenv(key, value) - for key in ("MCP_TOKENS", "MCP_BIND", "MCP_ALLOWED_HOSTS"): + for key in ("MCP_SERVICE_TOKENS", "MCP_SERVICE_BIND", "MCP_SERVICE_ALLOWED_HOSTS"): monkeypatch.delenv(key, raising=False) with pytest.raises(SystemExit, match="TELEGRAM_BOT_TOKEN is not set"): Config.from_env() # the bot can't start without it ... cfg = Config.from_env(bot=False) # ... the service can - assert cfg.mcp_tokens == () and cfg.mcp_bind == ("127.0.0.1", 8765) and cfg.mcp_allowed_hosts == ("127.0.0.1", "localhost") - monkeypatch.setenv("MCP_TOKENS", " bot:s3cret , phone:t0k:en, broken, :nameless") - monkeypatch.setenv("MCP_BIND", "0.0.0.0:9000") - monkeypatch.setenv("MCP_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") + assert cfg.mcp_service_tokens == () and cfg.mcp_service_bind == ("127.0.0.1", 8765) and cfg.mcp_service_allowed_hosts == ("127.0.0.1", "localhost") + monkeypatch.setenv("MCP_SERVICE_TOKENS", " s3cret , t0k:en,, s3cret") + monkeypatch.setenv("MCP_SERVICE_BIND", "0.0.0.0:9000") + monkeypatch.setenv("MCP_SERVICE_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") cfg = Config.from_env(bot=False) - assert cfg.mcp_tokens == (("bot", "s3cret"), ("phone", "t0k:en")) - assert "MCP_TOKENS: ignoring entry 3, entry 4" in caplog.text and "broken" not in caplog.text and "nameless" not in caplog.text - assert cfg.mcp_bind == ("0.0.0.0", 9000) and cfg.mcp_allowed_hosts == ("weather.lan", "192.168.1.5:9000") + assert cfg.mcp_service_tokens == ("s3cret", "t0k:en") and "s3cret" not in caplog.text + assert cfg.mcp_service_bind == ("0.0.0.0", 9000) and cfg.mcp_service_allowed_hosts == ("weather.lan", "192.168.1.5:9000") for value, want in (("[::1]:8800", ("::1", 8800)), ("9001", ("127.0.0.1", 9001)), ("host:port", ("127.0.0.1", 8765)), ("h:70000", ("127.0.0.1", 8765))): - monkeypatch.setenv("MCP_BIND", value) - assert Config.from_env(bot=False).mcp_bind == want, value + monkeypatch.setenv("MCP_SERVICE_BIND", value) + assert Config.from_env(bot=False).mcp_service_bind == want, value def test_one_service_per_data_folder(tmp_path): From 9891fd1f98640424818edfb0bd61b244a92d176c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 00:59:14 +0000 Subject: [PATCH 071/125] Docker: publish the service on all the host's addresses (8765:8765) by default LAN clients reach it with their own token; on the host network it binds 0.0.0.0 too. README: the allowed-hosts entry they need, plain HTTP, Docker bypassing ufw, and how to keep it to the host. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- DEVELOPMENT.md | 2 +- README.md | 6 ++++++ compose.host-network.yaml | 6 ++---- compose.yaml | 7 ++++--- 4 files changed, 13 insertions(+), 8 deletions(-) diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 600a1706..46fa6bb8 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -33,7 +33,7 @@ It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) les ``` set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them MCP_SERVICE_TOKENS=$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp -sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on 127.0.0.1:8765 +sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on the host's port 8765 ``` Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set diff --git a/README.md b/README.md index fe6e4bdf..ee9bcccc 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,12 @@ image (an MCP server for other clients, with the bot as one of them) on the bot' 4. Watch both: `sudo docker logs -tf ecobot-service` should show `MCP: http://.../mcp`, and `sudo docker logs -tf ecobot` with `Weather service: connected`. Then message `/report` to the bot. +The service is published on port 8765 of every address your machine has, so other devices on your network (Claude Code on a laptop, +say) can use it with their own token from `MCP_SERVICE_TOKENS`: add your machine's IP address or name, as they write it in the URL, to +`MCP_SERVICE_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. It is plain HTTP: keep it on your own network. +Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in `compose.yaml` to +`127.0.0.1:8765:8765`. + From then on, `sudo docker compose --profile service up -d --build` updates both. To go back: `sudo docker compose --profile service down` (it stops both), remove the lines from step 1, then `sudo docker compose up -d`. Only one process runs the service on the data folder: started beside a bot without `WEATHER_MCP_URL`, it stops, saying so in its log. diff --git a/compose.host-network.yaml b/compose.host-network.yaml index 331b3682..7933a778 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -1,10 +1,8 @@ services: ecobot: network_mode: host - # On the host's network too (its sources may be .local names), listening on the host's loopback only: the bot reaches it at - # http://127.0.0.1:8765/mcp, and nothing else on the network can. + # On the host's network too (its sources may be .local names), on port 8765 of every address the host has, as compose.yaml + # publishes it: the bot reaches it at http://127.0.0.1:8765/mcp, and other machines at the host's address. ecobot-service: network_mode: host - environment: - MCP_SERVICE_BIND: 127.0.0.1:8765 ports: !reset [] diff --git a/compose.yaml b/compose.yaml index d0eaa4e9..bff75908 100644 --- a/compose.yaml +++ b/compose.yaml @@ -21,12 +21,13 @@ services: max-file: "5" # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, - # at http://127.0.0.1:8765/mcp on the host (put TLS in front of it, e.g. Caddy, to reach it from elsewhere). Off unless asked for + # on port 8765 of every address the host has, so other machines on the network can reach it too (plain HTTP, with a token; put TLS + # in front of it, e.g. Caddy, to reach it over the internet; for this host only, publish 127.0.0.1:8765:8765). Off unless asked for # (`sudo docker compose --profile service up -d ecobot-service`). Run it only with the bot as its client (WEATHER_MCP_URL= # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_SERVICE_ALLOWED_HOSTS), recreating the # bot first: one process runs the service per data folder (service.lock), so it won't start beside a bot running it. It needs MCP_SERVICE_TOKENS # (token,token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. - # MCP_SERVICE_ALLOWED_HOSTS: add the name a proxy or a LAN client uses for it. + # MCP_SERVICE_ALLOWED_HOSTS: add the host's IP address or name, as LAN clients use it in their URL, and a proxy's name. ecobot-service: image: ecobot container_name: ecobot-service @@ -37,7 +38,7 @@ services: environment: MCP_SERVICE_BIND: 0.0.0.0:8765 ports: - - 127.0.0.1:8765:8765 + - 8765:8765 volumes: - /var/lib/private/ecobot:/data logging: From ee6d6221f662e6d3313c441e42b4f60438bba834 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 01:11:11 +0000 Subject: [PATCH 072/125] Bot: the reconnect warning names the HTTP refusal (401 token, 421 allowed hosts, 404 path) and what to change The SDK reports every HTTP error as "Server returned an error response"; a response hook keeps the status for the warning. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/upstream.py | 25 ++++++++++++++++++++----- tests/test_mcp_listen.py | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/lib/upstream.py b/lib/upstream.py index c8260f94..c7721761 100644 --- a/lib/upstream.py +++ b/lib/upstream.py @@ -20,8 +20,15 @@ BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated -def http_transport(url: str, token: str | None = None): - """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS.""" +REFUSED = {401: "401: WEATHER_MCP_TOKEN isn't one of the service's MCP_SERVICE_TOKENS", + 403: "403: the token was refused", + 421: "421: the service doesn't answer to this address: add its host part to the service's MCP_SERVICE_ALLOWED_HOSTS", + 404: "404: nothing at this path: the URL ends in /mcp"} + + +def http_transport(url: str, token: str | None = None, refused: dict | None = None): + """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS. + refused: given, its "status" is set to an HTTP error the service answered with (the SDK reports any of them as one message).""" import httpx2 from mcp.client.streamable_http import streamable_http_client from mcp.shared._httpx_utils import create_mcp_http_client @@ -30,6 +37,11 @@ def http_transport(url: str, token: str | None = None): async def connect(): headers = {"Authorization": f"Bearer {token}"} if token else None async with create_mcp_http_client(headers=headers, timeout=httpx2.Timeout(30.0, read=READ_SECONDS)) as http: + if refused is not None: + async def note(response): + if response.status_code >= 400: + refused["status"] = response.status_code + http.event_hooks["response"].append(note) async with streamable_http_client(url, http_client=http) as streams: yield streams return connect() @@ -55,14 +67,16 @@ def __init__(self, target, token: str | None = None, on_event=None, on_discover= self.client: Client | None = None self.connected = asyncio.Event() self.attempts = 0 + self.refused: dict = {} # the HTTP error the service last answered with def _client(self) -> Client: - server = http_transport(self.target, self.token) if isinstance(self.target, str) else self.target + server = http_transport(self.target, self.token, self.refused) if isinstance(self.target, str) else self.target return Client(server, mode=VERSION, cache=None) async def run(self): """Keep a connection, until cancelled.""" while True: + self.refused.clear() try: async with self._client() as client: raw = await client.session.send_discover(VERSION) @@ -82,8 +96,9 @@ async def run(self): raise if (me := asyncio.current_task()) is not None and me.cancelling(): # cancelled while connecting: the SDK may have raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same - cause = _leaf(e) - log.warning("Weather service: the service at %s isn't reachable (%s: %s); trying again", self.target, type(cause).__name__, cause) + cause, status = _leaf(e), self.refused.get("status") + why = (REFUSED.get(status, f"HTTP {status}") if status else f"{type(cause).__name__}: {cause}") + log.warning("Weather service: the service at %s isn't reachable (%s); trying again", self.target, why) finally: self.client = None self.connected.clear() diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 4da0f209..739f0d3f 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -5,6 +5,7 @@ refused; and `python -m ecobot_service` runs the sources and answers a tool call through the name a proxy uses.""" import asyncio +import contextlib import json import os import signal @@ -209,3 +210,22 @@ async def test_the_service_will_not_serve_without_tokens_on_an_address_others_ca monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) with pytest.raises(SystemExit, match="MCP_SERVICE_TOKENS"): await service_main.main() + + +async def test_the_bot_s_warning_says_why_the_service_refused_it(service, monkeypatch, caplog): + """The SDK reports every HTTP error as "Server returned an error response": the warning names the status and what to change.""" + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + port = free_port() + async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("localhost",)), port): + for url, token, want in ((f"http://localhost:{port}/mcp", "wrong", "401: WEATHER_MCP_TOKEN"), + (f"http://127.0.0.1:{port}/mcp", TOKENS["bot"], "421: the service doesn't answer to this address")): + caplog.clear() + task = asyncio.create_task(Upstream(url, token).run()) + for _ in range(100): + if want in caplog.text: + break + await asyncio.sleep(0.05) + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + assert want in caplog.text, caplog.text From 91c1fb46f060abdb154970ed303e9dd15f1dd8e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 01:16:09 +0000 Subject: [PATCH 073/125] Service: log each incoming request (who, which MCP method and tool or resource, status, time); refusals as warnings with the reason RequestLog is the app's outermost middleware, so the token's 401 and the Host check's 421 are logged too. Tokens are never logged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/mcp_server.py | 73 ++++++++++++++++++++++++++++++++++++++++ tests/test_mcp_listen.py | 21 ++++++++++++ 2 files changed, 94 insertions(+) diff --git a/lib/mcp_server.py b/lib/mcp_server.py index 411695af..7dc634b7 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -25,6 +25,7 @@ import json import logging import os +import time from collections.abc import Callable from datetime import date, datetime from pathlib import Path @@ -47,6 +48,7 @@ from .service.names import AIR_DEVICE, STATION, Catalogue log = logging.getLogger(__name__) +requests_log = logging.getLogger(__name__ + ".requests") # one line per HTTP request (RequestLog) NAME = "ecobot" COMPLETE = "ecobot/complete" # result _meta of a complete answer (3.7) @@ -407,6 +409,76 @@ def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: return types.GetPromptResult(description=what, messages=[types.PromptMessage(role="user", content=types.TextContent(text=question))]) +# ---------- the request log ---------- +WHY = {401: "no token, or one that isn't in MCP_SERVICE_TOKENS", + 421: "its Host isn't in MCP_SERVICE_ALLOWED_HOSTS", + 404: "nothing at this path, or the session has ended"} +BODY_READ = 1 << 20 # the most of a request's body read to name its MCP method (the SDK reads it all anyway) + + +def _rpc(body: bytes) -> str: + """What a JSON-RPC body asks: its method, and the tool, resource or prompt it names ("tools/call summary").""" + try: + msg = json.loads(body) + except ValueError: + return "" + msgs = msg if isinstance(msg, list) else [msg] + out = [] + for m in msgs: + if not isinstance(m, dict) or "method" not in m: + continue + params = m.get("params") if isinstance(m.get("params"), dict) else {} + target = params.get("name") or params.get("uri") + out.append(f"{m['method']} {target}" if isinstance(target, str) else str(m["method"])) + return ", ".join(out) + + +class RequestLog: + """ASGI middleware, outermost: one line per HTTP request, once its response starts (a listen stream's when it opens). INFO when + answered, WARNING when refused, with the reason for a 401 (the token), a 421 (the Host) and a 404. The token itself is never + logged; the client's address is the proxy's X-Forwarded-For when uvicorn trusts it.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + return await self.app(scope, receive, send) + start = time.monotonic() + held, body = [], b"" + if scope.get("method") == "POST": # (read here to name the MCP method, then handed on as it came) + while True: + message = await receive() + held.append(message) + if message["type"] != "http.request": + break + if len(body) < BODY_READ: + body += message.get("body", b"") + if not message.get("more_body"): + break + + async def replay(): + return held.pop(0) if held else await receive() + + async def sending(message): + if message["type"] == "http.response.start": + self.record(scope, _rpc(body) if body else "", message["status"], time.monotonic() - start) + await send(message) + await self.app(scope, replay, sending) + + @staticmethod + def record(scope, asked: str, status: int, took: float): + headers = dict(scope.get("headers") or []) + client = (scope.get("client") or ("?",))[0] + host = headers.get(b"host", b"").decode("latin-1") + what = f"{scope.get('method')} {scope.get('path')}" + (f" {asked}" if asked else "") + if status < 400: + requests_log.info("MCP %s: %s -> %d in %.2fs", client, what, status, took) + else: + why = WHY.get(status) + requests_log.warning("MCP %s refused: %s -> %d%s (Host %s)", client, what, status, f", {why}" if why else "", host or "none") + + def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", path: str = "/mcp"): """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (MCP_SERVICE_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth @@ -416,6 +488,7 @@ def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "lo streamable_http_path=path, transport_security=host_settings(allowed_hosts), auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None) if check else None, token_verifier=check) app.state.tokens = check + app.add_middleware(RequestLog) # (added last: outermost, so it sees the token's and the Host's refusals too) return app diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 739f0d3f..c26e8a5c 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -195,6 +195,7 @@ async def post_status(url) -> int: await asker log = caplog.text assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "1 token(s)" in log + assert "MCP 127.0.0.1: POST /mcp tools/call current -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] assert answered["direct"] == 421 @@ -229,3 +230,23 @@ async def test_the_bot_s_warning_says_why_the_service_refused_it(service, monkey with contextlib.suppress(asyncio.CancelledError): await task assert want in caplog.text, caplog.text + + +async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its_reason(service, caplog): + caplog.set_level("INFO", logger="lib.mcp_server.requests") + port = free_port() + url = f"http://127.0.0.1:{port}/mcp" + async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("127.0.0.1",)), port): + async with Client(http_transport(url, TOKENS["bot"]), mode="2026-07-28") as client: + assert not (await client.call_tool("about", {})).is_error + await client.read_resource("ecobot://health") + async with httpx.AsyncClient() as http: + await http.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, + headers={"Authorization": "Bearer wrong", "Accept": "application/json, text/event-stream"}) + await http.post(url, json={}, headers={"Authorization": f"Bearer {TOKENS['bot']}", "Host": "192.168.1.208:8765"}) + lines = [r.getMessage() for r in caplog.records if r.name == "lib.mcp_server.requests"] + assert any("MCP 127.0.0.1: POST /mcp tools/call about -> 200" in line for line in lines), lines + assert any("resources/read ecobot://health -> 200" in line for line in lines), lines + assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in MCP_SERVICE_TOKENS" in line for line in lines), lines + assert any("-> 421, its Host isn't in MCP_SERVICE_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines + assert not any(TOKENS["bot"] in line or "wrong" in line for line in lines) From dde2dc85e8a0d66560338ebf91534240dff4e76d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 01:26:34 +0000 Subject: [PATCH 074/125] Service request log: a tool call's readings, dates and interval after its name Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/mcp_server.py | 16 +++++++++++++++- tests/test_mcp_listen.py | 4 +++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/mcp_server.py b/lib/mcp_server.py index 7dc634b7..d0cedee8 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -429,10 +429,24 @@ def _rpc(body: bytes) -> str: continue params = m.get("params") if isinstance(m.get("params"), dict) else {} target = params.get("name") or params.get("uri") - out.append(f"{m['method']} {target}" if isinstance(target, str) else str(m["method"])) + line = f"{m['method']} {target}" if isinstance(target, str) else str(m["method"]) + if isinstance(args := params.get("arguments"), dict) and args: + line += " " + _arguments(args) + out.append(line) return ", ".join(out) +def _arguments(args: dict, most: int = 160) -> str: + """What a tool call asks for, short: its readings, its dates (the period as written, or start to end) and its interval + ("rain 1d", "outdoor.temperature 2026-11-01 to 2026-11-05 5min"), cut at `most` characters.""" + def text(v) -> str: + return ",".join(map(str, v)) if isinstance(v, list) else str(v) + metric = args.get("readings") or args.get("reading") + dates = args.get("period") or " to ".join(str(args[k]) for k in ("start", "end") if args.get(k)) + out = " ".join(text(v) for v in (metric, dates, args.get("interval")) if v not in (None, "", [])) + return out if len(out) <= most else out[:most - 1] + "…" + + class RequestLog: """ASGI middleware, outermost: one line per HTTP request, once its response starts (a listen stream's when it opens). INFO when answered, WARNING when refused, with the reason for a 401 (the token), a 421 (the Host) and a 404. The token itself is never diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index c26e8a5c..2f0ddbfd 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -195,7 +195,7 @@ async def post_status(url) -> int: await asker log = caplog.text assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "1 token(s)" in log - assert "MCP 127.0.0.1: POST /mcp tools/call current -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) + assert "MCP 127.0.0.1: POST /mcp tools/call current temperature -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] assert answered["direct"] == 421 @@ -239,6 +239,7 @@ async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("127.0.0.1",)), port): async with Client(http_transport(url, TOKENS["bot"]), mode="2026-07-28") as client: assert not (await client.call_tool("about", {})).is_error + await client.call_tool("summary", {"readings": ["rain"], "period": "1d", "chart": True}) await client.read_resource("ecobot://health") async with httpx.AsyncClient() as http: await http.post(url, json={"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, @@ -246,6 +247,7 @@ async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its await http.post(url, json={}, headers={"Authorization": f"Bearer {TOKENS['bot']}", "Host": "192.168.1.208:8765"}) lines = [r.getMessage() for r in caplog.records if r.name == "lib.mcp_server.requests"] assert any("MCP 127.0.0.1: POST /mcp tools/call about -> 200" in line for line in lines), lines + assert any("tools/call summary rain 1d -> 200" in line for line in lines), lines assert any("resources/read ecobot://health -> 200" in line for line in lines), lines assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in MCP_SERVICE_TOKENS" in line for line in lines), lines assert any("-> 421, its Host isn't in MCP_SERVICE_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines From d3d16f10d41d8659c486589a964aec0e18265c7d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 01:48:39 +0000 Subject: [PATCH 075/125] Service: charts as PNG images for a client that asks (?charts=png or _meta chart_image); the bot has its charts drawn by the service - lib/chart_images.py: whether a call wants images (request _meta chart_image "png"/"none", else the MCP URL's ?charts=png, read from the HTTP request the SDK hands the handler), the theme (DARKMODE, or _meta chart_dark), and the renderer (lib/charts.render_data), imported only at the first image; without Pillow, one warning and the JSON as before with a note. - lib/mcp_server.py: with images, the text block's charts are {title, period} with a chart_note for an attached image, one ImageContent per chart follows (drawn off the event loop, from every point unless the call says), the full chart JSON is in result _meta "ecobot/charts" and the theme in "ecobot/chart_dark"; a complete answer keeps its reply block, last. - Importing the server no longer imports Pillow (lib/periods and lib/alerts/pictures import the renderer when first drawing). - requirements.txt without Pillow; requirements-charts.txt pins it; requirements-dev.txt, the Dockerfile, the image job's paths and the README's install lines take both. - lib/weather.py: chart_image(name, args, meta) and picture(chart) (ChartImage: PNG, chart JSON, theme): in-process drawn with the same renderer, remote asked of the service in the bot's own theme (an alert's chart by replaying its drawn_by; drawn here if the service sends no image). The bot's _draw_call, period buttons, alert pictures and their refresh use it; the image cache keeps the theme it got. The model path, a question's charts and the gauges are unchanged. - Docs: mcp-service.md 3.7, step 5 and 6, testing; configuration.md; DEVELOPMENT.md; README. - Tests: off unchanged, per call and per connection under uvicorn, overrides both ways, without Pillow, no Pillow imported by the server (a subprocess), the remote bot's picture byte for byte the local render (a call and an alert's chart), and a service without Pillow drawn by the bot. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- .dockerignore | 1 + .github/workflows/ci.yml | 4 +- .github/workflows/docker.yml | 2 +- DEVELOPMENT.md | 20 ++++-- Dockerfile | 7 ++- README.md | 6 +- docs/configuration.md | 6 +- docs/mcp-service.md | 37 ++++++++++- ecobot.py | 2 +- ecobot.service | 2 +- ecobot_service/__main__.py | 2 + lib/alerts/notify.py | 10 +-- lib/alerts/pictures.py | 41 +++++++++--- lib/bot.py | 94 ++++++++++++++++++--------- lib/chart_images.py | 91 +++++++++++++++++++++++++++ lib/mcp_server.py | 77 +++++++++++++++++++---- lib/model_tools.py | 9 +-- lib/periods.py | 20 ++++-- lib/service/common.py | 13 +++- lib/weather.py | 108 ++++++++++++++++++++++++++++++- requirements-charts.txt | 3 + requirements-dev.txt | 1 + requirements.txt | 1 - scripts/update_charts.py | 2 +- tests/test_bot_remote.py | 40 ++++++++++++ tests/test_mcp_server.py | 119 ++++++++++++++++++++++++++++++++++- 26 files changed, 623 insertions(+), 95 deletions(-) create mode 100644 lib/chart_images.py create mode 100644 requirements-charts.txt diff --git a/.dockerignore b/.dockerignore index cc5365f9..c6c0ac0b 100644 --- a/.dockerignore +++ b/.dockerignore @@ -7,6 +7,7 @@ !schemas/ !scripts/ !requirements.txt +!requirements-charts.txt # the commit the log says it is running is read from these (a clone; the files are a few hundred bytes) !.git/HEAD !.git/refs/heads/ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd22f5e3..9f849626 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ env: jobs: test: - # The gate: the exact versions in requirements.txt (the ones production runs), tests and chart images included. + # The gate: the exact versions in requirements.txt and requirements-charts.txt (the ones production runs), tests and chart images included. if: github.event_name != 'schedule' runs-on: ubuntu-latest steps: @@ -58,7 +58,7 @@ jobs: newest: # Advisory, never blocks: the same tests with the newest Pillow. If the chart pictures differ, a new release - # draws things differently: look at the artifact, then bump the pins in requirements.txt and run scripts/update_charts.py. + # draws things differently: look at the artifact, then bump the pin in requirements-charts.txt and run scripts/update_charts.py. if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest continue-on-error: true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 7891d7f3..38355460 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -2,7 +2,7 @@ name: Docker image on: push: # any branch, so a pull request's commits carry the check too - paths: [Dockerfile, .dockerignore, requirements.txt, .github/workflows/docker.yml] + paths: [Dockerfile, .dockerignore, requirements.txt, requirements-charts.txt, .github/workflows/docker.yml] workflow_dispatch: permissions: diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 46fa6bb8..0c328df6 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -4,7 +4,7 @@ How to test the bot and what the GitHub checks do. (Running it is in `README.md` ## Tests ``` -pip install -r requirements-dev.txt +pip install -r requirements-dev.txt # requirements.txt, requirements-charts.txt (Pillow) and pytest python -m pytest # runs in parallel (pytest.ini); `-n0` for one process python scripts/eval_prompts.py # the saved questions: decisions made in code and the service expectations, no key needed ``` @@ -39,10 +39,14 @@ Only one process runs the service on a data folder: it holds `service.lock` ther a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set `WEATHER_MCP_URL` and restart the bot, then start the service; the bot waits for it and connects when it is up. Claude Code connects over HTTP: `claude mcp add --transport http ecobot http://127.0.0.1:8765/mcp --header "Authorization: Bearer "`. +A client that shows pictures can have the charts as images: `http://127.0.0.1:8765/mcp?charts=png` (or, per call, request `_meta` +`chart_image: "png"`; docs 3.7). Pillow (`requirements-charts.txt`) is imported only then: a service installed from `requirements.txt` alone +answers with the charts' JSON and a `chart_image_note`, and warns once. To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. Its tests: `tests/test_mcp_server.py` (the SDK's in-memory transport: every tool listed and answering as the ServiceTool does, each resource, -the alerts' template, the prompts, the publishing, the tokens) and `tests/test_mcp_listen.py` (the real app under uvicorn +the alerts' template, the prompts, the publishing, the tokens; the chart images asked per call and, under uvicorn, by the URL's +`?charts=png`, without Pillow, and that importing the server imports no Pillow) and `tests/test_mcp_listen.py` (the real app under uvicorn on a free localhost port: a client that listens loses its listen when the service stops and reads what it missed when it is back; the token and Host checks over HTTP; `python -m ecobot_service` with the fake sources, a tool call through a proxy's Host name). @@ -56,6 +60,10 @@ a backoff, listens again and reads the alerts after the last id it handled. Unse (`lib/weather.LocalWeather`). Both are one interface, `lib/weather.py`, which everything the bot asks of the service goes through: the model's tools and instructions, its shortcuts, report, gauges, charts drawn ahead and period buttons, Help and `/usage`, the alerts (lib/alerts/notify.AlertDelivery reads either log) and the irrigation check's rain and forecast (`ServiceRain`, `ServiceForecast`). +The charts the bot's own code asks for (charts drawn ahead, the period buttons, the alerts' pictures and their 🔄) come drawn by the +service (`chart_image`: the remote one sends its PNG, `chart_image: "png"` in the request's `_meta`, in the bot's own theme, `chart_dark`; +in-process, the same `lib/charts.render_data`); a question's charts (the model's answer, or a sentence answered in code) and the dashboard +(`lib/gauges.py`) are still drawn by the bot. ``` set -a; . <(sudo cat /etc/ecobot.env); set +a MCP_SERVICE_TOKENS=$TOKEN python -m ecobot_service & # the service, with the sources' settings @@ -65,17 +73,17 @@ In Docker (compose.yaml): in /etc/ecobot.env set `MCP_SERVICE_TOKENS=`, ` `WEATHER_MCP_TOKEN=` and `MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service`; then recreate the bot first (`sudo docker compose up -d --force-recreate ecobot`, which frees the data folder) and start the service (`sudo docker compose --profile service up -d ecobot-service`). Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a -question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through +question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, the service's PNG of a chart byte for byte the bot's own, an alert through the listen, the irrigation check's inputs; under uvicorn: a dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client). ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) | Job | When | What | |---|---|---| -| `test` | every push to `main` and every pull request | the exact versions in `requirements.txt`: pytest (chart pictures included) and the offline evals. The gate. | +| `test` | every push to `main` and every pull request | the exact versions in `requirements.txt` and `requirements-charts.txt`: pytest (chart pictures included) and the offline evals. The gate. | | `newest` | Sundays 21:17 UTC, or the Run workflow button | the tests with the newest Pillow. Advisory. | | `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` as the bot asks it (`python scripts/eval_prompts.py --live`: its prompt and the service's ten tools) and checks which tool it calls against `tests/evals/service_cases.json`; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 94. Skipped until the secrets below exist. | -| `image` | pushes that change `Dockerfile`, `.dockerignore` or `requirements.txt` (any branch), or the Run workflow button | builds the Docker image, checks the bot starts in it and names the commit, draws the sample charts in it (they must be in Inter and match `tests/charts`); the image's size goes in the run's summary. | +| `image` | pushes that change `Dockerfile`, `.dockerignore`, `requirements.txt` or `requirements-charts.txt` (any branch), or the Run workflow button | builds the Docker image, checks the bot starts in it and names the commit, draws the sample charts in it (they must be in Inter and match `tests/charts`); the image's size goes in the run's summary. | Repository secrets (Settings, Secrets and variables, Actions, New repository secret): - `OPENROUTER_API_KEY`: for `live-evals`. `OPENROUTER_MODEL` is optional (default `deepseek/deepseek-v4.1-flash-1017`): add it only if production runs another model. @@ -84,4 +92,4 @@ Repository secrets (Settings, Secrets and variables, Actions, New repository sec Dependabot (`.github/dependabot.yml`) opens weekly pull requests for the Python packages and the actions. `Pillow` comes in a group of its own, because the chart pictures depend on it. ## Chart pictures -Ten fixed sample charts and dashboards (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements.txt` because the pictures depend on it (charts and the dashboard are drawn with it, `lib/draw.py`); a Dependabot update whose chart test fails is the cue to redo the images. +Ten fixed sample charts and dashboards (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements-charts.txt` because the pictures depend on it (charts and the dashboard are drawn with it, `lib/draw.py`; the service needs it only for its chart images, so it is a file of its own); a Dependabot update whose chart test fails is the cue to redo the images. diff --git a/Dockerfile b/Dockerfile index 3e58a0ec..dc8d9dec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,10 +11,11 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends fonts-inter \ && mkdir /fonts \ && find /usr/share/fonts -name 'Inter-Regular.*' -o -name 'Inter-SemiBold.*' -o -name 'Inter-Bold.*' | xargs cp -t /fonts -COPY requirements.txt /tmp/ -# The base image's pip installs into a venv made without one +COPY requirements.txt requirements-charts.txt /tmp/ +# The base image's pip installs into a venv made without one; with Pillow (requirements-charts.txt): the bot draws its charts, and the +# service sends them as images when a client asks RUN python -m venv --without-pip /opt/venv \ - && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements.txt \ + && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements.txt -r /tmp/requirements-charts.txt \ && find /opt/venv -type d -name tests -prune -exec rm -rf {} + FROM base diff --git a/README.md b/README.md index ee9bcccc..1a5871e5 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ sudo python3.13 -m venv /opt/ecobot/.venv ``` ``` -sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt +sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt -r /opt/ecobot/requirements-charts.txt ``` ``` @@ -176,6 +176,8 @@ say) can use it with their own token from `MCP_SERVICE_TOKENS`: add your machine `MCP_SERVICE_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. It is plain HTTP: keep it on your own network. Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in `compose.yaml` to `127.0.0.1:8765:8765`. +A client that shows pictures can have the charts as images: add `?charts=png` to its URL (`http://192.168.1.5:8765/mcp?charts=png`). +The image has Pillow, which draws them; a service installed by hand from `requirements.txt` alone sends the charts' data instead. From then on, `sudo docker compose --profile service up -d --build` updates both. To go back: `sudo docker compose --profile service down` (it stops both), remove the lines from step 1, then `sudo docker compose up -d`. @@ -214,7 +216,7 @@ cd /opt/ecobot && sudo git pull ``` ``` -sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt +sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt -r /opt/ecobot/requirements-charts.txt ``` ``` diff --git a/docs/configuration.md b/docs/configuration.md index c8337bb1..4750e556 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,7 +70,7 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `CHART_ALL_FEELS_LIKE` | `off` | Add feels-like panel to "weather all week" | | `CHART_ALL_VPD` | `off` | Add VPD panel to "weather all week" | | `TELEGRAM_PRELOAD_CHAT` | off | Chat id (negative: group/channel) to pre-upload charts to: the other periods of each chart asked for, and, while the bot has been used in the last 15 minutes, the keyboard's charts every 5 minutes. Bot must be able to post there. Copies used for 30 min. Refused upload → no retry until restart | -| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the bot's time zone (the weather station's), light the rest of the day. The dashboard's gauges are dark whatever this says. | +| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the bot's time zone (the weather station's), light the rest of the day. The dashboard's gauges are dark whatever this says. The service reads it too, for the chart images it sends a client that asks for them (a call may say `chart_dark`); the bot as its client asks for its own theme, so this is the bot's setting for its pictures either way. | ### Storage and logging @@ -90,6 +90,8 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `MCP_SERVICE_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | | `MCP_SERVICE_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | +Chart images are not a setting of the service but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([mcp-service.md](mcp-service.md) 3.7). They need Pillow (`requirements-charts.txt`, in the Docker image): installed from `requirements.txt` alone the service answers with the charts' JSON and a note, and warns once. + ### The bot as the service's client @@ -98,6 +100,8 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. | `WEATHER_MCP_URL` | none | The service's MCP endpoint (`http://127.0.0.1:8765/mcp`, or its TLS address behind a proxy). Set: the bot is a client of the service ([mcp-service.md](mcp-service.md) step 5): it starts no sources, syncers or alert rules of its own, so the source settings (`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `POLLEN`, `FORECAST` …) are the service's and the bot needs none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are) and the alerts come from the service. Unset: the bot runs the service inside itself, as before | | `WEATHER_MCP_TOKEN` | none | The bearer token the bot sends: one of the service's `MCP_SERVICE_TOKENS` (give the bot its own) | +The bot asks the service for the pictures of the charts it draws ahead, of the period buttons and of the alerts (request `_meta` `chart_image: "png"`, in its own `DARKMODE` theme), so its `WEATHER_MCP_URL` needs no `?charts=png`; a question's charts and the dashboard it still draws itself. + While the service can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the alerts sent meanwhile that are still news are delivered once it is back. The irrigation controller (`TUYA_*`) stays the bot's: its daily check asks the service for the rain measured and the forecast. diff --git a/docs/mcp-service.md b/docs/mcp-service.md index a82da227..134c49bb 100644 --- a/docs/mcp-service.md +++ b/docs/mcp-service.md @@ -375,8 +375,23 @@ Charts are data: the client draws them, or its model does from the numbers. turn*. Our bot follows the rule while it lives, and any bot can; a client that doesn't (a desktop assistant) gives the result to its model as usual, which then has the reply ready to repeat. A result with no chart, an error or a note that needs the model's words is never complete. -- **Our bot**, while it lives, draws `charts` with its renderer (`lib/charts.py`, reading the JSON) and sends the picture; the rain - caption reads its bars. The renderer leaves with the bot. +- **Or as images, for a client that asks.** A client that shows pictures but can't draw JSON asks for the charts drawn: per connection + with its MCP URL's query, `/mcp?charts=png` (any client can set a URL; not all can set headers), or per call with request `_meta` + `chart_image: "png"` (or `"none"`, which overrides the connection's). Off by default: without it the result is as above, unchanged. + With it, a result with charts carries its JSON text with each chart's data replaced by `{title, period}` and a `chart_note` that fits + the image (the chart is the image attached: keep the text to the figures, don't describe it), then one `ImageContent` (`image/png`, + base64) per chart, in order; the full chart JSON, each with its `drawn_by` (what the period buttons replay), is in result `_meta` + `"ecobot/charts"`, for applications, and the theme in `"ecobot/chart_dark"`. A complete answer keeps its `reply` block for the + person, after the images, and `"ecobot/complete"`. The pictures are the bot's: the same renderer (`lib/charts.render_data`, Pillow, + run off the event loop), from every point (`chart_points` `"drawn"` unless the call says otherwise), so they and the golden images + don't change; dark per `DARKMODE`, or request `_meta` `chart_dark: true|false`. Pillow is optional on the service + (`requirements-charts.txt`) and imported at the first image asked for: without it the warning is logged once, and the result is the + JSON as if no image had been asked for, with `chart_image_note` saying images aren't available on this service. +- **Our bot**, while it lives, has the charts its own code asks for (charts drawn ahead, the period buttons, the alerts' pictures and + their 🔄) drawn by the service: in-process with the same renderer, remote as images (`chart_image: "png"`, in its own theme, + `chart_dark`, which it keeps with each picture in its image cache), so a remote bot draws none of those itself. A question's charts + (the model's answer, or a sentence answered in code) it still draws from `charts` (`lib/charts.py`, reading the JSON); the rain caption + reads its bars; the model is sent the charts' titles, never an image. The dashboard's gauges (`lib/gauges.py`) stay the bot's for now. ### 3.8 Connecting @@ -605,9 +620,22 @@ Each step ships on its own, with the tests and evals green and the bot working t the remote tools and the instructions from discover, a chart from a remote result with its buttons, an alert through the listen, a dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client); the path with the setting unset is the rest of the suite, unchanged. + - **Chart images (done).** The service draws a result's charts as PNGs for a client that asks (3.7: `?charts=png` on its URL, or + request `_meta` `chart_image`; `chart_dark`; the full JSON in result `_meta` `"ecobot/charts"`, the theme in `"ecobot/chart_dark"`), + with `lib/chart_images.py`, which imports Pillow and the renderer only at the first image (Pillow is `requirements-charts.txt`; + without it, the JSON with a note and one warning). `lib/weather.py` gains `chart_image(name, args, meta)` and `picture(chart)` + (`ChartImage`: the PNG, the chart's JSON, the theme): `LocalWeather` draws in-process with `lib/charts.render_data`, + `RemoteWeather` asks the service and takes the PNG from the `ImageContent` and the chart and theme from `_meta` (an alert's + chart by replaying its `drawn_by`; a service that sends no image has it drawn here). The bot's `_draw_call` (charts drawn ahead, + preloads, the 🔄 under an alert), the period buttons and the alerts' pictures (`lib/alerts/pictures.py`, `AlertDelivery`) use it; + the image cache keeps the theme the service drew in. The model path is unchanged; a question's charts and the dashboard are still + drawn by the bot. Tests: `tests/test_mcp_server.py` (in memory and under uvicorn: off unchanged, the URL's `?charts=png`, the + per-call override both ways, without Pillow, no Pillow imported by the server), `tests/test_bot_remote.py` (the service's PNG + byte for byte the bot's own, for a call and an alert's chart). - **Left: 5b**, the irrigation server in its own repository (3.9: its tools, the watchdog and the daily check, `irrigation://alerts`), the bot connecting to both and `lib/irrigation` going from here; and `show_request` and `report_inputs` as MCP clients. -6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. +6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. The renderer stays, for the service's + chart images (3.7), and the gauges go with the bot unless they move to the service first. ## 7. Testing @@ -633,6 +661,9 @@ Each step ships on its own, with the tests and evals green and the bot working t connection can't fail there, and the in-memory HTTP transport buffers a listen stream): the listen is lost, the client listens again and reads the alerts after its last id; the bot's model request carries the instructions from discover. - **A deploy check:** a tool call through the proxy's name succeeds (the allowed hosts and the token). +- **Chart images:** off, a result is as it was; asked by the URL (under uvicorn) or per call, each chart comes as a PNG byte for byte + the bot's own render, its JSON in `_meta`; a call overrides its connection both ways; without Pillow, the JSON with a note and one + warning; importing the server imports no Pillow. ## 8. Risks diff --git a/ecobot.py b/ecobot.py index 846fe45f..6ee5ea2c 100644 --- a/ecobot.py +++ b/ecobot.py @@ -67,7 +67,7 @@ def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Co feed, station, forecast = core.alert_log, bot.by_name.get("Ecowitt"), bot.by_name.get("Forecast") else: running, feed, station, forecast = [], weather.alerts, ServiceRain(weather), weather.forecast - delivery = AlertDelivery(feed, notify, bot.state, cfg.tz) + delivery = AlertDelivery(feed, notify, bot.state, cfg.tz, weather=bot.weather) # (its charts drawn by the service) zoned: list = [delivery] tasks.start(delivery.run()) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run diff --git a/ecobot.service b/ecobot.service index 3ae0ee0d..68311b71 100644 --- a/ecobot.service +++ b/ecobot.service @@ -1,6 +1,6 @@ # Install as /etc/systemd/system/ecobot.service, with the code outside every home directory: # sudo git clone /opt/ecobot && cd /opt/ecobot -# sudo python3.13 -m venv .venv && sudo .venv/bin/pip install -r requirements.txt # Python 3.13.5 (.python-version) +# sudo python3.13 -m venv .venv && sudo .venv/bin/pip install -r requirements.txt -r requirements-charts.txt # Python 3.13.5 (.python-version) # The files stay owned by root and readable by all: the service runs as a throw-away user (DynamicUser=) that cannot write to them, # so its bytecode goes to /var/cache/ecobot (CacheDirectory=, PYTHONPYCACHEPREFIX=) and is rebuilt on its own after an update. # Any other place needs only the WorkingDirectory and ExecStart lines changed. diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py index 7d874d7f..ecd0d580 100644 --- a/ecobot_service/__main__.py +++ b/ecobot_service/__main__.py @@ -15,6 +15,7 @@ import uvicorn +from lib import chart_images from lib.config import Config from lib.logs import LogFormat, on_journal, stream_handlers @@ -62,6 +63,7 @@ async def main(): configure(cfg) async with contextlib.AsyncExitStack() as stack: sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on + chart_images.configure(cfg.dark_mode, cfg.tz) # DARKMODE for the charts' images, when a client asks for them (Pillow not imported yet) for source in sources: stack.push_async_callback(source.close) if not sources: diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 8c3a50ae..96df9c74 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -272,10 +272,12 @@ class AlertDelivery: the log can also be replaced while the bot runs (the service back on another alerts.sqlite): that is looked for on every pass, and delivery goes on in the new log with what came since the old one was last read (_switched).""" - def __init__(self, log, notify: "Notifier", state: AlertState, tz, now: Callable[[], float] = time.time): + def __init__(self, log, notify: "Notifier", state: AlertState, tz, now: Callable[[], float] = time.time, weather=None): """log: the alert log in this process (lib/alert_log.py), or the remote service's read over MCP (lib/weather.RemoteAlerts, whose - reads are coroutines: it is looked at when `run` starts). now: the epoch clock (the events' times are compared with it).""" - self.log, self.notify, self.state, self.tz, self.now = log, notify, state, tz, now + reads are coroutines: it is looked at when `run` starts). now: the epoch clock (the events' times are compared with it). + weather: the service as the bot reaches it (lib/weather.py), which draws the events' charts (a remote one, on the service); + without it they are drawn here.""" + self.log, self.notify, self.state, self.tz, self.now, self.weather = log, notify, state, tz, now, weather self.begun = False self.seen_at: float | None = None # when the log was last read through (a pass of deliver_new began): see _switched if not getattr(log, "remote", False): @@ -378,5 +380,5 @@ async def deliver(self, event: dict) -> int: since = None async def chart() -> Picture | None: - return await picture_of(data, self.tz) + return await (picture_of(data, self.tz) if self.weather is None else picture_of(data, self.tz, self.weather)) return await self.notify(event["text"], kind=event["kind"], link=link, chart=chart, since=since, event=event["id"]) diff --git a/lib/alerts/pictures.py b/lib/alerts/pictures.py index d3f646f9..5e0fff1e 100644 --- a/lib/alerts/pictures.py +++ b/lib/alerts/pictures.py @@ -1,7 +1,8 @@ """The chart that goes with an alert: the same picture a typed request for it would give ("Wind chart 1d" is what the Wind button sends), so what an alert shows is defined once, by the button sentences, each a fixed service call (lib/intent.chart_call: "Wind chart 1d" is summary {readings: ["wind"], period: "1d", chart: true}), which the service draws: the rule puts the chart's data, with its drawn_by, in the alert's -event (chart_data), and the bot draws it (picture_of). AlertCharts keeps those charts with the bot's other charts (the ImageCache, +event (chart_data), and the bot has it drawn (picture_of: by the weather service it reaches, lib/weather.py, which a remote service draws +by replaying the chart's drawn_by). AlertCharts keeps those charts with the bot's other charts (the ImageCache, by call), so one is drawn once and uploaded once however many times it is sent.""" import asyncio @@ -12,7 +13,6 @@ from typing import Callable, NamedTuple from .. import intent -from ..charts import render_data from ..periods import call_key from ..specs import from_json from ..timeutil import now_local @@ -21,7 +21,13 @@ # The alert types that carry a chart, and the request it answers: what the alert is sent with, and what its Refresh draws again CHARTS = {"gusts": "Wind chart 1d", "uv": "UV chart 1d", "temps": "Temperature chart 1d", "particulates": "Particulates chart 1d"} -CHART_POINTS = "drawn" # every point, as drawn (lib/service/common.py AS_DRAWN): the bot draws the chart itself +CHART_POINTS = "drawn" # every point, as drawn (lib/service/common.py AS_DRAWN): the bot's picture + + +def render_data(data: dict, tz, *args, **kwargs) -> bytes: + """lib/charts.render_data, imported when first drawn: the service imports this module for chart_data, and draws nothing here.""" + from ..charts import render_data as render + return render(data, tz, *args, **kwargs) class Picture(NamedTuple): @@ -30,6 +36,7 @@ class Picture(NamedTuple): title: str newest: int | None # the time of the newest reading it draws (epoch), when the chart tells it drawn_by: dict | None = None # the call that draws it again + dark: bool | None = None # drawn in the dark theme (None: the theme charts are drawn in now) def call_of(text: str, now: datetime, tz: tzinfo) -> tuple[str, dict] | None: @@ -61,9 +68,18 @@ async def chart_data(source, text: str, tz, service=None) -> dict | None: return None -async def picture_of(data: dict, tz) -> Picture | None: - """A chart given as data, drawn (by the bot's renderer); None when it cannot be.""" +def _picture(image, tz) -> Picture: + """A lib/weather.ChartImage as an alert's Picture.""" + spec = from_json(image.chart) + return Picture(image.png, spec.caption(now_local(tz).date()), spec.newest, image.chart.get("drawn_by"), image.dark) + + +async def picture_of(data: dict, tz, weather=None) -> Picture | None: + """A chart given as data, drawn: by `weather` (the service as the bot reaches it, lib/weather.py: a remote one draws it), else by + the bot's renderer here; None when it cannot be.""" try: + if weather is not None: + return _picture(await weather.picture(data), tz) spec = from_json(data) return Picture(await asyncio.to_thread(render_data, data, tz), spec.caption(now_local(tz).date()), spec.newest, data.get("drawn_by")) except Exception as e: @@ -72,7 +88,18 @@ async def picture_of(data: dict, tz) -> Picture | None: async def chart(source, text: str, tz, service=None) -> Picture | None: - """The chart for the request `text`, drawn by the service the way the bot would answer it; None when it cannot be made.""" + """The chart for the request `text`, drawn by the service the way the bot would answer it; None when it cannot be made. `service` + may be the weather service as the bot reaches it (lib/weather.py), which draws it (a remote one, on the service).""" + if getattr(service, "is_weather", False): + try: + tool, args = call_of(text, now_local(tz), tz) + out, image = await service.chart_image(tool, args, {"chart_points": CHART_POINTS}) + if image is None: + raise ValueError(out.get("error") or "no chart") + return _picture(image, tz) + except Exception as e: + log.warning("The chart for the alert (%s) couldn't be made: %s: %s", text, type(e).__name__, e) + return None data = await chart_data(source, text, tz, service) return await picture_of(data, tz) if data else None @@ -120,7 +147,7 @@ def held(self, kind: str, since: int | None) -> bytes | str | None: def keep(self, kind: str, picture: Picture, since: int | None = None): """A chart just drawn for an alert of `kind` (about the reading `since`: it draws that reading, whatever its own time says).""" newest = max((t for t in (picture.newest, since) if t is not None), default=None) - self.images.put(self.key(kind), picture.png, picture.title, newest=newest, drawn_by=picture.drawn_by) + self.images.put(self.key(kind), picture.png, picture.title, newest=newest, drawn_by=picture.drawn_by, dark=picture.dark) def sent(self, kind: str, message, alerted: bool = True): """The chart of `kind` went out in `message` (as Telegram returned it): later sends use Telegram's copy. An alert (not a Refresh) diff --git a/lib/bot.py b/lib/bot.py index d491e20a..e14f7612 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -41,7 +41,7 @@ from .llm import Agent, shorten_old, strip_tool_turns, trim_history from .logs import BUGS, QUOTES, fit from .warm import Tasks # (the service's too: ecobot_service) -from .weather import UNREACHABLE, LocalWeather, ServiceUnreachable +from .weather import UNREACHABLE, ChartImage, ChartNotDrawn, LocalWeather, ServiceUnreachable log = logging.getLogger(__name__) @@ -387,6 +387,17 @@ async def deliver(msg: Message, text: str, photos: list[bytes], link: tuple[str, return Delivered(on_text and bool(text), sent) +class CallChart(NamedTuple): + """The chart a service call draws (Bot._draw_call).""" + png: bytes + title: str + caption: str | None # its words (the answer's caption, or answer) + newest: int | None # the time of its newest reading + drawn_by: dict | None # the call that draws it again + out: dict # the whole answer + dark: bool | None = None # drawn in the dark theme (None: as charts are drawn now) + + class Bot: def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: AlertState, irrigation=None, tasks: Tasks | None = None, service: Service | None = None, alert_log=None): @@ -400,7 +411,7 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler chart's drawn_by in.""" self.cfg, self.agent, self.sources, self.state, self.irrigation = cfg, agent, sources, state, irrigation self.weather = service if getattr(service, "is_weather", False) else \ - LocalWeather(sources, service, alert_log, tz=getattr(cfg, "tz", None)) + LocalWeather(sources, service, alert_log, tz=getattr(cfg, "tz", None), render=self._render) self.tasks = tasks or Tasks() self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends self.keyboard_version = templates.version(irrigation is not None) @@ -432,20 +443,33 @@ def names(self) -> set[str]: async def _service_call(self, tool: str, args: dict, ahead: bool = False) -> dict: """A service tool's answer as data: its charts as drawn (AS_DRAWN, so its pictures are as they were), a chart drawn ahead (nobody waiting) as a background request. {"error": ...} when it refuses or fails.""" + return (await self._call(tool, args, ahead))[0] + + async def _chart_call(self, tool: str, args: dict, ahead: bool = False, alone: bool = False) -> tuple[dict, ChartImage | None]: + """(a service tool's answer as data, as _service_call; its first chart drawn by the service, lib/weather.py chart_image: None + without one, or with more than one when `alone`). ChartNotDrawn when the chart came but can't be drawn.""" + return await self._call(tool, args, ahead, chart=True, alone=alone) + + async def _call(self, tool: str, args: dict, ahead: bool, chart: bool = False, alone: bool = False) -> tuple[dict, ChartImage | None]: found = self.service.get(tool) if found is None: - return {"error": f"There is no {tool} here."} + return {"error": f"There is no {tool} here."}, None meta = {"chart_points": AS_DRAWN, **({"priority": BACKGROUND} if ahead else {})} log.debug("Service call %s %s", tool, json.dumps(args, ensure_ascii=False), extra=QUOTES) try: - out = json.loads(await found.call(args, meta)) + if chart: + out, image = await self.weather.chart_image(tool, args, meta, alone=alone) + else: + out, image = json.loads(await found.call(args, meta)), None + except ChartNotDrawn: + raise except ServiceUnreachable as e: # (a remote service while it is being reached again: said once the person asks, _answer) (log.debug if ahead else log.warning)("Service tool %s: %s", tool, e) - return {"error": str(e)} + return {"error": str(e)}, None except Exception as e: log.error("Service tool %s failed: %s: %s", tool, type(e).__name__, e, exc_info=isinstance(e, BUGS)) - return {"error": f"{type(e).__name__}: {e}"} - return out if isinstance(out, dict) else {"error": "not an answer"} + return {"error": f"{type(e).__name__}: {e}"}, None + return (out, image) if isinstance(out, dict) else ({"error": "not an answer"}, None) def _catalogue(self): """The readings the service holds (the words of a shortcut are read against them).""" @@ -460,20 +484,31 @@ def _sentence_call(self, text: str, now: datetime) -> tuple[str, dict] | None: return intent.chart_call(text, now, self.cfg.tz, self._catalogue()) def _draw(self, chart: dict, times: dict | None = None) -> tuple[bytes, str, int]: - """(PNG, title, the time of its newest reading) of a chart given as data.""" + """(PNG, title, the time of its newest reading) of a chart given as data (a model's answer's: drawn here).""" spec = from_json(chart) return render_data(chart, self.cfg.tz, times), spec.caption(now_local(self.cfg.tz).date()), spec.newest - async def _draw_call(self, tool: str, args: dict, ahead: bool = True) -> tuple[bytes, str, str | None, int, dict | None, dict] | None: - """(PNG, title, its words, newest reading, drawn_by, the answer) of the chart a call draws; None when it draws none (the refusal - logged).""" - out = await self._service_call(tool, args, ahead=ahead) - charts = out.get("charts") or [] - if "error" in out or len(charts) != 1: + @staticmethod + def _render(chart: dict, tz, dark: bool | None = None) -> tuple[bytes, bool]: + """(PNG, dark) of a chart given as data: how the service in this process draws (LocalWeather's render). dark None: as DARKMODE + says now.""" + drawn_dark = periods.dark_now() if dark is None else dark + return (render_data(chart, tz) if dark is None else render_data(chart, tz, dark=dark)), drawn_dark + + def _titled(self, chart: dict) -> tuple[str, int | None]: + """(title, the time of its newest reading) of a chart given as data.""" + spec = from_json(chart) + return spec.caption(now_local(self.cfg.tz).date()), spec.newest + + async def _draw_call(self, tool: str, args: dict, ahead: bool = True) -> "CallChart | None": + """(PNG, title, its words, newest reading, drawn_by, the answer, dark) of the chart a call draws, drawn by the service; None when + it draws none (the refusal logged).""" + out, image = await self._chart_call(tool, args, ahead=ahead, alone=True) + if "error" in out or image is None: log.debug("No chart from %s %s: %s", tool, args, out.get("error")) return None - png, title, newest = await asyncio.to_thread(self._draw, charts[0]) - return png, title, out.get("caption") or out.get("answer"), newest, charts[0].get("drawn_by"), out + title, newest = await asyncio.to_thread(self._titled, image.chart) + return CallChart(image.png, title, out.get("caption") or out.get("answer"), newest, image.chart.get("drawn_by"), out, image.dark) def register(self, app): app.add_handler(CommandHandler(["start", "help"], self.on_start)) @@ -741,10 +776,10 @@ async def _redraw_alert(self, query, kind: str, event: int | None = None): try: if call := await self._alert_call(kind, event): made = await asyncio.wait_for(self._draw_call(*call, ahead=False), TURN_SECONDS) - picture = pictures.Picture(made[0], made[1], made[3], made[4]) if made else None + picture = pictures.Picture(made[0], made[1], made[3], made[4], getattr(made, "dark", None)) if made else None else: picture = await asyncio.wait_for(pictures.chart(self.by_name.get(menu.TYPES[kind][1]), pictures.CHARTS[kind], self.cfg.tz, - self.service), TURN_SECONDS) + self.weather), TURN_SECONDS) except TimeoutError: picture = None if picture is None: # (pictures.chart has said why) the message stays as it was @@ -982,19 +1017,18 @@ async def drawing(label: str): log.debug("Period button: cached chart sent in %.0f ms%s", (time.monotonic() - began) * 1000, " (Telegram's copy)" if isinstance(held.photo, str) else "") return - try: - out = await asyncio.wait_for(self._service_call(tool, args), TURN_SECONDS) + try: # (drawn before the toast, so a failure can be toasted) + out, image = await asyncio.wait_for(self._chart_call(tool, args), TURN_SECONDS) except TimeoutError: - out = {"error": "That took too long, please try again"} - charts = out.get("charts") or [] - if "error" in out or not charts: + out, image = {"error": "That took too long, please try again"}, None + if "error" in out or image is None: await toast_quietly(query, fit(str(out.get("error") or "No chart came of it for that period"), TOAST_LIMIT)) return - png, title, newest = await asyncio.to_thread(self._draw, charts[0]) # (drawn before the toast, so a failure can be toasted) + png, (title, newest) = image.png, await asyncio.to_thread(self._titled, image.chart) await drawing(label) - drawn = charts[0].get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} + drawn = image.chart.get("drawn_by") or {"tool": tool, "arguments": args, "periods": drawn_by.get("periods")} text = out.get("caption") or out.get("answer") or "" - self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn) + self.images.put(key, png, title, text or None, newest=newest, drawn_by=drawn, dark=image.dark) row = periods.periods_keyboard(drawn, period, now, self.cfg.tz) if not await self._redraw(message, text if words else "", png, title, row, {"drawn_by": drawn, "words": words}, key): sent = await deliver(message, text if words else "", [png], titles=[title], period_row=row) @@ -1267,8 +1301,8 @@ async def upload(period, args): return if drawn is None: return - png, title, caption, newest, by, _ = drawn - self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest, drawn_by=by) + png, title, caption, newest, by = drawn[:5] + self.images.put(key, png, title, caption, ttl=self.images.PRELOAD_TTL, newest=newest, drawn_by=by, dark=drawn.dark) if self.preload_off: # an upload was refused meanwhile return if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: @@ -1321,8 +1355,8 @@ async def draw_buttons_ahead(self, bot): continue if made is None: # it drew no chart (its source is not there) continue - png, title, caption, newest, drawn_by, _ = made - self.images.put(key, png, title, caption, newest=newest, drawn_by=drawn_by) + png, title, caption, newest, drawn_by = made[:5] + self.images.put(key, png, title, caption, newest=newest, drawn_by=drawn_by, dark=made.dark) drawn += 1 if chat is not None and not self.preload_off: if (why := await self._upload_ahead(bot, chat, key, png, title)) is not None: diff --git a/lib/chart_images.py b/lib/chart_images.py new file mode 100644 index 00000000..a401442a --- /dev/null +++ b/lib/chart_images.py @@ -0,0 +1,91 @@ +"""Chart images: a chart's JSON (schemas/chart.json) drawn as a PNG by the bot's renderer (lib/charts.render_data, Pillow), for the +service's tools when a client asks for images (docs/mcp-service.md 3.7) and for the bot's interface to the service (lib/weather.py). + +Pillow is optional on the service (requirements-charts.txt): nothing here imports it, nor lib.charts or lib.draw, until the first image +is asked for (`renderer`). Without it `renderer()` is None, said once as a warning, and the service answers with the charts' JSON as if +no image had been asked for, with UNAVAILABLE_NOTE. + + - `configure(mode, tz)`: the service's DARKMODE (lib/config.py's dark_mode) and the zone a time range is read in, handed to + lib.charts (charts.configure) when it is first imported here, or at once when it already is (the bot's process configures it itself); + - `wanted(meta, query)`: does a tool call want images: the request's `_meta` `chart_image` ("png" or "none"), else the connection's + MCP URL's query (`?charts=png`), else not; + - `render(chart, tz, dark)`: (PNG, dark), as the bot draws it; dark None: as DARKMODE says now (charts.dark_now).""" + +import importlib +import logging +import sys +from datetime import tzinfo + +log = logging.getLogger(__name__) + +PNG = "image/png" +IMAGE, NO_IMAGE = "png", "none" # request _meta chart_image, and the URL's ?charts=: images, or the JSON alone (the default) +CHARTS_META = "ecobot/charts" # result _meta with images: the full chart JSON, each with its drawn_by (3.7) +DARK_META = "ecobot/chart_dark" # result _meta with images: drawn in the dark theme (true) or the light (false) +IMAGE_NOTE = ("The chart is the image attached to this result: show it with your reply. Keep your text to the figures; don't describe " + "the chart.") +UNAVAILABLE_NOTE = "Chart images aren't available on this service: the chart's data is in `charts`." +NOT_DRAWN_NOTE = "The chart's image couldn't be drawn: the chart's data is in `charts`." +MODE: str | tuple[int, int] | None = None # the service's DARKMODE, once configured (None: as lib.charts is) +ZONE: tzinfo | None = None +_warned = False +_handed: tuple | None = None # the (MODE, ZONE) last handed to lib.charts + + +def configure(mode: str | tuple[int, int], tz: tzinfo | None = None): + """The service's DARKMODE and the zone it is read in, for its images (lib.charts.configure once lib.charts is imported).""" + global MODE, ZONE + MODE, ZONE = mode, tz + if (charts := sys.modules.get("lib.charts")) is not None: + _hand(charts) + + +def _hand(charts): + global _handed + if MODE is not None and _handed != (MODE, ZONE): + charts.configure(MODE, ZONE) + _handed = (MODE, ZONE) + + +def renderer(): + """lib.charts, imported now if it hasn't been (and given the service's DARKMODE); None when Pillow isn't installed (said once).""" + global _warned + try: + charts = importlib.import_module("lib.charts") + except ImportError as e: + if not _warned: + _warned = True + log.warning("Chart images were asked for but can't be drawn here (%s): install requirements-charts.txt (Pillow); " + "the charts are sent as JSON alone", e) + return None + _hand(charts) + return charts + + +def wanted(meta: dict | None, query: str | None = None) -> bool: + """Images for this call? The request's _meta `chart_image` ("png" or "none") decides; else the connection's (the MCP URL's + `?charts=png`, `query`); else not.""" + asked = str((meta or {}).get("chart_image") or "").strip().lower() + if asked in (IMAGE, NO_IMAGE): + return asked == IMAGE + return str(query or "").strip().lower() == IMAGE + + +def asked_dark(meta: dict | None) -> bool | None: + """The request's _meta `chart_dark` (true or false); None when not sent (DARKMODE decides).""" + dark = (meta or {}).get("chart_dark") + return dark if isinstance(dark, bool) else None + + +def render(chart: dict, tz: tzinfo, dark: bool | None = None) -> tuple[bytes, bool]: + """(PNG, dark) of a chart given as its JSON, as the bot draws it (lib.charts.render_data). Raises ImportError without Pillow, + ValueError for JSON that isn't a chart.""" + charts = renderer() + if charts is None: + raise ImportError("Pillow isn't installed: chart images can't be drawn") + dark = charts.dark_now() if dark is None else dark + return charts.render_data(chart, tz, dark=dark), dark + + +__all__ = ["CHARTS_META", "DARK_META", "IMAGE", "IMAGE_NOTE", "NOT_DRAWN_NOTE", "NO_IMAGE", "PNG", "UNAVAILABLE_NOTE", "asked_dark", + "configure", "render", "renderer", "wanted"] diff --git a/lib/mcp_server.py b/lib/mcp_server.py index d0cedee8..c620a9aa 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -8,6 +8,12 @@ `_meta` (`chart_points`, `fetch`, `priority`: common.request_meta) and answers its JSON as one text block, unchanged: its charts are the full chart JSON (3.7), sized by `chart_points`. A refusal is `isError`. A complete answer (3.7: `chart_answers_it` and a chart) also carries its `reply` as a second text block for the person (`audience: ["user"]`) and result `_meta` {"ecobot/complete": true}. + - **Chart images** (3.7, lib/chart_images.py), for a connection whose MCP URL asks (`/mcp?charts=png`) or a call whose `_meta` does + (`chart_image`: "png", or "none" against the connection's): the text block's charts are each {title, period} with a `chart_note` that + fits an attached image, followed by one ImageContent (image/png) per chart in order, drawn as the bot draws them (lib/charts, + off the event loop) from every point (`chart_points` "drawn" unless the call says); the full chart JSON, with drawn_by, is in + result `_meta` "ecobot/charts" and the theme in "ecobot/chart_dark" (DARKMODE, or the call's `chart_dark`). Pillow is imported at + the first image: without it the answer is the JSON as without images, with `chart_image_note` saying so. - **Resources** (3.4): RESOURCES, and the alerts with `since` and `expired` (the ALERTS_TEMPLATE). Each is JSON. The live ones are published as ResourceUpdated when they change (`publish_changes`, every PUBLISH_SECONDS, from what the sources keep: no request is made for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`watch_alerts`, lib/alert_log.py @@ -21,6 +27,7 @@ fetches, alerts or writes: ecobot_service runs the sources and the rules.""" import asyncio +import base64 import hmac import json import logging @@ -39,13 +46,15 @@ from mcp.server.transport_security import TransportSecuritySettings from mcp.shared.exceptions import MCPError +from . import chart_images from .config import ROOT from .service import Service from .service.about import AboutTool, alerts as alert_kinds -from .service.common import iso +from .service.common import AS_DRAWN, charts_as_titles, iso from .service.current import CurrentTool from .service.instructions import instructions from .service.names import AIR_DEVICE, STATION, Catalogue +from .tools import json_result log = logging.getLogger(__name__) requests_log = logging.getLogger(__name__ + ".requests") # one line per HTTP request (RequestLog) @@ -125,19 +134,45 @@ def tool_entry(tool) -> types.Tool: annotations=types.ToolAnnotations(read_only_hint=tool.read_only, open_world_hint=tool.open_world)) -def tool_result(text: str) -> types.CallToolResult: - """A ServiceTool's answer as tools/call gives it: the JSON as one text block, unchanged; `isError` for a refusal; a complete answer - (3.7) with its reply for the person as a second block (audience user) and result _meta {COMPLETE: true}.""" +def _loads(text: str): try: - data = json.loads(text) + return json.loads(text) except ValueError: - data = None - content: list = [types.TextContent(text=text)] - meta = None + return None + + +def charts_of(data) -> list[dict]: + """The charts of a tool's answer (none for a refusal).""" + charts = data.get("charts") if isinstance(data, dict) and "error" not in data else None + return charts if isinstance(charts, list) and charts and all(isinstance(c, dict) for c in charts) else [] + + +def tool_result(text: str, images: list[bytes] | None = None, dark: bool | None = None, note: str | None = None) -> types.CallToolResult: + """A ServiceTool's answer as tools/call gives it: the JSON as one text block, unchanged; `isError` for a refusal; a complete answer + (3.7) with its reply for the person as a last block (audience user) and result _meta {COMPLETE: true}. With `images` (a PNG per + chart): the charts in the text as {title, period} and chart_note IMAGE_NOTE, an ImageContent per chart after it, and result _meta + {CHARTS_META: the full charts, DARK_META: dark}. `note`: why images asked for aren't there (`chart_image_note`).""" + data = _loads(text) + content: list = [] + meta = {} + if images and (charts := charts_of(data)) and len(images) == len(charts): + content.append(types.TextContent(text=json_result(charts_as_titles(data, chart_images.IMAGE_NOTE)))) + content += [types.ImageContent(data=base64.b64encode(png).decode("ascii"), mime_type=chart_images.PNG) for png in images] + meta.update({chart_images.CHARTS_META: charts, chart_images.DARK_META: bool(dark)}) + elif note and charts_of(data): + content.append(types.TextContent(text=json_result({**data, "chart_image_note": note}))) + else: + content.append(types.TextContent(text=text)) if isinstance(data, dict) and data.get("complete") is True and isinstance(data.get("reply"), str) and "error" not in data: content.append(types.TextContent(text=data["reply"], annotations=types.Annotations(audience=["user"]))) - meta = {COMPLETE: True} - return types.CallToolResult(content=content, is_error=isinstance(data, dict) and "error" in data, _meta=meta) + meta[COMPLETE] = True + return types.CallToolResult(content=content, is_error=isinstance(data, dict) and "error" in data, _meta=meta or None) + + +def connection_query(ctx, name: str) -> str | None: + """A query parameter of the connection's MCP URL (`/mcp?charts=png`), from the HTTP request the call came in (None in memory).""" + params = getattr(getattr(ctx, "request", None), "query_params", None) + return params.get(name) if params is not None else None # ---------- auth ---------- @@ -205,7 +240,23 @@ async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.Ca tool = self._service.get(params.name) if tool is None: raise MCPError(types.INVALID_PARAMS, f"No tool {params.name!r}: the tools are {', '.join(t.name for t in self._service)}.") - return tool_result(await tool.call(params.arguments or {}, dict(ctx.meta or {}))) + meta = dict(ctx.meta or {}) + if not chart_images.wanted(meta, connection_query(ctx, "charts")): + return tool_result(await tool.call(params.arguments or {}, meta)) + render = chart_images.renderer() # (Pillow imported now, at the first image asked for) + if render is None: + return tool_result(await tool.call(params.arguments or {}, meta), note=chart_images.UNAVAILABLE_NOTE) + text = await tool.call(params.arguments or {}, {"chart_points": AS_DRAWN, **meta}) # (the picture from every point, as the bot's) + if not (charts := charts_of(_loads(text))): + return tool_result(text) + dark = chart_images.asked_dark(meta) + dark = render.dark_now() if dark is None else dark + try: + pngs = await asyncio.to_thread(lambda: [chart_images.render(c, self.ctx.zone, dark)[0] for c in charts]) + except Exception as e: + log.error("MCP: %s's chart couldn't be drawn: %s: %s", params.name, type(e).__name__, e) + return tool_result(text, note=chart_images.NOT_DRAWN_NOTE) + return tool_result(text, pngs, dark) async def refresh_catalogue(self) -> bool: """Read the file's catalogue of readings again; when it gained a reading (a sensor sent a field it never sent), build the tools @@ -506,5 +557,5 @@ def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "lo return app -__all__ = ["ALERTS_TEMPLATE", "ALERTS_URI", "COMPLETE", "EcobotServer", "PROMPTS", "RESOURCES", "TokenCheck", "host_settings", "http_app", - "prompt", "tool_entry", "tool_result"] +__all__ = ["ALERTS_TEMPLATE", "ALERTS_URI", "COMPLETE", "EcobotServer", "PROMPTS", "RESOURCES", "TokenCheck", "charts_of", "connection_query", + "host_settings", "http_app", "prompt", "tool_entry", "tool_result"] diff --git a/lib/model_tools.py b/lib/model_tools.py index dc613793..16599514 100644 --- a/lib/model_tools.py +++ b/lib/model_tools.py @@ -7,7 +7,7 @@ import json -from .service.common import AS_DRAWN +from .service.common import AS_DRAWN, charts_as_titles from .tools import Tool, Tools, Turn, json_result @@ -18,12 +18,7 @@ def for_model(out: dict) -> dict: """A result as the model is sent it: `charts` as [{title, period}] (the bot draws them) and `chart_note` saying so (BOT_CHART_NOTE), everything else as it is.""" - if not isinstance(out.get("charts"), list): - return out - told = {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} - if "chart_note" in out: - told["chart_note"] = BOT_CHART_NOTE - return told + return charts_as_titles(out, BOT_CHART_NOTE) def tool(service_tool) -> Tool: diff --git a/lib/periods.py b/lib/periods.py index f6fae87a..0cc17282 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -16,7 +16,6 @@ from telegram import InlineKeyboardMarkup from telegram.constants import KeyboardButtonStyle -from . import charts from .buttons import button PREFIX = "pd:" @@ -136,6 +135,13 @@ def remember(self, chat_id: int, message_id: int, record: str | dict): self.save() +def dark_now() -> bool: + """Are charts drawn dark now (DARKMODE: lib/charts.dark_now, imported when first asked: the service imports this module for + call_key, and draws nothing)?""" + from . import charts + return charts.dark_now() + + @dataclass class Drawn: """A chart in the ImageCache.""" @@ -172,7 +178,7 @@ def __init__(self, clock=None): def _kept(self, entry: Drawn | None) -> bool: """Is there a chart, still within its time to live, in the theme charts are drawn in now?""" - return entry is not None and self.age(entry) <= entry.ttl and entry.dark == charts.dark_now() + return entry is not None and self.age(entry) <= entry.ttl and entry.dark == dark_now() def get(self, key: str | None) -> tuple[bytes | str, str] | None: """(the picture: Telegram's file id once it has been sent, else the PNG; its title), or None.""" @@ -202,7 +208,7 @@ def ready(self, key: str | None) -> Drawn | None: """The chart made in code for this call in the last FRESH seconds (for someone's question, or uploaded ahead to TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" entry = self.items.get(key) if key else None - if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != charts.dark_now(): + if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != dark_now(): return None self.items.move_to_end(key) return entry @@ -211,12 +217,14 @@ def age(self, entry: Drawn) -> float: return self.clock() - entry.at def put(self, key: str | None, png: bytes, title: str, caption: str | None = None, ttl: float | None = None, newest: int | None = None, - drawn_by: dict | None = None): + drawn_by: dict | None = None, dark: bool | None = None): """caption: the answer's text, only for a chart made in code (then it can be ready). newest: the time of the newest reading - drawn, when known. drawn_by: the call that drew it (it is kept under that call's key too).""" + drawn, when known. drawn_by: the call that drew it (it is kept under that call's key too). dark: the theme it was drawn in (the + service says which, lib/weather.py); None: the one charts are drawn in now.""" if key is None: return - self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, dark=charts.dark_now(), + self.items[key] = Drawn(self.clock(), png, title, caption=caption, ttl=ttl or self.CHART_TTL, newest=newest, + dark=dark_now() if dark is None else dark, drawn_by=drawn_by) self.items.move_to_end(key) self._trim() diff --git a/lib/service/common.py b/lib/service/common.py index 642db055..dacfaff3 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -331,6 +331,17 @@ def with_charts(charts: list[specs.Chart], tz: tzinfo, meta: dict | None = None) return {"chart_note": CHART_NOTE, "charts": charts_field(charts, tz, meta)} if charts else {} +def charts_as_titles(out: dict, note: str) -> dict: + """An answer with its charts' data left out: `charts` as [{title, period}] and `chart_note` as `note` (the chart goes another way: + the bot sends it, or the service attaches its image), everything else as it is. An answer without charts as it is.""" + if not isinstance(out.get("charts"), list): + return out + told = {**out, "charts": [{"title": c.get("title"), "period": c.get("period")} for c in out["charts"] if isinstance(c, dict)]} + if "chart_note" in out: + told["chart_note"] = note + return told + + def complete(reply: str) -> dict: """The fields of an answer that is complete (3.7: `chart_answers_it` set and a chart made, with no error and no note that needs the model's words): {"reply": the finished reply for the person, "complete": True}. A client may send `reply` with the chart and end @@ -339,5 +350,5 @@ def complete(reply: str) -> dict: __all__ = ["AS_DRAWN", "BACKGROUND", "CHART_NOTE", "CHART_POINTS", "FRESH", "IGNORED_DATES", "SAME_DATES", "SET_ASIDE", "MAX_CHART_POINTS", "META", "NORMAL", "PERIOD_FORMS", "Refusal", - "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_field", "complete", "iso", "period_field", "period_properties", + "ServiceTool", "WHOLE_DAY_FORMS", "answer", "as_of_field", "charts_as_titles", "charts_field", "complete", "iso", "period_field", "period_properties", "read_period", "refuse", "sends_period", "refuse_period", "request_meta", "turn_meta", "with_charts"] diff --git a/lib/weather.py b/lib/weather.py index c8387158..e38f17f5 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -13,18 +13,28 @@ - `alerts`: the alert feed lib/alerts/notify.AlertDelivery reads (`last_id`, `identity`, `since`, `wait`), and `alert(id)` one event (the 🔄 under an alert replays its chart's drawn_by); - `resource(uri)`: a resource's content (ecobot://station, ecobot://forecast ...); - - `ready(wait)`: whether it can be reached (in-process, always; remote, once connected, waiting up to `wait` seconds for it). + - `ready(wait)`: whether it can be reached (in-process, always; remote, once connected, waiting up to `wait` seconds for it); + - `chart_image(name, args, meta)`: a tool's answer as data with its first chart drawn (ChartImage: the PNG, the chart's JSON with its + drawn_by, the theme), and `picture(chart)` a chart's JSON drawn (an alert's): in-process by lib/charts.render_data (the bot's + `render`, so its tests can stand in for it); remote by the service (request `_meta` `chart_image: "png"`, the image from the result's + ImageContent, the chart's JSON and theme from its `_meta`; a chart's picture by replaying its drawn_by), in the bot's own theme + (`chart_dark`: its DARKMODE, so its image cache's theme holds). A service that sends no image (no Pillow there) has its chart drawn + here. For the irrigation check while it is still the bot's (step 5b moves it to its own server): `ServiceRain` (the measured rain, from `summary {readings: ["rain"], period: "last 24 hours"}`) and `ServiceForecast` (ecobot://forecast, the last read kept when the service can't be reached), docs 3.9.""" import asyncio +import base64 import json import logging from datetime import date, datetime +from typing import NamedTuple from zoneinfo import ZoneInfo +from . import chart_images +from .service.common import AS_DRAWN, CHART_NOTE from .service.instructions import instructions as service_instructions from .timeutil import now_local @@ -46,6 +56,33 @@ def __init__(self, message: str = UNREACHABLE): super().__init__(message) +class ChartNotDrawn(RuntimeError): + """A chart came but couldn't be drawn (its JSON isn't a chart, or the renderer failed): not the service's refusal.""" + + +class ChartImage(NamedTuple): + """A chart drawn.""" + png: bytes + chart: dict # its JSON (schemas/chart.json), with the drawn_by that draws it again + dark: bool # drawn in the dark theme + + +def charts_of(out) -> list[dict]: + """The charts of an answer (none for a refusal).""" + charts = out.get("charts") if isinstance(out, dict) and "error" not in out else None + return [c for c in charts if isinstance(c, dict)] if isinstance(charts, list) else [] + + +async def draw_here(render, chart: dict, tz, dark: bool | None = None) -> ChartImage: + """A chart's JSON drawn in this process (off the event loop) by `render(chart, tz, dark)` -> (PNG, dark); ChartNotDrawn when it + can't be.""" + try: + png, drawn_dark = await asyncio.to_thread(render, chart, tz, dark) + except Exception as e: + raise ChartNotDrawn(f"{type(e).__name__}: {e}") from e + return ChartImage(png, chart, drawn_dark) + + async def value(x): """x, awaited when it is awaitable: the alert feed's methods are plain in-process and coroutines when remote.""" return await x if asyncio.iscoroutine(x) or isinstance(x, asyncio.Future) else x @@ -57,10 +94,12 @@ class LocalWeather: it runs over, the alert log.""" is_weather, remote = True, False - def __init__(self, sources=(), service=None, alert_log=None, tz=None): + def __init__(self, sources=(), service=None, alert_log=None, tz=None, render=None): + """render(chart, tz, dark) -> (PNG, dark): how a chart is drawn (lib/chart_images.render: lib/charts.render_data).""" self.sources, self.alert_log, self.tz = list(sources), alert_log, tz self.by_name = {s.name: s for s in self.sources} self._service = service + self.render = render or chart_images.render @property def service(self): @@ -109,8 +148,28 @@ async def resource(self, uri: str) -> dict: async def ready(self, wait: float = 0) -> bool: return True + async def chart_image(self, name: str, args: dict | None = None, meta: dict | None = None, + alone: bool = False) -> tuple[dict, ChartImage | None]: + """(the tool's answer as data, its first chart drawn; None without a chart, or with more than one when `alone`).""" + meta = dict(meta or {}) + out = json.loads(await self.service[name].call(args or {}, meta)) + charts = charts_of(out) + if not charts or (alone and len(charts) != 1): + return out, None + return out, await self.picture(charts[0], chart_images.asked_dark(meta)) + + async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: + """A chart's JSON drawn (dark None: as DARKMODE says now); ChartNotDrawn when it can't be.""" + return await draw_here(self.render, chart, self.tz or getattr(self.ctx, "zone", None), dark) + # ---------- over MCP ---------- +def bot_dark() -> bool: + """The bot's own theme now (DARKMODE: lib/charts.dark_now), sent as chart_dark.""" + from .periods import dark_now + return dark_now() + + class RemoteTool: """One of the service's tools as tools/list gave it, called over MCP.""" @@ -333,6 +392,49 @@ async def call_text(self, name: str, args: dict | None = None, meta: dict | None return block.text return json.dumps({"error": f"The service's {name} gave no answer."}) + async def chart_image(self, name: str, args: dict | None = None, meta: dict | None = None, + alone: bool = False) -> tuple[dict, ChartImage | None]: + """(the tool's answer as data, its first chart as the service drew it; None without a chart, or with more than one when + `alone`). Asked with `chart_image: "png"` and, unless `meta` says, `chart_dark` the bot's own theme now; the answer's charts are + the full JSON from the result's _meta (the text carries only their titles). A service that sent no image has it drawn here.""" + meta = {**(meta or {}), "chart_image": chart_images.IMAGE} + if chart_images.asked_dark(meta) is None: + meta["chart_dark"] = bot_dark() + client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) + result = await client.call_tool(name, args or {}, meta=meta) + text = next((b.text for b in result.content if getattr(b, "type", None) == "text"), None) + out = json.loads(text) if text is not None else {"error": f"The service's {name} gave no answer."} + extra = result.meta or {} + if isinstance(out, dict) and isinstance(full := extra.get(chart_images.CHARTS_META), list): + out["charts"] = full + if "chart_note" in out: + out["chart_note"] = CHART_NOTE + charts = charts_of(out) + if not charts or (alone and len(charts) != 1): + return out, None + pngs = [base64.b64decode(b.data) for b in result.content if getattr(b, "type", None) == "image"] + if pngs: + dark = extra.get(chart_images.DARK_META) + return out, ChartImage(pngs[0], charts[0], dark if isinstance(dark, bool) else meta["chart_dark"]) + log.debug("Weather service: %s sent no chart image (%s); drawn here", name, out.get("chart_image_note")) + return out, await draw_here(chart_images.render, charts[0], self.tz, meta["chart_dark"]) + + async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: + """A chart's JSON drawn by the service: its drawn_by replayed (as drawn: the same chart, with any newer reading); drawn here + when it has none, or the service draws no chart of it, or can't be reached. ChartNotDrawn when it can't be.""" + dark = bot_dark() if dark is None else dark + if isinstance(by := chart.get("drawn_by"), dict) and by.get("tool"): + try: + out, image = await self.chart_image(by["tool"], by.get("arguments") or {}, {"chart_points": AS_DRAWN, "chart_dark": dark}) + except ChartNotDrawn: + raise + except Exception as e: # (the service away, or its answer broken: the chart as it came is drawn here) + out, image = {"error": f"{type(e).__name__}: {e}"}, None + if image is not None: + return image + log.debug("Weather service: %s drew no chart again (%s); drawn here", by["tool"], out.get("error")) + return await draw_here(chart_images.render, chart, self.tz, dark) + async def resource(self, uri: str, wait=AS_A_CALL) -> dict: """A resource's content; `wait`: how long to wait for the service (CALL_WAIT; None as long as it takes).""" client = await self._client(CALL_WAIT if wait is AS_A_CALL else wait) @@ -415,4 +517,4 @@ def upcoming(self, count: int = 2) -> list[dict]: return [d for d in (self.days or []) if d["date"] >= today][:count] -__all__ = ["LocalWeather", "RemoteWeather", "ServiceForecast", "ServiceRain", "ServiceUnreachable", "UNREACHABLE", "value"] +__all__ = ["ChartImage", "ChartNotDrawn", "LocalWeather", "RemoteWeather", "ServiceForecast", "ServiceRain", "ServiceUnreachable", "UNREACHABLE", "value"] diff --git a/requirements-charts.txt b/requirements-charts.txt new file mode 100644 index 00000000..42b53b75 --- /dev/null +++ b/requirements-charts.txt @@ -0,0 +1,3 @@ +# The chart pictures (lib/charts.py, lib/draw.py, the gauges): the bot needs them; the service (python -m ecobot_service) only to send +# its charts as images (docs/mcp-service.md 3.7). Pinned: the reference images in tests/charts are drawn with this version. +pillow==13.0.0 diff --git a/requirements-dev.txt b/requirements-dev.txt index af4bba28..3f2ed2f4 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,5 @@ -r requirements.txt +-r requirements-charts.txt pytest pytest-asyncio pytest-xdist>=3.2 diff --git a/requirements.txt b/requirements.txt index 2690e49f..c6d2f174 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,5 @@ httpx mcp==2.3.0 openai python-telegram-bot>=22.8 -pillow==13.0.0 uvicorn==0.54.0 zeroconf diff --git a/scripts/update_charts.py b/scripts/update_charts.py index a85a3adf..5dea9413 100644 --- a/scripts/update_charts.py +++ b/scripts/update_charts.py @@ -8,7 +8,7 @@ python scripts/update_charts.py wind air # just these The images are drawn from the made-up data in tests/chart_samples.py with Pillow's own font, so the result is the same on any -machine with the same Pillow version (pinned in requirements.txt).""" +machine with the same Pillow version (pinned in requirements-charts.txt).""" import sys from pathlib import Path diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py index 0d53f5aa..60ffce8a 100644 --- a/tests/test_bot_remote.py +++ b/tests/test_bot_remote.py @@ -150,6 +150,46 @@ async def test_a_chart_is_drawn_from_a_remote_result_with_its_period_buttons(con assert bot.charted.get(1, 9)["drawn_by"] == chart["drawn_by"] +async def test_a_remote_bot_sends_the_services_picture_of_a_chart_byte_for_byte_the_one_it_would_draw_itself(connected, world, alert_state, + monkeypatch): + from lib.alerts import pictures + call = ("summary", {"readings": ["humidity"], "period": "7d", "chart": True}) + local = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(world.service)), [], alert_state, service=world.service) + for _ in range(3): # (what a call fetches inline, fetched first: the charts are then the same each time) + here = await local._draw_call(*call) + if here.png == (await local._draw_call(*call)).png: + break + event_chart = await pictures.chart_data(None, "Wind chart 1d", TZ, world.service) # (an alert's chart, as its event carries it) + drawn_here = await pictures.picture_of(event_chart, TZ) + + def not_here(*a, **k): + raise AssertionError("a remote bot doesn't draw the service's charts itself") + monkeypatch.setattr("lib.bot.render_data", not_here) + monkeypatch.setattr(weather_module, "draw_here", not_here) + monkeypatch.setattr(pictures, "render_data", not_here) + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), [], alert_state, service=connected) + made = await bot._draw_call(*call) + assert made.png == here.png and made.png.startswith(b"\x89PNG") and made.dark is False # the service's PNG, as the bot draws it + assert (made.title, made.caption, made.newest, made.drawn_by) == (here.title, here.caption, here.newest, here.drawn_by) + assert made.out["charts"] == here.out["charts"] # the chart's JSON, from the result's _meta + alert = await pictures.picture_of(event_chart, TZ, connected) # an alert's chart: its drawn_by replayed + assert (alert.png, alert.title, alert.drawn_by, alert.dark) == (drawn_here.png, drawn_here.title, event_chart["drawn_by"], False) + typed = await pictures.chart(None, "Wind chart 1d", TZ, connected) # the 🔄 under an alert from before the log + assert typed.png == drawn_here.png + + +async def test_a_service_without_pillow_sends_the_charts_json_and_the_remote_bot_draws_it_itself(connected, world, alert_state, monkeypatch): + from types import SimpleNamespace + from lib import chart_images, mcp_server + call = ("summary", {"readings": ["humidity"], "period": "7d", "chart": True}) + local = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(world.service)), [], alert_state, service=world.service) + here = await local._draw_call(*call) + monkeypatch.setattr(mcp_server, "chart_images", SimpleNamespace(**{**vars(chart_images), "renderer": lambda: None})) # (no Pillow there) + bot = Bot(NS(tz=TZ), Agent(None, "m", model_tools.tools(connected)), [], alert_state, service=connected) + made = await bot._draw_call(*call) + assert made.out["chart_image_note"] == chart_images.UNAVAILABLE_NOTE and made.png == here.png and made.drawn_by == here.drawn_by + + async def test_an_alert_reaches_the_subscribed_chats_through_the_listen(connected, world, tmp_path): publishing = asyncio.create_task(world.watch_alerts()) state = AlertState(tmp_path / "bot_state.json") diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 9f2cc367..7eef79bb 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -4,7 +4,11 @@ as docs 7 asks).""" import asyncio +import base64 import json +import os +import subprocess +import sys import time from types import SimpleNamespace as NS from zoneinfo import ZoneInfo @@ -15,11 +19,12 @@ from mcp.server.subscriptions import ResourceUpdated, ToolsListChanged from mcp.shared.exceptions import MCPError -from lib import mcp_server +from lib import chart_images, charts, mcp_server +from lib.config import ROOT from lib.alert_log import AlertLog from lib.mcp_server import (ALERTS_TEMPLATE, ALERTS_URI, COMPLETE, PROMPTS, EcobotServer, TokenCheck, host_settings, prompt, tool_result) -from lib.service.common import CHART_POINTS +from lib.service.common import AS_DRAWN, CHART_POINTS from lib.service.context import Context from lib.service.names import Catalogue from tests import evalkit, evalworld @@ -313,3 +318,113 @@ def test_one_service_per_data_folder(tmp_path): hold_data_folder(cfg, second) with contextlib.ExitStack() as again: # free once the first has closed hold_data_folder(cfg, again) + + +# ---------- chart images (3.7) ---------- +CHARTED = {"readings": ["temperature"], "period": "last 7 days", "chart": True} + + +def ours(result) -> dict: + """The result's _meta that is the service's own (not the SDK's serverInfo).""" + return {k: v for k, v in (result.meta or {}).items() if k.startswith("ecobot/")} + + +def images_of(result) -> list[bytes]: + return [base64.b64decode(b.data) for b in result.content if b.type == "image"] + + +async def test_without_images_asked_a_chart_comes_as_json_alone_as_before(world): + async with Client(world.server) as client: + plain = await client.call_tool("summary", CHARTED) + none = await client.call_tool("summary", CHARTED, meta={"chart_image": "none"}) + for got in (plain, none): + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert got.content[0].text == await world.service["summary"].call(CHARTED) + + +async def test_a_call_asking_for_images_gets_each_chart_as_a_png_after_the_figures_and_the_charts_json_in_meta(world): + async with Client(world.server) as client: + got = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + dark = await client.call_tool("summary", CHARTED, meta={"chart_image": "png", "chart_dark": True}) + told = json.loads(got.content[0].text) + whole = json.loads(await world.service["summary"].call(CHARTED, {"chart_points": AS_DRAWN})) # (drawn from every point, as the bot's) + assert told["charts"] == [{"title": c["title"], "period": c["period"]} for c in whole["charts"]] + assert told["chart_note"] == chart_images.IMAGE_NOTE and told["caption"] == whole["caption"] + assert {k: v for k, v in told.items() if k not in ("charts", "chart_note")} == {k: v for k, v in whole.items() if k not in ("charts", "chart_note")} + assert got.meta[chart_images.CHARTS_META] == whole["charts"] and got.meta[chart_images.DARK_META] is False + (png,) = images_of(got) + assert got.content[1].mime_type == "image/png" and png.startswith(b"\x89PNG") + assert png == charts.render_data(whole["charts"][0], TZ, dark=False) # the bot's renderer, byte for byte + assert dark.meta[chart_images.DARK_META] is True and images_of(dark)[0] == charts.render_data(whole["charts"][0], TZ, dark=True) + assert not got.is_error and COMPLETE not in got.meta + + +async def test_a_complete_answer_with_images_still_carries_its_reply_for_the_person_last(world): + args = {"readings": ["pressure"], "period": "this week", "chart_answers_it": True} + async with Client(world.server) as client: + got = await client.call_tool("summary", args, meta={"chart_image": "png"}) + data = json.loads(got.content[0].text) + assert [b.type for b in got.content] == ["text", "image", "text"] and data["complete"] is True + assert got.content[2].text == data["reply"] and got.content[2].annotations.audience == ["user"] + assert got.meta[COMPLETE] is True and len(got.meta[chart_images.CHARTS_META]) == 1 + + +async def test_a_refusal_or_an_answer_without_a_chart_is_as_it_was_with_images_asked(world): + async with Client(world.server) as client: + refused = await client.call_tool("summary", {"period": "the age of the dinosaurs"}, meta={"chart_image": "png"}) + plain = await client.call_tool("current", {"readings": ["temperature"]}, meta={"chart_image": "png"}) + assert refused.is_error and [b.type for b in refused.content] == ["text"] and not ours(refused) + assert [b.type for b in plain.content] == ["text"] and not ours(plain) and "charts" not in json.loads(plain.content[0].text) + + +async def test_without_pillow_images_asked_for_give_the_json_with_a_note_and_one_warning(world, monkeypatch, caplog): + monkeypatch.setitem(sys.modules, "lib.charts", None) # (as if Pillow weren't installed: the import fails) + monkeypatch.setattr(chart_images, "_warned", False) + async with Client(world.server) as client: + first = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + again = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + for got in (first, again): + data = json.loads(got.content[0].text) + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert data["chart_image_note"] == chart_images.UNAVAILABLE_NOTE + assert {k: v for k, v in data.items() if k != "chart_image_note"} == json.loads(await world.service["summary"].call(CHARTED)) + warned = [r for r in caplog.records if r.name == "lib.chart_images" and r.levelname == "WARNING"] + assert len(warned) == 1 and "requirements-charts.txt" in warned[0].getMessage() + + +def test_images_are_wanted_per_call_else_per_connection(): + assert not chart_images.wanted({}) and not chart_images.wanted({}, "json") and chart_images.wanted({}, "png") + assert chart_images.wanted({"chart_image": "png"}) and chart_images.wanted({"chart_image": "PNG"}, None) + assert not chart_images.wanted({"chart_image": "none"}, "png") and chart_images.wanted({"chart_image": "jpeg"}, "png") + assert chart_images.asked_dark({"chart_dark": True}) is True and chart_images.asked_dark({"chart_dark": "yes"}) is None + + +def test_the_service_imports_no_pillow_until_an_image_is_asked_for(tmp_path): + """Importing the server and building its app (as python -m ecobot_service does) imports neither Pillow nor the renderer.""" + code = ("import sys, ecobot_service.__main__; from zoneinfo import ZoneInfo; from lib.mcp_server import EcobotServer, http_app; " + "from lib.service.context import Context; http_app(EcobotServer(Context(tz=ZoneInfo('UTC'))), tokens=('t',)); " + "print(sorted(m for m in sys.modules if m.split('.')[0] == 'PIL' or m in ('lib.charts', 'lib.draw', 'lib.gauges')))") + done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, + env={**os.environ, "DATA_DIR": str(tmp_path)}) + assert done.returncode == 0, done.stderr + assert done.stdout.strip() == "[]" + + +async def test_over_http_the_connections_url_asks_for_images_and_a_call_can_say_otherwise(world): + from lib.upstream import http_transport + from tests.test_mcp_listen import Serving, free_port + port = free_port() + base = f"http://127.0.0.1:{port}/mcp" + async with Serving(mcp_server.http_app(world, tokens=("t",)), port): + async with Client(http_transport(f"{base}?charts=png", "t"), mode="2026-07-28") as client: + images = await client.call_tool("summary", CHARTED) + without = await client.call_tool("summary", CHARTED, meta={"chart_image": "none"}) + async with Client(http_transport(base, "t"), mode="2026-07-28") as client: + plain = await client.call_tool("summary", CHARTED) + asked = await client.call_tool("summary", CHARTED, meta={"chart_image": "png"}) + for got in (images, asked): + assert [b.type for b in got.content] == ["text", "image"] and len(got.meta[chart_images.CHARTS_META]) == 1 + assert images_of(got)[0] == charts.render_data(got.meta[chart_images.CHARTS_META][0], TZ, dark=False) + for got in (without, plain): + assert [b.type for b in got.content] == ["text"] and not ours(got) + assert got.content[0].text == await world.service["summary"].call(CHARTED) From a4f83d394a5f4394dd86aadd1b53d16725b4cb15 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 01:56:19 +0000 Subject: [PATCH 076/125] Chart images, review follow-ups: the bot's own calls ask for JSON, an alert picture doesn't fetch or wait long, a failed drawing answers as if off - RemoteWeather.call_text sends chart_image none unless told, so ?charts=png in WEATHER_MCP_URL can't take the bot's charts away - an alert's picture replay sends fetch false and waits PICTURE_WAIT (8 s) before drawing the alert's own data - a chart the service fails to draw: the tool's answer with the caller's own meta, not every drawn point Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/mcp_server.py | 2 +- lib/weather.py | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/mcp_server.py b/lib/mcp_server.py index c620a9aa..24f4e55f 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -255,7 +255,7 @@ async def _call_tool(self, ctx, params: types.CallToolRequestParams) -> types.Ca pngs = await asyncio.to_thread(lambda: [chart_images.render(c, self.ctx.zone, dark)[0] for c in charts]) except Exception as e: log.error("MCP: %s's chart couldn't be drawn: %s: %s", params.name, type(e).__name__, e) - return tool_result(text, note=chart_images.NOT_DRAWN_NOTE) + return tool_result(await tool.call(params.arguments or {}, meta), note=chart_images.NOT_DRAWN_NOTE) # (as if off) return tool_result(text, pngs, dark) async def refresh_catalogue(self) -> bool: diff --git a/lib/weather.py b/lib/weather.py index e38f17f5..1b8f41c0 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -262,6 +262,8 @@ async def wait(self, after: int, timeout: float | None = None) -> bool: return False +PICTURE_WAIT = 8.0 # seconds an alert's picture waits for the service to draw it again, before it is drawn here from the alert's data + class RemoteWeather: """The service at `target` (its MCP URL; in tests, a Server in-process), as the bot's interface. `run()` is the supervisor (the lib/upstream.py's Upstream: one client, discovered by hand for the instructions, listening; on a transport error or a lost or ended listen it @@ -385,8 +387,9 @@ async def call_text(self, name: str, args: dict | None = None, meta: dict | None """A tool's answer as its JSON text (the first text block: the tool's JSON, a refusal's too). A background request (nobody waiting) doesn't wait for the service.""" meta = dict(meta or {}) + meta.setdefault("chart_image", chart_images.NO_IMAGE) # (the JSON, even if WEATHER_MCP_URL asks for images: the bot draws these) client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) - result = await client.call_tool(name, args or {}, meta=meta or None) + result = await client.call_tool(name, args or {}, meta=meta) for block in result.content: if getattr(block, "type", None) == "text": return block.text @@ -425,7 +428,9 @@ async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: dark = bot_dark() if dark is None else dark if isinstance(by := chart.get("drawn_by"), dict) and by.get("tool"): try: - out, image = await self.chart_image(by["tool"], by.get("arguments") or {}, {"chart_points": AS_DRAWN, "chart_dark": dark}) + out, image = await asyncio.wait_for( # (an alert waits on this: nothing fetched for it, and not for long) + self.chart_image(by["tool"], by.get("arguments") or {}, {"chart_points": AS_DRAWN, "chart_dark": dark, "fetch": False}), + PICTURE_WAIT) except ChartNotDrawn: raise except Exception as e: # (the service away, or its answer broken: the chart as it came is drawn here) From a1e6bd0e3b52cfea078bab9bba0800842c9dd254 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 02:15:58 +0000 Subject: [PATCH 077/125] Docker: the service starts by default, the bot is optional (the bot profile); the service loads no Telegram - compose.yaml: ecobot-service has no profile and builds the image; ecobot is under profiles [bot], depends on it, and takes WEATHER_MCP_URL from docker/bot.env (read before /etc/ecobot.env, which wins); host network sends it to 127.0.0.1 - the service always answers 127.0.0.1, localhost and its own hostname (ecobot-service in Docker); MCP_SERVICE_ALLOWED_HOSTS adds - the alert types move to lib/alerts/kinds.py and periods imports Telegram only to build its keyboard, so the service never loads python-telegram-bot (tested) - README: Docker install and upgrade for the two containers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- .gitignore | 1 + DEVELOPMENT.md | 10 ++-- README.md | 81 ++++++++++++++++----------------- compose.host-network.yaml | 12 +++-- compose.yaml | 48 ++++++++++--------- docker/bot.env | 3 ++ docs/configuration.md | 2 +- ecobot_service/__main__.py | 6 ++- ecobot_service/core.py | 2 +- lib/alerts/forecast.py | 2 +- lib/alerts/irrigation.py | 2 +- lib/alerts/kinds.py | 20 ++++++++ lib/alerts/menu.py | 18 +------- lib/alerts/particulates.py | 2 +- lib/alerts/pollen_and_asthma.py | 2 +- lib/alerts/weather.py | 2 +- lib/periods.py | 9 ++-- tests/test_mcp_listen.py | 10 ++-- tests/test_mcp_server.py | 7 +-- 19 files changed, 130 insertions(+), 109 deletions(-) create mode 100644 docker/bot.env create mode 100644 lib/alerts/kinds.py diff --git a/.gitignore b/.gitignore index fe6a78c5..c4098450 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ bot_state.json.tmp *.db *.db-* *.env +!docker/*.env mcp_ecowitt.json chart-diffs/ !tests/data/*.sqlite diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 0c328df6..cfc222c7 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -33,7 +33,7 @@ It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) les ``` set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them MCP_SERVICE_TOKENS=$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp -sudo docker compose --profile service up -d ecobot-service # in Docker (compose.yaml), on the host's port 8765 +sudo docker compose up -d ecobot-service # in Docker (compose.yaml), on the host's port 8765 ``` Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set @@ -69,10 +69,10 @@ set -a; . <(sudo cat /etc/ecobot.env); set +a MCP_SERVICE_TOKENS=$TOKEN python -m ecobot_service & # the service, with the sources' settings WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN=$TOKEN python ecobot.py # the bot, its client ``` -In Docker (compose.yaml): in /etc/ecobot.env set `MCP_SERVICE_TOKENS=`, `WEATHER_MCP_URL=http://ecobot-service:8765/mcp`, -`WEATHER_MCP_TOKEN=` and `MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service`; then recreate the bot first -(`sudo docker compose up -d --force-recreate ecobot`, which frees the data folder) and start the service -(`sudo docker compose --profile service up -d ecobot-service`). Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a +In Docker (compose.yaml) this is how they run: `ecobot-service` always, and the bot (the `bot` profile) as its client, its +`WEATHER_MCP_URL` from docker/bot.env (the service's container name; 127.0.0.1 with compose.host-network.yaml), with +`MCP_SERVICE_TOKENS=` and `WEATHER_MCP_TOKEN=` in /etc/ecobot.env. The service answers its own hostname, so no +`MCP_SERVICE_ALLOWED_HOSTS` is needed for the bot. Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, the service's PNG of a chart byte for byte the bot's own, an alert through the listen, the irrigation check's inputs; under uvicorn: a dropped connection rebuilt and the alerts after the last id read once, the service down, `ecobot.main()` as a client). diff --git a/README.md b/README.md index 1a5871e5..179f9129 100644 --- a/README.md +++ b/README.md @@ -124,6 +124,15 @@ The service runs sandboxed as its own user, and keeps its data in `/var/lib/priv ### Docker +Docker runs two containers from one image: `ecobot-service`, the weather service (the readings, the alerts, and an MCP server that the +bot and other AI clients use), and `ecobot`, the Telegram bot, which is optional. Add to `/etc/ecobot.env` one token for the bot to +reach the service (make it with `openssl rand -hex 16`), the same value twice: + +``` +MCP_SERVICE_TOKENS= +WEATHER_MCP_TOKEN= +``` + ``` sudo mkdir -p /var/lib/private/ecobot && sudo chown -R 10001:10001 /var/lib/private/ecobot ``` @@ -136,59 +145,38 @@ sudo git clone https://github.com/robdevops/ecobot /opt/ecobot cd /opt/ecobot ``` +To run the Telegram bot too (leave this out for the service alone): + ``` -sudo docker compose up -d --build +echo "COMPOSE_PROFILES=bot" | sudo tee -a /opt/ecobot/.env ``` -Watch the logs: - ``` -sudo docker logs -tf ecobot +sudo docker compose up -d --build ``` -Then message `/report` to your Telegram bot. - -Docker uses the same data folder as the systemd service, so you can switch between them, one at a time. To go back to systemd: `sudo docker rm -f ecobot && sudo systemctl start ecobot`. +Watch the logs: `sudo docker logs -tf ecobot-service` shows `MCP: http://...:8765/mcp`, and `sudo docker logs -tf ecobot` shows +`Weather service: connected`. Then message `/report` to your Telegram bot. -#### The weather service on its own in Docker (optional) +Docker uses the same data folder as the systemd service, so you can switch between them, one at a time. To go back to systemd: +`sudo docker compose --profile bot down && sudo systemctl start ecobot`. Only one process runs the service on the data folder: started +beside a bot that runs it itself, it stops, saying so in its log. -Not needed: without it the bot runs everything itself, as before. The `ecobot-service` container runs the weather service from the same -image (an MCP server for other clients, with the bot as one of them) on the bot's data folder, so back that up first: -`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`. Then: - -1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`), and the `WEATHER_MCP_URL` line that matches your network: - ``` - MCP_SERVICE_TOKENS= - WEATHER_MCP_TOKEN= - # Docker's own network (the default): - WEATHER_MCP_URL=http://ecobot-service:8765/mcp - MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service - # or, with compose.host-network.yaml in COMPOSE_FILE: - WEATHER_MCP_URL=http://127.0.0.1:8765/mcp - ``` -2. Recreate the bot, now the service's client (it waits for the service): `sudo docker compose up -d --force-recreate ecobot` -3. Start the service: `sudo docker compose --profile service up -d ecobot-service` -4. Watch both: `sudo docker logs -tf ecobot-service` should show `MCP: http://.../mcp`, and `sudo docker logs -tf ecobot` with - `Weather service: connected`. Then message `/report` to the bot. +#### Other MCP clients The service is published on port 8765 of every address your machine has, so other devices on your network (Claude Code on a laptop, -say) can use it with their own token from `MCP_SERVICE_TOKENS`: add your machine's IP address or name, as they write it in the URL, to -`MCP_SERVICE_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. It is plain HTTP: keep it on your own network. -Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in `compose.yaml` to -`127.0.0.1:8765:8765`. -A client that shows pictures can have the charts as images: add `?charts=png` to its URL (`http://192.168.1.5:8765/mcp?charts=png`). -The image has Pillow, which draws them; a service installed by hand from `requirements.txt` alone sends the charts' data instead. - -From then on, `sudo docker compose --profile service up -d --build` updates both. To go back: `sudo docker compose --profile service down` -(it stops both), remove the lines from step 1, then `sudo docker compose up -d`. -Only one process runs the service on the data folder: started beside a bot without `WEATHER_MCP_URL`, it stops, saying so in its log. +say) can use it: give each its own token, added to `MCP_SERVICE_TOKENS` with a comma, and add your machine's IP address or name, as they +write it in the URL, to `MCP_SERVICE_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. For Claude Code: +`claude mcp add --transport http ecobot http://192.168.1.5:8765/mcp --header "Authorization: Bearer "`. It is plain HTTP: keep it +on your own network. Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in +`compose.yaml` to `127.0.0.1:8765:8765`. A client that shows pictures can have the charts as images: add `?charts=png` to its URL. #### Docker logging -Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot`): +Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot-service` or `CONTAINER_NAME=ecobot`): ``` -echo "COMPOSE_FILE=compose.yaml:compose.journald.yaml" | sudo tee /opt/ecobot/.env +echo "COMPOSE_FILE=compose.yaml:compose.journald.yaml" | sudo tee -a /opt/ecobot/.env ``` The bot writes warnings and errors to stderr and the rest to stdout, which Docker files in the journal at the priorities err and info, so `journalctl -p warning CONTAINER_NAME=ecobot` shows the warnings and errors alone. @@ -197,12 +185,14 @@ To use both this and [Docker host network](#docker-networking), set `COMPOSE_FIL #### Docker networking -`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or reconfigure the container for host network (then run the `docker compose` command again): +`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or put both containers on the host's network (then run the `docker compose` command again; the bot then reaches the service at 127.0.0.1): ``` -echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee /opt/ecobot/.env +echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee -a /opt/ecobot/.env ``` +`/opt/ecobot/.env` holds one `COMPOSE_FILE=` line: to use more than one of these files, list them all in it, separated by `:`. + ## Upgrading Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept. The log's first line, `Starting ecobot `, says which version is running. @@ -233,12 +223,21 @@ cd /opt/ecobot && sudo git pull sudo docker compose up -d --build ``` -Compose replaces the container only if the image or the settings changed. To remove the old images and build cache that upgrades leave behind: +Compose replaces a container only if its image or settings changed. To remove the old images and build cache that upgrades leave behind: ``` sudo docker image prune -f && sudo docker builder prune -f ``` +**From a version before the service ran on its own (November 2026):** the bot ran everything itself; now `ecobot-service` does, and the +bot is its client, under the `bot` profile. Back up first (`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`), add the +two token lines from [Docker](#docker) to `/etc/ecobot.env` (remove any `WEATHER_MCP_URL` line: Docker sets it), replace any +`COMPOSE_PROFILES=service` in `/opt/ecobot/.env` with `COMPOSE_PROFILES=bot` (or add it), then: + +``` +sudo docker compose --profile bot down && sudo docker compose up -d --build +``` + ## Configuration Settings are environment variables in `/etc/ecobot.env`. The ones you're most likely to change: diff --git a/compose.host-network.yaml b/compose.host-network.yaml index 7933a778..cdda353a 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -1,8 +1,12 @@ services: - ecobot: - network_mode: host - # On the host's network too (its sources may be .local names), on port 8765 of every address the host has, as compose.yaml - # publishes it: the bot reaches it at http://127.0.0.1:8765/mcp, and other machines at the host's address. + # On the host's network (its sources may be .local names), on port 8765 of every address the host has, as compose.yaml publishes + # it: the bot reaches it at http://127.0.0.1:8765/mcp, and other machines at the host's address. (No hostname of its own here: the + # host's name is its name, and it answers that.) ecobot-service: network_mode: host + hostname: !reset null ports: !reset [] + ecobot: + network_mode: host + environment: + WEATHER_MCP_URL: http://127.0.0.1:8765/mcp diff --git a/compose.yaml b/compose.yaml index bff75908..810827c1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,17 +1,31 @@ -# The bot in Docker: `sudo docker compose up -d --build` builds the image and starts the bot, and replaces a running one only when its -# image or settings changed (README). The commit the log's first line names is read from the clone's .git (see the Dockerfile). -# Logs: Docker's `local` driver (README: "Docker logging", compose.journald.yaml for the journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot`. +# ecobot in Docker (README). `sudo docker compose up -d --build` builds the image and starts the weather service; the Telegram bot is +# optional, under the `bot` profile: `sudo docker compose --profile bot up -d --build`, or COMPOSE_PROFILES=bot in /opt/ecobot/.env. +# Compose replaces a running container only when its image or settings changed. The commit the log's first line names is read from +# the clone's .git (see the Dockerfile). Logs: Docker's `local` driver (README: "Docker logging", compose.journald.yaml for the +# journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot-service` (or `ecobot`). services: - ecobot: + # The weather service (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the sources and their syncers, the alert rules + # and the MCP server, on port 8765 of every address the host has, so other machines on the network can reach it too (plain HTTP, + # with a token; put TLS in front of it, e.g. Caddy, to reach it over the internet; for this host only, publish 127.0.0.1:8765:8765). + # It needs MCP_SERVICE_TOKENS (token,token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses + # to do without tokens. It answers its own name (hostname, below), 127.0.0.1 and localhost; MCP_SERVICE_ALLOWED_HOSTS adds more: the + # host's IP address or name, as LAN clients write it in their URL, and a proxy's name. + ecobot-service: image: ecobot - container_name: ecobot + container_name: ecobot-service + hostname: ecobot-service build: context: . args: COMMIT: ${COMMIT:-} + command: ["python", "-m", "ecobot_service"] restart: unless-stopped # Docker's default network is private, where .local names (mDNS) can't be found (README: "Docker networking", compose.host-network.yaml) env_file: /etc/ecobot.env + environment: + MCP_SERVICE_BIND: 0.0.0.0:8765 + ports: + - 8765:8765 volumes: - /var/lib/private/ecobot:/data logging: @@ -20,25 +34,15 @@ services: max-size: 10m max-file: "5" - # The MCP service on its own (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the same image, `python -m ecobot_service`, - # on port 8765 of every address the host has, so other machines on the network can reach it too (plain HTTP, with a token; put TLS - # in front of it, e.g. Caddy, to reach it over the internet; for this host only, publish 127.0.0.1:8765:8765). Off unless asked for - # (`sudo docker compose --profile service up -d ecobot-service`). Run it only with the bot as its client (WEATHER_MCP_URL= - # http://ecobot-service:8765/mcp and WEATHER_MCP_TOKEN in /etc/ecobot.env, and ecobot-service in MCP_SERVICE_ALLOWED_HOSTS), recreating the - # bot first: one process runs the service per data folder (service.lock), so it won't start beside a bot running it. It needs MCP_SERVICE_TOKENS - # (token,token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses to do without tokens. - # MCP_SERVICE_ALLOWED_HOSTS: add the host's IP address or name, as LAN clients use it in their URL, and a proxy's name. - ecobot-service: + # The Telegram bot, a client of the service (WEATHER_MCP_URL, docker/bot.env; WEATHER_MCP_TOKEN, one of MCP_SERVICE_TOKENS, in + # /etc/ecobot.env). It keeps its own state (chats, alert settings) in the same data folder. + ecobot: image: ecobot - container_name: ecobot-service - profiles: [service] - command: ["python", "-m", "ecobot_service"] + container_name: ecobot + profiles: [bot] restart: unless-stopped - env_file: /etc/ecobot.env - environment: - MCP_SERVICE_BIND: 0.0.0.0:8765 - ports: - - 8765:8765 + depends_on: [ecobot-service] + env_file: [docker/bot.env, /etc/ecobot.env] volumes: - /var/lib/private/ecobot:/data logging: diff --git a/docker/bot.env b/docker/bot.env new file mode 100644 index 00000000..41353d8b --- /dev/null +++ b/docker/bot.env @@ -0,0 +1,3 @@ +# The bot's defaults in Docker (compose.yaml reads this before /etc/ecobot.env, so a setting there wins): the bot is a client of +# the ecobot-service container, reached by its name on the project's network. +WEATHER_MCP_URL=http://ecobot-service:8765/mcp diff --git a/docs/configuration.md b/docs/configuration.md index 4750e556..754dd679 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -88,7 +88,7 @@ At least one of Ecowitt, AirGradient (cloud or local) must be configured. |---|---|---| | `MCP_SERVICE_TOKENS` | none | `token,token`: the bearer tokens the service accepts (each client sends one as `Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart). Compared in constant time; a token is never logged, only its name. Unset → no auth, which the service allows only on a loopback `MCP_SERVICE_BIND` | | `MCP_SERVICE_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | -| `MCP_SERVICE_ALLOWED_HOSTS` | `127.0.0.1,localhost` | The `Host` names it answers, any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name a proxy or a LAN client uses | +| `MCP_SERVICE_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-service`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses | Chart images are not a setting of the service but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([mcp-service.md](mcp-service.md) 3.7). They need Pillow (`requirements-charts.txt`, in the Docker image): installed from `requirements.txt` alone the service answers with the charts' JSON and a note, and warns once. diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py index ecd0d580..f49c8814 100644 --- a/ecobot_service/__main__.py +++ b/ecobot_service/__main__.py @@ -12,6 +12,7 @@ import ipaddress import logging import signal +import socket import uvicorn @@ -75,7 +76,8 @@ async def main(): for source in sources: stack.push_async_callback(source.warmer.stop) server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) - app = http_app(server, tokens=cfg.mcp_service_tokens, allowed_hosts=cfg.mcp_service_allowed_hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") + hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.mcp_service_allowed_hosts))) # (its own name too: a container's hostname) + app = http_app(server, tokens=cfg.mcp_service_tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") core.log_startup() running = core.start_alerts() core.start_warmers() @@ -94,7 +96,7 @@ async def warm_up(): serving = asyncio.create_task(web.serve()) log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", host if ":" not in host else f"[{host}]", port, f"{len(cfg.mcp_service_tokens)} token(s)" if cfg.mcp_service_tokens else "no auth (loopback only)", - ", ".join(cfg.mcp_service_allowed_hosts)) + ", ".join(hosts)) waiting = asyncio.create_task(stop.wait()) await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) server.listen.close() # (the listen streams end gracefully: their clients know to listen again) diff --git a/ecobot_service/core.py b/ecobot_service/core.py index a08138b2..56c61b0b 100644 --- a/ecobot_service/core.py +++ b/ecobot_service/core.py @@ -24,7 +24,7 @@ from lib.airgradient import AirGradient from lib.airgradient import metrics as air_metrics from lib.alert_log import AlertLog -from lib.alerts.menu import LABELS, available_kinds +from lib.alerts.kinds import LABELS, available_kinds from lib.alerts.store import AlertStore from lib.compose import Composer from lib.config import ROOT, Config diff --git a/lib/alerts/forecast.py b/lib/alerts/forecast.py index 3cc6f1da..6bae855b 100644 --- a/lib/alerts/forecast.py +++ b/lib/alerts/forecast.py @@ -17,7 +17,7 @@ from ..forecast.source import describe_day from ..timeutil import at_hour -from .menu import kinds_of +from .kinds import kinds_of log = logging.getLogger(__name__) diff --git a/lib/alerts/irrigation.py b/lib/alerts/irrigation.py index 5ec7a818..9900d137 100644 --- a/lib/alerts/irrigation.py +++ b/lib/alerts/irrigation.py @@ -18,7 +18,7 @@ from ..irrigation.tuya import is_paused from ..timeutil import local_epoch, now_local, seconds_until, when from .forecast import RAIN_FROM_PCT -from .menu import kinds_of +from .kinds import kinds_of log = logging.getLogger(__name__) diff --git a/lib/alerts/kinds.py b/lib/alerts/kinds.py new file mode 100644 index 00000000..00fe1664 --- /dev/null +++ b/lib/alerts/kinds.py @@ -0,0 +1,20 @@ +"""The alert types: their names and which source sends each. Shared by the service (its alert rules, `about`) and the bot (its alert +menus, lib/alerts/menu.py), with nothing of Telegram in it, so the service doesn't load the Telegram library.""" + +# kind -> (the name on its button, the source that sends it: a source's name, or Irrigation for the controller), in the order listed +TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), + "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), + "forecast": ("forecast changes", "Forecast"), + "irrigation_battery": ("irrigation battery", "Irrigation"), "irrigation_pause": ("irrigation pause", "Irrigation")} +LABELS = {kind: label for kind, (label, _) in TYPES.items()} + + +def kinds_of(source: str) -> tuple[str, ...]: + """The alert types a source (by name) sends: a monitor's KINDS.""" + return tuple(kind for kind, (_, sender) in TYPES.items() if sender == source) + + +def available_kinds(sources, irrigation: bool = False) -> list[str]: + """The alert types the bot sends: those of its sources (by name), and the irrigation ones with a controller configured.""" + names = {*sources, *(["Irrigation"] if irrigation else [])} + return [kind for kind, (_, source) in TYPES.items() if source in names] diff --git a/lib/alerts/menu.py b/lib/alerts/menu.py index 5fc89042..bed3c1be 100644 --- a/lib/alerts/menu.py +++ b/lib/alerts/menu.py @@ -21,13 +21,8 @@ from telegram import InlineKeyboardMarkup from ..buttons import button, opener, toggle_button +from .kinds import LABELS, TYPES, available_kinds, kinds_of # noqa: F401 (named here too: the menus are built from them) -# kind -> (the name on its button, the source that sends it: a source's name, or Irrigation for the controller), in the order listed -TYPES = {"rain": ("rain", "Ecowitt"), "gusts": ("gusts", "Ecowitt"), "uv": ("UV", "Ecowitt"), "temps": ("temperature crossing", "Ecowitt"), - "particulates": ("particulates", "AirGradient"), "pollen_and_asthma": ("pollen & asthma", "Pollen"), - "forecast": ("forecast changes", "Forecast"), - "irrigation_battery": ("irrigation battery", "Irrigation"), "irrigation_pause": ("irrigation pause", "Irrigation")} -LABELS = {kind: label for kind, (label, _) in TYPES.items()} ALL = "all" TITLE = "🔔 Alerts in this chat" PER_ROW = 2 @@ -35,17 +30,6 @@ MENUS = {ALERTS: "🔔 Alerts", SOUND: "🔊 Sound"} # the /alerts buttons -def kinds_of(source: str) -> tuple[str, ...]: - """The alert types a source (by name) sends: a monitor's KINDS.""" - return tuple(kind for kind, (_, sender) in TYPES.items() if sender == source) - - -def available_kinds(sources, irrigation: bool = False) -> list[str]: - """The alert types the bot sends: those of its sources (by name), and the irrigation ones with a controller configured.""" - names = {*sources, *(["Irrigation"] if irrigation else [])} - return [kind for kind, (_, source) in TYPES.items() if source in names] - - def _verb(on: bool) -> str: return "on" if on else "off" diff --git a/lib/alerts/particulates.py b/lib/alerts/particulates.py index 35f20ac3..5f4a699f 100644 --- a/lib/alerts/particulates.py +++ b/lib/alerts/particulates.py @@ -13,7 +13,7 @@ from datetime import datetime from . import pictures, rules -from .menu import kinds_of +from .kinds import kinds_of log = logging.getLogger(__name__) diff --git a/lib/alerts/pollen_and_asthma.py b/lib/alerts/pollen_and_asthma.py index 8fa7191a..fad573ff 100644 --- a/lib/alerts/pollen_and_asthma.py +++ b/lib/alerts/pollen_and_asthma.py @@ -13,7 +13,7 @@ from ..pollen.parse import LEVEL_EMOJI, LEVELS from ..timeutil import at_hour, day_text -from .menu import kinds_of +from .kinds import kinds_of log = logging.getLogger(__name__) diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index b8a0085c..56f6a246 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -22,7 +22,7 @@ from ..ecowitt.glance import UVI_ALERT from . import pictures, rules -from .menu import kinds_of +from .kinds import kinds_of from .rules import due, remember from ..ecowitt.rain import Rows, duration, rain_amount, wet_flags from ..timeutil import at_hour, clock_text, to_local diff --git a/lib/periods.py b/lib/periods.py index 0cc17282..9ae8f076 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -13,10 +13,7 @@ from dataclasses import dataclass from datetime import date, datetime, timedelta, tzinfo -from telegram import InlineKeyboardMarkup -from telegram.constants import KeyboardButtonStyle -from .buttons import button PREFIX = "pd:" REMEMBERED = 300 # charts whose call is kept, newest first to stay @@ -99,9 +96,13 @@ def aware(t: datetime) -> datetime: # (naive: the station's clock) def periods_keyboard(drawn_by: dict, current: str | None = None, now: datetime | None = None, - tz: tzinfo | None = None) -> InlineKeyboardMarkup | None: + tz: tzinfo | None = None) -> "InlineKeyboardMarkup | None": """One button for each period the chart's drawn_by lists, labelled as the service labels it, the chart's own (`current`) shaded. When it lists none: a 🔄 that draws it again if its period runs to now (ends_now; `now` and `tz` given), else None.""" + from telegram import InlineKeyboardMarkup # (here, not at the top: the service imports this module's call_key, and knows no Telegram) + from telegram.constants import KeyboardButtonStyle + + from .buttons import button listed = drawn_by.get("periods") or [] if not listed: return InlineKeyboardMarkup([[button("🔄", f"{PREFIX}{RELOAD}")]]) if now and tz and ends_now(drawn_by, now, tz) else None diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 2f0ddbfd..ed60ec0d 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -182,14 +182,16 @@ async def through_the_proxy(): answered["tools"] = [t.name for t in (await client.list_tools()).tools] answered["current"] = json.loads((await client.call_tool("current", {"readings": ["temperature"]})).content[0].text) answered["health"] = json.loads((await client.read_resource("ecobot://health")).contents[0].text) - answered["direct"] = await post_status(url) # 127.0.0.1 is not among the allowed hosts here + answered["stranger"] = await post_status(url, "evil.example") # a Host it doesn't answer (127.0.0.1, localhost and its own + answered["own name"] = await post_status(url, socket.gethostname()) # hostname always are, beside MCP_SERVICE_ALLOWED_HOSTS) await until(lambda: any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text, 60, "the archives") os.kill(os.getpid(), signal.SIGTERM) - async def post_status(url) -> int: + async def post_status(url, host) -> int: async with httpx.AsyncClient() as http: - return (await http.post(url, headers={"Authorization": "Bearer pr0xy", "Content-Type": "application/json"}, json={})).status_code + return (await http.post(url, headers={"Authorization": "Bearer pr0xy", "Content-Type": "application/json", "Host": host}, + json={})).status_code asker = asyncio.create_task(ask_then_stop()) await service_main.main() await asker @@ -198,7 +200,7 @@ async def post_status(url) -> int: assert "MCP 127.0.0.1: POST /mcp tools/call current temperature -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] - assert answered["direct"] == 421 + assert answered["stranger"] == 421 and answered["own name"] != 421 assert "Ecowitt refresh" in answered["health"]["loops"] and answered["health"]["file"]["bytes"] > 0 assert "Alerts NOT running" not in log and "Telegram" not in log diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 7eef79bb..a00694c7 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -399,11 +399,12 @@ def test_images_are_wanted_per_call_else_per_connection(): assert chart_images.asked_dark({"chart_dark": True}) is True and chart_images.asked_dark({"chart_dark": "yes"}) is None -def test_the_service_imports_no_pillow_until_an_image_is_asked_for(tmp_path): - """Importing the server and building its app (as python -m ecobot_service does) imports neither Pillow nor the renderer.""" +def test_the_service_imports_no_pillow_until_an_image_is_asked_for_and_no_telegram_ever(tmp_path): + """Importing the server and building its app (as python -m ecobot_service does) imports neither Pillow nor the renderer, nor the + Telegram library: the service knows nothing of Telegram.""" code = ("import sys, ecobot_service.__main__; from zoneinfo import ZoneInfo; from lib.mcp_server import EcobotServer, http_app; " "from lib.service.context import Context; http_app(EcobotServer(Context(tz=ZoneInfo('UTC'))), tokens=('t',)); " - "print(sorted(m for m in sys.modules if m.split('.')[0] == 'PIL' or m in ('lib.charts', 'lib.draw', 'lib.gauges')))") + "print(sorted(m for m in sys.modules if m.split('.')[0] in ('PIL', 'telegram') or m in ('lib.charts', 'lib.draw', 'lib.gauges')))") done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, env={**os.environ, "DATA_DIR": str(tmp_path)}) assert done.returncode == 0, done.stderr From fef36e9b8130d97314a80cc2ce6c84183cabee63 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:00:39 +0000 Subject: [PATCH 078/125] ecobot-mcp: the MCP program renamed, settings named for their owner, a generated token, two Docker images Names: the package ecobot_service is ecobot_mcp (python -m ecobot_mcp), its logger ecobot.mcp, its data-folder lock mcp.lock; the compose service, container and image ecobot-mcp (target ecobot-mcp of the Dockerfile: requirements-mcp.txt and Pillow, no Telegram and no model client, checked at build); the bot's image ecobot (everything). docs/mcp-service.md is docs/ecobot-mcp.md. Log lines say ecobot-mcp ("ecobot-mcp: connected to ..."). Settings: ecobot-mcp's start with MCP_, the bot's with BOT_, the shared ones (TZ, DATA_DIR, LOG_LEVEL, DARKMODE, AUTH_TOKENS) have neither. An old name is still read when the new one is unset, named in one warning at start (never the value); both set, the new one wins. MCP_SERVICE_TOKENS is AUTH_TOKENS: ecobot-mcp accepts each, the bot sends the first. Unset, ecobot-mcp generates a token at its first start (DATA_DIR/auth_token, 0600, linked into place, reused) and the bot reads it from the same folder; ecobot-mcp no longer refuses a non-loopback bind. WEATHER_MCP_TOKEN is retired: sent only while AUTH_TOKENS is unset, with a warning. Docs (README install and upgrade with the renamed-settings table, configuration.md by owner, DEVELOPMENT.md), compose files, systemd units (ecobot-mcp.service unsets the bot's secrets by new and old names), CI (docker.yml builds and checks both images). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- .dockerignore | 3 +- .github/workflows/ci.yml | 24 +-- .github/workflows/docker.yml | 34 +++-- DEVELOPMENT.md | 105 +++++++------ Dockerfile | 66 ++++++--- README.md | 154 ++++++++++++------- TODO.md | 12 +- compose.host-network.yaml | 4 +- compose.journald.yaml | 2 +- compose.yaml | 38 +++-- docker/bot.env | 5 +- docs/configuration.md | 130 ++++++++-------- docs/{mcp-service.md => ecobot-mcp.md} | 40 ++--- docs/features.md | 8 +- docs/how-it-works.md | 12 +- docs/simplification-review.md | 16 +- docs/storage-plan.md | 8 +- ecobot-mcp.service | 23 +-- ecobot.py | 77 ++++++---- ecobot.service | 9 +- ecobot_mcp/__init__.py | 6 + {ecobot_service => ecobot_mcp}/__main__.py | 58 ++++---- {ecobot_service => ecobot_mcp}/core.py | 22 +-- ecobot_service/__init__.py | 7 - lib/admins.py | 8 +- lib/airgradient/local.py | 4 +- lib/airgradient/metrics.py | 2 +- lib/airgradient/source.py | 6 +- lib/alert_log.py | 2 +- lib/alerts/forecast.py | 2 +- lib/alerts/notify.py | 2 +- lib/alerts/particulates.py | 4 +- lib/alerts/store.py | 2 +- lib/alerts/weather.py | 6 +- lib/auth_token.py | 48 ++++++ lib/bot.py | 34 ++--- lib/chart_images.py | 2 +- lib/config.py | 165 +++++++++++++-------- lib/ecowitt/homeassistant.py | 4 +- lib/forecast/source.py | 4 +- lib/gauge_sheet.py | 2 +- lib/intent.py | 2 +- lib/llm.py | 4 +- lib/logs.py | 2 +- lib/mcp_server.py | 20 +-- lib/model_tools.py | 2 +- lib/partday.py | 2 +- lib/periods.py | 6 +- lib/periods_text.py | 2 +- lib/pollen/source.py | 2 +- lib/prompt.py | 2 +- lib/service/__init__.py | 2 +- lib/service/about.py | 6 +- lib/service/alerts.py | 2 +- lib/service/common.py | 2 +- lib/service/current.py | 2 +- lib/service/daylook.py | 2 +- lib/service/days.py | 2 +- lib/service/forecast.py | 2 +- lib/service/instructions.py | 2 +- lib/service/names.py | 6 +- lib/service/outlook.py | 2 +- lib/service/pollen.py | 2 +- lib/service/readings.py | 2 +- lib/service/relate.py | 2 +- lib/service/scan.py | 2 +- lib/service/summary.py | 2 +- lib/upstream.py | 29 ++-- lib/weather.py | 22 +-- requirements-charts.txt | 4 +- requirements-mcp.txt | 8 + requirements.txt | 8 +- scripts/bench_storage.py | 2 +- scripts/conditions.py | 6 +- scripts/ecowitt_metrics.py | 7 +- scripts/eval_prompts.py | 5 +- scripts/refill_airgradient.py | 2 +- tests/conftest.py | 16 +- tests/evalkit.py | 10 +- tests/fakes.py | 2 +- tests/old_tools.py | 2 +- tests/report_words.py | 2 +- tests/test_admin_only.py | 22 +-- tests/test_agent.py | 2 +- tests/test_airgradient.py | 6 +- tests/test_airgradient_local.py | 4 +- tests/test_alert_log.py | 2 +- tests/test_averages.py | 2 +- tests/test_bench_storage.py | 4 +- tests/test_bot_remote.py | 30 ++-- tests/test_chart_answers.py | 2 +- tests/test_dashboard.py | 2 +- tests/test_data_dir.py | 2 +- tests/test_forecast.py | 4 +- tests/test_forecast_alert.py | 2 +- tests/test_hass_live.py | 4 +- tests/test_intent.py | 2 +- tests/test_irrigation.py | 8 +- tests/test_logs.py | 2 +- tests/test_mcp_listen.py | 40 ++--- tests/test_mcp_server.py | 36 ++--- tests/test_packaging.py | 56 +++++++ tests/test_periods.py | 6 +- tests/test_periods_text.py | 2 +- tests/test_pollen.py | 2 +- tests/test_service_about.py | 2 +- tests/test_service_evals.py | 2 +- tests/test_service_instructions.py | 2 +- tests/test_service_switch.py | 2 +- tests/test_settings.py | 136 +++++++++++++++++ tests/test_startup.py | 60 ++++---- 111 files changed, 1133 insertions(+), 682 deletions(-) rename docs/{mcp-service.md => ecobot-mcp.md} (96%) create mode 100644 ecobot_mcp/__init__.py rename {ecobot_service => ecobot_mcp}/__main__.py (63%) rename {ecobot_service => ecobot_mcp}/core.py (93%) delete mode 100644 ecobot_service/__init__.py create mode 100644 lib/auth_token.py create mode 100644 requirements-mcp.txt create mode 100644 tests/test_packaging.py create mode 100644 tests/test_settings.py diff --git a/.dockerignore b/.dockerignore index c6c0ac0b..d683e365 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,11 +2,12 @@ # in the container: docker compose exec ecobot python scripts/...) * !ecobot.py -!ecobot_service/ +!ecobot_mcp/ !lib/ !schemas/ !scripts/ !requirements.txt +!requirements-mcp.txt !requirements-charts.txt # the commit the log says it is running is read from these (a clone; the files are a few hundred bytes) !.git/HEAD diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f849626..9ed90338 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,8 +21,8 @@ concurrency: cancel-in-progress: true env: - TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} # optional: set both secrets to get failures as a Telegram message - TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }} + NOTIFY_TELEGRAM_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }} # optional: set both secrets to get failures as a Telegram message (not the bot's + NOTIFY_TELEGRAM_CHAT: ${{ secrets.TELEGRAM_CHAT_ID }} # BOT_TELEGRAM_TOKEN setting: CI's own names) jobs: test: @@ -50,10 +50,10 @@ jobs: if-no-files-found: ignore retention-days: 14 - name: Tell me on Telegram (main only) - if: failure() && github.ref == 'refs/heads/main' && env.TELEGRAM_BOT_TOKEN != '' + if: failure() && github.ref == 'refs/heads/main' && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=CI failed on main: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true newest: @@ -84,15 +84,15 @@ jobs: if-no-files-found: ignore retention-days: 30 - name: Tell me on Telegram - if: (failure() || steps.pictures.outcome == 'failure') && env.TELEGRAM_BOT_TOKEN != '' + if: (failure() || steps.pictures.outcome == 'failure') && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=The newest Pillow changes something: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true live-evals: # Advisory, never blocks: asks the real model the few questions in tests/evals/weekly.txt and checks which tool it calls. Needs the - # repository secret OPENROUTER_API_KEY (skipped without it); OPENROUTER_MODEL is optional, for when production runs another model than deepseek/deepseek-v4.1-flash-1017. A failure is run once more before it is reported. + # repository secret OPENROUTER_API_KEY (skipped without it; the eval script's own names, not the bot's BOT_OPENROUTER_*); OPENROUTER_MODEL is optional, for when production runs another model than deepseek/deepseek-v4.1-flash-1017. A failure is run once more before it is reported. if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest continue-on-error: true @@ -115,8 +115,8 @@ jobs: if [ "$ALL_CASES" != "true" ]; then ids=(--ids "$(paste -sd, tests/evals/weekly.txt)"); fi python scripts/eval_prompts.py --live "${ids[@]}" || { echo "Failed: asking once more"; python scripts/eval_prompts.py --live "${ids[@]}"; } - name: Tell me on Telegram - if: failure() && env.TELEGRAM_BOT_TOKEN != '' + if: failure() && env.NOTIFY_TELEGRAM_TOKEN != '' run: | - curl -fsS "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ - --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \ + curl -fsS "https://api.telegram.org/bot${NOTIFY_TELEGRAM_TOKEN}/sendMessage" \ + --data-urlencode "chat_id=${NOTIFY_TELEGRAM_CHAT}" \ --data-urlencode "text=The model answers differently to the saved questions: ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" || true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 38355460..e67a6220 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,8 +1,8 @@ -name: Docker image +name: Docker images on: push: # any branch, so a pull request's commits carry the check too - paths: [Dockerfile, .dockerignore, requirements.txt, requirements-charts.txt, .github/workflows/docker.yml] + paths: [Dockerfile, .dockerignore, requirements.txt, requirements-mcp.txt, requirements-charts.txt, .github/workflows/docker.yml] workflow_dispatch: permissions: @@ -10,20 +10,29 @@ permissions: jobs: image: - # The image builds from the Dockerfile, the bot starts in it, and the charts it draws there are the approved ones, in Inter + # Both images build from the Dockerfile (each target's build imports its program, ecobot-mcp's with no Telegram and no model + # client in it), each program starts in its image, and the charts drawn there are the approved ones, in Inter runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - name: Build - run: docker build --build-arg COMMIT="$GITHUB_SHA" -t ecobot . + - name: Build ecobot-mcp + run: docker build --target ecobot-mcp --build-arg COMMIT="$GITHUB_SHA" -t ecobot-mcp . + - name: Build ecobot (the bot) + run: docker build --target ecobot --build-arg COMMIT="$GITHUB_SHA" -t ecobot . + - name: ecobot-mcp starts and names this commit + run: | + docker run --rm --network none ecobot-mcp > start-mcp.log 2>&1 || true # stops: no data source set + cat start-mcp.log + grep -q "Starting ecobot-mcp ${GITHUB_SHA::7}" start-mcp.log - name: The bot starts and names this commit run: | - docker run --rm --network none -e TELEGRAM_BOT_TOKEN=0:x -e OPENROUTER_API_KEY=x ecobot > start.log 2>&1 || true # stops: no data source set + docker run --rm --network none -e BOT_TELEGRAM_TOKEN=0:x -e BOT_OPENROUTER_API_KEY=x ecobot > start.log 2>&1 || true # stops: no data source set cat start.log grep -q "Starting ecobot ${GITHUB_SHA::7}" start.log - - name: Charts drawn in the image + - name: Charts drawn in each image run: | - docker run --rm --network none -v "$PWD/tests:/app/tests:ro" ecobot python -c ' + for image in ecobot ecobot-mcp; do + docker run --rm --network none -v "$PWD/tests:/app/tests:ro" "$image" python -c ' from PIL import Image from lib import charts from tests import chart_samples, imagecmp @@ -32,8 +41,11 @@ jobs: share = imagecmp.difference(imagecmp.snapshot(make(), name.endswith("_dark")), Image.open(imagecmp.GOLDEN / f"{name}.png"))[0] assert share <= imagecmp.TOLERANCE, f"{name}: {share:.2%} of the pixels differ from tests/charts/{name}.png" print("Inter with semibold titles; every sample chart matches its reference image")' + done - name: Size run: | - unpacked=$(docker run --rm --network none --user 0 --entrypoint du ecobot -sx --apparent-size --block-size=1M / | cut -f1) - compressed=$(docker save ecobot | gzip -c | wc -c) - echo "The image: ${unpacked} MB unpacked, $((compressed / 1000000)) MB compressed" | tee -a "$GITHUB_STEP_SUMMARY" + for image in ecobot-mcp ecobot; do + unpacked=$(docker run --rm --network none --user 0 --entrypoint du "$image" -sx --apparent-size --block-size=1M / | cut -f1) + compressed=$(docker save "$image" | gzip -c | wc -c) + echo "The image ${image}: ${unpacked} MB unpacked, $((compressed / 1000000)) MB compressed" | tee -a "$GITHUB_STEP_SUMMARY" + done diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index cfc222c7..1e079cd2 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -4,9 +4,9 @@ How to test the bot and what the GitHub checks do. (Running it is in `README.md` ## Tests ``` -pip install -r requirements-dev.txt # requirements.txt, requirements-charts.txt (Pillow) and pytest +pip install -r requirements-dev.txt # requirements.txt (with requirements-mcp.txt), requirements-charts.txt (Pillow) and pytest python -m pytest # runs in parallel (pytest.ini); `-n0` for one process -python scripts/eval_prompts.py # the saved questions: decisions made in code and the service expectations, no key needed +python scripts/eval_prompts.py # the saved questions: decisions made in code and the tools' expectations, no key needed ``` The suite takes about 25 s on four cores. The slowest fixture, the fake station's 18-month archive (`archived_cache` in `tests/conftest.py`), is built once an hour and shared by the workers and by later runs: it lives under pytest's own temp folder (`/tmp/pytest-of-/ecobot-archive-*.sqlite`), @@ -26,70 +26,85 @@ it and kept (`ecobot-archive-pinned-*.sqlite`); a tool's answer to words alone c The code targets Python 3.13.5 (`.python-version`). Claude Code sessions build the same Python into `.venv` with uv (`.claude/hooks/session-start.sh`). -## The MCP service -The service on its own ([docs/mcp-service.md](docs/mcp-service.md) 3.8, step 5): the sources and their syncers, the alert rules writing the -alert log, and the MCP server (`lib/mcp_server.py`) at `http://MCP_SERVICE_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). -It reads the bot's settings ([docs/configuration.md](docs/configuration.md)) less the bot's own, and `MCP_SERVICE_TOKENS`, `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS`: +## ecobot-mcp +ecobot-mcp, the MCP server on its own (`python -m ecobot_mcp`, the package `ecobot_mcp/`; [docs/ecobot-mcp.md](docs/ecobot-mcp.md) 3.8, +step 5): the sources and their syncers, the alert rules writing the alert log, and the MCP server (`lib/mcp_server.py`) at +`http://MCP_BIND/mcp` (Streamable HTTP, protocol 2026-07-28 and the older one). It reads the `MCP_` settings and the shared ones +([docs/configuration.md](docs/configuration.md)), the bot's (`BOT_`) not at all; its packages are `requirements-mcp.txt` (no Telegram, +no model client; `requirements.txt` is everything, for the bot): ``` -set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings, as the bot reads them -MCP_SERVICE_TOKENS=$(openssl rand -hex 16) python -m ecobot_service # http://127.0.0.1:8765/mcp -sudo docker compose up -d ecobot-service # in Docker (compose.yaml), on the host's port 8765 +set -a; . <(sudo cat /etc/ecobot.env); set +a # the settings +DATA_DIR=/tmp/ecobot python -m ecobot_mcp # http://127.0.0.1:8765/mcp +sudo docker compose up -d ecobot-mcp # in Docker (compose.yaml), on the host's port 8765 ``` -Only one process runs the service on a data folder: it holds `service.lock` there, so `python -m ecobot_service` refuses to start beside -a bot that runs the service itself (`WEATHER_MCP_URL` unset), and the other way round. Make the bot its client first (below): set -`WEATHER_MCP_URL` and restart the bot, then start the service; the bot waits for it and connects when it is up. -Claude Code connects over HTTP: `claude mcp add --transport http ecobot http://127.0.0.1:8765/mcp --header "Authorization: Bearer "`. +Every request needs a bearer token: one of `AUTH_TOKENS`, or, with that unset, the one it generates at its first start and keeps in +the data folder (`lib/auth_token.py`: `DATA_DIR/auth_token`, mode 0600, made whole and then linked into place; its path is logged, +never its value). Only one process runs ecobot-mcp's part on a data folder: it holds `mcp.lock` there, so `python -m ecobot_mcp` +refuses to start beside a bot that runs it itself (`BOT_MCP_URL` unset), and the other way round. Make the bot its client first +(below): set `BOT_MCP_URL` and restart the bot, then start ecobot-mcp; the bot waits for it and connects when it is up. +Claude Code connects over HTTP: `claude mcp add --transport http ecobot http://127.0.0.1:8765/mcp --header "Authorization: Bearer $(cat /tmp/ecobot/auth_token)"`. A client that shows pictures can have the charts as images: `http://127.0.0.1:8765/mcp?charts=png` (or, per call, request `_meta` -`chart_image: "png"`; docs 3.7). Pillow (`requirements-charts.txt`) is imported only then: a service installed from `requirements.txt` alone -answers with the charts' JSON and a `chart_image_note`, and warns once. +`chart_image: "png"`; docs 3.7). Pillow (`requirements-charts.txt`) is imported only then: installed from `requirements-mcp.txt` alone +ecobot-mcp answers with the charts' JSON and a `chart_image_note`, and warns once. To look at it by hand: `npx @modelcontextprotocol/inspector` against the URL with the header `Authorization: Bearer `. Its tests: `tests/test_mcp_server.py` (the SDK's in-memory transport: every tool listed and answering as the ServiceTool does, each resource, the alerts' template, the prompts, the publishing, the tokens; the chart images asked per call and, under uvicorn, by the URL's -`?charts=png`, without Pillow, and that importing the server imports no Pillow) and `tests/test_mcp_listen.py` (the real app under uvicorn -on a free localhost port: a client that listens loses its listen when the service stops and reads what it missed when it is back; the -token and Host checks over HTTP; `python -m ecobot_service` with the fake sources, a tool call through -a proxy's Host name). +`?charts=png`, without Pillow, and that importing the server imports no Pillow), `tests/test_mcp_listen.py` (the real app under uvicorn +on a free localhost port: a client that listens loses its listen when ecobot-mcp stops and reads what it missed when it is back; the +token and Host checks over HTTP; `python -m ecobot_mcp` with the fake sources, a tool call through a proxy's Host name), +`tests/test_settings.py` (each setting's owner prefix, the old names, the generated token) and `tests/test_packaging.py` (the two +images, compose, the systemd unit). -### The bot as the service's client -With `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`, one of the service's `MCP_SERVICE_TOKENS`) set, the bot runs no sources, syncers or alert rules of -its own and reaches the service over MCP (`lib/weather.RemoteWeather`, [docs/mcp-service.md](docs/mcp-service.md) 3.8): one client pinned -to protocol 2026-07-28, kept by one supervisor task (`lib/upstream.Upstream`), which discovers by hand for the instructions and listens to -`ecobot://alerts`, `ecobot://station` and `ecobot://forecast`; when the connection fails or the listen is lost it builds a new client after -a backoff, listens again and reads the alerts after the last id it handled. Unset, the bot runs the service in-process as before -(`lib/weather.LocalWeather`). Both are one interface, `lib/weather.py`, which everything the bot asks of the service goes through: -the model's tools and instructions, its shortcuts, report, gauges, charts drawn ahead and period buttons, Help and `/usage`, the alerts -(lib/alerts/notify.AlertDelivery reads either log) and the irrigation check's rain and forecast (`ServiceRain`, `ServiceForecast`). -The charts the bot's own code asks for (charts drawn ahead, the period buttons, the alerts' pictures and their 🔄) come drawn by the -service (`chart_image`: the remote one sends its PNG, `chart_image: "png"` in the request's `_meta`, in the bot's own theme, `chart_dark`; -in-process, the same `lib/charts.render_data`); a question's charts (the model's answer, or a sentence answered in code) and the dashboard -(`lib/gauges.py`) are still drawn by the bot. +### The bot as ecobot-mcp's client +With `BOT_MCP_URL` set, the bot runs no sources, syncers or alert rules of its own and reaches ecobot-mcp over MCP +(`lib/weather.RemoteWeather`, [docs/ecobot-mcp.md](docs/ecobot-mcp.md) 3.8), sending the first of `AUTH_TOKENS`, or, with that unset, +the token ecobot-mcp generated in the data folder they share (read again for each connection, so the bot may start first; +`ecobot.mcp_token`): one client pinned to protocol 2026-07-28, kept by one supervisor task (`lib/upstream.Upstream`), which discovers by +hand for the instructions and listens to `ecobot://alerts`, `ecobot://station` and `ecobot://forecast`; when the connection fails or the +listen is lost it builds a new client after a backoff, listens again and reads the alerts after the last id it handled. Unset, the bot +runs ecobot-mcp's part in-process as before (`lib/weather.LocalWeather`, over `ecobot_mcp/core.py`). Both are one interface, +`lib/weather.py`, which everything the bot asks for goes through: the model's tools and instructions, its shortcuts, report, gauges, +charts drawn ahead and period buttons, Help and `/usage`, the alerts (lib/alerts/notify.AlertDelivery reads either log) and the +irrigation check's rain and forecast (`ServiceRain`, `ServiceForecast`). +The charts the bot's own code asks for (charts drawn ahead, the period buttons, the alerts' pictures and their 🔄) come drawn by +ecobot-mcp (`chart_image`: the remote one sends its PNG, `chart_image: "png"` in the request's `_meta`, in the bot's own theme, +`chart_dark`; in-process, the same `lib/charts.render_data`); a question's charts (the model's answer, or a sentence answered in code) +and the dashboard (`lib/gauges.py`) are still drawn by the bot. ``` set -a; . <(sudo cat /etc/ecobot.env); set +a -MCP_SERVICE_TOKENS=$TOKEN python -m ecobot_service & # the service, with the sources' settings -WEATHER_MCP_URL=http://127.0.0.1:8765/mcp WEATHER_MCP_TOKEN=$TOKEN python ecobot.py # the bot, its client +export DATA_DIR=/tmp/ecobot +python -m ecobot_mcp & # ecobot-mcp, with the sources' settings (it writes the token) +BOT_MCP_URL=http://127.0.0.1:8765/mcp python ecobot.py # the bot, its client (it reads the token) ``` -In Docker (compose.yaml) this is how they run: `ecobot-service` always, and the bot (the `bot` profile) as its client, its -`WEATHER_MCP_URL` from docker/bot.env (the service's container name; 127.0.0.1 with compose.host-network.yaml), with -`MCP_SERVICE_TOKENS=` and `WEATHER_MCP_TOKEN=` in /etc/ecobot.env. The service answers its own hostname, so no -`MCP_SERVICE_ALLOWED_HOSTS` is needed for the bot. Its tests: `tests/test_bot_remote.py`, the bot against the real server (in memory: a -question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, the service's PNG of a chart byte for byte the bot's own, an alert through -the listen, the irrigation check's inputs; under uvicorn: a dropped connection rebuilt and the alerts after the last id read once, the -service down, `ecobot.main()` as a client). +In Docker (compose.yaml) this is how they run, each from its own image (the Dockerfile's targets `ecobot-mcp` and `ecobot`): +`ecobot-mcp` always, and the bot (the `bot` profile) as its client, its `BOT_MCP_URL` from docker/bot.env (the container's name, +`ecobot-mcp`; 127.0.0.1 with compose.host-network.yaml), the token from the data folder both mount. ecobot-mcp answers its own +hostname, so no `MCP_ALLOWED_HOSTS` is needed for the bot. Its tests: `tests/test_bot_remote.py`, the bot against the real server (in +memory: a question answered with the remote tools and the instructions from discover, a chart from a remote result with its buttons, +ecobot-mcp's PNG of a chart byte for byte the bot's own, an alert through the listen, the irrigation check's inputs; under uvicorn: a +dropped connection rebuilt and the alerts after the last id read once, ecobot-mcp down, `ecobot.main()` as a client). + +### Settings +Each is a field of `lib/config.Config`, named for the program that reads it (`MCP_`, `BOT_`, or none when both do; +docs/configuration.md), with its old name (`_setting(..., old=...)`), still read when the new one is unset and named in one warning at +start. Scripts that read one directly use `lib.config.env(name)`, which knows the old names too. The test suite unsets every setting's +variable, new and old, before each test (`tests/conftest.py`). `scripts/eval_prompts.py --live` has its own names, `OPENROUTER_API_KEY`, +`OPENROUTER_BASE_URL` and `OPENROUTER_MODEL` (the CI secrets'), not the bot's `BOT_OPENROUTER_*`. ## GitHub Actions (`.github/workflows/ci.yml`, and `docker.yml` for `image`) | Job | When | What | |---|---|---| | `test` | every push to `main` and every pull request | the exact versions in `requirements.txt` and `requirements-charts.txt`: pytest (chart pictures included) and the offline evals. The gate. | | `newest` | Sundays 21:17 UTC, or the Run workflow button | the tests with the newest Pillow. Advisory. | -| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` as the bot asks it (`python scripts/eval_prompts.py --live`: its prompt and the service's ten tools) and checks which tool it calls against `tests/evals/service_cases.json`; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 94. Skipped until the secrets below exist. | -| `image` | pushes that change `Dockerfile`, `.dockerignore`, `requirements.txt` or `requirements-charts.txt` (any branch), or the Run workflow button | builds the Docker image, checks the bot starts in it and names the commit, draws the sample charts in it (they must be in Inter and match `tests/charts`); the image's size goes in the run's summary. | +| `live-evals` | Sundays 21:17 UTC, or the Run workflow button | asks the real model the six questions in `tests/evals/weekly.txt` as the bot asks it (`python scripts/eval_prompts.py --live`: its prompt and the ten tools) and checks which tool it calls against `tests/evals/service_cases.json`; a failure is asked once more before it is reported. Advisory. The button's "all cases" box asks all 94. Skipped until the secrets below exist. | +| `image` | pushes that change `Dockerfile`, `.dockerignore`, `requirements.txt`, `requirements-mcp.txt` or `requirements-charts.txt` (any branch), or the Run workflow button | builds both Docker images (`ecobot-mcp` and `ecobot`; each build imports its program, ecobot-mcp's with no Telegram or model client in it), checks each program starts in its image and names the commit, draws the sample charts in each (they must be in Inter and match `tests/charts`); the images' sizes go in the run's summary. | Repository secrets (Settings, Secrets and variables, Actions, New repository secret): - `OPENROUTER_API_KEY`: for `live-evals`. `OPENROUTER_MODEL` is optional (default `deepseek/deepseek-v4.1-flash-1017`): add it only if production runs another model. -- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`: optional; failures of `newest` and `live-evals`, and of `test` on `main`, are then sent to Telegram. +- `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`: optional (CI's own: the workflow passes them on as `NOTIFY_TELEGRAM_TOKEN` and `NOTIFY_TELEGRAM_CHAT`, not the bot's settings); failures of `newest` and `live-evals`, and of `test` on `main`, are then sent to Telegram. Dependabot (`.github/dependabot.yml`) opens weekly pull requests for the Python packages and the actions. `Pillow` comes in a group of its own, because the chart pictures depend on it. ## Chart pictures -Ten fixed sample charts and dashboards (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements-charts.txt` because the pictures depend on it (charts and the dashboard are drawn with it, `lib/draw.py`; the service needs it only for its chart images, so it is a file of its own); a Dependabot update whose chart test fails is the cue to redo the images. +Ten fixed sample charts and dashboards (`tests/chart_samples.py`, made-up data, no clock) are drawn and compared with reference images in `tests/charts/` (`tests/test_chart_images.py`, marker `golden`). They are drawn with Pillow's own font (so they match on any machine; it lacks a few characters, such as ₂ and µ, shown as boxes there only), shrunk to 40% and cut to 64 colours, so each is 7 to 46 KB (about 220 KB in all). A chart passes when under 0.1% of its pixels differ noticeably; a failure leaves the new picture and a red-on-grey picture of the difference in `chart-diffs/` (CI uploads it as the `chart-diffs` artifact). After an intended change to how charts look, run `python scripts/update_charts.py` (or name charts: `... wind air`) and commit the changed images: GitHub shows old and new side by side in the pull request. `Pillow` is pinned in `requirements-charts.txt` because the pictures depend on it (charts and the dashboard are drawn with it, `lib/draw.py`; ecobot-mcp needs it only for its chart images, so it is a file of its own); a Dependabot update whose chart test fails is the cue to redo the images. diff --git a/Dockerfile b/Dockerfile index dc8d9dec..1f7181cc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,45 +1,71 @@ -# The bot (and the MCP service, python -m ecobot_service) as a small image: python:3.13-slim with the runtime packages in a venv that has no pip, no pip cache and no test suites, -# and bytecode for only what the bot imports at start (bytecode for everything is 48 MB more; none adds ~2 s to every start). -# docker build -t ecobot . -# docker compose up -d --build (compose.yaml) +# Two images from one Dockerfile, each python:3.13-slim with its runtime packages in a venv that has no pip, no pip cache and no test +# suites, and bytecode for only what its program imports at start (bytecode for everything is 48 MB more; none adds ~2 s to every start): +# ecobot-mcp (target ecobot-mcp): python -m ecobot_mcp, the sources, the alert rules and the MCP server; requirements-mcp.txt and +# Pillow (requirements-charts.txt), no Telegram and no model client; +# ecobot (target ecobot, the default): the Telegram bot, python ecobot.py; requirements.txt (everything: it draws charts, and runs +# ecobot-mcp's part in-process when BOT_MCP_URL is unset) and Pillow. +# docker build --target ecobot-mcp -t ecobot-mcp . +# docker build --target ecobot -t ecobot . +# docker compose up -d --build (compose.yaml builds both) # Settings come from the environment, as under systemd (README); the state and caches are kept in /data, the folder mounted from the host. FROM python:3.13-slim AS base -FROM base AS build +FROM base AS fonts # Inter for the charts, in the three weights they use (text, semibold titles, bold labels); the rest of the package stays here RUN apt-get update \ && apt-get install -y --no-install-recommends fonts-inter \ && mkdir /fonts \ && find /usr/share/fonts -name 'Inter-Regular.*' -o -name 'Inter-SemiBold.*' -o -name 'Inter-Bold.*' | xargs cp -t /fonts -COPY requirements.txt requirements-charts.txt /tmp/ -# The base image's pip installs into a venv made without one; with Pillow (requirements-charts.txt): the bot draws its charts, and the -# service sends them as images when a client asks + +# The base image's pip installs into a venv made without one +FROM base AS venv-mcp +COPY requirements-mcp.txt requirements-charts.txt /tmp/ +RUN python -m venv --without-pip /opt/venv \ + && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements-mcp.txt -r /tmp/requirements-charts.txt \ + && find /opt/venv -type d -name tests -prune -exec rm -rf {} + + +FROM base AS venv-bot +COPY requirements.txt requirements-mcp.txt requirements-charts.txt /tmp/ RUN python -m venv --without-pip /opt/venv \ && pip --python /opt/venv/bin/python install --no-cache-dir --no-compile --root-user-action=ignore -r /tmp/requirements.txt -r /tmp/requirements-charts.txt \ && find /opt/venv -type d -name tests -prune -exec rm -rf {} + -FROM base -COPY --from=build /opt/venv /opt/venv -COPY --from=build /fonts/ /usr/share/fonts/inter/ +# What both run: the user, the fonts, the shared code. The program reads the running commit for its start-up log line from .git (HEAD, +# the branch's ref, packed-refs: .dockerignore lets only these through), so building from a clone needs nothing more; COMMIT, if given, +# is used instead (a build from files that are not a clone). +FROM base AS app +COPY --from=fonts /fonts/ /usr/share/fonts/inter/ RUN groupadd --system --gid 10001 ecobot \ && useradd --system --uid 10001 --gid 10001 --no-create-home --home-dir /data ecobot \ && mkdir /data && chown 10001:10001 /data WORKDIR /app -COPY ecobot.py ./ -COPY ecobot_service ecobot_service +COPY ecobot_mcp ecobot_mcp COPY lib lib COPY schemas schemas COPY scripts scripts -ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 -# The bot reads the running commit for its start-up log line from .git (HEAD, the branch's ref, packed-refs: .dockerignore lets only these -# through), so building from a clone needs nothing more; COMMIT, if given, is used instead (a build from files that are not a clone). -# Importing the bot and the service once writes the bytecode of every module they load at start, and only those. COPY .git* .git/ ARG COMMIT= -RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi \ - && DATA_DIR=/tmp/build python -c "import lib.bot, ecobot, ecobot_service.__main__, lib.upstream, lib.mcp_server" \ +RUN if [ -n "$COMMIT" ]; then echo "$COMMIT" > .git/HEAD; fi +ENV PATH=/opt/venv/bin:$PATH PYTHONUNBUFFERED=1 + +# ecobot-mcp. Importing it once writes the bytecode of every module it loads at start, and only those, and checks it needs nothing +# but its own packages (no Telegram, no model client: they are not in this venv) +FROM app AS ecobot-mcp +COPY --from=venv-mcp /opt/venv /opt/venv +RUN DATA_DIR=/tmp/build python -c "import sys, importlib.util; import ecobot_mcp.__main__, lib.mcp_server; \ +assert not {'telegram', 'openai'} & set(sys.modules), 'ecobot-mcp imported the bot'; \ +assert importlib.util.find_spec('telegram') is None and importlib.util.find_spec('openai') is None" \ + && rm -rf /tmp/build +ENV DATA_DIR=/data +USER 10001:10001 +CMD ["python", "-m", "ecobot_mcp"] + +# The bot (the default target). The same: the bytecode of what it loads at start, the client of ecobot-mcp and the in-process part included +FROM app AS ecobot +COPY --from=venv-bot /opt/venv /opt/venv +COPY ecobot.py ./ +RUN DATA_DIR=/tmp/build python -c "import lib.bot, ecobot, ecobot_mcp.__main__, lib.upstream, lib.mcp_server" \ && rm -rf /tmp/build ENV DATA_DIR=/data USER 10001:10001 -# The bot; the same image runs the MCP service with `python -m ecobot_service` (compose.yaml's ecobot-service) CMD ["python", "ecobot.py"] diff --git a/README.md b/README.md index 179f9129..1e616484 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ A Telegram bot for your Ecowitt weather station and AirGradient air sensor. Ask - [Docker logging](#docker-logging) - [Docker networking](#docker-networking) - [Upgrading](#upgrading) + - [Renamed settings](#renamed-settings) - [systemd](#systemd-1) - [Docker](#docker-1) - [Configuration](#configuration) @@ -49,23 +50,26 @@ sudoedit /etc/ecobot.env ``` # Telegram bot token from @BotFather -TELEGRAM_BOT_TOKEN= +BOT_TELEGRAM_TOKEN= # Your Telegram user id (ask @userinfobot), so the bot answers you -ADMIN_CHAT_IDS= +BOT_ADMIN_CHAT_IDS= # AI model (optional) -OPENROUTER_API_KEY= +BOT_OPENROUTER_API_KEY= # Weather station (optional) -ECOWITT_API_KEY= -ECOWITT_APP_KEY= +MCP_ECOWITT_API_KEY= +MCP_ECOWITT_APP_KEY= # AirGradient sensor (optional) -AIRGRADIENT_API_TOKEN= -AIRGRADIENT_LOCATION_ID= +MCP_AIRGRADIENT_API_TOKEN= +MCP_AIRGRADIENT_LOCATION_ID= ``` +Settings that start with `MCP_` are read by ecobot-mcp (the part that fetches the readings and runs the alert rules), the ones that +start with `BOT_` by the Telegram bot; the few without either, such as `TZ`, by both. + ### systemd Needs Python 3.13. @@ -98,40 +102,36 @@ journalctl -fu ecobot Warnings and errors alone: `journalctl -p warning -u ecobot`. -#### The weather service on its own (optional) +#### ecobot-mcp on its own (optional) -Not needed: without it the bot runs everything itself, as before. `ecobot-mcp.service` runs the weather service as its own program -(`python -m ecobot_service`, an MCP server at `http://127.0.0.1:8765/mcp`) for other MCP clients, with the bot as one of them. It uses the +Not needed: without it the bot runs everything itself, as before. `ecobot-mcp.service` runs ecobot-mcp as its own program +(`python -m ecobot_mcp`, an MCP server at `http://127.0.0.1:8765/mcp`) for other MCP clients, with the bot as one of them. It uses the bot's data folder, so back that up first: `sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`. Then: -1. Add to `/etc/ecobot.env` (one token, made with `openssl rand -hex 16`): +1. Add to `/etc/ecobot.env`: ``` - MCP_SERVICE_TOKENS= - WEATHER_MCP_URL=http://127.0.0.1:8765/mcp - WEATHER_MCP_TOKEN= + BOT_MCP_URL=http://127.0.0.1:8765/mcp ``` -2. Restart the bot, now the service's client (it waits for the service): `sudo systemctl restart ecobot` -3. Start the service: `sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable --now ecobot-mcp` + No token is needed: at its first start ecobot-mcp makes one and keeps it in the data folder (`/var/lib/private/ecobot/auth_token`), + where the bot reads it. To choose your own instead, set `AUTH_TOKENS=` (both read it; the bot sends the first). +2. Restart the bot, now ecobot-mcp's client (it waits for it): `sudo systemctl restart ecobot` +3. Start ecobot-mcp: `sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl enable --now ecobot-mcp` 4. Check that both run as the same user and the folder's owner is unchanged (the three numbers match): `systemctl show -p UID --value ecobot ecobot-mcp; stat -c %u /var/lib/private/ecobot` -Logs: `journalctl -fu ecobot-mcp`. To go back: `sudo systemctl disable --now ecobot-mcp`, remove the three lines, `sudo systemctl restart ecobot`. -Only one process runs the service on the data folder: started beside a bot without `WEATHER_MCP_URL`, it stops, saying so in its log. +Logs: `journalctl -fu ecobot-mcp`. To go back: `sudo systemctl disable --now ecobot-mcp`, remove the `BOT_MCP_URL` line, `sudo systemctl restart ecobot`. +Only one process runs ecobot-mcp's part on the data folder: started beside a bot without `BOT_MCP_URL`, it stops, saying so in its log. +The token for [other MCP clients](#other-mcp-clients): `sudo cat /var/lib/private/ecobot/auth_token`. Then message `/report` to your Telegram bot. -The service runs sandboxed as its own user, and keeps its data in `/var/lib/private/ecobot`. +The bot runs sandboxed as its own user, and keeps its data in `/var/lib/private/ecobot`. ### Docker -Docker runs two containers from one image: `ecobot-service`, the weather service (the readings, the alerts, and an MCP server that the -bot and other AI clients use), and `ecobot`, the Telegram bot, which is optional. Add to `/etc/ecobot.env` one token for the bot to -reach the service (make it with `openssl rand -hex 16`), the same value twice: - -``` -MCP_SERVICE_TOKENS= -WEATHER_MCP_TOKEN= -``` +Docker runs two containers, each from its own image built from this repository: `ecobot-mcp` (the readings, the alerts, and an MCP +server that the bot and other AI clients use) and `ecobot`, the Telegram bot, which is optional. No token is needed between them: at +its first start ecobot-mcp makes one and keeps it in the data folder, where the bot reads it. ``` sudo mkdir -p /var/lib/private/ecobot && sudo chown -R 10001:10001 /var/lib/private/ecobot @@ -145,7 +145,7 @@ sudo git clone https://github.com/robdevops/ecobot /opt/ecobot cd /opt/ecobot ``` -To run the Telegram bot too (leave this out for the service alone): +To run the Telegram bot too (leave this out for ecobot-mcp alone): ``` echo "COMPOSE_PROFILES=bot" | sudo tee -a /opt/ecobot/.env @@ -155,25 +155,27 @@ echo "COMPOSE_PROFILES=bot" | sudo tee -a /opt/ecobot/.env sudo docker compose up -d --build ``` -Watch the logs: `sudo docker logs -tf ecobot-service` shows `MCP: http://...:8765/mcp`, and `sudo docker logs -tf ecobot` shows -`Weather service: connected`. Then message `/report` to your Telegram bot. +Watch the logs: `sudo docker logs -tf ecobot-mcp` shows `MCP: http://...:8765/mcp`, and `sudo docker logs -tf ecobot` shows +`ecobot-mcp: connected`. Then message `/report` to your Telegram bot. -Docker uses the same data folder as the systemd service, so you can switch between them, one at a time. To go back to systemd: -`sudo docker compose --profile bot down && sudo systemctl start ecobot`. Only one process runs the service on the data folder: started -beside a bot that runs it itself, it stops, saying so in its log. +Docker uses the same data folder as the systemd units, so you can switch between them, one at a time. To go back to systemd: +`sudo docker compose --profile bot down && sudo systemctl start ecobot`. Only one process runs ecobot-mcp's part on the data folder: +started beside a bot that runs it itself, it stops, saying so in its log. #### Other MCP clients -The service is published on port 8765 of every address your machine has, so other devices on your network (Claude Code on a laptop, -say) can use it: give each its own token, added to `MCP_SERVICE_TOKENS` with a comma, and add your machine's IP address or name, as they -write it in the URL, to `MCP_SERVICE_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. For Claude Code: +ecobot-mcp is published on port 8765 of every address your machine has, so other devices on your network (Claude Code on a laptop, +say) can use it with a token: the one it generated (`sudo cat /var/lib/private/ecobot/auth_token`), or, better, one each: set +`AUTH_TOKENS=,` in `/etc/ecobot.env` (made with `openssl rand -hex 16`; the bot sends the first, and a +token taken out is refused from the next start). Add your machine's IP address or name, as they write it in the URL, to +`MCP_ALLOWED_HOSTS`, e.g. `http://192.168.1.5:8765/mcp` needs `192.168.1.5`. For Claude Code: `claude mcp add --transport http ecobot http://192.168.1.5:8765/mcp --header "Authorization: Bearer "`. It is plain HTTP: keep it on your own network. Docker's published ports go around ufw's rules. To keep it to this machine only, change `8765:8765` in `compose.yaml` to `127.0.0.1:8765:8765`. A client that shows pictures can have the charts as images: add `?charts=png` to its URL. #### Docker logging -Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot-service` or `CONTAINER_NAME=ecobot`): +Logs go to Docker's own rotated log; to send them to the journal instead (kept across upgrades, read with `journalctl -f CONTAINER_NAME=ecobot-mcp` or `CONTAINER_NAME=ecobot`): ``` echo "COMPOSE_FILE=compose.yaml:compose.journald.yaml" | sudo tee -a /opt/ecobot/.env @@ -185,7 +187,7 @@ To use both this and [Docker host network](#docker-networking), set `COMPOSE_FIL #### Docker networking -`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or put both containers on the host's network (then run the `docker compose` command again; the bot then reaches the service at 127.0.0.1): +`.local` names (mDNS) can't be found from Docker's private network: use IP addresses for config values, or put both containers on the host's network (then run the `docker compose` command again; the bot then reaches ecobot-mcp at 127.0.0.1): ``` echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee -a /opt/ecobot/.env @@ -195,7 +197,37 @@ echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee -a /opt/ec ## Upgrading -Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept. The log's first line, `Starting ecobot `, says which version is running. +Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept; settings with an old name still work +([Renamed settings](#renamed-settings)). The log's first line, `Starting ecobot `, says which version is running. + +### Renamed settings + +In November 2026 every setting got the name of the program that reads it: `MCP_` for ecobot-mcp's, `BOT_` for the bot's, and none +for the few both read. The old names still work: when a new name is unset and its old one is set, the old one is used, and the log says +once at start which to rename (never their values). Rename them in `/etc/ecobot.env` when convenient: + +| Old name | New name | +|---|---| +| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY`, `ECOWITT_SOURCE` | `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY`, `MCP_ECOWITT_SOURCE` | +| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID`, `AIRGRADIENT_DASHBOARD_URL`, `AIRGRADIENT_LOCAL_URL`, `AIRGRADIENT_SOURCE` | the same with `MCP_` in front | +| `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | +| `PLACE`, `POLLEN`, `POLLEN_DISTRICT`, `FORECAST`, `FORECAST_LAT`, `FORECAST_LON` | the same with `MCP_` in front | +| `RAIN_QUIET_HOURS`, `ALERT_COOLDOWN_MINUTES`, `ANTISPIKE_REQUIRE_CONSECUTIVE` | the same with `MCP_` in front | +| `CHART_ALL_FEELS_LIKE`, `CHART_ALL_VPD` | `MCP_CHART_ALL_FEELS_LIKE`, `MCP_CHART_ALL_VPD` | +| `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS` | `MCP_BIND`, `MCP_ALLOWED_HOSTS` | +| `MCP_SERVICE_TOKENS` | `AUTH_TOKENS` | +| `TELEGRAM_BOT_TOKEN`, `TELEGRAM_PRELOAD_CHAT` | `BOT_TELEGRAM_TOKEN`, `BOT_TELEGRAM_PRELOAD_CHAT` | +| `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL`, `OPENROUTER_MODEL` | `BOT_OPENROUTER_API_KEY`, `BOT_OPENROUTER_BASE_URL`, `BOT_OPENROUTER_MODEL` | +| `ADMIN_ONLY`, `ADMIN_CHAT_IDS`, `LOG_WIDTH` | `BOT_ADMIN_ONLY`, `BOT_ADMIN_CHAT_IDS`, `BOT_LOG_WIDTH` | +| `TUYA_DEVICE_ID`, `TUYA_CLIENT_ID`, `TUYA_CLIENT_SECRET`, `TUYA_BASE_URL` | the same with `BOT_` in front | +| `IRRIGATION_CHECK_HOUR` | `BOT_IRRIGATION_CHECK_HOUR` | +| `WEATHER_MCP_URL` | `BOT_MCP_URL` | +| `WEATHER_MCP_TOKEN` | retired: the bot sends the first of `AUTH_TOKENS`. Still sent, with a warning, while `AUTH_TOKENS` is unset | + +`TZ`, `DATA_DIR`, `LOG_LEVEL` and `DARKMODE` keep their names. In Docker, `docker/bot.env` sets `BOT_MCP_URL`, so an old +`WEATHER_MCP_URL` in `/etc/ecobot.env` no longer overrides it: rename it if you set one. + +### Your data The weather station's and the air sensor's history lives in one file, `ecobot.sqlite`. A version from before 29 October 2026 kept it in `ecowitt_cache.sqlite`, the two files beside it, `airgradient_cache.sqlite` and `conditions_cache.sqlite`; the releases of that week moved them into the one file at start, so upgrade through one of those (commit 56a998c or earlier that week) if you still have the old files, then delete them. @@ -229,10 +261,25 @@ Compose replaces a container only if its image or settings changed. To remove th sudo docker image prune -f && sudo docker builder prune -f ``` -**From a version before the service ran on its own (November 2026):** the bot ran everything itself; now `ecobot-service` does, and the -bot is its client, under the `bot` profile. Back up first (`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`), add the -two token lines from [Docker](#docker) to `/etc/ecobot.env` (remove any `WEATHER_MCP_URL` line: Docker sets it), replace any -`COMPOSE_PROFILES=service` in `/opt/ecobot/.env` with `COMPOSE_PROFILES=bot` (or add it), then: +**From the layout with a container named `ecobot-service` (November 2026):** that container is now `ecobot-mcp`, from an image of +its own (`ecobot-mcp`; the bot's is still `ecobot`). Remove the old container first, or it keeps port 8765: + +``` +sudo docker rm -f ecobot-service +``` + +``` +sudo docker compose up -d --build +``` + +Your token lines still work (`MCP_SERVICE_TOKENS` is read as `AUTH_TOKENS`, and `WEATHER_MCP_TOKEN` is ignored once that is set, with +a warning): rename `MCP_SERVICE_TOKENS` to `AUTH_TOKENS` and delete `WEATHER_MCP_TOKEN`, or delete both to use the token ecobot-mcp +generates. See [Renamed settings](#renamed-settings). + +**From a version before ecobot-mcp ran on its own (November 2026):** the bot ran everything itself; now `ecobot-mcp` does, and the +bot is its client, under the `bot` profile. Back up first (`sudo cp -a /var/lib/private/ecobot /var/lib/private/ecobot.bak`), remove +any `BOT_MCP_URL` (or `WEATHER_MCP_URL`) line from `/etc/ecobot.env` (Docker sets it), replace any `COMPOSE_PROFILES=service` in +`/opt/ecobot/.env` with `COMPOSE_PROFILES=bot` (or add it), then: ``` sudo docker compose --profile bot down && sudo docker compose up -d --build @@ -244,16 +291,17 @@ Settings are environment variables in `/etc/ecobot.env`. The ones you're most li | Variable | What it does | |---|---| -| `TELEGRAM_BOT_TOKEN` | Required. | -| `ADMIN_CHAT_IDS` | Telegram user ids allowed to use the bot, besides the admins of groups it is in. | -| `OPENROUTER_API_KEY` | Enables the AI model. Without it the bot still does reports, charts, lookups and alerts. | -| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY` | Weather station through Ecowitt's cloud. | -| `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | Weather station through Home Assistant (instead of the cloud, or with it as a fallback; `ECOWITT_SOURCE`). | -| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID` | Air sensor, via AirGradient's cloud. | -| `AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | -| `AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | -| `POLLEN`, `FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | -| `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN` | Optional. The bot as a client of the weather service running on its own (`python -m ecobot_service`, e.g. `http://127.0.0.1:8765/mcp`, and one of its `MCP_SERVICE_TOKENS`): the bot then fetches nothing and runs no alert rules itself, and needs none of the source settings above. Unset (the default), the bot runs everything itself, as before. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-the-services-client). | +| `BOT_TELEGRAM_TOKEN` | Required. | +| `BOT_ADMIN_CHAT_IDS` | Telegram user ids allowed to use the bot, besides the admins of groups it is in. | +| `BOT_OPENROUTER_API_KEY` | Enables the AI model. Without it the bot still does reports, charts, lookups and alerts. | +| `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY` | Weather station through Ecowitt's cloud. | +| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | Weather station through Home Assistant (instead of the cloud, or with it as a fallback; `MCP_ECOWITT_SOURCE`). | +| `MCP_AIRGRADIENT_API_TOKEN`, `MCP_AIRGRADIENT_LOCATION_ID` | Air sensor, via AirGradient's cloud. | +| `MCP_AIRGRADIENT_LOCAL_URL` | Read the AirGradient sensor directly on your network e.g. `http://airgradient_.local` (use a fixed IP address for the URL in Docker, or see [Docker networking](#docker-networking)) | +| `MCP_AIRGRADIENT_SOURCE` | Where the air sensor's readings come from: `auto` (the default) is each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud, each filling only what the ones before it lack; `local`, `homeassistant` or `cloud` is that one alone. | +| `MCP_POLLEN`, `MCP_FORECAST` | `on` to add pollen and thunderstorm asthma, or the daily forecast. | +| `BOT_MCP_URL` | Optional. The bot as a client of ecobot-mcp running on its own (`python -m ecobot_mcp`, e.g. `http://127.0.0.1:8765/mcp`): the bot then fetches nothing and runs no alert rules itself, and needs none of the `MCP_` settings above. Unset (the default), the bot runs everything itself, as before. Docker sets it. See [DEVELOPMENT.md](DEVELOPMENT.md#the-bot-as-ecobot-mcps-client). | +| `AUTH_TOKENS` | Optional. The tokens ecobot-mcp accepts (`token,token,...`, one per client); the bot sends the first. Unset, ecobot-mcp generates one at its first start and keeps it in the data folder (`auth_token`), where the bot reads it. | After editing the file, restart: `sudo systemctl restart ecobot`, or for Docker `sudo docker compose up -d --force-recreate` (`docker restart` keeps the old settings). diff --git a/TODO.md b/TODO.md index 6bc9fde8..6465d74d 100644 --- a/TODO.md +++ b/TODO.md @@ -9,7 +9,7 @@ Does the sensor's `pm02Compensated` equal the cloud's `pm02_corrected`? Both rea meet the cloud's. When the air has real particles in it (smoke, incense, a dusty day), run these within a minute of each other, with `TOKEN` set to the -`AIRGRADIENT_API_TOKEN` and the sensor's address in place of the name if `.local` does not resolve: +`MCP_AIRGRADIENT_API_TOKEN` and the sensor's address in place of the name if `.local` does not resolve: ``` curl -s "https://api.airgradient.com/public/api/v1/locations/153523/measures/current?token=$TOKEN" | jq '{timestamp, pm02, pm02_corrected}' @@ -21,17 +21,17 @@ the interval) before deciding which to trust. ## Try on the real machines -- The sensor's own server: `AIRGRADIENT_LOCAL_URL` on a bot on the sensor's network. Check the log says "live readings from the sensor itself", that "air now" is +- The sensor's own server: `MCP_AIRGRADIENT_LOCAL_URL` on a bot on the sensor's network. Check the log says "live readings from the sensor itself", that "air now" is fresh, and that a chart of today has no step where the bot's readings begin. -- Without a cloud account (no `AIRGRADIENT_API_TOKEN`): nothing should be asked of the cloud, and the first charts only reach back to when the bot began recording. +- Without a cloud account (no `MCP_AIRGRADIENT_API_TOKEN`): nothing should be asked of the cloud, and the first charts only reach back to when the bot began recording. - `ecobot.service` as a real unit (`MemoryDenyWriteExecute`, `AF_NETLINK` for finding the sensor by name, `StateDirectory`, `CacheDirectory`): start it, then ask for a chart, an analysis question and something that reads the caches. - The Docker image with `zeroconf` in it: the `image` check on a pull request builds it. -- `ALERT_COOLDOWN_MINUTES` in the production env file: the default is now 60; a line setting it to 30 keeps 30. +- `MCP_ALERT_COOLDOWN_MINUTES` in the production env file: the default is now 60; a line setting it to 30 keeps 30. ## Try Home Assistant as the weather station's source, then redesign the storage -Set `HOMEASSISTANT_URL` and `HOMEASSISTANT_TOKEN` (and leave `ECOWITT_SOURCE` at `auto`, or try `homeassistant` with no Ecowitt keys) and run it for a week or two. +Set `MCP_HOMEASSISTANT_URL` and `MCP_HOMEASSISTANT_TOKEN` (and leave `MCP_ECOWITT_SOURCE` at `auto`, or try `homeassistant` with no Ecowitt keys) and run it for a week or two. It has only been run against a fake Home Assistant. Check in the log and the charts: - the start-up line says where the readings come from, and the live poll and minute pulls don't warn (or warn once and recover); - a chart of a few hours is drawn a reading a minute, a day or a week looks right, and a chart past Home Assistant's 10 days still has its bands (from the cache); @@ -41,4 +41,4 @@ It has only been run against a fake Home Assistant. Check in the log and the cha Then the storage redesign: [docs/storage-plan.md](docs/storage-plan.md) has the measurements, the design, the migration and the steps (the requirements that were here are its section 2, the decisions its section 6.1). Steps 0 and 1 are done (the measurements, and the new storage checked on the real cache); next is step 2, the station on it. Its step 4 takes the AirGradient's readings from the monitor itself first, -Home Assistant as the fallback and the cloud last (`AIRGRADIENT_SOURCE`; section 3.12 has how each source's PM2.5 is checked). +Home Assistant as the fallback and the cloud last (`MCP_AIRGRADIENT_SOURCE`; section 3.12 has how each source's PM2.5 is checked). diff --git a/compose.host-network.yaml b/compose.host-network.yaml index cdda353a..8b6d4076 100644 --- a/compose.host-network.yaml +++ b/compose.host-network.yaml @@ -2,11 +2,11 @@ services: # On the host's network (its sources may be .local names), on port 8765 of every address the host has, as compose.yaml publishes # it: the bot reaches it at http://127.0.0.1:8765/mcp, and other machines at the host's address. (No hostname of its own here: the # host's name is its name, and it answers that.) - ecobot-service: + ecobot-mcp: network_mode: host hostname: !reset null ports: !reset [] ecobot: network_mode: host environment: - WEATHER_MCP_URL: http://127.0.0.1:8765/mcp + BOT_MCP_URL: http://127.0.0.1:8765/mcp diff --git a/compose.journald.yaml b/compose.journald.yaml index 806c05eb..74489cf4 100644 --- a/compose.journald.yaml +++ b/compose.journald.yaml @@ -2,6 +2,6 @@ services: ecobot: logging: !override driver: journald - ecobot-service: + ecobot-mcp: logging: !override driver: journald diff --git a/compose.yaml b/compose.yaml index 810827c1..76e747d2 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,29 +1,32 @@ -# ecobot in Docker (README). `sudo docker compose up -d --build` builds the image and starts the weather service; the Telegram bot is +# ecobot in Docker (README). `sudo docker compose up -d --build` builds the images and starts ecobot-mcp; the Telegram bot is # optional, under the `bot` profile: `sudo docker compose --profile bot up -d --build`, or COMPOSE_PROFILES=bot in /opt/ecobot/.env. +# Two images from the one Dockerfile: ecobot-mcp (its target ecobot-mcp: no Telegram, no model client) and ecobot (the bot, everything). # Compose replaces a running container only when its image or settings changed. The commit the log's first line names is read from # the clone's .git (see the Dockerfile). Logs: Docker's `local` driver (README: "Docker logging", compose.journald.yaml for the -# journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot-service` (or `ecobot`). +# journal), which compresses and rotates its files (5 of 10 MB here); read them with `docker logs -tf ecobot-mcp` (or `ecobot`). +# Settings (/etc/ecobot.env, docs/configuration.md): MCP_ ones are ecobot-mcp's, BOT_ ones the bot's, the rest both read. services: - # The weather service (docs/mcp-service.md 3.8, DEVELOPMENT.md "The MCP service"): the sources and their syncers, the alert rules + # ecobot-mcp, the MCP server (docs/ecobot-mcp.md 3.8, DEVELOPMENT.md "ecobot-mcp"): the sources and their syncers, the alert rules # and the MCP server, on port 8765 of every address the host has, so other machines on the network can reach it too (plain HTTP, # with a token; put TLS in front of it, e.g. Caddy, to reach it over the internet; for this host only, publish 127.0.0.1:8765:8765). - # It needs MCP_SERVICE_TOKENS (token,token,..., in /etc/ecobot.env): it listens on all of the container's addresses, which it refuses - # to do without tokens. It answers its own name (hostname, below), 127.0.0.1 and localhost; MCP_SERVICE_ALLOWED_HOSTS adds more: the - # host's IP address or name, as LAN clients write it in their URL, and a proxy's name. - ecobot-service: - image: ecobot - container_name: ecobot-service - hostname: ecobot-service + # Every request needs a token: one of AUTH_TOKENS (token,token,..., in /etc/ecobot.env), or, with that unset, the one it generates + # at its first start in the data folder (/var/lib/private/ecobot/auth_token on the host), which the bot reads from there. It answers + # its own name (hostname, below), 127.0.0.1 and localhost; MCP_ALLOWED_HOSTS adds more: the host's IP address or name, as LAN + # clients write it in their URL, and a proxy's name. + ecobot-mcp: + image: ecobot-mcp + container_name: ecobot-mcp + hostname: ecobot-mcp build: context: . + target: ecobot-mcp args: COMMIT: ${COMMIT:-} - command: ["python", "-m", "ecobot_service"] restart: unless-stopped # Docker's default network is private, where .local names (mDNS) can't be found (README: "Docker networking", compose.host-network.yaml) env_file: /etc/ecobot.env environment: - MCP_SERVICE_BIND: 0.0.0.0:8765 + MCP_BIND: 0.0.0.0:8765 ports: - 8765:8765 volumes: @@ -34,14 +37,19 @@ services: max-size: 10m max-file: "5" - # The Telegram bot, a client of the service (WEATHER_MCP_URL, docker/bot.env; WEATHER_MCP_TOKEN, one of MCP_SERVICE_TOKENS, in - # /etc/ecobot.env). It keeps its own state (chats, alert settings) in the same data folder. + # The Telegram bot, a client of ecobot-mcp (BOT_MCP_URL, docker/bot.env), sending the first of AUTH_TOKENS, or, with that unset, the + # token ecobot-mcp generated in the data folder they share. It keeps its own state (chats, alert settings) in the same folder. ecobot: image: ecobot container_name: ecobot + build: + context: . + target: ecobot + args: + COMMIT: ${COMMIT:-} profiles: [bot] restart: unless-stopped - depends_on: [ecobot-service] + depends_on: [ecobot-mcp] env_file: [docker/bot.env, /etc/ecobot.env] volumes: - /var/lib/private/ecobot:/data diff --git a/docker/bot.env b/docker/bot.env index 41353d8b..4f3283ee 100644 --- a/docker/bot.env +++ b/docker/bot.env @@ -1,3 +1,4 @@ # The bot's defaults in Docker (compose.yaml reads this before /etc/ecobot.env, so a setting there wins): the bot is a client of -# the ecobot-service container, reached by its name on the project's network. -WEATHER_MCP_URL=http://ecobot-service:8765/mcp +# the ecobot-mcp container, reached by its name on the project's network. +# (An old WEATHER_MCP_URL in /etc/ecobot.env no longer overrides this: rename it BOT_MCP_URL.) +BOT_MCP_URL=http://ecobot-mcp:8765/mcp diff --git a/docs/configuration.md b/docs/configuration.md index 754dd679..7094f907 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,6 +1,14 @@ # Configuration -The bot is configured only through environment variables. They live in one file, `/etc/ecobot.env`, which the systemd unit (`EnvironmentFile=`) and Docker (`--env-file`) both read. Each data source switches on when its variables are set. +ecobot is configured only through environment variables. They live in one file, `/etc/ecobot.env`, which the systemd units (`EnvironmentFile=`) and Docker (`env_file:`) read. Each data source switches on when its variables are set. + +Each setting is named for the program that reads it: + +- `MCP_...`: read by **ecobot-mcp** (`python -m ecobot_mcp`: the sources, the alert rules, the MCP server). The bot reads them too while it runs all of that in-process (`BOT_MCP_URL` unset, the default under systemd). +- `BOT_...`: read by the **bot** (`ecobot.py`: Telegram, the model, the irrigation controller) alone. +- No prefix: read by **both**. + +Settings were renamed in November 2026 (README: [Renamed settings](../README.md#renamed-settings)). An old name still works when the new one is unset: it is used, and one warning at start names the new name (never the value). Where both are set, the new one wins and the old one is named as ignored. ## The environment file @@ -11,97 +19,103 @@ sudo install -m 600 -o root -g root /dev/null /etc/ecobot.env sudoedit /etc/ecobot.env ``` -One `NAME=value` per line, no `export`; a line starting with `#` is a comment (not text after a value). systemd reads it as root before it drops to the service's own user, so the service itself needs no access to the file, and nobody else on the machine can read your keys. To run the bot by hand from your own shell, load it with `set -a; . <(sudo cat /etc/ecobot.env); set +a`. (Docker reads the file as the person who runs `docker`, so use `sudo docker compose`, or give your user read access with `sudo chown root:youruser /etc/ecobot.env && sudo chmod 640 /etc/ecobot.env`. It also keeps quotes around a value that systemd would drop.) - -## Settings +One `NAME=value` per line, no `export`; a line starting with `#` is a comment (not text after a value). systemd reads it as root before it drops to the unit's own user, so the programs themselves need no access to the file, and nobody else on the machine can read your keys. ecobot-mcp's unit drops the bot's secrets (`UnsetEnvironment=`). To run the bot by hand from your own shell, load it with `set -a; . <(sudo cat /etc/ecobot.env); set +a`. (Docker reads the file as the person who runs `docker`, so use `sudo docker compose`, or give your user read access with `sudo chown root:youruser /etc/ecobot.env && sudo chmod 640 /etc/ecobot.env`. It also keeps quotes around a value that systemd would drop.) `on|off` values: `on yes true 1` / `off no false 0`. Any other value → default (logged). Blank → default. -### Required and model - -| Variable | Default | Description | -|---|---|---| -| `TELEGRAM_BOT_TOKEN` | – | Required by the bot (not the MCP service). Bot token (@BotFather) | -| `OPENROUTER_API_KEY` | – | [OpenRouter](https://openrouter.ai/keys) API key. Unset → no model: `/report`, chart commands, plain lookups ("how hot is it?", "rain chart 7d", "forecast") and all alerts work; anything needing the model gets a "no model" reply | -| `OPENROUTER_MODEL` | `deepseek/deepseek-v4.1-flash-1017` | Model, by its OpenRouter name | -| `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | API endpoint | +## ecobot-mcp's settings (`MCP_`) -At least one of Ecowitt, AirGradient (cloud or local) must be configured. +At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local or Home Assistant) must be configured. ### Sources | Variable | Default | Description | |---|---|---| -| `ECOWITT_API_KEY`, `ECOWITT_APP_KEY` | – | Enables Ecowitt through its cloud. Station's time zone is used | -| `ECOWITT_SOURCE` | `auto` | Where the station's readings come from. `auto`: Home Assistant if `HOMEASSISTANT_URL`/`TOKEN` are set, with Ecowitt's cloud (if its keys are set too) making up what it lacks; `cloud`: Ecowitt's cloud only; `homeassistant`: Home Assistant only (no Ecowitt keys needed) | -| `AIRGRADIENT_API_TOKEN`, `AIRGRADIENT_LOCATION_ID` | – | Enables AirGradient via cloud API: history and gap fill | -| `AIRGRADIENT_LOCAL_URL` | – | Sensor's local server, e.g. `http://airgradient_.local` or an IP. Live reading polled every 60 s, recorded as 5-min means (`pm02Compensated` over `pm02`). Cloud, if configured, only fills gaps. Without cloud vars: sensor + SQLite only, no cloud requests. `.local` resolved in-process (mDNS); in Docker needs the host network (README: Docker networking) or an IP. Sensor down → cloud fallback, retry after 5 min | -| `HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the bot reads the readings back to shade the recent charts between each 5 minutes' lowest and highest, for the days it was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from the bot's own readings | -| `AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | -| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne`. With `WEATHER_MCP_URL`, the service's station's zone wins once read (and is kept for a start while the service is down); `TZ` only until it has ever been read | -| `PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | -| `POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | -| `POLLEN_DISTRICT` | `Central` | East Gippsland, Mallee, North Central, North East, Northern Country, South West, West and South Gippsland, Wimmera. Case-insensitive; unknown → warning | -| `FORECAST` | `off` | Open-Meteo daily forecast: report, `weather_forecast` tool, forecast-change alert | -| `FORECAST_LAT`, `FORECAST_LON` | station's | Forecast location | -| `TUYA_DEVICE_ID`, `TUYA_CLIENT_ID`, `TUYA_CLIENT_SECRET` | – | Enables the irrigation controller (Tuya cloud): Irrigation button, rain delay check, pause/battery alerts | -| `TUYA_BASE_URL` | `https://openapi.tuyaeu.com` | Tuya data centre | -| `IRRIGATION_CHECK_HOUR` | `18` | Local hour of the daily rain-delay check (0–23) | +| `MCP_ECOWITT_API_KEY`, `MCP_ECOWITT_APP_KEY` | – | Enables Ecowitt through its cloud. Station's time zone is used | +| `MCP_ECOWITT_SOURCE` | `auto` | Where the station's readings come from. `auto`: Home Assistant if `MCP_HOMEASSISTANT_URL`/`TOKEN` are set, with Ecowitt's cloud (if its keys are set too) making up what it lacks; `cloud`: Ecowitt's cloud only; `homeassistant`: Home Assistant only (no Ecowitt keys needed) | +| `MCP_AIRGRADIENT_API_TOKEN`, `MCP_AIRGRADIENT_LOCATION_ID` | – | Enables AirGradient via cloud API: history and gap fill | +| `MCP_AIRGRADIENT_LOCAL_URL` | – | Sensor's local server, e.g. `http://airgradient_.local` or an IP. Live reading polled every 60 s, recorded as 5-min means (`pm02Compensated` over `pm02`). Cloud, if configured, only fills gaps. Without cloud vars: sensor + SQLite only, no cloud requests. `.local` resolved in-process (mDNS); in Docker needs the host network (README: Docker networking) or an IP. Sensor down → cloud fallback, retry after 5 min | +| `MCP_AIRGRADIENT_SOURCE` | `auto` | `auto`: each that is set, the sensor itself first, then Home Assistant (if it has the sensor), then the cloud; `local`, `homeassistant` or `cloud`: that one alone | +| `MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN` | – | Home Assistant (e.g. `http://192.168.1.219:8123`) and a long-lived access token (your profile page there). With its Ecowitt and AirGradient integrations the readings are read back to shade the recent charts between each 5 minutes' lowest and highest, for the days ecobot was not watching too (the last 31 days at most; Home Assistant keeps 10 unless its recorder says otherwise). Both needed. They also make Home Assistant a source of the station's readings (see `MCP_ECOWITT_SOURCE`): minute lines, a live reading every few seconds and rain alerts as the gauge reports; without them the shading comes from ecobot's own readings | +| `MCP_AIRGRADIENT_DASHBOARD_URL` | – | "live chart" link in air replies and alerts | +| `MCP_PLACE` | `Melbourne` | Name in the Pollen & asthma and Forecast headings | +| `MCP_POLLEN` | `off` | Melbourne grass pollen + thunderstorm asthma (melbournepollen.com.au): report, `pollen_asthma` tool, alert at High. Oct–Dec only | +| `MCP_POLLEN_DISTRICT` | `Central` | East Gippsland, Mallee, North Central, North East, Northern Country, South West, West and South Gippsland, Wimmera. Case-insensitive; unknown → warning | +| `MCP_FORECAST` | `off` | Open-Meteo daily forecast: report, `weather_forecast` tool, forecast-change alert | +| `MCP_FORECAST_LAT`, `MCP_FORECAST_LON` | station's | Forecast location | -### Access +### Alerts | Variable | Default | Description | |---|---|---| -| `ADMIN_ONLY` | `off` | `on`: answer only admins/creators of groups the bot is in. Others get "only group admins" when addressed. `/alerts` is openable by anyone in a group (changes stay admin-only). Admin list cached 10 min | -| `ADMIN_CHAT_IDS` | – | Extra allowed ids, comma/space separated. User id: allowed before any group exists. Group id (negative): adds its admins and anonymous admins | +| `MCP_ALERT_COOLDOWN_MINUTES` | `60` (5–150) | Rain: dry time before "stopped" (rain that starts again sooner is the same spell; "started" is never held). Temperature crossing: minimum gap between alerts; a change inside the cooldown is held, then sent if still different | +| `MCP_RAIN_QUIET_HOURS` | `0-6` | Local hours with no rain alerts; summarised afterwards. `22-6` wraps midnight, `off` disables | +| `MCP_ANTISPIKE_REQUIRE_CONSECUTIVE` | `2` | Readings in a row a PM1/PM2.5/PM10 rise needs to count (spike ≥ 2.5× and +5 µg/m³ over neighbours otherwise dropped from charts, figures, unhealthy-air alert). `1` / `off` disables. Live "air now" unaffected | -### Alerts +### Charts | Variable | Default | Description | |---|---|---| -| `ALERT_COOLDOWN_MINUTES` | `60` (5–150) | Rain: dry time before "stopped" (rain that starts again sooner is the same spell; "started" is never held). Temperature crossing: minimum gap between alerts; a change inside the cooldown is held, then sent if still different | -| `RAIN_QUIET_HOURS` | `0-6` | Local hours with no rain alerts; summarised afterwards. `22-6` wraps midnight, `off` disables | -| `ANTISPIKE_REQUIRE_CONSECUTIVE` | `2` | Readings in a row a PM1/PM2.5/PM10 rise needs to count (spike ≥ 2.5× and +5 µg/m³ over neighbours otherwise dropped from charts, figures, unhealthy-air alert). `1` / `off` disables. Live "air now" unaffected | +| `MCP_CHART_ALL_FEELS_LIKE` | `off` | Add feels-like panel to "weather all week" | +| `MCP_CHART_ALL_VPD` | `off` | Add VPD panel to "weather all week" | -### Charts +### The MCP server + +`python -m ecobot_mcp` ([ecobot-mcp.md](ecobot-mcp.md) 3.8, `DEVELOPMENT.md`): | Variable | Default | Description | |---|---|---| -| `CHART_ALL_FEELS_LIKE` | `off` | Add feels-like panel to "weather all week" | -| `CHART_ALL_VPD` | `off` | Add VPD panel to "weather all week" | -| `TELEGRAM_PRELOAD_CHAT` | off | Chat id (negative: group/channel) to pre-upload charts to: the other periods of each chart asked for, and, while the bot has been used in the last 15 minutes, the keyboard's charts every 5 minutes. Bot must be able to post there. Copies used for 30 min. Refused upload → no retry until restart | -| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the bot's time zone (the weather station's), light the rest of the day. The dashboard's gauges are dark whatever this says. The service reads it too, for the chart images it sends a client that asks for them (a call may say `chart_dark`); the bot as its client asks for its own theme, so this is the bot's setting for its pictures either way. | +| `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6; Docker sets `0.0.0.0:8765`). Serve it to other machines through TLS (a reverse proxy such as Caddy) | +| `MCP_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-mcp`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses | + +Every request needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once. + +## The bot's settings (`BOT_`) -### Storage and logging +### Telegram and the model | Variable | Default | Description | |---|---|---| -| `DATA_DIR` | `$STATE_DIRECTORY`, else app dir | State (`bot_state.json`) and SQLite caches. Relative paths from the working dir. Created if missing. | -| `LOG_WIDTH` | `24` | Characters of a chat message kept in the log, then `…`; `0` keeps all. No other line is cut | -| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. `DEBUG` adds the bot's own lines (chart timings) | +| `BOT_TELEGRAM_TOKEN` | – | Required by the bot (not by ecobot-mcp). Bot token (@BotFather) | +| `BOT_OPENROUTER_API_KEY` | – | [OpenRouter](https://openrouter.ai/keys) API key. Unset → no model: `/report`, chart commands, plain lookups ("how hot is it?", "rain chart 7d", "forecast") and all alerts work; anything needing the model gets a "no model" reply | +| `BOT_OPENROUTER_MODEL` | `deepseek/deepseek-v4.1-flash-1017` | Model, by its OpenRouter name | +| `BOT_OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` | API endpoint | +| `BOT_TELEGRAM_PRELOAD_CHAT` | off | Chat id (negative: group/channel) to pre-upload charts to: the other periods of each chart asked for, and, while the bot has been used in the last 15 minutes, the keyboard's charts every 5 minutes. Bot must be able to post there. Copies used for 30 min. Refused upload → no retry until restart | +| `BOT_LOG_WIDTH` | `24` | Characters of a chat message kept in the log, then `…`; `0` keeps all. No other line is cut | -### The MCP service - -`python -m ecobot_service` ([mcp-service.md](mcp-service.md) 3.8, `DEVELOPMENT.md`) reads every setting above that is not the bot's own (it needs no `TELEGRAM_BOT_TOKEN`, model or chat setting), and these: +### Access | Variable | Default | Description | |---|---|---| -| `MCP_SERVICE_TOKENS` | none | `token,token`: the bearer tokens the service accepts (each client sends one as `Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart). Compared in constant time; a token is never logged, only its name. Unset → no auth, which the service allows only on a loopback `MCP_SERVICE_BIND` | -| `MCP_SERVICE_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6). Serve it to other machines through TLS (a reverse proxy such as Caddy) | -| `MCP_SERVICE_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-service`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses | +| `BOT_ADMIN_ONLY` | `off` | `on`: answer only admins/creators of groups the bot is in. Others get "only group admins" when addressed. `/alerts` is openable by anyone in a group (changes stay admin-only). Admin list cached 10 min | +| `BOT_ADMIN_CHAT_IDS` | – | Extra allowed ids, comma/space separated. User id: allowed before any group exists. Group id (negative): adds its admins and anonymous admins | -Chart images are not a setting of the service but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([mcp-service.md](mcp-service.md) 3.7). They need Pillow (`requirements-charts.txt`, in the Docker image): installed from `requirements.txt` alone the service answers with the charts' JSON and a note, and warns once. +### Irrigation +| Variable | Default | Description | +|---|---|---| +| `BOT_TUYA_DEVICE_ID`, `BOT_TUYA_CLIENT_ID`, `BOT_TUYA_CLIENT_SECRET` | – | Enables the irrigation controller (Tuya cloud): Irrigation button, rain delay check, pause/battery alerts | +| `BOT_TUYA_BASE_URL` | `https://openapi.tuyaeu.com` | Tuya data centre | +| `BOT_IRRIGATION_CHECK_HOUR` | `18` | Local hour of the daily rain-delay check (0–23) | -### The bot as the service's client +### The bot as ecobot-mcp's client | Variable | Default | Description | |---|---|---| -| `WEATHER_MCP_URL` | none | The service's MCP endpoint (`http://127.0.0.1:8765/mcp`, or its TLS address behind a proxy). Set: the bot is a client of the service ([mcp-service.md](mcp-service.md) step 5): it starts no sources, syncers or alert rules of its own, so the source settings (`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `POLLEN`, `FORECAST` …) are the service's and the bot needs none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are) and the alerts come from the service. Unset: the bot runs the service inside itself, as before | -| `WEATHER_MCP_TOKEN` | none | The bearer token the bot sends: one of the service's `MCP_SERVICE_TOKENS` (give the bot its own) | +| `BOT_MCP_URL` | none (Docker: `http://ecobot-mcp:8765/mcp`) | ecobot-mcp's endpoint (`http://127.0.0.1:8765/mcp`, or its TLS address behind a proxy). Set: the bot is ecobot-mcp's client ([ecobot-mcp.md](ecobot-mcp.md) step 5): it starts no sources, syncers or alert rules of its own, so the `MCP_` settings are ecobot-mcp's and the bot needs none of them; its tools, the server's instructions, the station (time zone, sensors, which alerts there are) and the alerts come from ecobot-mcp. Unset: the bot runs ecobot-mcp's part inside itself, as before | + +The bot asks ecobot-mcp for the pictures of the charts it draws ahead, of the period buttons and of the alerts (request `_meta` `chart_image: "png"`, in its own `DARKMODE` theme), so its `BOT_MCP_URL` needs no `?charts=png`; a question's charts and the dashboard it still draws itself. + +While ecobot-mcp can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the +alerts sent meanwhile that are still news are delivered once it is back. The irrigation controller (`BOT_TUYA_*`) stays the bot's: its daily +check asks ecobot-mcp for the rain measured and the forecast. -The bot asks the service for the pictures of the charts it draws ahead, of the period buttons and of the alerts (request `_meta` `chart_image: "png"`, in its own `DARKMODE` theme), so its `WEATHER_MCP_URL` needs no `?charts=png`; a question's charts and the dashboard it still draws itself. +## Shared settings (no prefix) -While the service can't be reached the bot tells whoever asks so, and reconnects by itself (1, 2, 5, 10, then every 30 seconds); the -alerts sent meanwhile that are still news are delivered once it is back. The irrigation controller (`TUYA_*`) stays the bot's: its daily -check asks the service for the rain measured and the forecast. +| Variable | Default | Description | +|---|---|---| +| `AUTH_TOKENS` | generated | `token,token`: the bearer tokens ecobot-mcp accepts (each client sends one as `Authorization: Bearer `), one per client so one can be revoked alone (take it out and restart); the bot sends the first. Compared in constant time; a token is never logged. Unset: ecobot-mcp generates one at its first start and keeps it in the data folder (`DATA_DIR/auth_token`, mode 0600, the same one every start after; its path is logged, never its value), and the bot, with `AUTH_TOKENS` unset too, reads it from there (the same data folder: systemd's units and Docker's containers share it), warning when it can't. For another client: `sudo cat /var/lib/private/ecobot/auth_token`. (Replaces `MCP_SERVICE_TOKENS` and the bot's `WEATHER_MCP_TOKEN`; the latter, if set, is still sent while `AUTH_TOKENS` is unset, with a warning to move it into `AUTH_TOKENS`, and is ignored, with a warning, once `AUTH_TOKENS` is set) | +| `TZ` | system zone | Only used without Ecowitt (the station's zone wins; a mismatch is logged). IANA name, e.g. `Australia/Melbourne`. With `BOT_MCP_URL`, ecobot-mcp's station's zone wins once read (and is kept for a start while ecobot-mcp is down); `TZ` only until it has ever been read | +| `DATA_DIR` | `$STATE_DIRECTORY`, else app dir | State (`bot_state.json`), the alert log, the SQLite caches and the generated token. Relative paths from the working dir. Created if missing. Both programs use the same one | +| `DARKMODE` | `off` | The charts' colours. `off`: light; `on`: dark; a time range, e.g. `8pm-8am`, `20:00-8:00` or `20-8`: dark between those times in the station's time zone, light the rest of the day. The dashboard's gauges are dark whatever this says. ecobot-mcp reads it for the chart images it sends a client that asks for them (a call may say `chart_dark`); the bot as its client asks for its own theme, so this is the bot's setting for its pictures either way | +| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING`, `ERROR`. `DEBUG` adds the program's own lines (chart timings) | diff --git a/docs/mcp-service.md b/docs/ecobot-mcp.md similarity index 96% rename from docs/mcp-service.md rename to docs/ecobot-mcp.md index 134c49bb..57c1669a 100644 --- a/docs/mcp-service.md +++ b/docs/ecobot-mcp.md @@ -1,4 +1,10 @@ -# MCP service plan +# MCP service plan (ecobot-mcp) + +> **Names today.** The program this plan calls "the service" is **ecobot-mcp**: the package `ecobot_mcp` (`python -m ecobot_mcp`), +> the systemd unit `ecobot-mcp.service`, the Docker image and container `ecobot-mcp`. Its settings start with `MCP_`, the bot's with +> `BOT_`, the shared ones have neither (`AUTH_TOKENS`, which replaced `MCP_SERVICE_TOKENS` and `WEATHER_MCP_TOKEN`): see +> [configuration.md](configuration.md). Every request needs a token: with `AUTH_TOKENS` unset, ecobot-mcp generates one in the data +> folder, which the bot reads, so it no longer refuses a non-loopback address for want of tokens. The plan below keeps its history. The plan for turning this repository into a weather and air-quality service that any MCP client can use: the readings file, the syncers that fill it, and an MCP server over them. Claude Desktop, Claude Code, ChatGPT, Open WebUI or anyone's bot asks it questions @@ -395,14 +401,14 @@ Charts are data: the client draws them, or its model does from the numbers. ### 3.8 Connecting -- **One program:** `python -m ecobot_service` runs the syncers, the alert rules and the server, at `https:///mcp` +- **One program:** `python -m ecobot_mcp` runs the syncers, the alert rules and the server, at `https:///mcp` (Streamable HTTP, `streamable_http_app`, under uvicorn behind TLS: a reverse proxy such as Caddy, or uvicorn's own certificate). The server is the SDK's low-level `Server`, so each tool's input schema is hand-written JSON with its description; the list is built when - asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_SERVICE_ALLOWED_HOSTS)`: by + asked, so it follows the file's metrics. The app is built with `TransportSecuritySettings(allowed_hosts=MCP_ALLOWED_HOSTS)`: by default it answers only `Host: 127.0.0.1` or `localhost`, and refuses the name a proxy or a LAN client uses. - **No stdio:** clients connect over HTTP (Claude Code: `claude mcp add --transport http ...` with the bearer header). A stdio bridge for clients that can only start a local command was built in step 5 and removed: nothing here needs it. -- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `MCP_SERVICE_TOKENS` +- **Auth:** the service's own `TokenVerifier` (the SDK has only the protocol): a constant-time compare against `AUTH_TOKENS` (`token,token,…`, one per client, so one can be revoked alone), passed with `auth=AuthSettings(issuer_url="https://", resource_server_url=None)` (`issuer_url` is required but unused without an OAuth provider; no OAuth metadata is published). Bind to the LAN or a tailnet; nothing needs the internet to reach it. @@ -430,10 +436,10 @@ on its own (step 5). ### 3.10 Configuration -`ECOWITT_*`, `HOMEASSISTANT_*`, `AIRGRADIENT_*`, `ANTISPIKE_REQUIRE_CONSECUTIVE`, `POLLEN*`, `FORECAST_*`, `PLACE`, `TZ` (until the -station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `CHART_ALL_FEELS_LIKE`, `CHART_ALL_VPD`, -`MCP_SERVICE_TOKENS`, `MCP_SERVICE_BIND`, `MCP_SERVICE_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `WEATHER_MCP_URL`, `WEATHER_MCP_TOKEN`, -its own `MCP_SERVICE_TOKENS`. +`MCP_ECOWITT_*`, `MCP_HOMEASSISTANT_*`, `MCP_AIRGRADIENT_*`, `MCP_ANTISPIKE_REQUIRE_CONSECUTIVE`, `MCP_POLLEN*`, `MCP_FORECAST_*`, `MCP_PLACE`, `TZ` (until the +station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thresholds), `MCP_CHART_ALL_FEELS_LIKE`, `MCP_CHART_ALL_VPD`, +`AUTH_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `BOT_MCP_URL`, a token, +its own `AUTH_TOKENS`. ## 4. The bot until it is retired @@ -543,8 +549,8 @@ Each step ships on its own, with the tests and evals green and the bot working t figures behind each. - **Their state** is the service's (`lib/alerts/store.py`, `alert_state.json` beside `bot_state.json`): the first start with no `alert_state.json` moves the rules' keys out of `bot_state.json`'s `monitor` (once), so nothing re-fires after the upgrade; the - irrigation controller's stay in the bot's file. **Config**: the quiet hours and the cooldown stay `RAIN_QUIET_HOURS` and - `ALERT_COOLDOWN_MINUTES`, handed to the rules (and `about`) by the service; the thresholds stay the rules' own constants, which + irrigation controller's stay in the bot's file. **Config**: the quiet hours and the cooldown stay `MCP_RAIN_QUIET_HOURS` and + `MCP_ALERT_COOLDOWN_MINUTES`, handed to the rules (and `about`) by the service; the thresholds stay the rules' own constants, which `about` reads, as no setting changes them today. - **The forecast alert is station-wide** (deliberate): the first forecast fetched from 6 am is the day's baseline for today and tomorrow (no alert); a later one alerts, one event per day, when the high moves by more than 2°C or the chance of at least 1 mm @@ -565,7 +571,7 @@ Each step ships on its own, with the tests and evals green and the bot working t - Tests: the rules' tests assert events appended (`tests/test_alerts.py`), the log and the delivery (`tests/test_alert_log.py`), the forecast baseline (`tests/test_forecast_alert.py`). 5. **MCP, and the service on its own.** `lib/mcp_server.py` serves the tools, resources and prompts (the bus and listen handler, the - transport settings, the token check); the service starts as its own program (`python -m ecobot_service`, its compose file); the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the + transport settings, the token check); the service starts as its own program (`python -m ecobot_mcp`, its compose file); the bot becomes a client over the network (the supervisor, discover for the instructions, `charts` from results, the alert log; `schemas/` goes into the image, which `.dockerignore` keeps out today). `ecobot.py`'s `warm_up()` is split: the first fetch, the archive, the backfill, the Home Assistant imports and the startup line go to the service; the bot keeps only its charts drawn ahead, as `summary` calls at background priority, failing quietly until the service has warmed. The bot's poke of the sources @@ -581,17 +587,17 @@ Each step ships on its own, with the tests and evals green and the bot working t `ListenHandler`): `ResourceUpdated` for the live resources when what the sources keep changes (compared every 2 s, nothing fetched for it; a reading asked for again and unchanged is not sent), the alerts on each new event (`AlertLog.wait`), the station and `ToolsListChanged` when the file's catalogue gains a reading (read every minute; the tools and instructions are then built again). - `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_SERVICE_ALLOWED_HOSTS` and the `TokenCheck` verifier over - `MCP_SERVICE_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_service/`: `core.py` is the service's startup + `http_app`: `streamable_http_app` with `TransportSecuritySettings` over `MCP_ALLOWED_HOSTS` and the `TokenCheck` verifier over + `AUTH_TOKENS` (`AuthSettings(issuer_url=…, resource_server_url=None)`). `ecobot_mcp/`: `core.py` is the service's startup (`start_sources`, `Core`: the alert log, the tools, the alert rules, the keep-warm, and `warm_up`, the first fetch, the weather rules, the live poll, the archive, the backfill and Home Assistant's imports, each loop's last success and failure kept for `ecobot://health`), which `ecobot.py` now calls in-process, its behaviour unchanged; `__main__.py` runs it with the server under - uvicorn (`MCP_SERVICE_BIND`, refusing a non-loopback address without `MCP_SERVICE_TOKENS`); `lib/upstream.py` is the bot's one supervised - client, pinned to 2026-07-28, that discovers by hand, listens and re-listens after a backoff (a stdio bridge was built on it and later removed). The image ships `ecobot_service/` and - `schemas/`; compose has `ecobot-service`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and + uvicorn (`MCP_BIND`; at first it refused a non-loopback address without tokens, and now it always has one, `AUTH_TOKENS` or the generated one); `lib/upstream.py` is the bot's one supervised + client, pinned to 2026-07-28, that discovers by hand, listens and re-listens after a backoff (a stdio bridge was built on it and later removed). The image ships `ecobot_mcp/` and + `schemas/`; compose has `ecobot-mcp`, off unless its profile is asked for. Tests: `tests/test_mcp_server.py` (in memory) and `tests/test_mcp_listen.py` (uvicorn on a localhost port: the lost listen and the reading after the last id, auth, hosts, the service started with the fakes and called through a proxy's Host name). Settings: `Config.from_env(bot=False)` needs no Telegram token. - - **The bot as a client (done).** `WEATHER_MCP_URL` (and `WEATHER_MCP_TOKEN`) set: the bot starts no sources, syncers or alert rules + - **The bot as a client (done).** `BOT_MCP_URL` set (the token: the first of `AUTH_TOKENS`, or the generated one): the bot starts no sources, syncers or alert rules (`ecobot.connect`); unset: it runs the service in-process, unchanged. Both go through one interface, `lib/weather.py` (`LocalWeather` over lib/service and the sources; `RemoteWeather` over MCP): the tools as `Service` lists them (each `call(args, meta)` answering the tool's JSON), the sources there are (`names`), the catalogue, the instructions, the AirGradient link, the diff --git a/docs/features.md b/docs/features.md index bc588dc8..28c63605 100644 --- a/docs/features.md +++ b/docs/features.md @@ -34,10 +34,10 @@ Every alert carries a 🔔 button that opens its toggles: **Alert** (on or off i ## Who can use it -By default the bot answers everyone who messages it. `ADMIN_ONLY=on` answers only the admins of the groups it is in, plus any ids in `ADMIN_CHAT_IDS`; everyone else is told it is for group admins. A refused sender is logged once, with their id, so the owner can add them to `ADMIN_CHAT_IDS`. See [configuration.md](configuration.md). +By default the bot answers everyone who messages it. `BOT_ADMIN_ONLY=on` answers only the admins of the groups it is in, plus any ids in `BOT_ADMIN_CHAT_IDS`; everyone else is told it is for group admins. A refused sender is logged once, with their id, so the owner can add them to `BOT_ADMIN_CHAT_IDS`. See [configuration.md](configuration.md). ## Optional extras -- **Pollen and thunderstorm asthma** for Melbourne (October to December), from melbournepollen.com.au: `POLLEN=on`. -- **Daily forecast** from Open-Meteo, with the chance of at least 1 mm of rain: `FORECAST=on`. -- **Irrigation controller** (a Tuya smart timer): an Irrigation button with its status and buttons to water for 5 to 30 minutes, switch off, pause for 24 to 72 hours, and its own alert toggles. A daily check at 18:00 delays watering 24 hours when rain fell or is likely. Set the `TUYA_*` variables. +- **Pollen and thunderstorm asthma** for Melbourne (October to December), from melbournepollen.com.au: `MCP_POLLEN=on`. +- **Daily forecast** from Open-Meteo, with the chance of at least 1 mm of rain: `MCP_FORECAST=on`. +- **Irrigation controller** (a Tuya smart timer): an Irrigation button with its status and buttons to water for 5 to 30 minutes, switch off, pause for 24 to 72 hours, and its own alert toggles. A daily check at 18:00 delays watering 24 hours when rain fell or is likely. Set the `BOT_TUYA_*` variables. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index d78581fb..7f8430a5 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -11,9 +11,9 @@ The bot logs DEBUG and INFO lines to stdout and WARN and ERROR lines to stderr ( ``` ecobot.py wiring and lifecycle lib/config.py settings -lib/logs.py how log lines look: the module that spoke, and quoted requests and chat messages cut to LOG_WIDTH +lib/logs.py how log lines look: the module that spoke, and quoted requests and chat messages cut to BOT_LOG_WIDTH lib/bot.py Telegram handlers and replies; every button press comes in through one entry point that checks it first -lib/admins.py who may use the bot with ADMIN_ONLY: the admins of the groups it is in, plus ADMIN_CHAT_IDS +lib/admins.py who may use the bot with BOT_ADMIN_ONLY: the admins of the groups it is in, plus BOT_ADMIN_CHAT_IDS lib/llm.py, prompt.py tool-calling loop; system prompt lib/intent.py intent.read(text) -> one Reading: effort, needs data, fast path, chart asks, period hints lib/tools.py, warm.py tool registry and the per-question Turn; keep-warm helper shared by both sources @@ -58,7 +58,7 @@ Both are off by default. They are websites, not APIs (the pollen page is parsed) - Simple highs/lows, chart and "air quality now" questions are fetched by the bot first, so the model is called once, at the end, just to word the answer. - Recent readings are refreshed every minute (the weather station: written to its storage, those still settling as provisional readings the next fetch replaces) and every 4 minutes (the air sensor, in memory); a question that may need them starts a refresh as it arrives (a chart made in code doesn't: it reads just what it needs). A question never waits for a refresh in flight when the storage already holds what it needs (the newest readings for 5 minutes after they were fetched), and its own Ecowitt requests go before the background ones. -- A chart is drawn when it is asked for (a question, a button, an alert), and uploaded once: sending it again (to the next chat an alert goes to, toggling back to a period drawn lately, the next press of a button) uses Telegram's copy. The keyboard's charts, and the chart of each alert type sent in the last 6 hours, are drawn afresh every 5 minutes once the sources are warm, so a press, or the Refresh under an alert, is answered with a chart already drawn (`Bot.draw_buttons_ahead`); with `TELEGRAM_PRELOAD_CHAT` they are uploaded ahead too while the bot has been used in the last 15 minutes, as are the other periods of any chart asked for, so the press sends Telegram's copy. An alert's chart is kept with the bot's other charts (`lib/alerts/pictures.py`, `AlertCharts`): an alert whose chart the bot holds with the alert's newest reading sends that (Telegram's copy once it has been sent anywhere), and Refresh sends the chart drawn ahead since the message was last changed, else draws one and keeps it. +- A chart is drawn when it is asked for (a question, a button, an alert), and uploaded once: sending it again (to the next chat an alert goes to, toggling back to a period drawn lately, the next press of a button) uses Telegram's copy. The keyboard's charts, and the chart of each alert type sent in the last 6 hours, are drawn afresh every 5 minutes once the sources are warm, so a press, or the Refresh under an alert, is answered with a chart already drawn (`Bot.draw_buttons_ahead`); with `BOT_TELEGRAM_PRELOAD_CHAT` they are uploaded ahead too while the bot has been used in the last 15 minutes, as are the other periods of any chart asked for, so the press sends Telegram's copy. An alert's chart is kept with the bot's other charts (`lib/alerts/pictures.py`, `AlertCharts`): an alert whose chart the bot holds with the alert's newest reading sends that (Telegram's copy once it has been sent anywhere), and Refresh sends the chart drawn ahead since the message was last changed, else draws one and keeps it. - Each chart reply logs (at DEBUG) where its time went: `Chart ms: data 12, calc 6, draw 112, PNG 41 (22 KB), send 812`, or `Chart ms: drawn 40s ago, send 210 (Telegram's copy)` for one drawn lately. - The whole history of both sensors, and the last pollen page and forecast, are kept in one SQLite file, `ecobot.sqlite` (`lib/storage`, docs/storage-plan.md). A background archive copies every Ecowitt cycle (5-minute, 30-minute, 4-hour, daily) before Ecowitt expires it, and backfills @@ -66,8 +66,8 @@ Both are off by default. They are websites, not APIs (the pollen page is parsed) local days are worked out as its readings are written (the air sensor's with its glitches taken out), so `weather_days`, `air_days`, the dashboard and the long charts read a row a day. - A chart of 5-minute readings is shaded between each five minutes' lowest and highest, as Home Assistant's history graph is. Ecowitt's own 5-minute history has one number per reading and no range, so the bot keeps the ranges itself, as the bands of the 5-minute readings in `ecobot.sqlite` (`Ecowitt.live_marks`): every live reading it takes (about one a minute, Ecowitt's real_time) is counted in the five minutes around the nearest 5-minute mark, and a stretch with two or more readings has a range, which widens that 5-minute reading's band. Temperature, humidity, dew point, feels like, pressure, solar, UV and the indoor readings are kept; wind has its gusts as its range and rain is bars. Every weather line is shaded, whatever the period (the old rule that left the lines of 31 days or fewer clean is gone). The ranges are promoted into wider buckets as a chart needs them: a 5-minute reading takes its own five minutes', a 30-minute reading (a week's or a month's chart) takes the lowest and highest of the half hour (its band widened from the 5-minute readings inside it whenever they are written, so a chart reads a few hundred rows a reading; it only ever widens Ecowitt's own range, or the lowest and highest of the 5-minute values), and a wider bucket the extremes of the 30-minute ones it holds. Only where the bot was watching: before that the band is Ecowitt's own range, as ever, and past 31 days it is Ecowitt's daily record. The gauges' Daily and Monthly highs and lows take in the recorded ranges too (the year's row takes in the month's). Only a chart asks for them, at a cost of a few milliseconds a reading. About a reading a minute is as fine as Ecowitt's cloud gives, so a range is made of a handful of readings, fewer than Home Assistant's local feed. -- With the station's readings coming from the cloud and Home Assistant set (`HOMEASSISTANT_URL`, `HOMEASSISTANT_TOKEN`), the Ecowitt ranges come from it (`lib/ecowitt/homeassistant.py`); with Home Assistant as the station's source its history carries the bands with the readings, so nothing is read back. Its Ecowitt integration is sent every reading the gateway makes (every 16 to 60 seconds) and keeps each change for 10 days by default, which is finer than the cloud and covers the time the bot was down. The bot finds the station's entities by name (`sensor._outdoor_temperature` and so on), reads their history over the REST API (`/api/history/period`, at start for the last 31 days at most and then the last 3 hours every 15 minutes) and folds it into the same 5-minute ranges: a stretch's range is the values it changed to in that time and the one it held as it began. Home Assistant only records a change of state, so a stretch where nothing changed has a range of nothing, which counts. Temperature, humidity, dew point, feels like, VPD, pressure, solar and UV, and the indoor readings, are read. If Home Assistant can't be reached it is logged once and the bot's own readings carry on. -- The air sensor has three sources (`AIRGRADIENT_SOURCE`; `lib/airgradient/source.py`, docs/storage-plan.md 3.12), each filling only what the ones before it lack, which the file's write rules do (a reading from the bot itself ranks above Home Assistant's, Home Assistant's above the cloud's; a lower one fills only a cell a higher one left empty). The sensor's own server (`AIRGRADIENT_LOCAL_URL`) is read every minute: each 5 minutes' readings are a row (their mean, with their lowest and highest as its band, loaded as a reading's `_range` and shaded on the charts), and each reading is kept as a minute (`1min`, 10 days), so a chart of up to 8 hours is drawn a reading a minute, as the station's are. Home Assistant (`lib/airgradient/homeassistant.py`), when it has the sensor (its entities are found by name: `sensor._voc_index`, `_pm2_5`, `_carbon_dioxide` ...; with several sensors, the one whose reading is nearest), is read the same way while the sensor does not answer the bot (its states, every minute: the live reading, and the rows and minutes), and its history (`/api/history/period`: 31 days at start, as far back as it has them, then the last 3 hours every 15 minutes) is read back for the times the bot did not read the sensor at all: each 5 minutes' mean with its lowest and highest as the band, the bands of the buckets the bot has, and the minutes of the last 9 hours. The cloud fills what neither has: the history before Home Assistant's 10 days (the backfill), the times both were down, and the sensor's name. Its current reading is the live one only when neither answers. +- With the station's readings coming from the cloud and Home Assistant set (`MCP_HOMEASSISTANT_URL`, `MCP_HOMEASSISTANT_TOKEN`), the Ecowitt ranges come from it (`lib/ecowitt/homeassistant.py`); with Home Assistant as the station's source its history carries the bands with the readings, so nothing is read back. Its Ecowitt integration is sent every reading the gateway makes (every 16 to 60 seconds) and keeps each change for 10 days by default, which is finer than the cloud and covers the time the bot was down. The bot finds the station's entities by name (`sensor._outdoor_temperature` and so on), reads their history over the REST API (`/api/history/period`, at start for the last 31 days at most and then the last 3 hours every 15 minutes) and folds it into the same 5-minute ranges: a stretch's range is the values it changed to in that time and the one it held as it began. Home Assistant only records a change of state, so a stretch where nothing changed has a range of nothing, which counts. Temperature, humidity, dew point, feels like, VPD, pressure, solar and UV, and the indoor readings, are read. If Home Assistant can't be reached it is logged once and the bot's own readings carry on. +- The air sensor has three sources (`MCP_AIRGRADIENT_SOURCE`; `lib/airgradient/source.py`, docs/storage-plan.md 3.12), each filling only what the ones before it lack, which the file's write rules do (a reading from the bot itself ranks above Home Assistant's, Home Assistant's above the cloud's; a lower one fills only a cell a higher one left empty). The sensor's own server (`MCP_AIRGRADIENT_LOCAL_URL`) is read every minute: each 5 minutes' readings are a row (their mean, with their lowest and highest as its band, loaded as a reading's `_range` and shaded on the charts), and each reading is kept as a minute (`1min`, 10 days), so a chart of up to 8 hours is drawn a reading a minute, as the station's are. Home Assistant (`lib/airgradient/homeassistant.py`), when it has the sensor (its entities are found by name: `sensor._voc_index`, `_pm2_5`, `_carbon_dioxide` ...; with several sensors, the one whose reading is nearest), is read the same way while the sensor does not answer the bot (its states, every minute: the live reading, and the rows and minutes), and its history (`/api/history/period`: 31 days at start, as far back as it has them, then the last 3 hours every 15 minutes) is read back for the times the bot did not read the sensor at all: each 5 minutes' mean with its lowest and highest as the band, the bands of the buckets the bot has, and the minutes of the last 9 hours. The cloud fills what neither has: the history before Home Assistant's 10 days (the backfill), the times both were down, and the sensor's name. Its current reading is the live one only when neither answers. - Each metric of a lower source is checked against what the bot holds from the ones above it before it fills a gap, over the five minutes both hold (within 2 µg/m³ or 15%, in four in five of them, is the same reading). The sensor corrects its PM2.5 as it is set to (the dashboard's correction when it takes its configuration from there, else its own, none by default) and Home Assistant shows that; the cloud gives the dashboard's. So a metric that differs (the raw PM2.5 against the corrected one) fills no gaps of the sources above it (they are drawn as gaps), and is said once in the log with the fix: set the sensor's PM2.5 correction to the dashboard's, or have it take its configuration from the dashboard. The cloud is asked for the whole of each finished day the bot read itself (one request): the day's check, and its readings fill what the bot lacked. With the sensor alone, nothing to check against, the start-up line says which correction it applies (from its `/config`). ## The report and plain lookups @@ -86,7 +86,7 @@ The system prompt starts with what never changes (the model provider caches the ## Home Assistant as the weather station's source -- `ECOWITT_SOURCE` picks where the readings come from (`auto` is Home Assistant if it is set, the cloud filling in if its keys are set too; `AIRGRADIENT_SOURCE` does the same for the air sensor, see above). `lib/ecowitt/hass_api.py` answers the three calls the bot makes of Ecowitt's cloud (`devices`, `realtime`, `history`) from Home Assistant, in the cloud's shapes and units, so the cache, archive, charts and alerts are the same code whichever answers. `lib/ecowitt/hass_map.py` is the table of entities (`sensor._`, found by name) and `hass_history.py` tells Home Assistant's recorded changes as the cloud's buckets (1 minute, 5, 30, 4 hours, a day), time-weighted means, the highest gust, the last rain counter, with the true lowest and highest of each bucket as `_low`/`_high`. +- `MCP_ECOWITT_SOURCE` picks where the readings come from (`auto` is Home Assistant if it is set, the cloud filling in if its keys are set too; `MCP_AIRGRADIENT_SOURCE` does the same for the air sensor, see above). `lib/ecowitt/hass_api.py` answers the three calls the bot makes of Ecowitt's cloud (`devices`, `realtime`, `history`) from Home Assistant, in the cloud's shapes and units, so the cache, archive, charts and alerts are the same code whichever answers. `lib/ecowitt/hass_map.py` is the table of entities (`sensor._`, found by name) and `hass_history.py` tells Home Assistant's recorded changes as the cloud's buckets (1 minute, 5, 30, 4 hours, a day), time-weighted means, the highest gust, the last rain counter, with the true lowest and highest of each bucket as `_low`/`_high`. - Both set: `lib/ecowitt/fallback.py`. Home Assistant answers; a live reading older than 10 minutes, or none, is replaced by the cloud's if newer; the buckets Home Assistant has none of (before it began recording, while it was down) are asked of the cloud in one request for the span they cover. A failure of either is logged once, with its recovery. - Faster: the live reading is polled every 5 seconds (`Ecowitt.watch_live`), a reading newer than the last is kept for "weather now", the report and the gauges, and the rain alert looks at it at once (`WeatherMonitor.check_rain`) instead of at the next minute's refresh. The gateway itself reports about every minute, so the alert is within seconds of that. A chart of up to 8 hours is drawn a reading a minute (`1min`, Home Assistant only). The bot takes the minutes as they come (the last 9 hours at start, then at each new live reading) into the storage's `1min` rows (`lib/ecowitt/query.py` holds the constants) and drops what is older, so such a chart is drawn without asking Home Assistant; if the minutes don't reach back to its start it uses the 5-minute readings, as longer charts do. - Caveats: Home Assistant keeps 10 days of states unless its recorder is set otherwise, so older history comes from the cache the bot built, or from the cloud where it is set. An answer with nothing in it from Home Assistant alone is not recorded as fetched. diff --git a/docs/simplification-review.md b/docs/simplification-review.md index 028b7f00..e3072322 100644 --- a/docs/simplification-review.md +++ b/docs/simplification-review.md @@ -34,7 +34,7 @@ the contracts. | where | lines | what | recommendation | |---|---|---|---| -| lib/storage/migrate.py (whole), write.py `exact=` 219-227, __init__.py `bulk` 82-109/162-163, ecobot.py 76-79, `open_storage` in both sources | ~510 (+122 scripts/migrate_storage.py, +300 tests, conftest `old_archived_cache`) | the one-off move of the old files into ecobot.sqlite, its checks, and the merge of a part into an existing file | Retire once the old files have been moved on every deployment and deleted. Until then it still fires when a part is enabled later (POLLEN switched on with conditions_cache.sqlite still present). Carries a second upsert SQL and a second "hourly day" rule that go with it | +| lib/storage/migrate.py (whole), write.py `exact=` 219-227, __init__.py `bulk` 82-109/162-163, ecobot.py 76-79, `open_storage` in both sources | ~510 (+122 scripts/migrate_storage.py, +300 tests, conftest `old_archived_cache`) | the one-off move of the old files into ecobot.sqlite, its checks, and the merge of a part into an existing file | Retire once the old files have been moved on every deployment and deleted. Until then it still fires when a part is enabled later (MCP_POLLEN switched on with conditions_cache.sqlite still present). Carries a second upsert SQL and a second "hourly day" rule that go with it | | lib/counts.py (whole), ecobot.py:225, bot.py:1071/1199/1025, warm.py:256, storage `counts.connect`/`uncounted` (6 sites), tools timing fields | ~110 | SQL-statement and thread-hop counters via a sqlite3 Connection subclass and a monkeypatched `asyncio.to_thread`, for the DEBUG `Chart ms` line and the bench script | The redesign it measured is done. Remove from the production path (the monkeypatch of `asyncio.to_thread` at start is the riskiest line in the repo for its value); keep wall-clock timing in scripts/bench_storage.py | | lib/config.py:190-192, 290-291 | 6 | the three old file paths on Config | go with the migration | | ecobot.py:252-253 | 2 | "XAI_API_KEY is no longer used" hint | removed | @@ -43,13 +43,13 @@ the contracts. | feature | lines | where | note | |---|---|---|---| -| ADMIN_ONLY | ~120 | lib/admins.py, bot.py:53-54,334-335,364-394 and the `_allowed` calls, ecobot.py:255-259, config.py:109-119,221-222 | documented and tested. If kept, `_is_group_admin` (bot.py:390-394) should use `Admins`' cache (one `get_chat_member` call per press saved) | -| TELEGRAM_PRELOAD_CHAT | ~95 | bot.py:339-348,997-1063,1203-1204; periods.py:80,112-115,130-132; config.py:142-150,224 | self-contained; `_draw_ahead`, `has_copy`, PRELOAD_TTL have no other caller | +| BOT_ADMIN_ONLY | ~120 | lib/admins.py, bot.py:53-54,334-335,364-394 and the `_allowed` calls, ecobot.py:255-259, config.py:109-119,221-222 | documented and tested. If kept, `_is_group_admin` (bot.py:390-394) should use `Admins`' cache (one `get_chat_member` call per press saved) | +| BOT_TELEGRAM_PRELOAD_CHAT | ~95 | bot.py:339-348,997-1063,1203-1204; periods.py:80,112-115,130-132; config.py:142-150,224 | self-contained; `_draw_ahead`, `has_copy`, PRELOAD_TTL have no other caller | | "Thinking..." draft preview | ~45 | bot.py:207-241,50-51,987,1089-1091,1124; llm.py streaming branch | the newest Telegram feature; without it `keep_typing` suffices and llm.py loses a code path (always stream: -8) | | AirGradient's own temperature/humidity on charts | ~60 | compose.py:60-68,33,192-208; panels.py:49-69; series.py:64-69; intent.py:382-389; tools.py `asked=`/`schemas_for`; airgradient extras | one eval case; the `Tool.asked` mechanism exists for it | -| mDNS for a `.local` AIRGRADIENT_LOCAL_URL | 33 + the zeroconf dependency | lib/airgradient/local.py:32-64 | drop if the URL is an IP or a DNS name | +| mDNS for a `.local` MCP_AIRGRADIENT_LOCAL_URL | 33 + the zeroconf dependency | lib/airgradient/local.py:32-64 | drop if the URL is an IP or a DNS name | | PM2.5 correction note on the start-up line | 28 | airgradient/source.py:176-185,71,167-168,202-203; local.py:126-138 | only when the monitor is the sole source; informational | -| Home Assistant's bands via `import_ranges` | ~55 | ecowitt/homeassistant.py:29-30,52-67,156-167; ecowitt/source.py:86-87,276-293; ecobot.py:172-173 | only needed for ECOWITT_SOURCE=cloud with HOMEASSISTANT_URL set; in auto/homeassistant modes `hass_api.history` already writes the same bands, with a different bucket alignment (mark-centred vs bucket-start). Pick one alignment, then gate or drop | +| Home Assistant's bands via `import_ranges` | ~55 | ecowitt/homeassistant.py:29-30,52-67,156-167; ecowitt/source.py:86-87,276-293; ecobot.py:172-173 | only needed for MCP_ECOWITT_SOURCE=cloud with MCP_HOMEASSISTANT_URL set; in auto/homeassistant modes `hass_api.history` already writes the same bands, with a different bucket alignment (mark-centred vs bucket-start). Pick one alignment, then gate or drop | | `invert_second_axis` | ~10 | compose.py:52-53,197-202; panels two_axes; specs Panel.flip_right; charts `_right_axis(flip)` | no eval, one test | | FEELS_LIKE_IN_ALL / VPD_IN_ALL | ~10 | intent.py:362-368, config.py:214-215, ecobot.py:232-233 | runtime flags for which panels "weather all week" draws | | Several AirGradients in Home Assistant | ~12 | airgradient/homeassistant.py:38-57; source.py:217,225-227 | the nearest-reading tie-break; one monitor in practice | @@ -97,11 +97,11 @@ Each handles a real path; most have a test. Line counts are approximate. Telegram and the bot (bot.py, notify.py, logs.py): `answer_query` swallowing "query is too old" after a restart (11); `ChatMigrated` on a press under an old alert (4); `_press` refusing callback data not on the message's own keyboard (18, security); messages older than 10 minutes ignored (4); the `_send` error ladder in notify.py:252-283 (ChatMigrated, Forbidden and "chat not found" marking a chat gone, RetryAfter and NetworkError one retry, catch-all so other chats still get the alert; ~30, all tested); photo refused falls back to text (7); file-id reuse so a chart is uploaded once (15); the `_flood_wait` int-or-timedelta shim (4, until the PTB upgrade settles); state file moved aside as `.damaged-…` when unreadable (5); group-to-supergroup baseline move (3); reply-keyboard versioning so a changed keyboard reaches phones (~30; only the startup `refresh_keyboards` is redundant); the after-timeout retry at one reasoning step lower (19); `shorten_old` and the identical-tool-call cache in llm.py (37); topic memory (33, what keeps the prompt short and cacheable); `commit_in` reading .git by hand (15); TZ and token/network exits in ecobot.py (11); journald priorities and the httpx line strip (22). -Alerts: quiet hours across midnight with the overnight summary (~50, configured by RAIN_QUIET_HOURS); "rain ended while not watching" closing a spell after downtime (3, required: without it `wet_times[0]` raises; worth a test); `_fell` re-reading a long spell's start (6); gusts only newer than the last check (2); `check_rain` on the live reading with its lock (13, Home Assistant only); irrigation's 24-hour delay renewal (7, needed: the check runs when the delay lapses); stale forecast and controller-unreachable rules (14); the watchdog closing a valve after a run (47, safety); Tuya signing, token retry and shape checks (20). +Alerts: quiet hours across midnight with the overnight summary (~50, configured by MCP_RAIN_QUIET_HOURS); "rain ended while not watching" closing a spell after downtime (3, required: without it `wet_times[0]` raises; worth a test); `_fell` re-reading a long spell's start (6); gusts only newer than the last check (2); `check_rain` on the live reading with its lock (13, Home Assistant only); irrigation's 24-hour delay renewal (7, needed: the check runs when the delay lapses); stale forecast and controller-unreachable rules (14); the watchdog closing a valve after a run (47, safety); Tuya signing, token retry and shape checks (20). Ecowitt: `_TurnLock` one request at a time with an urgent lane (31; "Operation too frequent" is real); retries with backoff and key redaction (38); `UNIT_FIXES` for VPD in inHg (27, about the live API, not only old files); `daily_run` DST wording (7); archive probing groups singly after a refusal and dropping the piezo gauge (20); `OUTAGE_STOP` and the settle edge snapped to whole buckets (13); `Recent` freshness and provisional/final handling in fetch.py (~45); the HA-cloud fallback itself (~70, this is auto mode); `_look` for HA's first state (11); unit conversion from HA (19); DNS-failure hint (9); the bot's own 5-minute bands from live polling (~70, the only band source in cloud-only mode); parts of days at the finest held resolution and `_exact` (27); `only=` dropped when the question never said holiday (6); `DERIVED` fields hidden unless asked (12); `_in_focus`, `rain_from_daily`, `monthly_note` (30); HA-only mode adopting the file's MAC and archive pace (8). -Storage and AirGradient: `NewerFile` refusing a newer schema (6); ALTER TABLE for new catalogue columns (8); unknown time zone name (7); unknown Ecowitt group kept in `extra` (8); UV written whole or with one decimal (3); refetch when a group gains a field (6); the coverage rules of a fetch (10); day rows recomputed when the zone changes (15); a band arriving before its reading (10); daily records taking lo/hi times from the 4-hour readings (20); 23/25-hour days and UTC-day labels (13); half hours with finer readings bucketed from those alone (3); the spike rule in SQL and in Python (55: the SQL feeds the day rows at write time, the Python filters read-back rows for charts; a test checks they agree); a day refetched at the other resolution (4); cloud 404 as empty (2); backfill empty-day stop rules (14); the per-metric gap rule and the agreement verdicts (~90, plan 3.12); rating on the last two readings and `sustained` for the particulates alert (30); AIRGRADIENT_SOURCE modes (10). +Storage and AirGradient: `NewerFile` refusing a newer schema (6); ALTER TABLE for new catalogue columns (8); unknown time zone name (7); unknown Ecowitt group kept in `extra` (8); UV written whole or with one decimal (3); refetch when a group gains a field (6); the coverage rules of a fetch (10); day rows recomputed when the zone changes (15); a band arriving before its reading (10); daily records taking lo/hi times from the 4-hour readings (20); 23/25-hour days and UTC-day labels (13); half hours with finer readings bucketed from those alone (3); the spike rule in SQL and in Python (55: the SQL feeds the day rows at write time, the Python filters read-back rows for charts; a test checks they agree); a day refetched at the other resolution (4); cloud 404 as empty (2); backfill empty-day stop rules (14); the per-metric gap rule and the agreement verdicts (~90, plan 3.12); rating on the last two readings and `sustained` for the particulates alert (30); MCP_AIRGRADIENT_SOURCE modes (10). Charts and intent: rain behind the lines, zero floor, negative bars (25); DST-correct time axis, local-midnight bars, clock slots (25); smoothing and the 10am daily records (9); `_pills` collision resolution (14); `model_prefetch` for "will it rain" (28, saves a model round trip); OPINION/RIGHT_NOW (6); plot_chart validation of model-supplied arguments (14); `grouping_in` fallback when the model omits group_by (18). @@ -121,5 +121,5 @@ archive, the alerts, irrigation, pollen, forecast, the charts, the LLM routing. so much as wide; shrinking it further means dropping features, not cleaning code. Suggested order: (1) the dead batch and the counts instrumentation, one commit, no risk; (2) the no-behaviour-change simplifications in -intent.py, bot.py and query.py, which also fix the `MAX_ROWS` fallback; (3) the owner decides on ADMIN_ONLY, TELEGRAM_PRELOAD_CHAT, the +intent.py, bot.py and query.py, which also fix the `MAX_ROWS` fallback; (3) the owner decides on BOT_ADMIN_ONLY, BOT_TELEGRAM_PRELOAD_CHAT, the draft preview, mDNS and the other optional features; (4) retire the migration after the old files are deleted from the data folder. diff --git a/docs/storage-plan.md b/docs/storage-plan.md index 8546af78..dd22ef73 100644 --- a/docs/storage-plan.md +++ b/docs/storage-plan.md @@ -314,8 +314,8 @@ Left to Python on purpose: ### 3.12 The AirGradient's sources: the monitor, then Home Assistant, then the cloud -`AIRGRADIENT_SOURCE` does for the air monitor what `ECOWITT_SOURCE` does for the station. `auto` (the default) uses each source that is -set, in this order: the monitor's own server (`AIRGRADIENT_LOCAL_URL`), Home Assistant (when it has the monitor, found by its entities' +`MCP_AIRGRADIENT_SOURCE` does for the air monitor what `MCP_ECOWITT_SOURCE` does for the station. `auto` (the default) uses each source that is +set, in this order: the monitor's own server (`MCP_AIRGRADIENT_LOCAL_URL`), Home Assistant (when it has the monitor, found by its entities' names as its ranges are now: `airgradient.homeassistant.find_prefix`), and AirGradient's cloud (its token and location). `local`, `homeassistant` or `cloud` is that one alone. Each source fills only what the ones before it lack, which the write rules already do (3.8): the bot's own readings rank above Home Assistant's, Home Assistant's above the cloud's, and a lower one only fills a cell a higher one left @@ -351,7 +351,7 @@ The PM2.5, and the other readings the monitor corrects: dashboard. The history from before stays as it came from the cloud, so a chart across the bot's first days can show the step until the fix. The check runs again each day on the newest day, so a correction changed on the monitor or the dashboard is followed. - **With nothing to check against** (one source alone), its values are taken as they are, and the start-up line says which correction the - monitor applies, from its `/config` when `AIRGRADIENT_LOCAL_URL` is set ("PM2.5: the monitor's EPA 2021 correction", "PM2.5: as + monitor applies, from its `/config` when `MCP_AIRGRADIENT_LOCAL_URL` is set ("PM2.5: the monitor's EPA 2021 correction", "PM2.5: as measured, no correction"). ## 4. How each request reads @@ -500,7 +500,7 @@ Each step is a commit (or a few) pushed to the dev branch with the tests and eva (`test_every_air_day_row_is_what_the_glitch_rule_in_python_gives`). On the stand-in: `air_days` over 4 years 15 ms (was 584 ms, 662 at the start), one statement; the air charts still load every reading of their period and filter it in Python (1M: 314 ms), the lines bucketed by the database, as the station's are, being step 4's, with its rewrite of what the source reads. -4. **The AirGradient from the monitor, Home Assistant and the cloud** (3.12). `AIRGRADIENT_SOURCE`; its readings, minutes and live +4. **The AirGradient from the monitor, Home Assistant and the cloud** (3.12). `MCP_AIRGRADIENT_SOURCE`; its readings, minutes and live reading from the monitor itself, Home Assistant filling what the bot did not read and the cloud what neither has, each metric checked against the source ranked above it before it fills a gap; the settings table and the start-up line. After step 3, since it writes the `air` table's rows, minutes and bands by the same rules as the station's, and its readings back to Home Assistant's first state need the diff --git a/ecobot-mcp.service b/ecobot-mcp.service index 594d1bc7..6e9bf3ef 100644 --- a/ecobot-mcp.service +++ b/ecobot-mcp.service @@ -1,14 +1,17 @@ -# The weather service on its own (python -m ecobot_service, docs/mcp-service.md step 5): the sources and their syncers, the alert rules -# and the MCP server at http://127.0.0.1:8765/mcp. Install it beside ecobot.service, from the same checkout and venv (see that file): +# ecobot-mcp, the MCP server on its own (python -m ecobot_mcp, docs/ecobot-mcp.md step 5): the sources and their syncers, the alert +# rules and the MCP server at http://127.0.0.1:8765/mcp. Install it beside ecobot.service, from the same checkout and venv (see that file): # sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload -# Only one process runs the service on a data folder (service.lock): before enabling this, make the bot its client (WEATHER_MCP_URL -# and WEATHER_MCP_TOKEN in /etc/ecobot.env, with the token in MCP_SERVICE_TOKENS) and restart it; otherwise this one stops at start, saying so. +# Only one process runs ecobot-mcp's part on a data folder (mcp.lock): before enabling this, make the bot its client (BOT_MCP_URL in +# /etc/ecobot.env) and restart it; otherwise this one stops at start, saying so. # The data folder is the bot's own, /var/lib/private/ecobot (StateDirectory=ecobot): User=ecobot gives this unit the same dynamic user -# as ecobot.service, so the two share the folder's owner and neither takes it from the other when it starts. -# It reads /etc/ecobot.env as the bot does, less the bot's own secrets (UnsetEnvironment=). MCP_SERVICE_BIND defaults to 127.0.0.1:8765; to -# reach it from other machines set MCP_SERVICE_BIND=0.0.0.0:8765 (refused without MCP_SERVICE_TOKENS) and put TLS in front of it. +# as ecobot.service, so the two share the folder's owner and neither takes it from the other when it starts. The token: the first of +# AUTH_TOKENS, which the bot sends and this accepts; with AUTH_TOKENS unset, the one this generates at its first start in the data +# folder (/var/lib/private/ecobot/auth_token, readable by that user only), which the bot reads from there. +# It reads /etc/ecobot.env as the bot does, less the bot's own secrets, by their names and their old ones (UnsetEnvironment=): its +# settings are the MCP_ ones and the shared ones (docs/configuration.md). MCP_BIND defaults to 127.0.0.1:8765; to reach it from other +# machines set MCP_BIND=0.0.0.0:8765 and put TLS in front of it. [Unit] -Description=ecobot weather service (MCP) +Description=ecobot-mcp (the ecobot MCP server: sources, alert rules) After=network-online.target Wants=network-online.target Before=ecobot.service @@ -19,12 +22,12 @@ User=ecobot Group=ecobot WorkingDirectory=/opt/ecobot EnvironmentFile=/etc/ecobot.env -UnsetEnvironment=TELEGRAM_BOT_TOKEN OPENROUTER_API_KEY WEATHER_MCP_TOKEN TUYA_CLIENT_ID TUYA_CLIENT_SECRET +UnsetEnvironment=BOT_TELEGRAM_TOKEN TELEGRAM_BOT_TOKEN BOT_OPENROUTER_API_KEY OPENROUTER_API_KEY BOT_TUYA_CLIENT_ID TUYA_CLIENT_ID BOT_TUYA_CLIENT_SECRET TUYA_CLIENT_SECRET WEATHER_MCP_TOKEN Environment=PYTHONUNBUFFERED=1 Environment=PYTHONPYCACHEPREFIX=/var/cache/ecobot/pycache StateDirectory=ecobot CacheDirectory=ecobot -ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_service +ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_mcp Restart=on-failure RestartSec=10 TimeoutStopSec=30 diff --git a/ecobot.py b/ecobot.py index 6ee5ea2c..4dbf80e0 100644 --- a/ecobot.py +++ b/ecobot.py @@ -2,12 +2,12 @@ answered by a model through OpenRouter, with proactive alerts. Settings come from environment variables (see lib/config.py); run it under systemd with the unit's EnvironmentFile set. -The service's half (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and -Home Assistant's imports) is ecobot_service/core.py, which the service (python -m ecobot_service) runs the same way. With WEATHER_MCP_URL +ecobot-mcp's half (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the backfills and +Home Assistant's imports) is ecobot_mcp/core.py, which ecobot-mcp (python -m ecobot_mcp) runs the same way. With BOT_MCP_URL unset the bot runs it in-process, beside its own half (Telegram, the model, delivering the alerts, the irrigation controller, its charts -drawn ahead). With it set the bot is the service's client over MCP (lib/weather.RemoteWeather, docs/mcp-service.md 3.8 and step 5): it -runs no sources, syncers or alert rules of its own; its tools, instructions, station and alerts come from the service. Either way the bot -reaches the service through one interface (lib/weather.py). +drawn ahead). With it set the bot is ecobot-mcp's client over MCP (lib/weather.RemoteWeather, docs/ecobot-mcp.md 3.8 and step 5): it +runs no sources, syncers or alert rules of its own; its tools, instructions, station and alerts come from ecobot-mcp. Either way the bot +reaches them through one interface (lib/weather.py). """ import asyncio @@ -17,14 +17,15 @@ import signal from zoneinfo import ZoneInfo -from lib.config import Config +from lib import auth_token +from lib.config import RETIRED_TOKEN, Config from telegram import Update from telegram.error import InvalidToken, NetworkError from telegram.ext import Application, Defaults -from ecobot_service.core import Core, commit_in, configure, start_sources, version # noqa: F401 (commit_in, start_sources: named here for the tests) +from ecobot_mcp.core import Core, commit_in, configure, start_sources, version # noqa: F401 (commit_in, start_sources: named here for the tests) from lib import charts from lib.airgradient import AirGradient # noqa: F401 (the sources, named here for the startup tests) from lib.alerts.irrigation import IrrigationMonitor @@ -51,23 +52,23 @@ logging.getLogger("telegram.ext.Application").setLevel(logging.WARNING) # "Application started" etc. log = logging.getLogger("ecobot") -STARTUP_WAIT = 30.0 # seconds the bot waits for a remote service at start (its station names the time zone) before it carries on without +STARTUP_WAIT = 30.0 # seconds the bot waits for ecobot-mcp at start (its station names the time zone) before it carries on without def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Core | None, weather: RemoteWeather | None = None) -> tuple[list[str], AlertRules | None, list]: - """In-process (`core`): hook up the service's alert rules over every source that started (core.start_alerts: they append to the - alert log); the weather rules start in warm_up, once the station has been read. Remote (`weather`): the rules are the service's, and + """In-process (`core`): hook up ecobot-mcp's alert rules over every source that started (core.start_alerts: they append to the + alert log); the weather rules start in warm_up, once the station has been read. Remote (`weather`): the rules are ecobot-mcp's, and its alert log is read over MCP. Either way the bot delivers from the log (AlertDelivery), and runs the irrigation controller's check - and watchdog (sent by the bot itself until it is a server of its own, step 5b; remote, its rain and forecast are asked of the - service). Returns the alert types now running here, the rules (None when remote), and what keeps the time zone (the delivery, the + and watchdog (sent by the bot itself until it is a server of its own, step 5b; remote, its rain and forecast are asked of + ecobot-mcp). Returns the alert types now running here, the rules (None when remote), and what keeps the time zone (the delivery, the irrigation check: follow_zone).""" if core is not None: running = core.start_alerts(moved_from=bot.state) # (the first start moves the rules' state out of bot_state.json) feed, station, forecast = core.alert_log, bot.by_name.get("Ecowitt"), bot.by_name.get("Forecast") else: running, feed, station, forecast = [], weather.alerts, ServiceRain(weather), weather.forecast - delivery = AlertDelivery(feed, notify, bot.state, cfg.tz, weather=bot.weather) # (its charts drawn by the service) + delivery = AlertDelivery(feed, notify, bot.state, cfg.tz, weather=bot.weather) # (its charts drawn by ecobot-mcp) zoned: list = [delivery] tasks.start(delivery.run()) if bot.irrigation: # the daily check (rain delay, battery) and the watchdog that closes the valve after a run @@ -87,9 +88,9 @@ def _zone(name: str | None): def follow_zone(weather: RemoteWeather, bot: Bot, state: AlertState, zoned: list): - """Remote: the bot in the station's time zone whenever it is read (the first read, if the service couldn't be reached at start, or + """Remote: the bot in the station's time zone whenever it is read (the first read, if ecobot-mcp couldn't be reached at start, or another zone later): the bot's settings, the charts, the alerts' charts, and what start_alerts started (`zoned`: AlertDelivery, - IrrigationMonitor, whose wait for the check time is timed again). The zone is kept in bot_state.json, for a start while the service + IrrigationMonitor, whose wait for the check time is timed again). The zone is kept in bot_state.json, for a start while ecobot-mcp can't be reached (connect).""" def apply(zone): if state.zone != str(zone): @@ -111,12 +112,32 @@ def apply(zone): apply(weather.station_tz) +def mcp_token(cfg: Config): + """The token the bot sends ecobot-mcp: the first of AUTH_TOKENS; else the retired WEATHER_MCP_TOKEN, with a warning; else the one + ecobot-mcp generated in the data folder they share, read again for each connection (a function: ecobot-mcp may write it after the + bot starts), with a warning when it isn't there yet. Never logged: only where it is.""" + if cfg.auth_tokens: + if cfg.retired_mcp_token: + log.warning("%s is retired and ignored: the bot sends the first of AUTH_TOKENS", RETIRED_TOKEN) + return cfg.auth_tokens[0] + if cfg.retired_mcp_token: + log.warning("%s is retired: the bot sends it for now, but move it into AUTH_TOKENS (and into ecobot-mcp's AUTH_TOKENS, " + "if it isn't there already)", RETIRED_TOKEN) + return cfg.retired_mcp_token + folder = cfg.state_path.parent + if auth_token.read(folder) is None: + log.warning("AUTH_TOKENS is not set and there is no token at %s (yet): ecobot-mcp writes it there at its first start, on the same " + "data folder. Until it can be read the bot sends none and is refused; set AUTH_TOKENS (the same in both) if ecobot-mcp " + "keeps another folder", auth_token.path(folder)) + return lambda: auth_token.read(folder) + + async def connect(cfg: Config, stack: contextlib.AsyncExitStack, state: AlertState) -> tuple[RemoteWeather, Config]: - """The bot as the service's client (WEATHER_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to + """The bot as ecobot-mcp's client (BOT_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to STARTUP_WAIT seconds; the settings in the station's time zone once it has been read, else in the one last read (kept in bot_state.json), else in TZ's, with a warning. Read later, it is followed then (follow_zone).""" kept = _zone(state.zone) - weather = RemoteWeather(cfg.weather_mcp_url, cfg.weather_mcp_token or None, kept or cfg.tz) + weather = RemoteWeather(cfg.mcp_url, mcp_token(cfg), kept or cfg.tz) supervisor = asyncio.create_task(weather.run()) async def stop(): @@ -127,8 +148,8 @@ async def stop(): try: await asyncio.wait_for(weather.listening.wait(), STARTUP_WAIT) except TimeoutError: - log.warning("The weather service at %s isn't reachable yet: questions are told so until it is (the time zone is %s, %s, " - "until its station is read)", cfg.weather_mcp_url, "the station's last read" if kept else "TZ's", weather.tz) + log.warning("ecobot-mcp at %s isn't reachable yet: questions are told so until it is (the time zone is %s, %s, " + "until its station is read)", cfg.mcp_url, "the station's last read" if kept else "TZ's", weather.tz) if str(weather.tz) != str(cfg.tz): cfg = dataclasses.replace(cfg, tz=weather.tz) return weather, cfg @@ -171,10 +192,10 @@ async def main(): .connect_timeout(10).read_timeout(15).write_timeout(15) # default 5s is tight .build()) handshake = asyncio.create_task(app.initialize()) # Telegram is asked who the bot is while the sources start - weather = None # (WEATHER_MCP_URL: the service, reached over MCP) + weather = None # (BOT_MCP_URL: ecobot-mcp, reached over MCP) state = AlertState(cfg.state_path) try: - if cfg.weather_mcp_url: # a client of the service: no sources of its own + if cfg.mcp_url: # ecobot-mcp's client: no sources of its own sources = [] weather, cfg = await connect(cfg, stack, state) else: @@ -192,12 +213,12 @@ async def main(): if client: stack.push_async_callback(safely, client.close) else: - log.warning("OPENROUTER_API_KEY is not set: running without the model, so answers are limited") + log.warning("BOT_OPENROUTER_API_KEY is not set: running without the model, so answers are limited") if cfg.admin_only and not cfg.admin_chat_ids and not any(chat < 0 for chat in state.chats): - log.warning("Admin only is on but no group is known yet and ADMIN_CHAT_IDS is empty, so nobody can use the bot: " - "add it to a group, list your user id in ADMIN_CHAT_IDS, or set ADMIN_ONLY=off") + log.warning("Admin only is on but no group is known yet and BOT_ADMIN_CHAT_IDS is empty, so nobody can use the bot: " + "add it to a group, list your user id in BOT_ADMIN_CHAT_IDS, or set BOT_ADMIN_ONLY=off") tasks = Tasks() # everything that runs in the background, the bot's own uploads among it; cancelled first on the way out (tasks.close, below) - # The service in-process (ecobot_service/core.py): the alert log the rules write and the bot delivers from, and the ten tools + # ecobot-mcp's part in-process (ecobot_mcp/core.py): the alert log the rules write and the bot delivers from, and the ten tools # over the sources that started (lib/service); or, remote, the same over MCP (lib/weather.py). The model is offered the tools # (lib/model_tools.py), and the bot's own code paths call them (its shortcuts, report, gauges, alert charts and period buttons) core = await Core.open(cfg, sources, stack, tasks) if weather is None else None @@ -216,7 +237,7 @@ async def main(): await handshake stack.push_async_callback(app.shutdown) # one task runs everything, so connections open and close cleanly except InvalidToken: # (its message names the token, so it is not shown) - raise SystemExit("TELEGRAM_BOT_TOKEN was rejected by Telegram: check it is the token @BotFather gave for this bot") from None + raise SystemExit("BOT_TELEGRAM_TOKEN was rejected by Telegram: check it is the token @BotFather gave for this bot") from None except NetworkError as e: # (the host's network or DNS, most often): one line, not the library's pages of stack raise SystemExit(f"Can't reach Telegram ({type(e).__name__}: {e}): check the network and DNS of the machine or container") from None await app.start() @@ -232,7 +253,7 @@ async def main(): if core is not None: core.log_startup() # what each source is reading, in the order they are listed else: - log.info("Weather service: %s (%s)", cfg.weather_mcp_url, ", ".join(sorted(weather.names)) or "not reached yet") + log.info("ecobot-mcp: %s (%s)", cfg.mcp_url, ", ".join(sorted(weather.names)) or "not reached yet") notify = Notifier(app.bot, state, bot.alert_charts) # the alerts' charts, kept with the bot's await bot.publish_commands(app.bot) # the / menu running, rules, zoned = start_alerts(cfg, bot, notify, tasks, core, weather) @@ -241,7 +262,7 @@ async def main(): if core is not None: core.start_warmers() # keeping warm: everything questions need, refreshed before they arrive tasks.start(warm_up(bot, core, running, tasks, app.bot)) - else: # the service keeps itself warm: the bot only draws its keyboard's charts ahead (quietly nothing while it can't be reached) + else: # ecobot-mcp keeps itself warm: the bot only draws its keyboard's charts ahead (quietly nothing while it can't be reached) tasks.start(every(AHEAD_SECONDS, lambda: bot.draw_buttons_ahead(app.bot))) await stop.wait() diff --git a/ecobot.service b/ecobot.service index 68311b71..bf00810f 100644 --- a/ecobot.service +++ b/ecobot.service @@ -1,14 +1,15 @@ # Install as /etc/systemd/system/ecobot.service, with the code outside every home directory: # sudo git clone /opt/ecobot && cd /opt/ecobot # sudo python3.13 -m venv .venv && sudo .venv/bin/pip install -r requirements.txt -r requirements-charts.txt # Python 3.13.5 (.python-version) -# The files stay owned by root and readable by all: the service runs as a throw-away user (DynamicUser=) that cannot write to them, +# The files stay owned by root and readable by all: the bot runs as a throw-away user (DynamicUser=) that cannot write to them, # so its bytecode goes to /var/cache/ecobot (CacheDirectory=, PYTHONPYCACHEPREFIX=) and is rebuilt on its own after an update. # Any other place needs only the WorkingDirectory and ExecStart lines changed. -# The bot never opens the environment file itself: systemd loads it (TZ, OPENROUTER_*, ECOWITT_*, AIRGRADIENT_*, TUYA_*, -# TELEGRAM_BOT_TOKEN, ...). +# The bot never opens the environment file itself: systemd loads it (docs/configuration.md: its BOT_ settings, the shared ones such as +# TZ and AUTH_TOKENS, and, while it runs ecobot-mcp's part in-process, BOT_MCP_URL unset, the MCP_ ones too). With ecobot-mcp.service +# installed, set BOT_MCP_URL=http://127.0.0.1:8765/mcp: the bot is then its client. # StateDirectory= gives the bot /var/lib/ecobot (the state file and the SQLite caches): the bot finds it through # STATE_DIRECTORY, so no DATA_DIR is needed, and it is the only place the sandbox below lets it write. Files an older install kept in -# the checkout (bot_state.json, *_cache.sqlite) are not read from there: with the service stopped, copy them into /var/lib/ecobot once; +# the checkout (bot_state.json, *_cache.sqlite) are not read from there: with the bot stopped, copy them into /var/lib/ecobot once; # systemd hands the folder to the dynamic user when it starts. [Unit] Description=ecobot (Telegram weather and air-quality bot) diff --git a/ecobot_mcp/__init__.py b/ecobot_mcp/__init__.py new file mode 100644 index 00000000..5d5e689b --- /dev/null +++ b/ecobot_mcp/__init__.py @@ -0,0 +1,6 @@ +"""ecobot-mcp, the MCP server on its own (docs/ecobot-mcp.md 3.8, step 5): the readings file, the sources and syncers that fill it, the +alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). + + - `python -m ecobot_mcp` (__main__.py): ecobot-mcp, Streamable HTTP at http://MCP_BIND/mcp; + - core.py: its startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, the + backfills and Home Assistant's imports), which ecobot-mcp and the bot (ecobot.py, while it runs everything in-process) both call.""" diff --git a/ecobot_service/__main__.py b/ecobot_mcp/__main__.py similarity index 63% rename from ecobot_service/__main__.py rename to ecobot_mcp/__main__.py index f49c8814..d71d122b 100644 --- a/ecobot_service/__main__.py +++ b/ecobot_mcp/__main__.py @@ -1,33 +1,33 @@ -"""python -m ecobot_service: the weather and air service on its own (docs/mcp-service.md 3.8). It runs the sources and their syncers -(ecobot_service/core.py: the keep-warm, the first fetch, the archive, the backfills, Home Assistant's imports), the alert rules writing -the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_SERVICE_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a +"""python -m ecobot_mcp: ecobot-mcp, the MCP server on its own (docs/ecobot-mcp.md 3.8). It runs the sources and their syncers +(ecobot_mcp/core.py: the keep-warm, the first fetch, the archive, the backfills, Home Assistant's imports), the alert rules writing +the alert log, and the MCP server (lib/mcp_server.py) at http://MCP_BIND/mcp, Streamable HTTP under uvicorn: put it behind TLS (a reverse proxy such as Caddy) to reach it from elsewhere. -Settings come from the environment, as the bot reads them (lib/config.py, docs/configuration.md), less the bot's own (no Telegram token -is needed), with MCP_SERVICE_TOKENS (token,token,..., one per client), MCP_SERVICE_BIND (host:port, default 127.0.0.1:8765) and MCP_SERVICE_ALLOWED_HOSTS (the -Host names it answers, default 127.0.0.1 and localhost). Without MCP_SERVICE_TOKENS it serves without auth, and then only on a loopback address.""" +Settings come from the environment (lib/config.py, docs/configuration.md): the MCP_ ones and the shared ones; the bot's (BOT_) are not +needed. Among them MCP_BIND (host:port, default 127.0.0.1:8765), MCP_ALLOWED_HOSTS (the Host names it answers, default 127.0.0.1 and +localhost) and AUTH_TOKENS (token,token,..., one per client). Every request needs one of the tokens: with AUTH_TOKENS unset, the one +it generates at its first start and keeps in the data folder (lib/auth_token.py).""" import asyncio import contextlib -import ipaddress import logging import signal import socket import uvicorn -from lib import chart_images +from lib import auth_token, chart_images from lib.config import Config from lib.logs import LogFormat, on_journal, stream_handlers from .core import Core, configure, start_sources, version -log = logging.getLogger("ecobot.service") -SHUTDOWN_SECONDS = 3 # how long uvicorn waits for open connections (a listen stream) to end when the service stops +log = logging.getLogger("ecobot.mcp") +SHUTDOWN_SECONDS = 3 # how long uvicorn waits for open connections (a listen stream) to end when ecobot-mcp stops class Uvicorn(uvicorn.Server): - """uvicorn's server, leaving SIGINT and SIGTERM to the service (which closes everything in order: uvicorn's own handling raises the + """uvicorn's server, leaving SIGINT and SIGTERM to ecobot-mcp (which closes everything in order: uvicorn's own handling raises the signal again once it has stopped, ending the process before the sources are closed).""" @contextlib.contextmanager @@ -35,15 +35,6 @@ def capture_signals(self): yield -def loopback(host: str) -> bool: - if host == "localhost": - return True - try: - return ipaddress.ip_address(host).is_loopback - except ValueError: - return False - - def server_config(app, host: str, port: int) -> uvicorn.Config: """uvicorn's settings for the app: its lifespan on (the MCP session manager runs in it), its own access log off, and an open listen stream given SHUTDOWN_SECONDS to end when it stops (else it would wait for the client to hang up).""" @@ -51,16 +42,27 @@ def server_config(app, host: str, port: int) -> uvicorn.Config: timeout_graceful_shutdown=SHUTDOWN_SECONDS) +def generated_token(cfg: Config) -> str: + """AUTH_TOKENS unset: the token kept in the data folder, made at the first start (its place is logged, never its value).""" + folder = cfg.state_path.parent + try: + token = auth_token.ensure(folder) + except OSError as e: + raise SystemExit(f"AUTH_TOKENS is not set and a token couldn't be kept in {auth_token.path(folder)} ({type(e).__name__}: {e}): " + "set AUTH_TOKENS (token,token,...), or make the data folder writable") from None + log.info("AUTH_TOKENS is not set: accepting the token kept in %s (the bot reads it from there; give it to any other client)", + auth_token.path(folder)) + return token + + async def main(): from lib.mcp_server import EcobotServer, http_app - log.info("Starting the ecobot service %s", version()) + log.info("Starting ecobot-mcp %s", version()) cfg = Config.from_env(bot=False) for name in ("ecobot", "lib"): logging.getLogger(name).setLevel(cfg.log_level) - host, port = cfg.mcp_service_bind - if not cfg.mcp_service_tokens and not loopback(host): - raise SystemExit(f"MCP_SERVICE_BIND is {host}:{port}, which other machines can reach, and MCP_SERVICE_TOKENS is empty: set MCP_SERVICE_TOKENS " - "(token,token,...) or bind to 127.0.0.1") + host, port = cfg.mcp_bind + tokens = cfg.auth_tokens or (generated_token(cfg),) configure(cfg) async with contextlib.AsyncExitStack() as stack: sources, cfg = await start_sources(cfg) # in the weather station's time zone from here on @@ -76,8 +78,8 @@ async def main(): for source in sources: stack.push_async_callback(source.warmer.stop) server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) - hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.mcp_service_allowed_hosts))) # (its own name too: a container's hostname) - app = http_app(server, tokens=cfg.mcp_service_tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") + hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.mcp_allowed_hosts))) # (its own name too: a container's hostname) + app = http_app(server, tokens=tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") core.log_startup() running = core.start_alerts() core.start_warmers() @@ -95,7 +97,7 @@ async def warm_up(): web = Uvicorn(server_config(app, host, port)) serving = asyncio.create_task(web.serve()) log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", host if ":" not in host else f"[{host}]", port, - f"{len(cfg.mcp_service_tokens)} token(s)" if cfg.mcp_service_tokens else "no auth (loopback only)", + f"{len(tokens)} token(s) from AUTH_TOKENS" if cfg.auth_tokens else f"the token in {auth_token.path(cfg.state_path.parent)}", ", ".join(hosts)) waiting = asyncio.create_task(stop.wait()) await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) diff --git a/ecobot_service/core.py b/ecobot_mcp/core.py similarity index 93% rename from ecobot_service/core.py rename to ecobot_mcp/core.py index 56c61b0b..326e5621 100644 --- a/ecobot_service/core.py +++ b/ecobot_mcp/core.py @@ -1,5 +1,5 @@ -"""The service's startup (docs/mcp-service.md step 5: "ecobot.py's warm_up() is split"), shared by the service (python -m -ecobot_service) and the bot (ecobot.py), which runs it in-process until it is a client of the service: +"""ecobot-mcp's startup (docs/ecobot-mcp.md step 5: "ecobot.py's warm_up() is split"), shared by ecobot-mcp (python -m ecobot_mcp) +and the bot (ecobot.py), which runs it in-process unless it is ecobot-mcp's client (BOT_MCP_URL): 1. `configure(cfg)`: the settings the engines read as module values (the anti-spike rule, what "all" draws, what `about` says); 2. `start_sources(cfg)`: every configured source that starts, the weather station first (its time zone wins); @@ -42,7 +42,7 @@ from lib.storage import Storage from lib.warm import Tasks, every, safely -log = logging.getLogger("ecobot.service") # (under the bot's own logger: LOG_LEVEL reaches it) +log = logging.getLogger("ecobot.mcp") # (under the bot's own logger: LOG_LEVEL reaches it) def configure(cfg: Config): @@ -147,27 +147,27 @@ def report(self) -> dict: return {"loops": loops, **({"archive": archive} if archive else {})} -# ---------- the service ---------- +# ---------- ecobot-mcp ---------- def hold_data_folder(cfg: Config, stack): - """One service per data folder: the bot running it in-process and `python -m ecobot_service` on the same folder would both fetch + """One ecobot-mcp per data folder: the bot running it in-process and `python -m ecobot_mcp` on the same folder would both fetch and both write each alert (sent twice). The lock is the kernel's, so it goes with the process, however that ends.""" import fcntl - path = cfg.state_path.parent / "service.lock" + path = cfg.state_path.parent / "mcp.lock" path.parent.mkdir(parents=True, exist_ok=True) held = open(path, "w") try: fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: held.close() - raise SystemExit(f"Another process already runs the weather service on {path.parent} (the bot without WEATHER_MCP_URL, or " - f"python -m ecobot_service). Stop it first, or set WEATHER_MCP_URL to use it.") + raise SystemExit(f"Another process already runs ecobot-mcp's work (the sources and the alert rules) on {path.parent} (the bot without BOT_MCP_URL, or " + f"python -m ecobot_mcp). Stop it first, or set BOT_MCP_URL to use it.") stack.callback(held.close) @dataclass class Core: - """The service as it runs: its settings, sources, alert log, tools and their Context, the alert rules once started.""" + """ecobot-mcp as it runs (in its own process or the bot's): its settings, sources, alert log, tools and their Context, the alert rules once started.""" cfg: Config sources: list[Source] alert_log: AlertLog @@ -194,7 +194,7 @@ async def open(cls, cfg: Config, sources: list[Source], stack, tasks: Tasks) -> ctx = await Context.open(eco=eco, air=air, composer=composer, forecast=by_name.get("Forecast"), pollen=by_name.get("Pollen"), tz=cfg.tz) service = Service.of(ctx) - log.info("Service tools: %s", ", ".join(t.name for t in service)) + log.info("Tools: %s", ", ".join(t.name for t in service)) health = Health(cfg.tz) for source in sources: # (the keep-warm's refreshes, recorded) source.warmer.refresh = health.track(f"{source.name} refresh", source.warmer.refresh) @@ -298,7 +298,7 @@ def version() -> str: def commit_in(git_dir) -> str: """The short hash HEAD points at, read from the repository's files rather than by running git (which refuses a folder owned by - another user, as when the service runs as its own user). "unknown" when it cannot be read.""" + another user, as when the program runs as its own user). "unknown" when it cannot be read.""" try: head = (git_dir / "HEAD").read_text().strip() if head.startswith("ref:"): diff --git a/ecobot_service/__init__.py b/ecobot_service/__init__.py deleted file mode 100644 index 45ad69b9..00000000 --- a/ecobot_service/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -"""The weather and air service on its own (docs/mcp-service.md 3.8, step 5): the readings file, the sources and syncers that fill it, the -alert rules that write the alert log, and the MCP server over them (lib/mcp_server.py). - - - `python -m ecobot_service` (__main__.py): the service, Streamable HTTP at http://MCP_SERVICE_BIND/mcp; - - core.py: the service's startup (the sources, the alert log, the tools, the alert rules, the keep-warm, the first fetch, the archive, - the backfills and Home Assistant's imports), the one function the service and the bot (ecobot.py, while it runs everything - in-process) both call.""" diff --git a/lib/admins.py b/lib/admins.py index 207d5252..ec4fe3e7 100644 --- a/lib/admins.py +++ b/lib/admins.py @@ -1,8 +1,8 @@ -"""Who may talk to the bot when ADMIN_ONLY is on: the admins of the groups it is in, and the ids listed in ADMIN_CHAT_IDS. +"""Who may talk to the bot when BOT_ADMIN_ONLY is on: the admins of the groups it is in, and the ids listed in BOT_ADMIN_CHAT_IDS. A "known admin" is anyone Telegram lists as an administrator or creator of a group the bot knows (a group becomes known when the bot is -added to it or someone speaks in it) or of a group named by a negative id in ADMIN_CHAT_IDS. The lists are asked for once and kept for -ten minutes. ADMIN_CHAT_IDS is added to that, never instead of it: a positive id is a user (it bootstraps a bot that is in no group yet), +added to it or someone speaks in it) or of a group named by a negative id in BOT_ADMIN_CHAT_IDS. The lists are asked for once and kept for +ten minutes. BOT_ADMIN_CHAT_IDS is added to that, never instead of it: a positive id is a user (it bootstraps a bot that is in no group yet), a negative id is a group, whose own admins are then looked up and whose anonymous admins are let in: a message an admin sends "as the group" carries the group as its `sender_chat` and no real user, so it is allowed only when that group's id is listed. The groups' lists are asked for together, and messages that arrive together while a list is being fetched wait for that one lookup. @@ -26,7 +26,7 @@ def __init__(self, state, extra_ids=(), ttl: float = TTL_SECONDS, clock=time.mon self._looking: dict[int, asyncio.Lock] = {} # group -> held while its list is fetched def groups(self) -> list[int]: - """The groups whose admins count: the ones the bot is in (not one that removed it), and the ones ADMIN_CHAT_IDS names.""" + """The groups whose admins count: the ones the bot is in (not one that removed it), and the ones BOT_ADMIN_CHAT_IDS names.""" known = {c for c in self.state.present() if c < 0} return sorted(known | {i for i in self.extra if i < 0}) diff --git a/lib/airgradient/local.py b/lib/airgradient/local.py index bc1f4720..72870cad 100644 --- a/lib/airgradient/local.py +++ b/lib/airgradient/local.py @@ -1,4 +1,4 @@ -"""The sensor's own web server, for the live reading: GET http:///measures/current on the local network (AIRGRADIENT_LOCAL_URL, +"""The sensor's own web server, for the live reading: GET http:///measures/current on the local network (MCP_AIRGRADIENT_LOCAL_URL, e.g. http://airgradient_d83bda1c1e08.local). Nothing is asked of the cloud for it, and it is as fresh as the device's last measurement. The device only knows "now", so history, charts and the archive still come from the cloud. @@ -117,7 +117,7 @@ async def read(self) -> dict | None: self.address, self.retry_at = None, self.clock() + RETRY_SECONDS if self.working is not False: log.warning("AirGradient: (%s) did not answer (%s: %s); %strying again in %d min%s", self.describe(), type(e).__name__, e, - "using the cloud, " if self.cloud else "", RETRY_SECONDS // 60, local_name_hint(self.host, "AIRGRADIENT_LOCAL_URL")) + "using the cloud, " if self.cloud else "", RETRY_SECONDS // 60, local_name_hint(self.host, "MCP_AIRGRADIENT_LOCAL_URL")) self.working = False return None self.working = True diff --git a/lib/airgradient/metrics.py b/lib/airgradient/metrics.py index cbd0dc5b..7e601869 100644 --- a/lib/airgradient/metrics.py +++ b/lib/airgradient/metrics.py @@ -38,7 +38,7 @@ SPIKE_RATIO = 2.5 # a particle reading that is this many times the readings either side of it ... SPIKE_RISE = 5.0 # ... and this far (µg/m³) above both, with nothing like it next to it, is a glitch of the sensor, not the air SPIKE_NEIGHBOUR = 900 # the readings either side must be within this many seconds -REQUIRE_CONSECUTIVE = 2 # ANTISPIKE_REQUIRE_CONSECUTIVE: readings in a row a rise needs to be the air (set at startup); 1 turns the rule off +REQUIRE_CONSECUTIVE = 2 # MCP_ANTISPIKE_REQUIRE_CONSECUTIVE: readings in a row a rise needs to be the air (set at startup); 1 turns the rule off def without_spikes(rows: list[dict], require: int | None = None) -> list[dict]: diff --git a/lib/airgradient/source.py b/lib/airgradient/source.py index 11836878..dd31697a 100644 --- a/lib/airgradient/source.py +++ b/lib/airgradient/source.py @@ -2,7 +2,7 @@ start() checks the monitor, tools are what the model can call, warm()/poke() keep recent readings ready, backfill() caches the monitor's whole history, current() feeds the alert monitor. -Its readings come from each of its sources that is set (AIRGRADIENT_SOURCE; docs/storage-plan.md 3.12), each filling only what the ones +Its readings come from each of its sources that is set (MCP_AIRGRADIENT_SOURCE; docs/storage-plan.md 3.12), each filling only what the ones before it lack: the monitor's own server (local.py: read every minute, each 5 minutes' readings averaged into a row with their lowest and highest as its band, and each reading kept as a minute), Home Assistant (homeassistant.py: its states of the monitor sampled the same way while the monitor does not answer the bot, and its history read back for the times the bot did not read it at all), and AirGradient's @@ -97,7 +97,7 @@ def __init__(self, cfg: Config, transport=None, ha: HomeAssistant | None = None, owned: the file is this source's to close (so when it opened it, or no station has it).""" self.loc, self.tz = cfg.airgradient_location or "local", cfg.tz # (the stored readings are kept under this) self.token = cfg.airgradient_token - self.cloud = cfg.airgradient_cloud # without an account (or with AIRGRADIENT_SOURCE saying not) the cloud is never asked + self.cloud = cfg.airgradient_cloud # without an account (or with MCP_AIRGRADIENT_SOURCE saying not) the cloud is never asked self.link = ("live chart", cfg.airgradient_dashboard) if cfg.airgradient_dashboard else None self.client = httpx.AsyncClient(timeout=15, transport=transport) self.local = LocalSensor(cfg.airgradient_local_url, cloud=self.cloud) if cfg.airgradient_local else None # the monitor's own server @@ -307,7 +307,7 @@ async def _current_row(self, refresh: bool = False) -> dict: return self._current[0] async def _fetch_current(self) -> dict: - """The live reading: from the monitor's own server when AIRGRADIENT_LOCAL_URL answers, else Home Assistant's states of it (each + """The live reading: from the monitor's own server when MCP_AIRGRADIENT_LOCAL_URL answers, else Home Assistant's states of it (each with the cloud's name for the sensor, last heard), else the cloud.""" row, _ = await self._sample() if row is not None: diff --git a/lib/alert_log.py b/lib/alert_log.py index ea18744c..1fd52fe8 100644 --- a/lib/alert_log.py +++ b/lib/alert_log.py @@ -1,4 +1,4 @@ -"""The alert log (docs/mcp-service.md 3.6): every alert the service's rules decide, as an event a client reads and delivers. +"""The alert log (docs/ecobot-mcp.md 3.6): every alert the service's rules decide, as an event a client reads and delivers. An event is {id, kind, time, expires, title, text, data, [link: {label, url}], [chart]}: - id: monotonic (1, 2, ...), never reused, so a client resumes from the last one it handled; diff --git a/lib/alerts/forecast.py b/lib/alerts/forecast.py index 6bae855b..986064c9 100644 --- a/lib/alerts/forecast.py +++ b/lib/alerts/forecast.py @@ -1,4 +1,4 @@ -"""The forecast revised: station-wide, for today and tomorrow (docs/mcp-service.md 3.6). +"""The forecast revised: station-wide, for today and tomorrow (docs/ecobot-mcp.md 3.6). Each day, the first forecast fetched after 6 am is the baseline for today and tomorrow. Every later fetch is compared with it, day by day, and a day that changed substantially is an alert, saying what changed: diff --git a/lib/alerts/notify.py b/lib/alerts/notify.py index 96df9c74..829aca83 100644 --- a/lib/alerts/notify.py +++ b/lib/alerts/notify.py @@ -262,7 +262,7 @@ async def _send(self, chat_id: int, text: str, entities, kind: str, photo: bytes class AlertDelivery: - """The bot's side of the alert log (lib/alert_log.py, docs/mcp-service.md section 4): it reads each new event and sends it, as the + """The bot's side of the alert log (lib/alert_log.py, docs/ecobot-mcp.md section 4): it reads each new event and sends it, as the Notifier does, to the chats subscribed to its kind, with its link, its chart drawn from the event's chart data (and the 🔄 that replays the chart's drawn_by) or the text alone. The id of the last event handled is kept in bot_state.json (AlertState.read), so a restart resumes after it; the events that expired meanwhile are skipped (the morning's rain is not news by the afternoon). With no id diff --git a/lib/alerts/particulates.py b/lib/alerts/particulates.py index 5f4a699f..51d91b93 100644 --- a/lib/alerts/particulates.py +++ b/lib/alerts/particulates.py @@ -2,7 +2,7 @@ "Wear a mask outside" when PM2.5 or PM10 reaches US AQI 151+ ("unhealthy", the official level at which masks are advised for everyone) in two readings in a row, each check counting only when the sensor's last -ANTISPIKE_REQUIRE_CONSECUTIVE (2) readings are all that high (a spike never does); "back to safe" when both are at +MCP_ANTISPIKE_REQUIRE_CONSECUTIVE (2) readings are all that high (a spike never does); "back to safe" when both are at AQI 100 or below in two readings in a row (rules.py: a check that brings no new reading counts for nothing). Every episode gets the pair. Particles only: masks filter particles, not gases like CO2/VOC/NOx. Each is an event in the alert log (lib/alert_log.py) with the sensor's dashboard as its link and the 1-day particulates chart as data; @@ -45,7 +45,7 @@ async def check(self, latest=None, now: datetime | None = None): return if when is not None and not rules.new_reading(m, when.timestamp()): # the sensor has said nothing new since the last check return - # held: the lowest of the last readings (ANTISPIKE_REQUIRE_CONSECUTIVE), so a spike alone can't make the air unhealthy + # held: the lowest of the last readings (MCP_ANTISPIKE_REQUIRE_CONSECUTIVE), so a spike alone can't make the air unhealthy high25, high10 = held.get("pm2_5", pm25), held.get("pm10", pm10) bad = (high25 is not None and high25 >= MASK_PM25) or (high10 is not None and high10 >= MASK_PM10) good = (pm25 is None or pm25 <= SAFE_PM25) and (pm10 is None or pm10 <= SAFE_PM10) diff --git a/lib/alerts/store.py b/lib/alerts/store.py index 99b51373..06735e6c 100644 --- a/lib/alerts/store.py +++ b/lib/alerts/store.py @@ -1,7 +1,7 @@ """The alert rules' own state (alert_state.json in DATA_DIR): what each rule last alerted and the runs it is counting, so a restart neither forgets nor repeats. The service's, apart from the bot's chats and settings (bot_state.json), which the rules know nothing of. -Before step 4 of docs/mcp-service.md the rules kept it in bot_state.json's "monitor": the first start with no alert_state.json moves it +Before step 4 of docs/ecobot-mcp.md the rules kept it in bot_state.json's "monitor": the first start with no alert_state.json moves it here (MOVED), so nothing alerted before the upgrade alerts again. The irrigation controller's (irrigation_monitor, irrigation_watchdog) stay with the bot until it moves to its own server; the forecast each chat was sent (forecast_sent) goes: the forecast alert is station-wide now.""" diff --git a/lib/alerts/weather.py b/lib/alerts/weather.py index 56f6a246..cc4563ee 100644 --- a/lib/alerts/weather.py +++ b/lib/alerts/weather.py @@ -2,7 +2,7 @@ 5-minute readings; the rain check also reads the gauge's live value, one small request). - Rain: "started" (one tip of the gauge is enough, told at once, however lately it stopped) and "stopped" (dry for - ALERT_COOLDOWN_MINUTES, so patchy showers are one spell), with how much fell over the whole spell. Not during quiet hours (RAIN_QUIET_HOURS, default midnight to 6am, and they may run across midnight): + MCP_ALERT_COOLDOWN_MINUTES, so patchy showers are one spell), with how much fell over the whole spell. Not during quiet hours (MCP_RAIN_QUIET_HOURS, default midnight to 6am, and they may run across midnight): those are kept quiet and one summary of the rain that fell in them is sent after they end. - Strong gusts: one alert when a gust goes over 40 km/h, and no more until the gusts have stayed at or under it for an hour, so a blustery afternoon is one message, not twenty. @@ -10,7 +10,7 @@ below 10 for an hour. - Temperatures crossing: outdoor becomes warmer than indoor (or cooler); it has to differ by more than 1 degree, which stops sensor noise flip-flopping. - The crossing has a back-off rule (rules.py): after an alert, a change is held for ALERT_COOLDOWN_MINUTES and then + The crossing has a back-off rule (rules.py): after an alert, a change is held for MCP_ALERT_COOLDOWN_MINUTES and then announced if the state still differs from the one last alerted; if it is back where it was, nothing is sent. Each alert is an event appended to the alert log (lib/alert_log.py), news for a while (rain RAIN_EXPIRES_SECONDS, gusts and UV their rearm time, the crossing its cooldown); gusts, UV and the crossing carry their chart as data, with the call that draws it again. @@ -29,7 +29,7 @@ log = logging.getLogger(__name__) -ALERT_COOLDOWN_SECONDS = 60 * 60 # the default; ALERT_COOLDOWN_MINUTES sets it (the readings looked at go back 3 hours, so 150 minutes is the most) +ALERT_COOLDOWN_SECONDS = 60 * 60 # the default; MCP_ALERT_COOLDOWN_MINUTES sets it (the readings looked at go back 3 hours, so 150 minutes is the most) CROSS_MARGIN = 1.0 GUST_ALERT_KMH = 40 GUST_REARM_SECONDS = 3600 diff --git a/lib/auth_token.py b/lib/auth_token.py new file mode 100644 index 00000000..a92c8878 --- /dev/null +++ b/lib/auth_token.py @@ -0,0 +1,48 @@ +"""The token ecobot-mcp generates when AUTH_TOKENS is unset: made at its first start, kept in the data folder (auth_token, readable by +its own user only) and used again at every start after. The bot, with AUTH_TOKENS unset too, reads it from the same folder and sends it. +Its value is never logged: only where it is.""" + +import contextlib +import os +import secrets +from pathlib import Path + +FILE = "auth_token" + + +def path(folder: Path) -> Path: + return Path(folder) / FILE + + +def read(folder: Path) -> str | None: + """The token kept in `folder`; None when there is none yet, or it can't be read.""" + try: + return path(folder).read_text().strip() or None + except (OSError, UnicodeDecodeError): + return None + + +def ensure(folder: Path) -> str: + """The token kept in `folder`, made first if there is none: written whole to a file of its own (mode 0600) and then linked into + place, so a reader never sees half of one, and two starting at once keep the one that got there first.""" + if token := read(folder): + return token + target = path(folder) + token = secrets.token_urlsafe(32) + temporary = target.with_name(f".{FILE}.{os.getpid()}.{secrets.token_hex(4)}") + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + try: + with os.fdopen(fd, "w") as f: + f.write(token + "\n") + f.flush() + os.fsync(f.fileno()) + try: + os.link(temporary, target) # (fails if one is there: an empty or unreadable one is replaced, a good one is kept) + except FileExistsError: + if kept := read(folder): + return kept + os.replace(temporary, target) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(temporary) + return token diff --git a/lib/bot.py b/lib/bot.py index e14f7612..7b544830 100644 --- a/lib/bot.py +++ b/lib/bot.py @@ -40,7 +40,7 @@ from .timeutil import clock_text, day_text, now_local from .llm import Agent, shorten_old, strip_tool_turns, trim_history from .logs import BUGS, QUOTES, fit -from .warm import Tasks # (the service's too: ecobot_service) +from .warm import Tasks # (the service's too: ecobot_mcp) from .weather import UNREACHABLE, ChartImage, ChartNotDrawn, LocalWeather, ServiceUnreachable log = logging.getLogger(__name__) @@ -73,7 +73,7 @@ "/particulates, /wind), \"weather now\" and a reading's chart over a period like \"rain chart 7d\" or \"humidity 30d\", " "as well as all the alerts.") OUT_OF_DATE = "That chart is out of date, please ask again" -SERVICE_DOWN = "Sorry, I can't reach the weather service right now. Please try again in a minute." # (WEATHER_MCP_URL: it is another program) +SERVICE_DOWN = "Sorry, I can't reach the weather service right now. Please try again in a minute." # (BOT_MCP_URL: it is another program) @dataclass @@ -188,7 +188,7 @@ def strip_chart_talk(text: str) -> str: def complete_reply(results: list[str]) -> str | None: - """The reply of a step whose every result is complete (docs/mcp-service.md 3.7: `complete: true`, a chart made and its `reply` + """The reply of a step whose every result is complete (docs/ecobot-mcp.md 3.7: `complete: true`, a chart made and its `reply` ready): the replies in order; None when any isn't.""" replies = [] for result in results: @@ -404,7 +404,7 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler """state: the known chats and their settings. irrigation: the Tuya client of the irrigation controller, when one is configured (its button replaces Wind). tasks: where the bot's background work runs (the uploads of a chart's other periods); its own when none is given. service: the weather service as the bot reaches it (lib/weather.py: RemoteWeather over MCP, with - WEATHER_MCP_URL; `sources` is then empty), or the service's tools in this process (lib/service), which the bot's own code paths + BOT_MCP_URL; `sources` is then empty), or the service's tools in this process (lib/service), which the bot's own code paths call (its shortcuts, report, gauges, alert charts and period buttons), built over `sources` when none is given (LocalWeather). The model is offered the same tools (agent.tools: lib/model_tools.py), with the server's instructions after the bot's persona. alert_log: the service's alert log in this process (lib/alert_log.py), whose events the 🔄 under an alert's chart finds its @@ -415,15 +415,15 @@ def __init__(self, cfg: Config, agent: Agent, sources: list[Source], state: Aler self.tasks = tasks or Tasks() self.watchdog = Watchdog(irrigation, state) if irrigation else None # closes the valve after a run, however it ends self.keyboard_version = templates.version(irrigation is not None) - self.admin_only = bool(getattr(cfg, "admin_only", False)) # ADMIN_ONLY: only the admins of the groups the bot is in may use it + self.admin_only = bool(getattr(cfg, "admin_only", False)) # BOT_ADMIN_ONLY: only the admins of the groups the bot is in may use it self.admins = Admins(state, getattr(cfg, "admin_chat_ids", ())) - self._refused: set[int] = set() # the senders ADMIN_ONLY has turned away, each logged once with its id (for ADMIN_CHAT_IDS) + self._refused: set[int] = set() # the senders BOT_ADMIN_ONLY has turned away, each logged once with its id (for BOT_ADMIN_CHAT_IDS) self.chats: dict[tuple, ChatState] = defaultdict(ChatState) self.by_name = {s.name: s for s in sources} self.images = periods.ImageCache() # charts drawn lately, so toggling the period buttons is instant self.alert_charts = pictures.AlertCharts(self.images, lambda: now_local(self.cfg.tz), tz=getattr(cfg, "tz", None)) # the alerts' charts, kept with them - self.preloading: set[str] = set() # the calls whose other periods are being uploaded (TELEGRAM_PRELOAD_CHAT) + self.preloading: set[str] = set() # the calls whose other periods are being uploaded (BOT_TELEGRAM_PRELOAD_CHAT) self.last_used = 0.0 # when a message or a press last came in (monotonic; 0: never) self.preload_off = False # Telegram refused an upload to that chat (not a flood limit or a timeout): no more are tried until restart self.charted = periods.Charted(state.charts, state.save) # the call behind each chart sent (kept across restarts) @@ -544,7 +544,7 @@ def _sender(update: Update) -> tuple[str, int, str] | None: return ("user", update.effective_user.id, update.effective_user.full_name) if update.effective_user else None async def _allowed(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool: - """With ADMIN_ONLY on, only known group admins (and ADMIN_CHAT_IDS) get through; anyone else is told so, once, and False is + """With BOT_ADMIN_ONLY on, only known group admins (and BOT_ADMIN_CHAT_IDS) get through; anyone else is told so, once, and False is returned. A group the bot hears from is remembered first: it has to be known for its admins to count.""" chat = update.effective_chat if chat is not None and chat.type != ChatType.PRIVATE: @@ -553,7 +553,7 @@ async def _allowed(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> return True if (who := self._sender(update)) and who[1] not in self._refused: # once per sender in this run: the id is for the owner to list self._refused.add(who[1]) - log.info("%s: refused: %s %d (%s) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in", describe_source(update), *who) + log.info("%s: refused: %s %d (%s) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in", describe_source(update), *who) if update.callback_query is not None: await toast_quietly(update.callback_query, NOT_ADMIN_TOAST) elif update.effective_message is not None: @@ -600,7 +600,7 @@ def buttons(self) -> dict: async def on_button(self, update: Update, context: ContextTypes.DEFAULT_TYPE): """The one place every button press comes in: believed (_press), a known family (a prefix nobody handles is refused, so a - new kind of button is dead until it is added to buttons()), allowed (ADMIN_ONLY), then handled.""" + new kind of button is dead until it is added to buttons()), allowed (BOT_ADMIN_ONLY), then handled.""" query = update.callback_query if query is None or not await self._press(query): return @@ -1246,7 +1246,7 @@ async def _dashboard(self) -> Answer: @staticmethod def _complete(calls: list[dict], results: list[str]) -> str | None: - """The model loop's finish: when every call of a step gave a complete result (docs/mcp-service.md 3.7: its chart and its ready + """The model loop's finish: when every call of a step gave a complete result (docs/ecobot-mcp.md 3.7: its chart and its ready reply), their replies in order are the answer and the model is asked nothing more; else None, and the model answers as usual.""" return complete_reply(results) @@ -1273,7 +1273,7 @@ async def _ask_model(self, working: list[dict], system: str, read, turn: Turn, d effort, budget, retried = lower, RETRY_SECONDS, True def preload_soon(self, bot, drawn_by: dict | None): - """With TELEGRAM_PRELOAD_CHAT set, upload the chart of each other period its drawn_by lists, in the background.""" + """With BOT_TELEGRAM_PRELOAD_CHAT set, upload the chart of each other period its drawn_by lists, in the background.""" chat = getattr(self.cfg, "telegram_preload_chat", None) key = periods.drawn_key(drawn_by) if chat is None or self.preload_off or not drawn_by or not drawn_by.get("periods") or key in self.preloading: @@ -1312,7 +1312,7 @@ async def upload(period, args): await asyncio.gather(*(upload(period, args) for period, args in asked.items())) if skipped: - log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) + log.warning("BOT_TELEGRAM_PRELOAD_CHAT %s didn't take %d of the charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) if done: log.info("[Telegram] Preloaded %s %s to %s in %.1fs", tool, json.dumps(periods.with_period(drawn_by, "…"), ensure_ascii=False), chat, time.monotonic() - started, extra=QUOTES) @@ -1330,14 +1330,14 @@ async def _upload_ahead(self, bot, chat: int, key: str, png: bytes, title: str) except TelegramError as e: if not self.preload_off: self.preload_off = True - log.warning("Couldn't upload to TELEGRAM_PRELOAD_CHAT %s (%s: %s); not preloading charts", chat, type(e).__name__, e) + log.warning("Couldn't upload to BOT_TELEGRAM_PRELOAD_CHAT %s (%s: %s); not preloading charts", chat, type(e).__name__, e) return None async def draw_buttons_ahead(self, bot): """The chart of each keyboard button (each a fixed service call: the call its sentence is read as), and of each alert type sent in the last hours (alert_charts.warm, by their calls), drawn afresh (every AHEAD_SECONDS, from ecobot.warm_up), so a press, or the Refresh under the alert, is answered with a chart already drawn (images.ready, AlertCharts.newer_than) instead of drawing one - then; with TELEGRAM_PRELOAD_CHAT set and the bot used in the last 15 minutes, uploaded too, so the press sends Telegram's copy and + then; with BOT_TELEGRAM_PRELOAD_CHAT set and the bot used in the last 15 minutes, uploaded too, so the press sends Telegram's copy and uploads nothing. A chart drawn for a question in the last minute is left. Nobody is waiting: the requests are background ones, and the logs are quiet.""" started, now = time.monotonic(), now_local(self.cfg.tz) @@ -1366,7 +1366,7 @@ async def draw_buttons_ahead(self, bot): if drawn: log.debug("Drew %d button charts ahead%s in %.1fs", drawn, f", uploaded {uploaded} to {chat}" if uploaded else "", time.monotonic() - started) if skipped: - log.warning("TELEGRAM_PRELOAD_CHAT %s didn't take %d of the button charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) + log.warning("BOT_TELEGRAM_PRELOAD_CHAT %s didn't take %d of the button charts just now (%s: %s)", chat, len(skipped), type(skipped[0]).__name__, skipped[0]) async def respond(self, update: Update, context: ContextTypes.DEFAULT_TYPE, text: str): """Answer `text`.""" @@ -1442,7 +1442,7 @@ async def _answer(self, msg: Message, read, turn: Turn, working: list[dict], dra if answer.reply is not None: working.append({"role": "assistant", "content": answer.reply}) return answer - if not getattr(self.agent, "ready", True): # no OPENROUTER_API_KEY: what is left is for the model + if not getattr(self.agent, "ready", True): # no BOT_OPENROUTER_API_KEY: what is left is for the model answer.reply = NO_MODEL working.append({"role": "assistant", "content": answer.reply}) return answer diff --git a/lib/chart_images.py b/lib/chart_images.py index a401442a..1dd120a8 100644 --- a/lib/chart_images.py +++ b/lib/chart_images.py @@ -1,5 +1,5 @@ """Chart images: a chart's JSON (schemas/chart.json) drawn as a PNG by the bot's renderer (lib/charts.render_data, Pillow), for the -service's tools when a client asks for images (docs/mcp-service.md 3.7) and for the bot's interface to the service (lib/weather.py). +service's tools when a client asks for images (docs/ecobot-mcp.md 3.7) and for the bot's interface to the service (lib/weather.py). Pillow is optional on the service (requirements-charts.txt): nothing here imports it, nor lib.charts or lib.draw, until the first image is asked for (`renderer`). Without it `renderer()` is None, said once as a warning, and the service answers with the charts' JSON as if diff --git a/lib/config.py b/lib/config.py index 758da6a1..b69fa712 100644 --- a/lib/config.py +++ b/lib/config.py @@ -62,11 +62,11 @@ def _required(value: str, default: str, name: str) -> str: raise SystemExit(f"{name} is not set: the bot can't start without it (see docs/configuration.md)") -REQUIRED_BY_BOT = ("telegram_token",) # read only by the bot: the service (python -m ecobot_service) runs without them +REQUIRED_BY_BOT = ("telegram_token",) # read only by the bot: ecobot-mcp (python -m ecobot_mcp) runs without them def _tokens(value: str, default: tuple, name: str) -> tuple[str, ...]: - """"s3cret, t0ken" -> ("s3cret", "t0ken"): the bearer tokens the service accepts, one per client, so one can be revoked alone (take + """"s3cret, t0ken" -> ("s3cret", "t0ken"): the bearer tokens ecobot-mcp accepts, one per client, so one can be revoked alone (take it out and restart). Blank entries are skipped; a token given twice counts once.""" return tuple(dict.fromkeys(filter(None, (p.strip() for p in value.split(","))))) or default @@ -223,64 +223,101 @@ def _level(value: str, default: str, name: str) -> str: return default -def _setting(name: str, default=None, read=None): - """A Config field read from the environment variable `name` by `read` (a reader above; none: the text, blank being the default).""" - return field(default=default, metadata={"env": name, "read": read}) +def _setting(name: str, default=None, read=None, old: str | None = None): + """A Config field read from the environment variable `name` by `read` (a reader above; none: the text, blank being the default). + old: the name it had before (docs/configuration.md, "Renamed settings"), still read when `name` is unset, with a warning.""" + return field(default=default, metadata={"env": name, "read": read, "old": old}) -def _from_env(f) -> object: - text = os.getenv(f.metadata["env"], "").strip() - return f.metadata["read"](text, f.default, f.metadata["env"]) if f.metadata["read"] else text or f.default +def _text(f, renamed: list | None = None) -> tuple[str, str]: + """The setting's text (stripped) and the variable it was read from: its own name, else its old one (noted in `renamed`).""" + name, old = f.metadata["env"], f.metadata.get("old") + text = os.getenv(name, "").strip() + if not text and old and (text := os.getenv(old, "").strip()): + if renamed is not None: + renamed.append((old, name)) + return text, old + if text and old and os.getenv(old, "").strip() and renamed is not None: + renamed.append((old, None)) # both set: the old one is ignored + return text, name + + +def _from_env(f, renamed: list | None = None) -> object: + text, name = _text(f, renamed) + return f.metadata["read"](text, f.default, name) if f.metadata["read"] else text or f.default + + +def warn_renamed(renamed: list[tuple[str, str | None]]): + """One warning naming the old variables found and their new names (never their values).""" + used = [f"{old} -> {new}" for old, new in renamed if new] + ignored = [old for old, new in renamed if not new] + if used: + log.warning("Old setting names, still read for now: rename %s (docs/configuration.md, \"Renamed settings\")", ", ".join(used)) + if ignored: + log.warning("Ignoring %s: the new name%s set", ", ".join(ignored), " is" if len(ignored) == 1 else "s are") + + +def env(name: str) -> str: + """A setting's text by its name, or by its old one when that is all that is set (for the scripts, which read a few directly).""" + for f in fields(Config): + if f.metadata.get("env") == name: + return _text(f)[0] + return os.getenv(name, "").strip() + + +RETIRED_TOKEN = "WEATHER_MCP_TOKEN" # the bot's token before AUTH_TOKENS: still sent when AUTH_TOKENS is unset, with a warning @dataclass(frozen=True) class Config: tz: tzinfo state_path: Path - storage_path: Path # the bot's one file of readings, the pollen page and the forecast (lib/storage) - telegram_token: str = _setting("TELEGRAM_BOT_TOKEN", "") # the bot's (REQUIRED_BY_BOT: it stops without it) - openrouter_api_key: str = _setting("OPENROUTER_API_KEY", "") # unset: the bot runs without the model, answering only what it works out in code - openrouter_base_url: str = _setting("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1") - openrouter_model: str = _setting("OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017") - ecowitt_api_key: str = _setting("ECOWITT_API_KEY", "") - ecowitt_app_key: str = _setting("ECOWITT_APP_KEY", "") - airgradient_token: str = _setting("AIRGRADIENT_API_TOKEN", "") - airgradient_location: str = _setting("AIRGRADIENT_LOCATION_ID", "") - airgradient_dashboard: str = _setting("AIRGRADIENT_DASHBOARD_URL", "") - airgradient_local_url: str = _setting("AIRGRADIENT_LOCAL_URL", "") # the sensor's own server for the live reading, e.g. http://airgradient_.local - airgradient_source: str = _setting("AIRGRADIENT_SOURCE", "auto", _air_source) # auto: the monitor itself, then Home Assistant, then the cloud, each that is set; or one alone - homeassistant_url: str = _setting("HOMEASSISTANT_URL", "", _url) # Home Assistant, where the station's readings are read from (its Ecowitt integration), e.g. http://192.168.1.219:8123 - homeassistant_token: str = _setting("HOMEASSISTANT_TOKEN", "") # a long-lived access token (your profile page in Home Assistant) - ecowitt_source: str = _setting("ECOWITT_SOURCE", "auto", _source) # auto: Home Assistant if set, Ecowitt's cloud as its fallback if set too; cloud: the cloud only; homeassistant: Home Assistant only - place: str = _setting("PLACE", "Melbourne") # named after the Pollen & asthma and Forecast headings in the report - pollen: bool = _setting("POLLEN", False, _flag) # Melbourne grass pollen and thunderstorm asthma risk (a scraped website) - pollen_district: str = _setting("POLLEN_DISTRICT", "Central") # the Victorian forecast district whose thunderstorm asthma risk is used - forecast: bool = _setting("FORECAST", False, _flag) # the daily forecast from Open-Meteo - forecast_lat: float | None = _setting("FORECAST_LAT", None, _number) # the weather station's own location when unset - forecast_lon: float | None = _setting("FORECAST_LON", None, _number) - rain_quiet_hours: tuple[int, int] | None = _setting("RAIN_QUIET_HOURS", (0, 6), _hours) # "0-6", local hours ("off" for none): no rain alerts, a summary after - chart_all_feels_like: bool = _setting("CHART_ALL_FEELS_LIKE", False, _flag) # "weather all week" also draws the feels-like panel (off: it nearly repeats temperature) - chart_all_vpd: bool = _setting("CHART_ALL_VPD", False, _flag) # "weather all week" also draws the vapour pressure deficit panel (off: it is temperature and humidity combined) - tuya_device_id: str = _setting("TUYA_DEVICE_ID", "") # all three switch the irrigation controller on - tuya_client_id: str = _setting("TUYA_CLIENT_ID", "") - tuya_client_secret: str = _setting("TUYA_CLIENT_SECRET", "") - tuya_base_url: str = _setting("TUYA_BASE_URL", "https://openapi.tuyaeu.com", _url) # the data centre's address (EU by default) - irrigation_check_hour: int = _setting("IRRIGATION_CHECK_HOUR", 18, _hour) # the local hour of the daily check (0 to 23) - dark_mode: str | tuple[int, int] = _setting("DARKMODE", "off", _dark_mode) # off: light charts; on: dark; "8pm-8am" (or 20:00-8:00, 20-8): dark those hours in the bot's time zone - admin_only: bool = _setting("ADMIN_ONLY", False, _flag) # on: the bot answers nobody but the admins of the groups it is in (and ADMIN_CHAT_IDS) - admin_chat_ids: frozenset[int] = _setting("ADMIN_CHAT_IDS", frozenset(), _ids) # more ids allowed besides those admins (a user id, or a group id for its anonymous admins) - alert_cooldown_minutes: int = _setting("ALERT_COOLDOWN_MINUTES", 60, _between(5, 150)) # dry this long before "the rain has stopped"; and the temperature-crossing alert's minimum gap - telegram_preload_chat: int | None = _setting("TELEGRAM_PRELOAD_CHAT", None, _chat_id) # a chat the other periods of each chart are silently uploaded to ahead of the press (none: off) - antispike_require_consecutive: int = _setting("ANTISPIKE_REQUIRE_CONSECUTIVE", 2, _readings_in_a_row) # readings in a row a rise of the particles needs to be the air, not a glitch of the sensor (1: off) - log_width: int = _setting("LOG_WIDTH", 24, _whole) # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all - log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the bot's own debug lines; the libraries keep theirs - # The MCP service (python -m ecobot_service: docs/mcp-service.md 3.8) - mcp_service_tokens: tuple[str, ...] = _setting("MCP_SERVICE_TOKENS", (), _tokens) # "token,token,...", one per client; none: no auth, loopback only - mcp_service_bind: tuple[str, int] = _setting("MCP_SERVICE_BIND", ("127.0.0.1", 8765), _bind) # host:port the service listens on - mcp_service_allowed_hosts: tuple[str, ...] = _setting("MCP_SERVICE_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names) # the Host names it answers (any port, unless one is given) - # The bot as the service's client (docs/mcp-service.md step 5): set, the bot runs no sources, syncers or alert rules of its own - weather_mcp_url: str = _setting("WEATHER_MCP_URL", "", _url) # the service's MCP endpoint, e.g. http://127.0.0.1:8765/mcp; unset: the service runs inside the bot - weather_mcp_token: str = _setting("WEATHER_MCP_TOKEN", "") # the bearer token the bot sends it (one of the service's MCP_SERVICE_TOKENS) + storage_path: Path # the one file of readings, the pollen page and the forecast (lib/storage) + # ecobot-mcp's (python -m ecobot_mcp): the sources, the alert rules and the MCP server. The bot reads them too when it runs all of + # that in-process (BOT_MCP_URL unset) + ecowitt_api_key: str = _setting("MCP_ECOWITT_API_KEY", "", old="ECOWITT_API_KEY") + ecowitt_app_key: str = _setting("MCP_ECOWITT_APP_KEY", "", old="ECOWITT_APP_KEY") + ecowitt_source: str = _setting("MCP_ECOWITT_SOURCE", "auto", _source, old="ECOWITT_SOURCE") # auto: Home Assistant if set, Ecowitt's cloud as its fallback if set too; cloud: the cloud only; homeassistant: Home Assistant only + airgradient_token: str = _setting("MCP_AIRGRADIENT_API_TOKEN", "", old="AIRGRADIENT_API_TOKEN") + airgradient_location: str = _setting("MCP_AIRGRADIENT_LOCATION_ID", "", old="AIRGRADIENT_LOCATION_ID") + airgradient_dashboard: str = _setting("MCP_AIRGRADIENT_DASHBOARD_URL", "", old="AIRGRADIENT_DASHBOARD_URL") + airgradient_local_url: str = _setting("MCP_AIRGRADIENT_LOCAL_URL", "", old="AIRGRADIENT_LOCAL_URL") # the sensor's own server for the live reading, e.g. http://airgradient_.local + airgradient_source: str = _setting("MCP_AIRGRADIENT_SOURCE", "auto", _air_source, old="AIRGRADIENT_SOURCE") # auto: the monitor itself, then Home Assistant, then the cloud, each that is set; or one alone + homeassistant_url: str = _setting("MCP_HOMEASSISTANT_URL", "", _url, old="HOMEASSISTANT_URL") # Home Assistant, where the station's readings are read from (its Ecowitt integration), e.g. http://192.168.1.219:8123 + homeassistant_token: str = _setting("MCP_HOMEASSISTANT_TOKEN", "", old="HOMEASSISTANT_TOKEN") # a long-lived access token (your profile page in Home Assistant) + place: str = _setting("MCP_PLACE", "Melbourne", old="PLACE") # named after the Pollen & asthma and Forecast headings in the report + pollen: bool = _setting("MCP_POLLEN", False, _flag, old="POLLEN") # Melbourne grass pollen and thunderstorm asthma risk (a scraped website) + pollen_district: str = _setting("MCP_POLLEN_DISTRICT", "Central", old="POLLEN_DISTRICT") # the Victorian forecast district whose thunderstorm asthma risk is used + forecast: bool = _setting("MCP_FORECAST", False, _flag, old="FORECAST") # the daily forecast from Open-Meteo + forecast_lat: float | None = _setting("MCP_FORECAST_LAT", None, _number, old="FORECAST_LAT") # the weather station's own location when unset + forecast_lon: float | None = _setting("MCP_FORECAST_LON", None, _number, old="FORECAST_LON") + rain_quiet_hours: tuple[int, int] | None = _setting("MCP_RAIN_QUIET_HOURS", (0, 6), _hours, old="RAIN_QUIET_HOURS") # "0-6", local hours ("off" for none): no rain alerts, a summary after + alert_cooldown_minutes: int = _setting("MCP_ALERT_COOLDOWN_MINUTES", 60, _between(5, 150), old="ALERT_COOLDOWN_MINUTES") # dry this long before "the rain has stopped"; and the temperature-crossing alert's minimum gap + antispike_require_consecutive: int = _setting("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", 2, _readings_in_a_row, old="ANTISPIKE_REQUIRE_CONSECUTIVE") # readings in a row a rise of the particles needs to be the air, not a glitch of the sensor (1: off) + chart_all_feels_like: bool = _setting("MCP_CHART_ALL_FEELS_LIKE", False, _flag, old="CHART_ALL_FEELS_LIKE") # "weather all week" also draws the feels-like panel (off: it nearly repeats temperature) + chart_all_vpd: bool = _setting("MCP_CHART_ALL_VPD", False, _flag, old="CHART_ALL_VPD") # "weather all week" also draws the vapour pressure deficit panel (off: it is temperature and humidity combined) + mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind, old="MCP_SERVICE_BIND") # host:port ecobot-mcp listens on + mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names, old="MCP_SERVICE_ALLOWED_HOSTS") # the Host names it answers (any port, unless one is given) + # The bot's (ecobot.py) + telegram_token: str = _setting("BOT_TELEGRAM_TOKEN", "", old="TELEGRAM_BOT_TOKEN") # (REQUIRED_BY_BOT: it stops without it) + telegram_preload_chat: int | None = _setting("BOT_TELEGRAM_PRELOAD_CHAT", None, _chat_id, old="TELEGRAM_PRELOAD_CHAT") # a chat the other periods of each chart are silently uploaded to ahead of the press (none: off) + openrouter_api_key: str = _setting("BOT_OPENROUTER_API_KEY", "", old="OPENROUTER_API_KEY") # unset: the bot runs without the model, answering only what it works out in code + openrouter_base_url: str = _setting("BOT_OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1", old="OPENROUTER_BASE_URL") + openrouter_model: str = _setting("BOT_OPENROUTER_MODEL", "deepseek/deepseek-v4.1-flash-1017", old="OPENROUTER_MODEL") + admin_only: bool = _setting("BOT_ADMIN_ONLY", False, _flag, old="ADMIN_ONLY") # on: the bot answers nobody but the admins of the groups it is in (and BOT_ADMIN_CHAT_IDS) + admin_chat_ids: frozenset[int] = _setting("BOT_ADMIN_CHAT_IDS", frozenset(), _ids, old="ADMIN_CHAT_IDS") # more ids allowed besides those admins (a user id, or a group id for its anonymous admins) + log_width: int = _setting("BOT_LOG_WIDTH", 24, _whole, old="LOG_WIDTH") # the most characters of a chat message kept in the log, then an ellipsis (…); 0 keeps all + tuya_device_id: str = _setting("BOT_TUYA_DEVICE_ID", "", old="TUYA_DEVICE_ID") # all three switch the irrigation controller on + tuya_client_id: str = _setting("BOT_TUYA_CLIENT_ID", "", old="TUYA_CLIENT_ID") + tuya_client_secret: str = _setting("BOT_TUYA_CLIENT_SECRET", "", old="TUYA_CLIENT_SECRET") + tuya_base_url: str = _setting("BOT_TUYA_BASE_URL", "https://openapi.tuyaeu.com", _url, old="TUYA_BASE_URL") # the data centre's address (EU by default) + irrigation_check_hour: int = _setting("BOT_IRRIGATION_CHECK_HOUR", 18, _hour, old="IRRIGATION_CHECK_HOUR") # the local hour of the daily check (0 to 23) + mcp_url: str = _setting("BOT_MCP_URL", "", _url, old="WEATHER_MCP_URL") # ecobot-mcp's endpoint, e.g. http://127.0.0.1:8765/mcp: set, the bot is its client and runs no sources, syncers or alert rules of its own; unset: all of that runs inside the bot + retired_mcp_token: str = _setting(RETIRED_TOKEN, "") # retired: sent only when AUTH_TOKENS is unset (ecobot.mcp_token) + # Both read them + dark_mode: str | tuple[int, int] = _setting("DARKMODE", "off", _dark_mode) # off: light charts; on: dark; "8pm-8am" (or 20:00-8:00, 20-8): dark those hours in the station's time zone + log_level: str = _setting("LOG_LEVEL", "INFO", _level) # DEBUG adds the program's own debug lines; the libraries keep theirs + auth_tokens: tuple[str, ...] = _setting("AUTH_TOKENS", (), _tokens, old="MCP_SERVICE_TOKENS") # "token,token,...": ecobot-mcp accepts each, the bot sends the first; unset: the one ecobot-mcp generates in the data folder (lib/auth_token.py) @property def alert_state_path(self) -> Path: @@ -298,12 +335,12 @@ def homeassistant(self) -> bool: @property def ecowitt_cloud(self) -> bool: - """The station's readings are asked of Ecowitt's cloud (its keys are set, and ECOWITT_SOURCE does not say Home Assistant only).""" + """The station's readings are asked of Ecowitt's cloud (its keys are set, and MCP_ECOWITT_SOURCE does not say Home Assistant only).""" return bool(self.ecowitt_api_key and self.ecowitt_app_key) and self.ecowitt_source != "homeassistant" @property def ecowitt_home_assistant(self) -> bool: - """... of Home Assistant (it is set, and ECOWITT_SOURCE does not say the cloud only).""" + """... of Home Assistant (it is set, and MCP_ECOWITT_SOURCE does not say the cloud only).""" return self.homeassistant and self.ecowitt_source != "cloud" @property @@ -317,17 +354,17 @@ def irrigation(self) -> bool: @property def airgradient_cloud(self) -> bool: - """The air monitor's readings are asked of AirGradient's cloud (its token and location are set, and AIRGRADIENT_SOURCE allows).""" + """The air monitor's readings are asked of AirGradient's cloud (its token and location are set, and MCP_AIRGRADIENT_SOURCE allows).""" return bool(self.airgradient_token and self.airgradient_location) and self.airgradient_source in ("auto", "cloud") @property def airgradient_local(self) -> bool: - """... of the monitor itself (its address is set, and AIRGRADIENT_SOURCE allows).""" + """... of the monitor itself (its address is set, and MCP_AIRGRADIENT_SOURCE allows).""" return bool(self.airgradient_local_url) and self.airgradient_source in ("auto", "local") @property def airgradient_homeassistant(self) -> bool: - """... of Home Assistant (it is set, and AIRGRADIENT_SOURCE allows; whether it has the monitor is found at start).""" + """... of Home Assistant (it is set, and MCP_AIRGRADIENT_SOURCE allows; whether it has the monitor is found at start).""" return self.homeassistant and self.airgradient_source in ("auto", "homeassistant") @property @@ -338,7 +375,8 @@ def airgradient(self) -> bool: @classmethod def from_env(cls, bot: bool = True) -> "Config": """Every setting from its variable, the files in the data folder. Stops, saying why, when one the bot can't run without is - missing or the folder can't be written. bot: False for the service (python -m ecobot_service), which has no Telegram token.""" + missing or the folder can't be written. bot: False for ecobot-mcp (python -m ecobot_mcp), which has no Telegram token. Old + names still read are named in one warning (never their values).""" data = data_dir() try: data.mkdir(parents=True, exist_ok=True) @@ -348,12 +386,15 @@ def from_env(cls, bot: bool = True) -> "Config": if not writable: raise SystemExit(f"{data} is not writable by this user: set DATA_DIR to a writable folder " "(under systemd with StateDirectory=ecobot that is /var/lib/ecobot)") + renamed: list = [] cfg = cls(tz=local_tz(), state_path=data / "bot_state.json", storage_path=data / "ecobot.sqlite", - **{f.name: _from_env(f) for f in fields(cls) if "env" in f.metadata}) + **{f.name: _from_env(f, renamed) for f in fields(cls) if "env" in f.metadata}) + warn_renamed(renamed) for f in fields(cls): if bot and f.name in REQUIRED_BY_BOT: _required(getattr(cfg, f.name), f.default, f.metadata["env"]) - if not (cfg.ecowitt or cfg.airgradient) and not (bot and cfg.weather_mcp_url): # (a client of the service needs no source) - raise SystemExit("Set ECOWITT_API_KEY + ECOWITT_APP_KEY and/or HOMEASSISTANT_URL + HOMEASSISTANT_TOKEN and/or AIRGRADIENT_API_TOKEN + " - "AIRGRADIENT_LOCATION_ID and/or AIRGRADIENT_LOCAL_URL") + if not (cfg.ecowitt or cfg.airgradient) and not (bot and cfg.mcp_url): # (a client of ecobot-mcp needs no source) + raise SystemExit("Set MCP_ECOWITT_API_KEY + MCP_ECOWITT_APP_KEY and/or MCP_HOMEASSISTANT_URL + MCP_HOMEASSISTANT_TOKEN and/or " + "MCP_AIRGRADIENT_API_TOKEN + MCP_AIRGRADIENT_LOCATION_ID and/or MCP_AIRGRADIENT_LOCAL_URL" + + ("" if not bot else ", or BOT_MCP_URL to use ecobot-mcp")) return cfg diff --git a/lib/ecowitt/homeassistant.py b/lib/ecowitt/homeassistant.py index 6a122ac9..ec3fc72b 100644 --- a/lib/ecowitt/homeassistant.py +++ b/lib/ecowitt/homeassistant.py @@ -83,8 +83,8 @@ def failed(self, what: str, error: object, then: str = ""): self.failing = True hint = "" if any(m in str(error).lower() for m in NAME_NOT_FOUND): - hint = local_name_hint(urlsplit(self.url).hostname or "", "HOMEASSISTANT_URL") or ( - f". The name in HOMEASSISTANT_URL ({self.url}) can't be found from here: check it, or use the address (http://192.168.x.x:8123)") + hint = local_name_hint(urlsplit(self.url).hostname or "", "MCP_HOMEASSISTANT_URL") or ( + f". The name in MCP_HOMEASSISTANT_URL ({self.url}) can't be found from here: check it, or use the address (http://192.168.x.x:8123)") log.warning("Home Assistant: the %s failed (%s)%s%s", what, error, f"; {then}" if then else "", hint) def ok(self): diff --git a/lib/forecast/source.py b/lib/forecast/source.py index 5ccc4b72..7d677299 100644 --- a/lib/forecast/source.py +++ b/lib/forecast/source.py @@ -70,7 +70,7 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra self.tz, self.place = cfg.tz, cfg.place configured = (cfg.forecast_lat, cfg.forecast_lon) if configured != (None, None) and None in configured: - log.warning("FORECAST_LAT and FORECAST_LON go together: with only one set, the weather station's location is used") + log.warning("MCP_FORECAST_LAT and MCP_FORECAST_LON go together: with only one set, the weather station's location is used") self.location = configured if None not in configured else location if location and None not in location else None self.client = httpx.AsyncClient(timeout=15, headers=HEADERS, follow_redirects=True, transport=transport) self.days: list[dict] | None = None @@ -82,7 +82,7 @@ def __init__(self, cfg: Config, location: tuple[float, float] | None = None, tra async def start(self): if not self.location: - raise RuntimeError("no location: set FORECAST_LAT and FORECAST_LON (or the weather station supplies one)") + raise RuntimeError("no location: set MCP_FORECAST_LAT and MCP_FORECAST_LON (or the weather station supplies one)") try: await self.warm(True) self.summary = f"{SOURCE}: {len(self.days or [])} days (every {self.warmer.interval:g}s)" diff --git a/lib/gauge_sheet.py b/lib/gauge_sheet.py index 055d2a3e..5756b505 100644 --- a/lib/gauge_sheet.py +++ b/lib/gauge_sheet.py @@ -1,4 +1,4 @@ -"""The gauges' sheet (specs.Dashboard, what lib/gauges.py draws), laid out by the bot as a client of the service (docs/mcp-service.md +"""The gauges' sheet (specs.Dashboard, what lib/gauges.py draws), laid out by the bot as a client of the service (docs/ecobot-mcp.md 3.1, 4): each gauge's scale and colours (lib/ecowitt/dashboard.py GAUGES) filled from the service's `current` with `context`, its reading now and the highs and lows of today, the month and the year beside it (rain: its totals and wettest day; wind: its highest gust). diff --git a/lib/intent.py b/lib/intent.py index 1c630288..2119749c 100644 --- a/lib/intent.py +++ b/lib/intent.py @@ -1,4 +1,4 @@ -"""What the bot decides about a message with patterns rather than the model (docs/mcp-service.md 4): +"""What the bot decides about a message with patterns rather than the model (docs/ecobot-mcp.md 4): - how much the model should think (only predictions, analysis and "describe it" questions get reasoning); - the few shortcuts the bot answers in code, each a fixed call to a service tool: the report, the gauges, "weather now", and a diff --git a/lib/llm.py b/lib/llm.py index a9729a93..e4ba3185 100644 --- a/lib/llm.py +++ b/lib/llm.py @@ -29,7 +29,7 @@ class Agent: def __init__(self, client: "AsyncOpenAI | None", model: str, tools: Tools): - self.client, self.model, self.tools = client, model, tools # no client (no OPENROUTER_API_KEY): the tools are still called, the model never is + self.client, self.model, self.tools = client, model, tools # no client (no BOT_OPENROUTER_API_KEY): the tools are still called, the model never is @property def ready(self) -> bool: @@ -91,7 +91,7 @@ async def run(self, messages: list[dict], system_prompt: str, effort: str, *, to data: when the tool results of a question pass WARN_TOKENS (twice a 500-point query), so the chat can be told first. The work carries on; nothing waits for a reply. finish(calls, results) is asked after each step of the model's tool calls: text from it is the reply, and the turn ends there - with no further model call (a complete result, docs/mcp-service.md 3.7).""" + with no further model call (a complete result, docs/ecobot-mcp.md 3.7).""" cache: dict = {} # identical tool calls within one question are only made once async def call(name: str, args: str) -> str: diff --git a/lib/logs.py b/lib/logs.py index 5b98582a..19f73917 100644 --- a/lib/logs.py +++ b/lib/logs.py @@ -1,5 +1,5 @@ """How the bot's log lines look: the message alone, marked WARN, ERROR or DEBUG when it is not an ordinary (INFO) line. Only a chat -message (a request quoted last on a line) is shortened: put on one line and cut to the log width (LOG_WIDTH) with an ellipsis (…) +message (a request quoted last on a line) is shortened: put on one line and cut to the log width (BOT_LOG_WIDTH) with an ellipsis (…) marking the cut. Every other line, and a traceback, is logged whole. DEBUG and INFO lines go to stdout, WARN and ERROR to stderr, so Docker (and its journald driver) tells them apart. Under systemd both go diff --git a/lib/mcp_server.py b/lib/mcp_server.py index 24f4e55f..7530244e 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -1,4 +1,4 @@ -"""The service over MCP (docs/mcp-service.md 3.4-3.8): the SDK's low-level Server serving the ten tools (lib/service), the resources and +"""The service over MCP (docs/ecobot-mcp.md 3.4-3.8): the SDK's low-level Server serving the ten tools (lib/service), the resources and prompts, the server's instructions (lib/service/instructions.py) and the `subscriptions/listen` stream, as Streamable HTTP behind a bearer token check. @@ -20,11 +20,11 @@ `wait`), the station when the catalogue gains a reading. - **Prompts** (3.5): PROMPTS, each a question in words with its period an argument; no logic. - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against the allowed hosts - (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_SERVICE_ALLOWED_HOSTS says), each request's bearer token against - MCP_SERVICE_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). + (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_ALLOWED_HOSTS says), each request's bearer token against + AUTH_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). `EcobotServer(ctx, alert_log)` builds it over the service's Context; `run()` is its publishing, for as long as it runs. Nothing here -fetches, alerts or writes: ecobot_service runs the sources and the rules.""" +fetches, alerts or writes: ecobot_mcp runs the sources and the rules.""" import asyncio import base64 @@ -177,8 +177,8 @@ def connection_query(ctx, name: str) -> str | None: # ---------- auth ---------- class TokenCheck: - """The service's TokenVerifier (3.8): a bearer token is one of MCP_SERVICE_TOKENS, compared in constant time against every one of - them. `revoke(token)` takes one out while the service runs (MCP_SERVICE_TOKENS without it does the same at the next start).""" + """The service's TokenVerifier (3.8): a bearer token is one of AUTH_TOKENS, compared in constant time against every one of + them. `revoke(token)` takes one out while the service runs (AUTH_TOKENS without it does the same at the next start).""" def __init__(self, tokens): self.tokens = list(dict.fromkeys(tokens)) @@ -208,7 +208,7 @@ def host_settings(allowed: tuple[str, ...] | list[str]) -> TransportSecuritySett # ---------- the server ---------- class EcobotServer: """The service's MCP server over a Context (lib/service/context.py) and the alert log. health: a callable giving the service's own - health figures (ecobot_service's loops), merged into ecobot://health.""" + health figures (ecobot_mcp's loops), merged into ecobot://health.""" def __init__(self, ctx, alert_log=None, *, health: Callable[[], dict] | None = None, version: str = "", bus=None): self.ctx, self.alert_log, self.health_of = ctx, alert_log, health @@ -461,8 +461,8 @@ def prompt(name: str, arguments: dict | None = None) -> types.GetPromptResult: # ---------- the request log ---------- -WHY = {401: "no token, or one that isn't in MCP_SERVICE_TOKENS", - 421: "its Host isn't in MCP_SERVICE_ALLOWED_HOSTS", +WHY = {401: "no token, or one that isn't in AUTH_TOKENS", + 421: "its Host isn't in MCP_ALLOWED_HOSTS", 404: "nothing at this path, or the session has ended"} BODY_READ = 1 << 20 # the most of a request's body read to name its MCP method (the SDK reads it all anyway) @@ -546,7 +546,7 @@ def record(scope, asked: str, status: int, took: float): def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", path: str = "/mcp"): - """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (MCP_SERVICE_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth + """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (AUTH_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth metadata is published (resource_server_url=None).""" check = TokenCheck(tokens) if tokens else None app = server.server.streamable_http_app( diff --git a/lib/model_tools.py b/lib/model_tools.py index 16599514..e18a71e3 100644 --- a/lib/model_tools.py +++ b/lib/model_tools.py @@ -1,4 +1,4 @@ -"""The service's ten tools (lib/service) as the bot offers them to its model (docs/mcp-service.md 4): each by its own name, description +"""The service's ten tools (lib/service) as the bot offers them to its model (docs/ecobot-mcp.md 4): each by its own name, description and parameters, as they are. The bot draws the charts itself, so it asks for them as drawn (request `_meta` `chart_points: "drawn"`) and keeps each whole result on the question's Turn (`Turn.results`: for drawing, the period buttons, the complete result that ends the turn; a call that gave no JSON object leaves None); the model is sent the result less the charts' data (`for_model`): each chart as its title and period, diff --git a/lib/partday.py b/lib/partday.py index d0f61d2f..597bca38 100644 --- a/lib/partday.py +++ b/lib/partday.py @@ -1,4 +1,4 @@ -"""Part of each day (docs/mcp-service.md 3.3): a sensor's figures over one stretch of local time on each day of a period, worked out as a +"""Part of each day (docs/ecobot-mcp.md 3.3): a sensor's figures over one stretch of local time on each day of a period, worked out as a day row is from a whole day's readings (lib/storage/days.py), so the overnight low, the nights below 5°C or the 3pm temperature can be found, ranked and counted as days are. diff --git a/lib/periods.py b/lib/periods.py index 9ae8f076..434dbb2d 100644 --- a/lib/periods.py +++ b/lib/periods.py @@ -1,6 +1,6 @@ """The period buttons under a chart, and the charts drawn lately. -A chart the service drew carries `drawn_by` (docs/mcp-service.md 3.7): the call that drew it and the periods it is worth drawing over, +A chart the service drew carries `drawn_by` (docs/ecobot-mcp.md 3.7): the call that drew it and the periods it is worth drawing over, each with its label ("7d", "7D"). Its buttons are those periods, the chart's own shaded (the blue of an alert toggle that is on), and none when it lists none (but a 🔄, "pd:reload", that draws it again when its period runs to now); a button's data is the period ("pd:7d"), never the call, which Telegram's 64 bytes couldn't hold. Pressing one replays the call with that period @@ -170,7 +170,7 @@ class ImageCache: CHART_TTL = 10 * 60 CHART_IMAGES = 60 - PRELOAD_TTL = 30 * 60 # a chart uploaded ahead (TELEGRAM_PRELOAD_CHAT) is used for this long, then drawn afresh + PRELOAD_TTL = 30 * 60 # a chart uploaded ahead (BOT_TELEGRAM_PRELOAD_CHAT) is used for this long, then drawn afresh FRESH = 330 # a chart made in code this lately answers the same call again as it is (the readings move slowly) def __init__(self, clock=None): @@ -207,7 +207,7 @@ def has_copy(self, key: str | None) -> bool: def ready(self, key: str | None) -> Drawn | None: """The chart made in code for this call in the last FRESH seconds (for someone's question, or uploaded ahead to - TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" + BOT_TELEGRAM_PRELOAD_CHAT), with the text that went with it; None if there is none.""" entry = self.items.get(key) if key else None if entry is None or entry.caption is None or self.age(entry) > self.FRESH or entry.dark != dark_now(): return None diff --git a/lib/periods_text.py b/lib/periods_text.py index f556e09d..a429212e 100644 --- a/lib/periods_text.py +++ b/lib/periods_text.py @@ -1,5 +1,5 @@ """Periods in words: the person's own words for a stretch of time ("this week", "3m", "yesterday afternoon"), read by one table in -the station's time zone, so a model never works out a date (docs/mcp-service.md 3.2). Every tool that takes a period reads it here, +the station's time zone, so a model never works out a date (docs/ecobot-mcp.md 3.2). Every tool that takes a period reads it here, and its result begins with how it was read. - `period` must be one of the table's forms as a whole phrase, case aside; N is a number in digits or a word up to twelve. There is diff --git a/lib/pollen/source.py b/lib/pollen/source.py index a32ba1b7..ac47b2e7 100644 --- a/lib/pollen/source.py +++ b/lib/pollen/source.py @@ -32,7 +32,7 @@ def _district(name: str) -> str: """The site's name for this district, whatever its case. One the site doesn't have is warned about: no level can be found for it.""" known = {d.lower(): d for d in DISTRICTS} if name.lower() not in known: - log.warning("POLLEN_DISTRICT %r is not one of the site's districts (%s): no district level will be found", name, + log.warning("MCP_POLLEN_DISTRICT %r is not one of the site's districts (%s): no district level will be found", name, ", ".join(sorted(DISTRICTS))) return known.get(name.lower(), name) diff --git a/lib/prompt.py b/lib/prompt.py index 65700c14..6b599912 100644 --- a/lib/prompt.py +++ b/lib/prompt.py @@ -1,4 +1,4 @@ -"""The bot's system prompt (docs/mcp-service.md 4): its persona, a friendly Telegram bot, then the server's instructions +"""The bot's system prompt (docs/ecobot-mcp.md 4): its persona, a friendly Telegram bot, then the server's instructions (lib/service/instructions.py) and the date and time now. Everything about the tools and the data is in their descriptions and results (3.2): nothing here is about which tool to call or how to read what comes back.""" diff --git a/lib/service/__init__.py b/lib/service/__init__.py index 7c61afa6..a70b7e9d 100644 --- a/lib/service/__init__.py +++ b/lib/service/__init__.py @@ -1,4 +1,4 @@ -"""The service's tools (docs/mcp-service.md 3.2 and 3.3): the ten that will replace the bot's twelve, each in a module of its own, on +"""The service's tools (docs/ecobot-mcp.md 3.2 and 3.3): the ten that will replace the bot's twelve, each in a module of its own, on what every one of them shares: - common.py: how a tool is made, what it is sent (its arguments and the request's metadata, nothing else), and the shape of what it diff --git a/lib/service/about.py b/lib/service/about.py index 6f6063dd..6c13ef24 100644 --- a/lib/service/about.py +++ b/lib/service/about.py @@ -1,4 +1,4 @@ -"""The `about` tool (docs/mcp-service.md 3.3): what the service measures and what it doesn't, how far back each kind of history goes, +"""The `about` tool (docs/ecobot-mcp.md 3.3): what the service measures and what it doesn't, how far back each kind of history goes, the alerts there are with their thresholds, and that alerts can't be added or changed by asking. It replaces what the bot's prompt told its model outside the tools (lib/prompt.py: NEVER_AVAILABLE, the capabilities, ALERT_WORDS), whose lists are copied here (the prompt goes with the bot), and the bot's Help list (lib/templates.py MEASURES: `lines`, the same words). @@ -8,7 +8,7 @@ - history: for each sensor, from when to when each resolution is held, and on how many days, from the coverage of the file (the minutes, which have none, from the readings themselves): what "on record" reaches, and how fine a record is in each stretch of it; - alerts: each kind there is for the sources there are (lib/alerts/menu.py TYPES, copied), with what it is, its rule in words and its - thresholds as figures, from the alert rules' own constants and the settings (RAIN_QUIET_HOURS, ALERT_COOLDOWN_MINUTES). + thresholds as figures, from the alert rules' own constants and the settings (MCP_RAIN_QUIET_HOURS, MCP_ALERT_COOLDOWN_MINUTES). It takes no arguments and reads only what is held, so `fetch` and `priority` change nothing. """ @@ -36,7 +36,7 @@ NAME = "about" # ---------- the settings the alerts follow ---------- -# The rain alert's quiet hours and the alerts' cooldown are the service's config (RAIN_QUIET_HOURS, ALERT_COOLDOWN_MINUTES): set from it at +# The rain alert's quiet hours and the alerts' cooldown are the service's config (MCP_RAIN_QUIET_HOURS, MCP_ALERT_COOLDOWN_MINUTES): set from it at # startup, as names.FEELS_LIKE_IN_ALL is. These are the config's defaults. RAIN_QUIET_HOURS: tuple[int, int] | None = (0, 6) # local hours with no rain alerts, a summary after; None: none ALERT_COOLDOWN_MINUTES = 60 # dry this long before "the rain has stopped"; the temperature crossing's least gap diff --git a/lib/service/alerts.py b/lib/service/alerts.py index bfe30e86..630dfb05 100644 --- a/lib/service/alerts.py +++ b/lib/service/alerts.py @@ -1,4 +1,4 @@ -"""The service's alert rules (docs/mcp-service.md 3.6), each on the trigger it has: the weather alerts after every refresh of the station +"""The service's alert rules (docs/ecobot-mcp.md 3.6), each on the trigger it has: the weather alerts after every refresh of the station (and the rain on each live reading), particulates every CHECK_SECONDS, pollen and the forecast after each refresh of their pages. Their settings (quiet hours, cooldown) are the service's config, their state its own store (lib/alerts/store.py, alert_state.json), and what they decide goes to the alert log (lib/alert_log.py), which clients read: they know nothing of chats or Telegram. diff --git a/lib/service/common.py b/lib/service/common.py index dacfaff3..46762a09 100644 --- a/lib/service/common.py +++ b/lib/service/common.py @@ -1,4 +1,4 @@ -"""What every service tool shares (docs/mcp-service.md 3.2, 3.7): how a tool is made and what it is sent, how it reads a period, and +"""What every service tool shares (docs/ecobot-mcp.md 3.2, 3.7): how a tool is made and what it is sent, how it reads a period, and the shape of what it answers. A tool is a ServiceTool: its handler is `handler(args, meta)`, the arguments as sent and the request's metadata (`request_meta`), and diff --git a/lib/service/current.py b/lib/service/current.py index f0e95870..06a07528 100644 --- a/lib/service/current.py +++ b/lib/service/current.py @@ -1,4 +1,4 @@ -"""The `current` tool (docs/mcp-service.md 3.3): how it is now, from the weather station and the air sensor, every reading or the ones +"""The `current` tool (docs/ecobot-mcp.md 3.3): how it is now, from the weather station and the air sensor, every reading or the ones named, and with `context` today's, this month's and this year's highs and lows beside each reading, as the gauges show them. It replaces weather_now and air_quality without dates (and the gauges' figures), on their engines: diff --git a/lib/service/daylook.py b/lib/service/daylook.py index b8374c02..b723814a 100644 --- a/lib/service/daylook.py +++ b/lib/service/daylook.py @@ -1,4 +1,4 @@ -"""A day's look: one word and an emoji for that day's outdoor weather, worked out from its figures (docs/mcp-service.md 3.2, "Answers +"""A day's look: one word and an emoji for that day's outdoor weather, worked out from its figures (docs/ecobot-mcp.md 3.2, "Answers ready to pass on"), so a model quotes `day_look: {word: "wet", emoji: "🌧️"}` beside a day and never guesses it. The rule takes the first that holds: diff --git a/lib/service/days.py b/lib/service/days.py index 18cb6182..fa29baaf 100644 --- a/lib/service/days.py +++ b/lib/service/days.py @@ -1,4 +1,4 @@ -"""The `days` tool (docs/mcp-service.md 3.3): days found, ranked, counted or totalled by their figures, over the weather station's and +"""The `days` tool (docs/ecobot-mcp.md 3.3): days found, ranked, counted or totalled by their figures, over the weather station's and the air sensor's day figures, or over part of each day (`hours`). It replaces weather_days and air_days, on their engines: - the fields are theirs: the station's (lib/ecowitt/days.py FIELDS: temp_max, rain, humidity_avg, indoor_temp_min ...) and the air diff --git a/lib/service/forecast.py b/lib/service/forecast.py index 05eaaddb..46f44b7a 100644 --- a/lib/service/forecast.py +++ b/lib/service/forecast.py @@ -1,4 +1,4 @@ -"""The `forecast` tool (docs/mcp-service.md 3.3): today and the days ahead, from the forecast source (lib/forecast, Open-Meteo), for a +"""The `forecast` tool (docs/ecobot-mcp.md 3.3): today and the days ahead, from the forecast source (lib/forecast, Open-Meteo), for a period in words that look ahead ("tomorrow", "next 3 days", "this weekend"), read here: lib/periods_text.py reads only what has been measured, and refuses the future by pointing to this tool. diff --git a/lib/service/instructions.py b/lib/service/instructions.py index 119af0da..05ed644d 100644 --- a/lib/service/instructions.py +++ b/lib/service/instructions.py @@ -1,4 +1,4 @@ -"""The server's instructions (docs/mcp-service.md 3.2): a short summary of what the tools read, for a client that passes it to its model +"""The server's instructions (docs/ecobot-mcp.md 3.2): a short summary of what the tools read, for a client that passes it to its model (over MCP a client gets it by asking: `server/discover`). Nothing depends on it: every rule a choice of tool or the reading of a result depends on is in the tool's description or in the result, and the evals are run with and without it (`--live --service --instructions`, docs 7). diff --git a/lib/service/names.py b/lib/service/names.py index 248c663f..4a90783a 100644 --- a/lib/service/names.py +++ b/lib/service/names.py @@ -1,4 +1,4 @@ -"""The readings the service has, one name each, and the words people use for them (docs/mcp-service.md 3.2, "One naming scheme"). +"""The readings the service has, one name each, and the words people use for them (docs/ecobot-mcp.md 3.2, "One naming scheme"). A reading's name is `sensor.reading`: the weather station's Ecowitt group and the reading's column (`outdoor.temperature`, `indoor.humidity`, `pressure.relative`, `wind.wind_gust`), with rain as `rainfall.rain`, the mm that fell (the file keeps the running @@ -30,7 +30,7 @@ # ---------- "all" ---------- # The settings "all" follows: the panels of "weather all week", top to bottom, as lib/series.py names the readings. intent.chart_fields -# reads them here too. ecobot.py sets the two flags from the config (CHART_ALL_FEELS_LIKE, CHART_ALL_VPD) at startup. +# reads them here too. ecobot.py sets the two flags from the config (MCP_CHART_ALL_FEELS_LIKE, MCP_CHART_ALL_VPD) at startup. ALL_ORDER = ("temperature", "humidity", "solar", "pressure", "rain", "dew_point", "feels_like", "vpd", "uv", "wind") LEFT_OUT_OF_ALL = ("uv",) # the UV index has the same shape as solar radiation FEELS_LIKE_IN_ALL = False # the feels-like panel: off, as it nearly repeats temperature @@ -204,7 +204,7 @@ async def open(cls, eco=None, air=None) -> "Catalogue": @classmethod def listed(cls, entries: Iterable[dict]) -> "Catalogue": """The catalogue another process holds, from the readings it lists ({name, label, unit}, as ecobot://station's sensors give - them: a client's, docs/mcp-service.md step 5): each reading as this catalogue makes it, with the label and unit listed.""" + them: a client's, docs/ecobot-mcp.md step 5): each reading as this catalogue makes it, with the label and unit listed.""" wanted = {e["name"]: e for e in entries if isinstance(e, dict) and e.get("name")} made = (_reading(m, set(wanted)) for m in [*station_metrics(None), *air_metrics(extra=True)]) return cls(replace(r, label=wanted[r.name].get("label") or r.label, unit=wanted[r.name].get("unit", r.unit)) diff --git a/lib/service/outlook.py b/lib/service/outlook.py index b5979b36..1aa86401 100644 --- a/lib/service/outlook.py +++ b/lib/service/outlook.py @@ -1,4 +1,4 @@ -"""The `outlook` tool (docs/mcp-service.md 3.3): will it rain in the next few hours. No arguments. +"""The `outlook` tool (docs/ecobot-mcp.md 3.3): will it rain in the next few hours. No arguments. The bot's prompt told the model how to read the station for this (lib/prompt.py, its "outlook" block) and fetched the reading now and the last 3 hours for it (intent.model_prefetch). Here the same rules are worked out in code, from the station's 5-minute readings of diff --git a/lib/service/pollen.py b/lib/service/pollen.py index cb5d0fce..b2547890 100644 --- a/lib/service/pollen.py +++ b/lib/service/pollen.py @@ -1,4 +1,4 @@ -"""The `pollen` tool (docs/mcp-service.md 3.3): Melbourne's grass pollen and the thunderstorm asthma risk, from the pollen source +"""The `pollen` tool (docs/ecobot-mcp.md 3.3): Melbourne's grass pollen and the thunderstorm asthma risk, from the pollen source (lib/pollen, melbournepollen.com.au). No arguments. The answer is today's pollen_asthma's, in the service's shape: the same `lines` (Pollen.lines), each level with its emoji and its diff --git a/lib/service/readings.py b/lib/service/readings.py index 3aa3bde2..562f5a82 100644 --- a/lib/service/readings.py +++ b/lib/service/readings.py @@ -1,4 +1,4 @@ -"""The `readings` tool (docs/mcp-service.md 3.3): one reading's values at an interval, a row per interval with its time, over a period in +"""The `readings` tool (docs/ecobot-mcp.md 3.3): one reading's values at an interval, a row per interval with its time, over a period in the person's words. It replaces the bot's `readings` tool, and wraps its engine (lib/history.py): the same rows read the same way (read_intervals, read_days: an interval's average with its lowest and highest, rain as the mm that fell, gusts as the highest, wind direction as the reading at the interval's end, days from the day rows), the same cap of MAX_ROWS rows with the interval that fits when diff --git a/lib/service/relate.py b/lib/service/relate.py index bf9bf37d..93b3babf 100644 --- a/lib/service/relate.py +++ b/lib/service/relate.py @@ -1,4 +1,4 @@ -"""The `relate` tool (docs/mcp-service.md 3.3): rain against one reading, the two read together at 30-minute resolution over whole days +"""The `relate` tool (docs/ecobot-mcp.md 3.3): rain against one reading, the two read together at 30-minute resolution over whole days to yesterday. For pressure, humidity or wind: does rain follow a change in it (lib/ecowitt/link.py, today's weather_link); for PM2.5 or PM10: is the air cleaner after rain (lib/compose.py Composer.air_link, today's air_link). Their findings come back as they are, in the service's shape; a chart, when asked, is the reading with rain as bars behind it, carrying the call that drew it (drawn_by, 3.7). diff --git a/lib/service/scan.py b/lib/service/scan.py index af82995f..618c7aaa 100644 --- a/lib/service/scan.py +++ b/lib/service/scan.py @@ -1,4 +1,4 @@ -"""The `scan` tool (docs/mcp-service.md 3.3): each air reading against every weather reading, read together at 30-minute resolution +"""The `scan` tool (docs/ecobot-mcp.md 3.3): each air reading against every weather reading, read together at 30-minute resolution over whole days to yesterday, for the relationships that stand out (lib/compose.py Composer.air_scan, today's air_scan, over lib/analysis/scan.py). Its verdict and findings come back as they are, in the service's shape; a chart, when asked, is the strongest pair over time, carrying the call that drew it (drawn_by, 3.7). diff --git a/lib/service/summary.py b/lib/service/summary.py index e6efcee9..fac54645 100644 --- a/lib/service/summary.py +++ b/lib/service/summary.py @@ -1,4 +1,4 @@ -"""The `summary` tool (docs/mcp-service.md 3.3): a period's figures from the weather station and the air sensor, each reading's lowest +"""The `summary` tool (docs/ecobot-mcp.md 3.3): a period's figures from the weather station and the air sensor, each reading's lowest and highest with when and that day's look, averages, a breakdown by day or by month, wind direction, the rain that fell, the air's ratings and AQI, and a chart of any readings from either sensor or both. It replaces weather_history, air_quality with dates and plot_chart, and wraps their engines, each given only what this tool's arguments say (a Turn built from them, never from words): diff --git a/lib/upstream.py b/lib/upstream.py index c7721761..58771a04 100644 --- a/lib/upstream.py +++ b/lib/upstream.py @@ -1,4 +1,4 @@ -"""The bot's one connection to the weather service (WEATHER_MCP_URL, docs/mcp-service.md 3.8), kept by one supervisor task (Upstream): +"""The bot's one connection to ecobot-mcp (BOT_MCP_URL, docs/ecobot-mcp.md 3.8), kept by one supervisor task (Upstream): the protocol revision is pinned (2026-07-28, so a proxy's 502 during a restart can't land it on the older revision, which can't listen) and discovered by hand for the instructions; when the connection fails or the listen is lost, the client is dropped and a new one built after a backoff, which listens again (there is no replay: the caller reads what it missed). A request while it is down is refused with @@ -16,18 +16,19 @@ VERSION = "2026-07-28" # the protocol revision pinned: the one that can listen READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed -CONNECT_WAIT = 10.0 # how long a request waits for the service to be reached before it is refused +CONNECT_WAIT = 10.0 # how long a request waits for ecobot-mcp to be reached before it is refused BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated -REFUSED = {401: "401: WEATHER_MCP_TOKEN isn't one of the service's MCP_SERVICE_TOKENS", +REFUSED = {401: "401: the token the bot sends isn't one ecobot-mcp accepts: give both the same AUTH_TOKENS, or leave it unset in both " + "on one data folder (the generated token)", 403: "403: the token was refused", - 421: "421: the service doesn't answer to this address: add its host part to the service's MCP_SERVICE_ALLOWED_HOSTS", + 421: "421: ecobot-mcp doesn't answer to this address: add its host part to ecobot-mcp's MCP_ALLOWED_HOSTS", 404: "404: nothing at this path: the URL ends in /mcp"} def http_transport(url: str, token: str | None = None, refused: dict | None = None): - """The Streamable HTTP transport to the service, its bearer token sent with every request, its read timeout READ_SECONDS. + """The Streamable HTTP transport to ecobot-mcp, its bearer token sent with every request, its read timeout READ_SECONDS. refused: given, its "status" is set to an HTTP error the service answered with (the SDK reports any of them as one message).""" import httpx2 from mcp.client.streamable_http import streamable_http_client @@ -55,10 +56,11 @@ def _leaf(e: BaseException) -> BaseException: class Upstream: - """The one client of the service, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or - its listen is lost or ends, and built again after a backoff. `target`: the service's URL, or (in tests) a Server in-process.""" + """The one client of ecobot-mcp, owned by one supervisor task (`run`): built, discovered and listening; dropped when it fails or + its listen is lost or ends, and built again after a backoff. `target`: ecobot-mcp's URL, or (in tests) a Server in-process. `token`: the + bearer token, or a function giving it (called for each connection), or None.""" - def __init__(self, target, token: str | None = None, on_event=None, on_discover=None, on_listening=None, resources=None): + def __init__(self, target, token=None, on_event=None, on_discover=None, on_listening=None, resources=None): """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. resources: the URIs listened to, of those the service lists (None: every one).""" @@ -70,7 +72,8 @@ def __init__(self, target, token: str | None = None, on_event=None, on_discover= self.refused: dict = {} # the HTTP error the service last answered with def _client(self) -> Client: - server = http_transport(self.target, self.token, self.refused) if isinstance(self.target, str) else self.target + token = self.token() if callable(self.token) else self.token # (a function: read again for each connection) + server = http_transport(self.target, token, self.refused) if isinstance(self.target, str) else self.target return Client(server, mode=VERSION, cache=None) async def run(self): @@ -86,9 +89,9 @@ async def run(self): await self.on_discover(discovered) self.client, self.attempts = client, 0 self.connected.set() - log.info("Weather service: connected to %s", self.target if isinstance(self.target, str) else "the service") + log.info("ecobot-mcp: connected to %s", self.target if isinstance(self.target, str) else "the service") await self._listen(client) - log.warning("Weather service: the service ended the listen; connecting again") + log.warning("ecobot-mcp ended the listen; connecting again") except asyncio.CancelledError: raise except BaseException as e: # (a transport failure ends the whole client, as an exception group too) @@ -98,7 +101,7 @@ async def run(self): raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same cause, status = _leaf(e), self.refused.get("status") why = (REFUSED.get(status, f"HTTP {status}") if status else f"{type(cause).__name__}: {cause}") - log.warning("Weather service: the service at %s isn't reachable (%s); trying again", self.target, why) + log.warning("ecobot-mcp at %s isn't reachable (%s); trying again", self.target, why) finally: self.client = None self.connected.clear() @@ -124,5 +127,5 @@ async def get(self) -> Client: except TimeoutError: pass if self.client is None: - raise MCPError(types.INTERNAL_ERROR, f"The weather service isn't reachable ({self.target}): try again shortly.") + raise MCPError(types.INTERNAL_ERROR, f"ecobot-mcp isn't reachable ({self.target}): try again shortly.") return self.client diff --git a/lib/weather.py b/lib/weather.py index 1b8f41c0..3b3611aa 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -1,7 +1,7 @@ -"""The weather service as the bot reaches it (docs/mcp-service.md section 4 and step 5): one interface, whether the service runs in this -process (LocalWeather: lib/service's tools over the bot's own sources, the alert log in this process; WEATHER_MCP_URL unset, as before) -or is another program reached over MCP (RemoteWeather: WEATHER_MCP_URL, a client pinned to protocol 2026-07-28 that one supervisor -task keeps connected). Everything the bot asks of the service goes through it, so the bot doesn't branch on where the service runs: +"""ecobot-mcp's tools as the bot reaches them (docs/ecobot-mcp.md section 4 and step 5): one interface, whether they run in this +process (LocalWeather: lib/service's tools over the bot's own sources, the alert log in this process; BOT_MCP_URL unset, as before) +or in ecobot-mcp, another program reached over MCP (RemoteWeather: BOT_MCP_URL, a client pinned to protocol 2026-07-28 that one supervisor +task keeps connected). Everything the bot asks of them goes through it, so the bot doesn't branch on where they run: - `service`: the tools, as lib.service.Service gives them: iterated in order, `get(name)` or `service[name]`, each with its name, description, parameters and `call(args, meta)`, which returns the tool's JSON text (lib/model_tools.py offers them to the model; the @@ -273,7 +273,7 @@ class RemoteWeather: then refused with ServiceUnreachable.""" is_weather, remote = True, True - def __init__(self, target, token: str | None = None, tz=None): + def __init__(self, target, token=None, tz=None): from lib.upstream import Upstream self.target, self.fallback_tz, self.station_tz = target, tz, None self.upstream = Upstream(target, token, on_event=self._event, on_discover=self._discovered, on_listening=self._listening, @@ -309,7 +309,7 @@ async def _listening(self): try: await refresh() except Exception as e: # (the connection is still good: the listen's events refresh them later) - log.warning("Weather service: couldn't read %s (%s: %s)", refresh.__name__.removeprefix("_read_"), type(e).__name__, e) + log.warning("ecobot-mcp: couldn't read %s (%s: %s)", refresh.__name__.removeprefix("_read_"), type(e).__name__, e) self.alerts.changed() self._soon(self.forecast.refresh) self.listening.set() @@ -333,7 +333,7 @@ async def run(): try: await fn() except Exception as e: - log.debug("Weather service: %s failed (%s: %s)", getattr(fn, "__name__", fn), type(e).__name__, e) + log.debug("ecobot-mcp: %s failed (%s: %s)", getattr(fn, "__name__", fn), type(e).__name__, e) task = asyncio.create_task(run()) self._background.add(task) task.add_done_callback(self._background.discard) @@ -387,7 +387,7 @@ async def call_text(self, name: str, args: dict | None = None, meta: dict | None """A tool's answer as its JSON text (the first text block: the tool's JSON, a refusal's too). A background request (nobody waiting) doesn't wait for the service.""" meta = dict(meta or {}) - meta.setdefault("chart_image", chart_images.NO_IMAGE) # (the JSON, even if WEATHER_MCP_URL asks for images: the bot draws these) + meta.setdefault("chart_image", chart_images.NO_IMAGE) # (the JSON, even if BOT_MCP_URL asks for images: the bot draws these) client = await self._client(0 if meta.get("priority") == BACKGROUND else CALL_WAIT) result = await client.call_tool(name, args or {}, meta=meta) for block in result.content: @@ -419,7 +419,7 @@ async def chart_image(self, name: str, args: dict | None = None, meta: dict | No if pngs: dark = extra.get(chart_images.DARK_META) return out, ChartImage(pngs[0], charts[0], dark if isinstance(dark, bool) else meta["chart_dark"]) - log.debug("Weather service: %s sent no chart image (%s); drawn here", name, out.get("chart_image_note")) + log.debug("ecobot-mcp: %s sent no chart image (%s); drawn here", name, out.get("chart_image_note")) return out, await draw_here(chart_images.render, charts[0], self.tz, meta["chart_dark"]) async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: @@ -437,7 +437,7 @@ async def picture(self, chart: dict, dark: bool | None = None) -> ChartImage: out, image = {"error": f"{type(e).__name__}: {e}"}, None if image is not None: return image - log.debug("Weather service: %s drew no chart again (%s); drawn here", by["tool"], out.get("error")) + log.debug("ecobot-mcp: %s drew no chart again (%s); drawn here", by["tool"], out.get("error")) return await draw_here(chart_images.render, chart, self.tz, dark) async def resource(self, uri: str, wait=AS_A_CALL) -> dict: @@ -468,7 +468,7 @@ async def alert(self, event_id: int) -> dict | None: try: return await asyncio.wait_for(self.alerts.get(event_id), CALL_WAIT) except Exception as e: # (not reached in time, or refused: the alert's type's own chart is drawn instead) - log.debug("Weather service: alert %s couldn't be read (%s: %s)", event_id, type(e).__name__, e) + log.debug("ecobot-mcp: alert %s couldn't be read (%s: %s)", event_id, type(e).__name__, e) return None async def close(self): diff --git a/requirements-charts.txt b/requirements-charts.txt index 42b53b75..9a509495 100644 --- a/requirements-charts.txt +++ b/requirements-charts.txt @@ -1,3 +1,3 @@ -# The chart pictures (lib/charts.py, lib/draw.py, the gauges): the bot needs them; the service (python -m ecobot_service) only to send -# its charts as images (docs/mcp-service.md 3.7). Pinned: the reference images in tests/charts are drawn with this version. +# The chart pictures (lib/charts.py, lib/draw.py, the gauges): the bot needs them; ecobot-mcp (python -m ecobot_mcp) only to send +# its charts as images (docs/ecobot-mcp.md 3.7). Both Docker images have it. Pinned: the reference images in tests/charts are drawn with this version. pillow==13.0.0 diff --git a/requirements-mcp.txt b/requirements-mcp.txt new file mode 100644 index 00000000..a41f45f5 --- /dev/null +++ b/requirements-mcp.txt @@ -0,0 +1,8 @@ +# ecobot-mcp's packages (python -m ecobot_mcp: the sources, the alert rules, the MCP server), and the Docker image ecobot-mcp's. The +# bot needs these too (requirements.txt) and Pillow for its charts (requirements-charts.txt, which ecobot-mcp uses only to send charts +# as images when a client asks). +holidays +httpx +mcp==2.3.0 +uvicorn==0.54.0 +zeroconf diff --git a/requirements.txt b/requirements.txt index c6d2f174..68ffbeab 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,5 @@ -holidays -httpx -mcp==2.3.0 +# Everything: the bot (ecobot.py), which can also run ecobot-mcp's part in-process, and ecobot-mcp itself; the systemd install and +# the Docker image ecobot. With requirements-charts.txt (Pillow). +-r requirements-mcp.txt openai python-telegram-bot>=22.8 -uvicorn==0.54.0 -zeroconf diff --git a/scripts/bench_storage.py b/scripts/bench_storage.py index 1edd4240..5c6551e6 100644 --- a/scripts/bench_storage.py +++ b/scripts/bench_storage.py @@ -67,7 +67,7 @@ def copy(source: Path, target: Path): def settings(folder: Path) -> Config: """The bot's settings with its files in `folder`, and nothing that would reach the network (Home Assistant, the sensor itself).""" os.environ["DATA_DIR"] = str(folder) - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): # (never used: nothing is asked of them) + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): # (never used: nothing is asked of them) os.environ.setdefault(name, "bench") cfg = Config.from_env() location = None diff --git a/scripts/conditions.py b/scripts/conditions.py index fac2ba8d..a507ad28 100644 --- a/scripts/conditions.py +++ b/scripts/conditions.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Fetch the pollen / thunderstorm asthma page and the forecast once, the way the bot does, and print what the report would show. -Use it to check the real sites before switching POLLEN=on / FORECAST=on. +Use it to check the real sites before switching MCP_POLLEN=on / MCP_FORECAST=on. python scripts/conditions.py --lat -37.8 --lon 144.9 [--district Central] [--raw] @@ -16,7 +16,7 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from lib.config import local_tz # noqa: E402 +from lib.config import env, local_tz # noqa: E402 from lib.forecast import Forecast # noqa: E402 from lib.pollen import Pollen # noqa: E402 @@ -29,7 +29,7 @@ async def main(): ap.add_argument("--raw", action="store_true") args = ap.parse_args() cfg = SimpleNamespace(tz=local_tz(), pollen_district=args.district, forecast_lat=args.lat, forecast_lon=args.lon, - place=os.getenv("PLACE", "Melbourne"), storage_path=os.path.join(tempfile.mkdtemp(), "ecobot.sqlite")) # a scratch file: the bot's is left alone + place=env("MCP_PLACE") or "Melbourne", storage_path=os.path.join(tempfile.mkdtemp(), "ecobot.sqlite")) # a scratch file: the bot's is left alone pollen = Pollen(cfg) try: diff --git a/scripts/ecowitt_metrics.py b/scripts/ecowitt_metrics.py index 69261022..6c59e53f 100644 --- a/scripts/ecowitt_metrics.py +++ b/scripts/ecowitt_metrics.py @@ -14,12 +14,11 @@ """ import asyncio -import os from datetime import datetime, timedelta from _common import parser # noqa: E402 (also puts the repo on sys.path) -from lib.config import local_tz # noqa: E402 +from lib.config import env, local_tz # noqa: E402 from lib.ecowitt.api import GROUPS, EcowittAPI, EcowittError # noqa: E402 # Data groups the API's documentation (real_time and history "call_back") lists. Channels are numbered. @@ -65,9 +64,9 @@ async def main(): ap.add_argument("--groups", help="comma-separated groups to ask about, instead of the documented list") ap.add_argument("--history", action="store_true", help="also ask for the last 6 hours at 30 minutes, to list the history fields") args = ap.parse_args() - key, app = os.getenv("ECOWITT_API_KEY", "").strip(), os.getenv("ECOWITT_APP_KEY", "").strip() + key, app = env("MCP_ECOWITT_API_KEY"), env("MCP_ECOWITT_APP_KEY") # (or their old names) if not (key and app): - raise SystemExit("Set ECOWITT_API_KEY and ECOWITT_APP_KEY in the environment first (see the top of this file).") + raise SystemExit("Set MCP_ECOWITT_API_KEY and MCP_ECOWITT_APP_KEY in the environment first (see the top of this file).") if args.groups: names = [g.strip() for g in args.groups.split(",") if g.strip()] else: diff --git a/scripts/eval_prompts.py b/scripts/eval_prompts.py index 8a6b615a..3fb2bc3d 100644 --- a/scripts/eval_prompts.py +++ b/scripts/eval_prompts.py @@ -4,7 +4,8 @@ report, the gauges, "weather now", a named reading's chart and a period) are checked over cases.json, and every service expectation is checked against the tools it names (each one they take). -With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment) and checks +With --live: also asks the real model (OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_MODEL in the environment: this script's own +names, as CI's secrets are called, not the bot's BOT_OPENROUTER_* settings) and checks which tools it called and with what. Nothing is fetched. The bot's own request is the default: its system prompt (the persona, the server's instructions, the date and time; lib/prompt.py), the ten tools as it offers them, its reasoning effort from the words, and a question it answers in code scored by its fixed calls without asking the model. Each call is answered by the real tool over the @@ -23,7 +24,7 @@ python scripts/eval_prompts.py --live --effort low # force a reasoning level to see what it fixes python scripts/eval_prompts.py --live --repeat 5 --ids 3m-average,public-holidays # how reliable is one case? -With --service: the ten tools alone (docs/mcp-service.md 7): the model is offered only their names, descriptions and parameters, with a +With --service: the ten tools alone (docs/ecobot-mcp.md 7): the model is offered only their names, descriptions and parameters, with a neutral system line and the date, time and zone, and none of the bot's prompt or shortcuts; every call is answered "no data" (the model may call again or reply, up to the Agent's 10 steps), and every call of the turn is scored (what the descriptions lead a model to, with nothing real to react to). --instructions adds the server's instructions diff --git a/scripts/refill_airgradient.py b/scripts/refill_airgradient.py index 68aacc72..a6cd12e5 100644 --- a/scripts/refill_airgradient.py +++ b/scripts/refill_airgradient.py @@ -22,7 +22,7 @@ async def main(days: int, pace: float): cfg = Config.from_env() if not cfg.airgradient_cloud: - raise SystemExit("Set AIRGRADIENT_API_TOKEN and AIRGRADIENT_LOCATION_ID: the history comes from the cloud") + raise SystemExit("Set MCP_AIRGRADIENT_API_TOKEN and MCP_AIRGRADIENT_LOCATION_ID: the history comes from the cloud") air = AirGradient(cfg) try: before = await air.store.lacking() diff --git a/tests/conftest.py b/tests/conftest.py index f7dd0dba..bb50963a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,9 +23,23 @@ def pytest_collection_modifyitems(items): items.sort(key=lambda item: (item.path.name not in HEAVY, HEAVY.index(item.path.name) if item.path.name in HEAVY else 0)) +@pytest.fixture(autouse=True) +def no_settings_from_outside(monkeypatch): + """Every setting's variable, by its name and its old one, unset for each test (a test sets what it reads): one set where the suite + runs (a CI secret named like an old setting, an env file loaded in the shell) changes nothing.""" + from dataclasses import fields + + from lib.config import RETIRED_TOKEN, Config + for f in fields(Config): + for name in (f.metadata.get("env"), f.metadata.get("old")): + if name: + monkeypatch.delenv(name, raising=False) + monkeypatch.delenv(RETIRED_TOKEN, raising=False) + + @pytest.fixture(autouse=True) def the_log_levels_as_they_were(): - """The programs' main() (ecobot.py, ecobot_service) set the "ecobot" and "lib" loggers' levels from LOG_LEVEL: put back after every + """The programs' main() (ecobot.py, ecobot_mcp) set the "ecobot" and "lib" loggers' levels from LOG_LEVEL: put back after every test, so a test that reads the debug lines doesn't depend on which ran before it on its worker.""" import logging levels = {name: logging.getLogger(name).level for name in ("ecobot", "lib")} diff --git a/tests/evalkit.py b/tests/evalkit.py index 6e86bc73..262459b3 100644 --- a/tests/evalkit.py +++ b/tests/evalkit.py @@ -1,6 +1,6 @@ """Saved questions with what should happen to them, so every fix we make for a real report stays fixed. -tests/evals/cases.json holds the questions (real ones from the logs) and the decisions the bot still makes in code (docs/mcp-service.md 4): +tests/evals/cases.json holds the questions (real ones from the logs) and the decisions the bot still makes in code (docs/ecobot-mcp.md 4): the reasoning effort from the words, and its few shortcuts (the report, the gauges, "weather now", a named reading's chart and a period, each a fixed call to a service tool). pytest checks them (`deterministic`). tests/evals/service_cases.json holds, for the same case ids, what a model offered the service's ten tools (lib/service) should call: @@ -174,7 +174,7 @@ def shortcut_calls(r) -> list[tuple[str, dict]] | None: return [r.chart] if r.chart else None -# Where the bot's own shortcuts differ from what a model is expected to call, on purpose (docs/mcp-service.md 4): the report's forecast +# Where the bot's own shortcuts differ from what a model is expected to call, on purpose (docs/ecobot-mcp.md 4): the report's forecast # is the next 3 days, as it always was; a chart the bot draws itself sends its caption, so it needs no chart_answers_it SHORTCUT_LEAVES = {"forecast": ("period",), "summary": ("chart_answers_it",)} @@ -273,7 +273,7 @@ def turn_calls(messages: list[dict]) -> list[tuple[str, dict, bool, int]]: async def run_live(case: Case, client, model: str, effort: str | None = None, service=None) -> LiveTurn: - """The bot's own request (docs/mcp-service.md 4): a question it answers in code gives its fixed calls (no model); any other is asked + """The bot's own request (docs/ecobot-mcp.md 4): a question it answers in code gives its fixed calls (no model); any other is asked of the model with the bot's system prompt, the ten tools as it offers them, its reasoning effort from the words, tool_choice auto, and the turn ended on a complete result as the bot ends it. With `service` (evalworld.World.fresh: the ten tools over the frozen world) each call is answered by the real tool, wrapped as the bot wraps it (lib/model_tools.py: the model is sent for_model of the @@ -293,7 +293,7 @@ async def run_live(case: Case, client, model: str, effort: str | None = None, se return LiveTurn([(n, a) for n, a, *_ in made], reply, [no for _, _, no, _ in made], steps=[s for *_, s in made]) -# ---------- the service's ten tools, offered alone (docs/mcp-service.md 6, step 2; 7) ---------- +# ---------- the service's ten tools, offered alone (docs/ecobot-mcp.md 6, step 2; 7) ---------- # The same questions asked of a model given only the service's tool list: no prompt of ours (a neutral line, the date, time and zone), # no hints, no fast path, nothing filled in from the words. tests/evals/service_cases.json says, for every case id in cases.json, which # of the ten tools answers it and with which arguments, as a client that has never seen this repository would call them. @@ -348,7 +348,7 @@ async def handler(args, turn=None): def service_system(now: datetime = NOW, instructions: str | None = None) -> str: """The whole system prompt of a service run: the neutral line, and the date, time and zone now; with `instructions` (the server's, - service_instructions()), those after it, as a client that passes them on to its model would (docs/mcp-service.md 3.2, 7).""" + service_instructions()), those after it, as a client that passes them on to its model would (docs/ecobot-mcp.md 3.2, 7).""" system = f"{SERVICE_SYSTEM}\nNow: {now:%A} {now.day} {now:%B %Y}, {now:%H:%M} ({NOW_TZ} time)." return f"{system}\n\n{instructions}" if instructions else system diff --git a/tests/fakes.py b/tests/fakes.py index e8671e92..746f6d69 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -72,7 +72,7 @@ def config(tmp_path, **over) -> Config: base = dict(telegram_token="1:x", openrouter_api_key="k", openrouter_base_url="http://x", openrouter_model="m", tz=TZ, ecowitt_api_key="a", ecowitt_app_key="b", airgradient_token="t", airgradient_location="42", airgradient_dashboard="https://example.com/live", state_path=tmp_path / "state.json", - storage_path=tmp_path / "ecobot.sqlite", admin_only=False) # tests that are about ADMIN_ONLY switch it on + storage_path=tmp_path / "ecobot.sqlite", admin_only=False) # tests that are about BOT_ADMIN_ONLY switch it on return Config(**{**base, **over}) diff --git a/tests/old_tools.py b/tests/old_tools.py index a44ddefa..eb49b216 100644 --- a/tests/old_tools.py +++ b/tests/old_tools.py @@ -1,4 +1,4 @@ -"""The bot's twelve old tools' handlers, as they answered before the model got the service's tools (docs/mcp-service.md 6, step 3), kept +"""The bot's twelve old tools' handlers, as they answered before the model got the service's tools (docs/ecobot-mcp.md 6, step 3), kept for the tests only: they drive the engines the service wraps the way the old tools did (HistoryQuery, AirGradient.history, the day rows, link, the readings), and they are the oracle the service's words were ported against (with tests/report_words.py). The corrections from the person's words are gone with step 3. Deleted with the bot (step 6).""" diff --git a/tests/report_words.py b/tests/report_words.py index 0948079a..834d6f1e 100644 --- a/tests/report_words.py +++ b/tests/report_words.py @@ -1,4 +1,4 @@ -"""The bot's words before step 2 (docs/mcp-service.md 6): lib/report.py as it was, the report, "weather now" and the plain lookups +"""The bot's words before step 2 (docs/ecobot-mcp.md 6): lib/report.py as it was, the report, "weather now" and the plain lookups written in code from the old tools' results. The bot now quotes the service's words instead; these stay as the oracle the service's words are checked against (tests/test_service_current.py, _forecast, _pollen, _summary), word for word.""" diff --git a/tests/test_admin_only.py b/tests/test_admin_only.py index ef8ffe92..1395f971 100644 --- a/tests/test_admin_only.py +++ b/tests/test_admin_only.py @@ -1,4 +1,4 @@ -"""ADMIN_ONLY (who may use the bot), /alerts in groups, /usage, and the checks every button press goes through.""" +"""BOT_ADMIN_ONLY (who may use the bot), /alerts in groups, /usage, and the checks every button press goes through.""" import asyncio import random @@ -106,19 +106,19 @@ def board(*data): # ---------- the settings ---------- def test_admin_only_is_off_unless_switched_on_and_the_listed_ids_are_read_safely(monkeypatch, caplog): - for k, v in {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "k", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b"}.items(): + for k, v in {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "k", "MCP_ECOWITT_API_KEY": "a", "MCP_ECOWITT_APP_KEY": "b"}.items(): monkeypatch.setenv(k, v) - monkeypatch.delenv("ADMIN_ONLY", raising=False) + monkeypatch.delenv("BOT_ADMIN_ONLY", raising=False) assert Config.from_env().admin_only is False and Config.from_env().admin_chat_ids == frozenset() for value, on in (("", False), ("on", True), ("ON", True), ("1", True), ("yes", True), ("off", False), ("Off", False), ("0", False), ("no", False), ("false", False), ("ture", False), ("of", False)): # a typo keeps the default - monkeypatch.setenv("ADMIN_ONLY", value) + monkeypatch.setenv("BOT_ADMIN_ONLY", value) assert Config.from_env().admin_only is on, value - assert "ADMIN_ONLY: 'ture' is not on or off; keeping the default (off)" in caplog.text - ids = lambda text: _ids(text, frozenset(), "ADMIN_CHAT_IDS") + assert "BOT_ADMIN_ONLY: 'ture' is not on or off; keeping the default (off)" in caplog.text + ids = lambda text: _ids(text, frozenset(), "BOT_ADMIN_CHAT_IDS") assert ids("1, -1001 22,,x, 3.5 -7") == frozenset({1, -1001, 22, -7}) and ids("") == frozenset() - assert "ADMIN_CHAT_IDS: ignoring 'x', '3.5'" in caplog.text - monkeypatch.setenv("ADMIN_CHAT_IDS", "5 -9") + assert "BOT_ADMIN_CHAT_IDS: ignoring 'x', '3.5'" in caplog.text + monkeypatch.setenv("BOT_ADMIN_CHAT_IDS", "5 -9") assert Config.from_env().admin_chat_ids == frozenset({5, -9}) @@ -247,13 +247,13 @@ async def test_a_refused_sender_is_logged_once_with_the_id_to_list(tmp_path, cap update, sent = message("how warm is it", user=STRANGER) await bot.on_message(update, ctx(tg)) assert [b for b, _ in sent] == [NOT_ADMIN] # told every time - assert refused() == [f"[Telegram {STRANGER}]: @u: refused: user {STRANGER} (U) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in"] + assert refused() == [f"[Telegram {STRANGER}]: @u: refused: user {STRANGER} (U) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in"] update, sent = message("hello", user=8) # another stranger: its own line await bot.on_message(update, ctx(tg)) assert len(refused()) == 2 and refused()[1].startswith("[Telegram 8]: @u: refused: user 8 (U) is not") update, sent = message("@testbot hi", user=ANONYMOUS, kind="supergroup", sender_chat=NS(id=GROUP, title="Home")) # as the group: the chat await bot.on_message(update, ctx(tg)) - assert refused()[2] == f"[Telegram {GROUP}]: @u, group 'Home': refused: chat {GROUP} (Home) is not a known group admin; add the id to ADMIN_CHAT_IDS to let them in" + assert refused()[2] == f"[Telegram {GROUP}]: @u, group 'Home': refused: chat {GROUP} (Home) is not a known group admin; add the id to BOT_ADMIN_CHAT_IDS to let them in" async def test_a_listed_user_can_use_the_bot_before_it_is_in_any_group(tmp_path): @@ -366,7 +366,7 @@ async def test_a_stranger_is_refused_on_every_family_of_buttons_and_an_admin_is_ press = Press("ir:open:water", irrigation_menu.keyboard(True, True), user=STRANGER) off = make(tmp_path, admin_only=False, irrigation=Remote())[0] await off.on_button(press.update(), ctx(tg)) - assert press.edits # ADMIN_ONLY=off: as before + assert press.edits # BOT_ADMIN_ONLY=off: as before async def test_alert_buttons_in_a_group_stay_admin_only_even_when_admin_only_is_off(tmp_path): diff --git a/tests/test_agent.py b/tests/test_agent.py index de2f668e..daed7eac 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -228,7 +228,7 @@ async def buggy(args, turn=None): def test_the_prompt_is_the_persona_then_the_servers_instructions_then_the_time(): - """docs/mcp-service.md 4: the bot adds only its persona (a friendly Telegram bot, plain text, bullets, the caption a photo allows) + """docs/ecobot-mcp.md 4: the bot adds only its persona (a friendly Telegram bot, plain text, bullets, the caption a photo allows) to the server's instructions; nothing about the tools, the periods or the data.""" from datetime import datetime from zoneinfo import ZoneInfo diff --git a/tests/test_airgradient.py b/tests/test_airgradient.py index b249004b..dd65b074 100644 --- a/tests/test_airgradient.py +++ b/tests/test_airgradient.py @@ -539,12 +539,12 @@ async def day_rows(day, refresh=False): def test_the_antispike_setting_is_a_number_of_readings_default_2_and_off_is_1(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("ANTISPIKE_REQUIRE_CONSECUTIVE", raising=False) + monkeypatch.delenv("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", raising=False) assert Config.from_env().antispike_require_consecutive == 2 for value, want in (("3", 3), ("1", 1), ("0", 1), ("off", 1), ("junk", 2), ("", 2)): - monkeypatch.setenv("ANTISPIKE_REQUIRE_CONSECUTIVE", value) + monkeypatch.setenv("MCP_ANTISPIKE_REQUIRE_CONSECUTIVE", value) assert Config.from_env().antispike_require_consecutive == want, value diff --git a/tests/test_airgradient_local.py b/tests/test_airgradient_local.py index 62c757a2..a19f63bc 100644 --- a/tests/test_airgradient_local.py +++ b/tests/test_airgradient_local.py @@ -310,8 +310,8 @@ async def test_airgradient_source_picks_the_monitors_sources_and_a_typo_keeps_au assert (air.local is not None, air.ha is not None, air.cloud) == (monitor, home, cloud), kwargs await air.close() from lib.config import _air_source - assert _air_source("Cloud", "auto", "AIRGRADIENT_SOURCE") == "cloud" - assert _air_source("sensor", "auto", "AIRGRADIENT_SOURCE") == "auto" and "AIRGRADIENT_SOURCE: 'sensor' is not" in caplog.text + assert _air_source("Cloud", "auto", "MCP_AIRGRADIENT_SOURCE") == "cloud" + assert _air_source("sensor", "auto", "MCP_AIRGRADIENT_SOURCE") == "auto" and "MCP_AIRGRADIENT_SOURCE: 'sensor' is not" in caplog.text async def test_each_reading_of_the_monitor_is_kept_as_a_minute_and_a_short_chart_is_drawn_from_them(tmp_path, monkeypatch): diff --git a/tests/test_alert_log.py b/tests/test_alert_log.py index cff08654..cd71ddbb 100644 --- a/tests/test_alert_log.py +++ b/tests/test_alert_log.py @@ -1,5 +1,5 @@ """The alert log (lib/alert_log.py), the rules' own store (lib/alerts/store.py) and the bot's delivery from the log -(lib/alerts/notify.AlertDelivery): docs/mcp-service.md 3.6 and section 4.""" +(lib/alerts/notify.AlertDelivery): docs/ecobot-mcp.md 3.6 and section 4.""" import asyncio from types import SimpleNamespace as NS diff --git a/tests/test_averages.py b/tests/test_averages.py index 71f0fc34..50de6997 100644 --- a/tests/test_averages.py +++ b/tests/test_averages.py @@ -1,4 +1,4 @@ -"""Averages weighted by time (docs/mcp-service.md 3.3): weather_history's and air_quality's average of a period count each day for the time of +"""Averages weighted by time (docs/ecobot-mcp.md 3.3): weather_history's and air_quality's average of a period count each day for the time of it the period holds (lines.time_mean), so the part of a day at either end counts for its hours, not as a whole day, and an air day held only as hourly averages counts for its 24 hours, not for its 24 readings against a 5-minute day's 288. Rain rate has an average; the rain counters, which are totals, have none.""" diff --git a/tests/test_bench_storage.py b/tests/test_bench_storage.py index 272020be..b9f191f4 100644 --- a/tests/test_bench_storage.py +++ b/tests/test_bench_storage.py @@ -27,7 +27,7 @@ async def test_the_benchmark_reads_a_copy_of_the_file_and_asks_nothing_of_the_ne copy = tmp_path / "copy" copy.mkdir() bench_storage.copy(data / "ecobot.sqlite", copy / "ecobot.sqlite") - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): # (the benchmark sets them where they are missing) + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): # (the benchmark sets them where they are missing) monkeypatch.setenv(name, "t") monkeypatch.setenv("DATA_DIR", str(copy)) rows = await bench_storage.bench(copy, 1, TZ) @@ -49,7 +49,7 @@ async def test_the_benchmark_s_own_cache_is_as_old_as_asked_and_its_short_chart_ held = {cycle: min(storage.coverage.days(s.id, cycle) for s in sensors) for cycle in days} storage.close() assert all(n - 2 <= held[cycle] <= n for cycle, n in days.items()), held # (the newest hours are still settling) - for name in ("TELEGRAM_BOT_TOKEN", "ECOWITT_API_KEY", "ECOWITT_APP_KEY"): + for name in ("BOT_TELEGRAM_TOKEN", "MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY"): monkeypatch.setenv(name, "t") monkeypatch.setenv("DATA_DIR", str(tmp_path)) rows = {r[0]: r for r in await bench_storage.bench(tmp_path, 1, TZ)} diff --git a/tests/test_bot_remote.py b/tests/test_bot_remote.py index 60ffce8a..315de3aa 100644 --- a/tests/test_bot_remote.py +++ b/tests/test_bot_remote.py @@ -1,8 +1,8 @@ -"""The bot as the service's client over MCP (WEATHER_MCP_URL: lib/weather.RemoteWeather, docs/mcp-service.md 3.8 and step 5), against the +"""The bot as the service's client over MCP (BOT_MCP_URL: lib/weather.RemoteWeather, docs/ecobot-mcp.md 3.8 and step 5), against the real server (lib/mcp_server.EcobotServer): over the SDK's in-memory transport for a question answered with the remote tools, a chart drawn from a remote result with its buttons, an alert delivered through the listen and the irrigation check's inputs; under uvicorn on a localhost port (a connection can fail there) for a dropped connection rebuilt with the alerts after the last id read once, the service down (the bot -says so), and ecobot.main() as a client. The path with WEATHER_MCP_URL unset is the rest of the suite's.""" +says so), and ecobot.main() as a client. The path with BOT_MCP_URL unset is the rest of the suite's.""" import asyncio import json @@ -355,7 +355,7 @@ async def test_with_the_service_down_the_bot_says_so_and_carries_on(alert_state, async def test_main_as_a_client_runs_no_sources_and_answers_from_the_service(bare, tmp_path, monkeypatch, caplog): - """ecobot.main() with WEATHER_MCP_URL: no source is started (no keys are set), the service's station names the time zone, the + """ecobot.main() with BOT_MCP_URL: no source is started (no keys are set), the service's station names the time zone, the bot draws its keyboard's charts ahead, and an alert the service logs reaches a chat.""" import os import signal @@ -364,12 +364,12 @@ async def test_main_as_a_client_runs_no_sources_and_answers_from_the_service(bar from tests.test_startup import FakeApp, FakeBuilder caplog.set_level("INFO") port = free_port() - cfg = config(tmp_path, weather_mcp_url=f"http://127.0.0.1:{port}/mcp", weather_mcp_token=TOKEN, ecowitt_api_key="", + cfg = config(tmp_path, mcp_url=f"http://127.0.0.1:{port}/mcp", auth_tokens=(TOKEN,), ecowitt_api_key="", ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") (tmp_path / "bot").mkdir() AlertState(cfg.state_path).add_chat(5, "private") app = FakeApp() - monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) # (main sets LOG_WIDTH's: put back after; the levels: conftest) + monkeypatch.setattr(ecobot._format, "width", ecobot._format.width) # (main sets BOT_LOG_WIDTH's: put back after; the levels: conftest) drawn = [] async def note(self, tg_bot): @@ -401,13 +401,13 @@ async def alert(): publishing.cancel() await asyncio.gather(publishing, return_exceptions=True) assert started == [] and "Ecowitt: " not in caplog.text and "Telegram: @testbot" in caplog.text - assert f"Weather service: {cfg.weather_mcp_url}" in caplog.text + assert f"ecobot-mcp: {cfg.mcp_url}" in caplog.text assert [(chat, text) for chat, text, _ in app.sent] == [(5, "🌧️ Raining")] assert drawn == [app.bot] async def test_a_start_while_the_service_cant_be_reached_follows_the_station_s_zone_once_read_and_keeps_it(tmp_path, monkeypatch, caplog): - """ecobot.main() with WEATHER_MCP_URL and the service not up within STARTUP_WAIT starts in TZ's zone (UTC here, as a container's); once + """ecobot.main() with BOT_MCP_URL and the service not up within STARTUP_WAIT starts in TZ's zone (UTC here, as a container's); once the service is reached, its station's zone (Melbourne) is the bot's, the charts', the alert delivery's and the irrigation check's, and it is kept in bot_state.json: the next start with the service down runs in it, not in UTC.""" import os @@ -420,7 +420,7 @@ async def test_a_start_while_the_service_cant_be_reached_follows_the_station_s_z caplog.set_level("INFO") utc = ZoneInfo("Etc/UTC") port = free_port() - cfg = config(tmp_path, tz=utc, weather_mcp_url=f"http://127.0.0.1:{port}/mcp", weather_mcp_token=TOKEN, ecowitt_api_key="", + cfg = config(tmp_path, tz=utc, mcp_url=f"http://127.0.0.1:{port}/mcp", auth_tokens=(TOKEN,), ecowitt_api_key="", ecowitt_app_key="", airgradient_token="", airgradient_location="", state_path=tmp_path / "bot" / "bot_state.json") (tmp_path / "bot").mkdir() monkeypatch.setattr(ecobot, "STARTUP_WAIT", 0.3) @@ -508,13 +508,13 @@ def now_local(tz): def test_a_client_of_the_service_needs_no_source_settings(monkeypatch, tmp_path): from lib.config import Config monkeypatch.setenv("DATA_DIR", str(tmp_path)) - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "1:x") - for name in ("ECOWITT_API_KEY", "ECOWITT_APP_KEY", "HOMEASSISTANT_URL", "HOMEASSISTANT_TOKEN", "AIRGRADIENT_API_TOKEN", - "AIRGRADIENT_LOCATION_ID", "AIRGRADIENT_LOCAL_URL", "WEATHER_MCP_URL"): + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "1:x") + for name in ("MCP_ECOWITT_API_KEY", "MCP_ECOWITT_APP_KEY", "MCP_HOMEASSISTANT_URL", "MCP_HOMEASSISTANT_TOKEN", "MCP_AIRGRADIENT_API_TOKEN", + "MCP_AIRGRADIENT_LOCATION_ID", "MCP_AIRGRADIENT_LOCAL_URL", "BOT_MCP_URL"): monkeypatch.delenv(name, raising=False) - with pytest.raises(SystemExit, match="ECOWITT_API_KEY"): + with pytest.raises(SystemExit, match="MCP_ECOWITT_API_KEY"): Config.from_env() - monkeypatch.setenv("WEATHER_MCP_URL", "http://127.0.0.1:8765/mcp/") - monkeypatch.setenv("WEATHER_MCP_TOKEN", "t0ken") + monkeypatch.setenv("BOT_MCP_URL", "http://127.0.0.1:8765/mcp/") + monkeypatch.setenv("AUTH_TOKENS", "t0ken, other") cfg = Config.from_env() - assert (cfg.weather_mcp_url, cfg.weather_mcp_token) == ("http://127.0.0.1:8765/mcp", "t0ken") and not cfg.ecowitt + assert (cfg.mcp_url, cfg.auth_tokens) == ("http://127.0.0.1:8765/mcp", ("t0ken", "other")) and not cfg.ecowitt diff --git a/tests/test_chart_answers.py b/tests/test_chart_answers.py index 369cb305..ec8b3393 100644 --- a/tests/test_chart_answers.py +++ b/tests/test_chart_answers.py @@ -1,5 +1,5 @@ """A question that is only a chart: the model sets chart_answers_it, the service's result comes complete (its chart and its `reply`), -and the turn ends with that reply: the model is asked nothing more (docs/mcp-service.md 3.7). A real Agent over a scripted model and +and the turn ends with that reply: the model is asked nothing more (docs/ecobot-mcp.md 3.7). A real Agent over a scripted model and stand-in service tools (offered as the bot offers them, lib/model_tools.py), through the bot's own model call.""" import json diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 83b6b4b4..eceeebab 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -341,7 +341,7 @@ def day(w, d, low, high, band): storage.close() -# ---------- the gauges from the service's current, with context (docs/mcp-service.md 3.1, 6 step 2) ---------- +# ---------- the gauges from the service's current, with context (docs/ecobot-mcp.md 3.1, 6 step 2) ---------- STATUS_TITLES = ("Temperature", "Humidity", "Rain") GAUGE_RESULT = { "sensors": { diff --git a/tests/test_data_dir.py b/tests/test_data_dir.py index fd376682..5ab27aad 100644 --- a/tests/test_data_dir.py +++ b/tests/test_data_dir.py @@ -11,7 +11,7 @@ def configured(monkeypatch, **env): - for key, value in {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "x", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b", **env}.items(): + for key, value in {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "x", "MCP_ECOWITT_API_KEY": "a", "MCP_ECOWITT_APP_KEY": "b", **env}.items(): monkeypatch.setenv(key, value) return Config.from_env() diff --git a/tests/test_forecast.py b/tests/test_forecast.py index 0d0626b6..bfb1728b 100644 --- a/tests/test_forecast.py +++ b/tests/test_forecast.py @@ -118,9 +118,9 @@ async def test_the_station_location_is_used_when_none_is_configured_and_without_ cfg = config(tmp_path, forecast=True) assert Forecast(cfg, (-37.8, 144.9)).location == (-37.8, 144.9) half = config(tmp_path, forecast=True, forecast_lat=-33.9) # one half alone is not a place: not paired with the station's - assert Forecast(half, (-37.8, 144.9)).location == (-37.8, 144.9) and "FORECAST_LAT and FORECAST_LON go together" in caplog.text + assert Forecast(half, (-37.8, 144.9)).location == (-37.8, 144.9) and "MCP_FORECAST_LAT and MCP_FORECAST_LON go together" in caplog.text assert Forecast(config(tmp_path, forecast=True, forecast_lat=-33.9, forecast_lon=151.2), (-37.8, 144.9)).location == (-33.9, 151.2) - with pytest.raises(RuntimeError, match="FORECAST_LAT"): + with pytest.raises(RuntimeError, match="MCP_FORECAST_LAT"): await Forecast(cfg).start() diff --git a/tests/test_forecast_alert.py b/tests/test_forecast_alert.py index 90605d0a..087f8ebc 100644 --- a/tests/test_forecast_alert.py +++ b/tests/test_forecast_alert.py @@ -1,4 +1,4 @@ -"""The forecast alert, station-wide (docs/mcp-service.md 3.6): today's and tomorrow's forecast against the day's baseline (the first one +"""The forecast alert, station-wide (docs/ecobot-mcp.md 3.6): today's and tomorrow's forecast against the day's baseline (the first one fetched from 6 am), an alert when the high moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or less), the alerted forecast the new baseline.""" diff --git a/tests/test_hass_live.py b/tests/test_hass_live.py index ddd74af1..d08b10ce 100644 --- a/tests/test_hass_live.py +++ b/tests/test_hass_live.py @@ -87,7 +87,7 @@ def nowhere(request): await asyncio.sleep(0.2) task.cancel() assert caplog.text.count("Home Assistant: the ") == 1 # ranges, minutes and live reading: one line - assert "can't find .local names: put the IP address in HOMEASSISTANT_URL" in caplog.text and "host network" in caplog.text + assert "can't find .local names: put the IP address in MCP_HOMEASSISTANT_URL" in caplog.text and "host network" in caplog.text await eco.close() @@ -97,5 +97,5 @@ def test_outside_docker_a_name_that_cannot_be_found_is_to_be_checked_or_given_as monkeypatch.setattr(netenv, "docker_private_network", lambda: False) caplog.set_level(logging.INFO) Trouble("http://homeassistant.local:8123").failed("live reading", "[Errno -2] Name or service not known") - assert "The name in HOMEASSISTANT_URL (http://homeassistant.local:8123) can't be found from here: check it, or use the address" in caplog.text + assert "The name in MCP_HOMEASSISTANT_URL (http://homeassistant.local:8123) can't be found from here: check it, or use the address" in caplog.text assert "Docker" not in caplog.text diff --git a/tests/test_intent.py b/tests/test_intent.py index ef28bda4..a81c63ce 100644 --- a/tests/test_intent.py +++ b/tests/test_intent.py @@ -1,4 +1,4 @@ -"""intent: the reasoning effort from the words, and the few shortcuts the bot answers in code (docs/mcp-service.md 4): the report, +"""intent: the reasoning effort from the words, and the few shortcuts the bot answers in code (docs/ecobot-mcp.md 4): the report, the gauges, "weather now" and a named reading's chart and a period, each a fixed call to a service tool. Everything else is the model's.""" diff --git a/tests/test_irrigation.py b/tests/test_irrigation.py index 652ced8a..f1862907 100644 --- a/tests/test_irrigation.py +++ b/tests/test_irrigation.py @@ -150,14 +150,14 @@ async def test_status_points_with_no_value_or_no_code_are_read_safely(tmp_path): def test_the_controller_is_on_only_with_all_three_settings_and_the_hour_is_read_safely(monkeypatch, tmp_path): assert cfg(tmp_path).irrigation and not config(tmp_path).irrigation and not config(tmp_path, tuya_device_id="d", tuya_client_id="c").irrigation - env = {"TELEGRAM_BOT_TOKEN": "t", "OPENROUTER_API_KEY": "k", "ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b"} + env = {"BOT_TELEGRAM_TOKEN": "t", "BOT_OPENROUTER_API_KEY": "k", "MCP_ECOWITT_API_KEY": "a", "MCP_ECOWITT_APP_KEY": "b"} for k, v in env.items(): monkeypatch.setenv(k, v) for value, hour in (("", 18), ("6", 6), ("0", 0), ("23", 23), ("24", 18), ("noon", 18), ("-1", 18)): - monkeypatch.setenv("IRRIGATION_CHECK_HOUR", value) + monkeypatch.setenv("BOT_IRRIGATION_CHECK_HOUR", value) assert Config.from_env().irrigation_check_hour == hour, value - monkeypatch.setenv("TUYA_BASE_URL", "https://openapi.tuyaus.com/") - monkeypatch.setenv("TUYA_DEVICE_ID", " dev ") + monkeypatch.setenv("BOT_TUYA_BASE_URL", "https://openapi.tuyaus.com/") + monkeypatch.setenv("BOT_TUYA_DEVICE_ID", " dev ") assert Config.from_env().tuya_base_url == "https://openapi.tuyaus.com" and Config.from_env().tuya_device_id == "dev" diff --git a/tests/test_logs.py b/tests/test_logs.py index a3b46058..9b4f007a 100644 --- a/tests/test_logs.py +++ b/tests/test_logs.py @@ -77,5 +77,5 @@ async def nowhere(host): text = caplog.text assert ("AirGradient: (airgradient_d83bda1c1e08.local) did not answer (OSError: airgradient_d83bda1c1e08.local was not found on " "the network); " + ("using the cloud, " if cloud else "") + "trying again in 5 min") in text - assert ("put the IP address in AIRGRADIENT_LOCAL_URL, or put the container on the host network" in text) == private + assert ("put the IP address in MCP_AIRGRADIENT_LOCAL_URL, or put the container on the host network" in text) == private await sensor.close() diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index ed60ec0d..0cee84cc 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -1,8 +1,8 @@ -"""The service over the network (docs/mcp-service.md 7, "a client that listens", "a deploy check"): the real Streamable HTTP app under +"""The service over the network (docs/ecobot-mcp.md 7, "a client that listens", "a deploy check"): the real Streamable HTTP app under uvicorn on a localhost port each test starts and stops, not the in-memory transport (a connection can't fail there, and it buffers a listen stream). A client that listens hears a new alert, loses its listen when the service stops, listens again once it is back and reads the alerts after its last id, once; a request without the token, with a wrong or revoked one, or to a Host not allowed is -refused; and `python -m ecobot_service` runs the sources and answers a tool call through the name a proxy uses.""" +refused; and `python -m ecobot_mcp` runs the sources and answers a tool call through the name a proxy uses.""" import asyncio import contextlib @@ -19,7 +19,7 @@ from mcp import Client from lib import upstream -from ecobot_service.__main__ import Uvicorn, server_config +from ecobot_mcp.__main__ import Uvicorn, server_config from lib.upstream import Upstream, http_transport from lib.alert_log import AlertLog from lib.mcp_server import ALERTS_URI, EcobotServer, http_app @@ -143,18 +143,18 @@ async def post(token=None, host=None) -> int: async def test_the_service_runs_the_sources_and_answers_a_tool_call_through_the_proxys_name(tmp_path, monkeypatch, caplog): - """A deploy check: `python -m ecobot_service` (main) with the fake sources, MCP_SERVICE_ALLOWED_HOSTS the name a reverse proxy sends, a + """A deploy check: `python -m ecobot_mcp` (main) with the fake sources, MCP_ALLOWED_HOSTS the name a reverse proxy sends, a tool call with a token through that name answered, the archives run, then SIGTERM closes it all.""" - import ecobot_service.__main__ as service_main - from ecobot_service import core + import ecobot_mcp.__main__ as service_main + from ecobot_mcp import core from lib.config import Config from lib.ecowitt import archive from lib.airgradient import source as air_source from tests.fakes import air_transport, config, ecowitt_transport caplog.set_level("INFO") port = free_port() - cfg = config(tmp_path, telegram_token="", mcp_service_tokens=("pr0xy",), mcp_service_bind=("127.0.0.1", port), - mcp_service_allowed_hosts=("weather.lan",)) + cfg = config(tmp_path, telegram_token="", auth_tokens=("pr0xy",), mcp_bind=("127.0.0.1", port), + mcp_allowed_hosts=("weather.lan",)) eco_t, _ = ecowitt_transport(history_days=10) air_t, _ = air_transport(oldest=datetime.now(timezone.utc) - timedelta(days=5)) monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) @@ -183,7 +183,7 @@ async def through_the_proxy(): answered["current"] = json.loads((await client.call_tool("current", {"readings": ["temperature"]})).content[0].text) answered["health"] = json.loads((await client.read_resource("ecobot://health")).contents[0].text) answered["stranger"] = await post_status(url, "evil.example") # a Host it doesn't answer (127.0.0.1, localhost and its own - answered["own name"] = await post_status(url, socket.gethostname()) # hostname always are, beside MCP_SERVICE_ALLOWED_HOSTS) + answered["own name"] = await post_status(url, socket.gethostname()) # hostname always are, beside MCP_ALLOWED_HOSTS) await until(lambda: any("Backfill Ecowitt: " in l and " fetched/failed, " in l for l in caplog.text.splitlines()) and "Backfill AirGradient:" in caplog.text, 60, "the archives") os.kill(os.getpid(), signal.SIGTERM) @@ -196,7 +196,7 @@ async def post_status(url, host) -> int: await service_main.main() await asker log = caplog.text - assert "Ecowitt: 'Fairleigh' (" in log and "Service tools: current, summary" in log and "1 token(s)" in log + assert "Ecowitt: 'Fairleigh' (" in log and "Tools: current, summary" in log and "1 token(s)" in log assert "MCP 127.0.0.1: POST /mcp tools/call current temperature -> 200" in log and "-> 421, its Host isn't in" in log # (the request log) assert answered["tools"] == ["current", "summary", "readings", "days", "relate", "scan", "outlook", "about"] # (no forecast, no pollen) assert answered["current"]["sensors"]["outdoor"]["temperature"]["unit"] @@ -205,23 +205,13 @@ async def post_status(url, host) -> int: assert "Alerts NOT running" not in log and "Telegram" not in log -async def test_the_service_will_not_serve_without_tokens_on_an_address_others_can_reach(tmp_path, monkeypatch): - import ecobot_service.__main__ as service_main - from lib.config import Config - from tests.fakes import config - cfg = config(tmp_path, telegram_token="", mcp_service_bind=("0.0.0.0", free_port())) - monkeypatch.setattr(Config, "from_env", classmethod(lambda cls, bot=True: cfg)) - with pytest.raises(SystemExit, match="MCP_SERVICE_TOKENS"): - await service_main.main() - - -async def test_the_bot_s_warning_says_why_the_service_refused_it(service, monkeypatch, caplog): +async def test_the_bot_s_warning_says_why_ecobot_mcp_refused_it(service, monkeypatch, caplog): """The SDK reports every HTTP error as "Server returned an error response": the warning names the status and what to change.""" monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) port = free_port() async with Serving(http_app(service, tokens=TOKENS.values(), allowed_hosts=("localhost",)), port): - for url, token, want in ((f"http://localhost:{port}/mcp", "wrong", "401: WEATHER_MCP_TOKEN"), - (f"http://127.0.0.1:{port}/mcp", TOKENS["bot"], "421: the service doesn't answer to this address")): + for url, token, want in ((f"http://localhost:{port}/mcp", "wrong", "401: the token the bot sends isn't one ecobot-mcp accepts"), + (f"http://127.0.0.1:{port}/mcp", TOKENS["bot"], "421: ecobot-mcp doesn't answer to this address")): caplog.clear() task = asyncio.create_task(Upstream(url, token).run()) for _ in range(100): @@ -251,6 +241,6 @@ async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its assert any("MCP 127.0.0.1: POST /mcp tools/call about -> 200" in line for line in lines), lines assert any("tools/call summary rain 1d -> 200" in line for line in lines), lines assert any("resources/read ecobot://health -> 200" in line for line in lines), lines - assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in MCP_SERVICE_TOKENS" in line for line in lines), lines - assert any("-> 421, its Host isn't in MCP_SERVICE_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines + assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in AUTH_TOKENS" in line for line in lines), lines + assert any("-> 421, its Host isn't in MCP_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines assert not any(TOKENS["bot"] in line or "wrong" in line for line in lines) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index a00694c7..a707f097 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -1,4 +1,4 @@ -"""The service over MCP (lib/mcp_server.py, docs/mcp-service.md 3.4-3.8): the ten tools listed and called over the SDK's in-memory +"""The service over MCP (lib/mcp_server.py, docs/ecobot-mcp.md 3.4-3.8): the ten tools listed and called over the SDK's in-memory transport with the same answers as the ServiceTools themselves, the resources and the alerts' template, the prompts, the publishing of changes, the auth and the allowed hosts. The listen over the network is tests/test_mcp_listen.py's (under uvicorn, as docs 7 asks).""" @@ -266,7 +266,7 @@ async def test_the_prompts_are_questions_in_words_with_their_period_an_argument( # ---------- auth and hosts ---------- -async def test_a_token_is_one_of_mcp_service_tokens_and_one_can_be_revoked_alone(): +async def test_a_token_is_one_of_auth_tokens_and_one_can_be_revoked_alone(): check = TokenCheck(("s3cret-bot", "s3cret-phone")) assert await check.verify_token("s3cret-bot") and await check.verify_token("s3cret-phone") for wrong in ("", "s3cret", "s3cret-bot ", "S3CRET-BOT"): @@ -285,36 +285,36 @@ def test_the_allowed_hosts_take_any_port_unless_one_is_named(): def test_the_service_reads_its_settings_and_needs_no_telegram_token(monkeypatch, tmp_path, caplog): from lib.config import Config monkeypatch.setenv("DATA_DIR", str(tmp_path)) - for key, value in {"ECOWITT_API_KEY": "a", "ECOWITT_APP_KEY": "b", "TELEGRAM_BOT_TOKEN": ""}.items(): + for key, value in {"MCP_ECOWITT_API_KEY": "a", "MCP_ECOWITT_APP_KEY": "b", "BOT_TELEGRAM_TOKEN": ""}.items(): monkeypatch.setenv(key, value) - for key in ("MCP_SERVICE_TOKENS", "MCP_SERVICE_BIND", "MCP_SERVICE_ALLOWED_HOSTS"): + for key in ("AUTH_TOKENS", "MCP_BIND", "MCP_ALLOWED_HOSTS"): monkeypatch.delenv(key, raising=False) - with pytest.raises(SystemExit, match="TELEGRAM_BOT_TOKEN is not set"): + with pytest.raises(SystemExit, match="BOT_TELEGRAM_TOKEN is not set"): Config.from_env() # the bot can't start without it ... cfg = Config.from_env(bot=False) # ... the service can - assert cfg.mcp_service_tokens == () and cfg.mcp_service_bind == ("127.0.0.1", 8765) and cfg.mcp_service_allowed_hosts == ("127.0.0.1", "localhost") - monkeypatch.setenv("MCP_SERVICE_TOKENS", " s3cret , t0k:en,, s3cret") - monkeypatch.setenv("MCP_SERVICE_BIND", "0.0.0.0:9000") - monkeypatch.setenv("MCP_SERVICE_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") + assert cfg.auth_tokens == () and cfg.mcp_bind == ("127.0.0.1", 8765) and cfg.mcp_allowed_hosts == ("127.0.0.1", "localhost") + monkeypatch.setenv("AUTH_TOKENS", " s3cret , t0k:en,, s3cret") + monkeypatch.setenv("MCP_BIND", "0.0.0.0:9000") + monkeypatch.setenv("MCP_ALLOWED_HOSTS", "weather.lan, 192.168.1.5:9000") cfg = Config.from_env(bot=False) - assert cfg.mcp_service_tokens == ("s3cret", "t0k:en") and "s3cret" not in caplog.text - assert cfg.mcp_service_bind == ("0.0.0.0", 9000) and cfg.mcp_service_allowed_hosts == ("weather.lan", "192.168.1.5:9000") + assert cfg.auth_tokens == ("s3cret", "t0k:en") and "s3cret" not in caplog.text + assert cfg.mcp_bind == ("0.0.0.0", 9000) and cfg.mcp_allowed_hosts == ("weather.lan", "192.168.1.5:9000") for value, want in (("[::1]:8800", ("::1", 8800)), ("9001", ("127.0.0.1", 9001)), ("host:port", ("127.0.0.1", 8765)), ("h:70000", ("127.0.0.1", 8765))): - monkeypatch.setenv("MCP_SERVICE_BIND", value) - assert Config.from_env(bot=False).mcp_service_bind == want, value + monkeypatch.setenv("MCP_BIND", value) + assert Config.from_env(bot=False).mcp_bind == want, value def test_one_service_per_data_folder(tmp_path): - """The bot running the service in-process and python -m ecobot_service on one folder would both fetch and both write each alert.""" + """The bot running the service in-process and python -m ecobot_mcp on one folder would both fetch and both write each alert.""" import contextlib from types import SimpleNamespace - from ecobot_service.core import hold_data_folder + from ecobot_mcp.core import hold_data_folder cfg = SimpleNamespace(state_path=tmp_path / "bot_state.json") with contextlib.ExitStack() as first: hold_data_folder(cfg, first) - with contextlib.ExitStack() as second, pytest.raises(SystemExit, match="already runs the weather service"): + with contextlib.ExitStack() as second, pytest.raises(SystemExit, match="already runs ecobot-mcp.s work"): hold_data_folder(cfg, second) with contextlib.ExitStack() as again: # free once the first has closed hold_data_folder(cfg, again) @@ -400,9 +400,9 @@ def test_images_are_wanted_per_call_else_per_connection(): def test_the_service_imports_no_pillow_until_an_image_is_asked_for_and_no_telegram_ever(tmp_path): - """Importing the server and building its app (as python -m ecobot_service does) imports neither Pillow nor the renderer, nor the + """Importing the server and building its app (as python -m ecobot_mcp does) imports neither Pillow nor the renderer, nor the Telegram library: the service knows nothing of Telegram.""" - code = ("import sys, ecobot_service.__main__; from zoneinfo import ZoneInfo; from lib.mcp_server import EcobotServer, http_app; " + code = ("import sys, ecobot_mcp.__main__; from zoneinfo import ZoneInfo; from lib.mcp_server import EcobotServer, http_app; " "from lib.service.context import Context; http_app(EcobotServer(Context(tz=ZoneInfo('UTC'))), tokens=('t',)); " "print(sorted(m for m in sys.modules if m.split('.')[0] in ('PIL', 'telegram') or m in ('lib.charts', 'lib.draw', 'lib.gauges')))") done = subprocess.run([sys.executable, "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=120, diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 00000000..7ca3f75d --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,56 @@ +"""The two programs as they are installed: two Docker images from one Dockerfile (ecobot-mcp with only its own packages, ecobot with +everything), compose running each from its own, and the systemd unit of ecobot-mcp without the bot's secrets, by their new and old names. +(Read as text: the CI workflow docker.yml builds and runs the images themselves.)""" + +import re +from dataclasses import fields +from pathlib import Path + +from lib.config import Config + +ROOT = Path(__file__).resolve().parent.parent + + +def requirements(name: str) -> set[str]: + found = set() + for line in (ROOT / name).read_text().splitlines(): + line = line.split("#")[0].strip() + if line.startswith("-r "): + found |= requirements(line[3:].strip()) + elif line: + found.add(re.split(r"[=<>!\[ ]", line)[0].lower()) + return found + + +def test_ecobot_mcp_needs_no_telegram_and_no_model_client_and_the_bot_has_everything(): + mcp, bot = requirements("requirements-mcp.txt"), requirements("requirements.txt") + assert {"mcp", "uvicorn", "httpx"} <= mcp and not {"python-telegram-bot", "openai"} & mcp + assert mcp < bot and {"python-telegram-bot", "openai"} <= bot + + +def test_one_dockerfile_builds_both_images_each_checked_at_build(): + text = (ROOT / "Dockerfile").read_text() + assert re.search(r"^FROM app AS ecobot-mcp$", text, re.M) and re.search(r"^FROM app AS ecobot$", text, re.M) + mcp, bot = text.split("FROM app AS ecobot-mcp")[1].split("FROM app AS ecobot\n") + assert "requirements-mcp.txt" in text.split("FROM base AS venv-mcp")[1].split("FROM base AS venv-bot")[0] + assert 'CMD ["python", "-m", "ecobot_mcp"]' in mcp and "import ecobot_mcp.__main__" in mcp and "find_spec('telegram') is None" in mcp + assert 'CMD ["python", "ecobot.py"]' in bot and "import lib.bot, ecobot" in bot + assert "requirements-mcp.txt" in (ROOT / ".dockerignore").read_text() + + +def test_compose_runs_each_program_from_its_own_image(): + text = (ROOT / "compose.yaml").read_text() + services = dict(re.findall(r"^ ([\w-]+):\n((?: .*\n|\s*\n)+)", text, re.M)) + mcp, bot = services["ecobot-mcp"], services["ecobot"] + assert "image: ecobot-mcp" in mcp and "target: ecobot-mcp" in mcp and "hostname: ecobot-mcp" in mcp and "- 8765:8765" in mcp + assert "image: ecobot\n" in bot and "target: ecobot\n" in bot and "profiles: [bot]" in bot and "depends_on: [ecobot-mcp]" in bot + assert "BOT_MCP_URL=http://ecobot-mcp:8765/mcp" in (ROOT / "docker" / "bot.env").read_text() + + +def test_the_ecobot_mcp_unit_drops_the_bots_secrets_by_their_new_and_old_names(): + text = (ROOT / "ecobot-mcp.service").read_text() + unset = set(re.search(r"^UnsetEnvironment=(.*)$", text, re.M)[1].split()) + by_env = {f.metadata["env"]: f.metadata.get("old") for f in fields(Config) if f.metadata.get("env")} + for name in ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "BOT_TUYA_CLIENT_ID", "BOT_TUYA_CLIENT_SECRET"): + assert {name, by_env[name]} <= unset, name + assert "AUTH_TOKENS" not in unset and "ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_mcp" in text diff --git a/tests/test_periods.py b/tests/test_periods.py index c966ea59..94ebefb6 100644 --- a/tests/test_periods.py +++ b/tests/test_periods.py @@ -320,7 +320,7 @@ async def test_a_chart_is_drawn_again_once_it_is_stale_and_never_answers_another def preloading_bot(alert_state, monkeypatch, refuse=None, clock=None): - """A bot with TELEGRAM_PRELOAD_CHAT set, and the (chat, photo, silent) of every upload to it. The periods are uploaded side by side, + """A bot with BOT_TELEGRAM_PRELOAD_CHAT set, and the (chat, photo, silent) of every upload to it. The periods are uploaded side by side, in no fixed order, so each period's picture is its period's words and its file id "file " and those words; context.refused.error is what the uploads raise (none: they go through).""" bot, uploads, refused = make_bot(alert_state, monkeypatch), [], NS(error=refuse) @@ -382,7 +382,7 @@ async def test_nothing_is_uploaded_ahead_without_the_setting_and_a_refused_uploa await settle(bot) await bot.respond(pressed(bot, []), context, "Temperature chart 30d") await settle(bot) - assert [r for r in caplog.records if "TELEGRAM_PRELOAD_CHAT" in r.getMessage()].__len__() == 1 and uploads == [] and bot.preload_off + assert [r for r in caplog.records if "BOT_TELEGRAM_PRELOAD_CHAT" in r.getMessage()].__len__() == 1 and uploads == [] and bot.preload_off async def test_a_flood_limit_or_a_timeout_skips_those_uploads_and_the_next_chart_uploads_again(alert_state, monkeypatch, caplog): @@ -398,7 +398,7 @@ async def test_a_flood_limit_or_a_timeout_skips_those_uploads_and_the_next_chart await bot.respond(pressed(bot, []), context, asked) await settle(bot) assert uploads == [] and not bot.preload_off - assert len([r for r in caplog.records if "TELEGRAM_PRELOAD_CHAT" in r.getMessage()]) == 2 # one a chart, though several uploads were skipped + assert len([r for r in caplog.records if "BOT_TELEGRAM_PRELOAD_CHAT" in r.getMessage()]) == 2 # one a chart, though several uploads were skipped context.refused.error = None await bot.respond(pressed(bot, []), context, "Temperature chart 90d") await settle(bot) diff --git a/tests/test_periods_text.py b/tests/test_periods_text.py index a6fd25b5..c7d41aaf 100644 --- a/tests/test_periods_text.py +++ b/tests/test_periods_text.py @@ -1,4 +1,4 @@ -"""Periods in words (lib/periods_text.py): the table of docs/mcp-service.md 3.2 read at fixed times, every answer worked out by hand. +"""Periods in words (lib/periods_text.py): the table of docs/ecobot-mcp.md 3.2 read at fixed times, every answer worked out by hand. Melbourne's clocks go back an hour at 3am on 5 Apr 2026 (2am to 3am happens twice) and forward at 2am on 4 Oct 2026 (2am to 3am never happens).""" diff --git a/tests/test_pollen.py b/tests/test_pollen.py index a0706d94..f0425022 100644 --- a/tests/test_pollen.py +++ b/tests/test_pollen.py @@ -85,7 +85,7 @@ async def test_the_district_is_the_sites_whatever_its_case_and_one_it_lacks_is_w await pollen.close() with caplog.at_level("WARNING"): pollen, _ = make(tmp_path, pollen_district="Centrl") - assert pollen.district == "Centrl" and "POLLEN_DISTRICT 'Centrl' is not one of the site's districts" in caplog.text + assert pollen.district == "Centrl" and "MCP_POLLEN_DISTRICT 'Centrl' is not one of the site's districts" in caplog.text await pollen.close() diff --git a/tests/test_service_about.py b/tests/test_service_about.py index 79c90a4b..52c82d94 100644 --- a/tests/test_service_about.py +++ b/tests/test_service_about.py @@ -111,7 +111,7 @@ def test_each_alert_has_its_rule_and_the_thresholds_the_rules_use(monkeypatch): assert rules["rain"]["thresholds"] == {"dry_minutes": 60, "quiet_hours": "00:00-06:00"} assert rules["rain"]["rule"].endswith("None from 12am to 6am: one summary of the rain in those hours after them.") assert all(a["what"] == ab.ALERT_WORDS[a["kind"]] and a["name"] == menu.LABELS[a["kind"]] for a in rules.values()) - monkeypatch.setattr(ab, "RAIN_QUIET_HOURS", None) # the service's settings, as the config sets them + monkeypatch.setattr(ab, "RAIN_QUIET_HOURS", None) # ecobot-mcp's settings, as the config sets them monkeypatch.setattr(ab, "ALERT_COOLDOWN_MINUTES", 90) rules = {a["kind"]: a for a in ab.alerts(EVERY)} assert rules["rain"]["thresholds"] == {"dry_minutes": 90, "quiet_hours": None} and "None from" not in rules["rain"]["rule"] diff --git a/tests/test_service_evals.py b/tests/test_service_evals.py index 82a1ea3d..61cfa722 100644 --- a/tests/test_service_evals.py +++ b/tests/test_service_evals.py @@ -575,5 +575,5 @@ async def test_the_tools_alone_answer_no_data_to_every_call_and_score_every_call assert await evalkit.run_service([case("will-it-rain")], EXPECT, model, "m", out=lines.append) == 0, lines assert len(model.requests) == 3 script_doc = ast.get_docstring(ast.parse((ROOT / "scripts" / "eval_prompts.py").read_text())) - for text in (script_doc, evalkit.run_service.__doc__, evalkit.__doc__, (ROOT / "docs" / "mcp-service.md").read_text()): + for text in (script_doc, evalkit.run_service.__doc__, evalkit.__doc__, (ROOT / "docs" / "ecobot-mcp.md").read_text()): assert "first round" not in text and "(one round)" not in text diff --git a/tests/test_service_instructions.py b/tests/test_service_instructions.py index 811c52d8..583162ca 100644 --- a/tests/test_service_instructions.py +++ b/tests/test_service_instructions.py @@ -1,4 +1,4 @@ -"""The server's instructions (lib/service/instructions.py; docs/mcp-service.md 3.2): the devices and their nicknames, Indoor and Outdoor, +"""The server's instructions (lib/service/instructions.py; docs/ecobot-mcp.md 3.2): the devices and their nicknames, Indoor and Outdoor, the units, built from the Context's sources and the catalogue.""" from zoneinfo import ZoneInfo diff --git a/tests/test_service_switch.py b/tests/test_service_switch.py index 05595912..de89f9e8 100644 --- a/tests/test_service_switch.py +++ b/tests/test_service_switch.py @@ -1,5 +1,5 @@ """The bot's own answers (everything it answers without the model) pinned word for word, chart for chart, on the archived fake station -at a fixed time (Tue 10 Nov 2026 2:05pm, Melbourne), so moving them onto the service's tools (docs/mcp-service.md 6, step 2) changes +at a fixed time (Tue 10 Nov 2026 2:05pm, Melbourne), so moving them onto the service's tools (docs/ecobot-mcp.md 6, step 2) changes nothing the person sees but what is meant to change. What is pinned, for each question the bot answers in code (its keyboard's charts, the shortcuts and plain lookups intent.read answers, diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 00000000..c737f158 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,136 @@ +"""The settings' names (docs/configuration.md): ecobot-mcp's start with MCP_, the bot's with BOT_, the shared ones have neither; an old +name still works when the new one is unset, with one warning naming the new name (never the value). And the token: AUTH_TOKENS, or the +one ecobot-mcp generates in the data folder, which the bot reads from there (lib/auth_token.py).""" + +import logging +import os +import stat +from dataclasses import fields + +import pytest + +import ecobot +from ecobot_mcp import __main__ as mcp_main +from lib import auth_token +from lib.config import Config, env +from tests.fakes import config + +SHARED = {"DARKMODE", "LOG_LEVEL", "AUTH_TOKENS"} +MCP_ONLY = {"ecowitt_api_key", "ecowitt_app_key", "ecowitt_source", "airgradient_token", "airgradient_location", "airgradient_dashboard", + "airgradient_local_url", "airgradient_source", "homeassistant_url", "homeassistant_token", "place", "pollen", "pollen_district", + "forecast", "forecast_lat", "forecast_lon", "rain_quiet_hours", "alert_cooldown_minutes", "antispike_require_consecutive", + "chart_all_feels_like", "chart_all_vpd", "mcp_bind", "mcp_allowed_hosts"} + + +def test_every_setting_is_named_for_the_program_that_reads_it(): + for f in fields(Config): + name = f.metadata.get("env") + if not name or name == "WEATHER_MCP_TOKEN": # (retired) + continue + if name in SHARED: + assert not name.startswith(("MCP_", "BOT_")), name + elif f.name in MCP_ONLY: + assert name.startswith("MCP_"), name + else: + assert name.startswith("BOT_"), name + + +def bot_settings(monkeypatch, tmp_path): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "1:x") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + + +OLD_AND_NEW = [("ECOWITT_API_KEY", "MCP_ECOWITT_API_KEY", "ecowitt_api_key", "k3y", "k3y"), + ("HOMEASSISTANT_URL", "MCP_HOMEASSISTANT_URL", "homeassistant_url", "http://ha:8123/", "http://ha:8123"), + ("PLACE", "MCP_PLACE", "place", "Hobart", "Hobart"), + ("RAIN_QUIET_HOURS", "MCP_RAIN_QUIET_HOURS", "rain_quiet_hours", "22-6", (22, 6)), + ("CHART_ALL_VPD", "MCP_CHART_ALL_VPD", "chart_all_vpd", "on", True), + ("MCP_SERVICE_BIND", "MCP_BIND", "mcp_bind", "0.0.0.0:9000", ("0.0.0.0", 9000)), + ("MCP_SERVICE_ALLOWED_HOSTS", "MCP_ALLOWED_HOSTS", "mcp_allowed_hosts", "weather.lan", ("weather.lan",)), + ("MCP_SERVICE_TOKENS", "AUTH_TOKENS", "auth_tokens", "s3cret,other", ("s3cret", "other")), + ("OPENROUTER_API_KEY", "BOT_OPENROUTER_API_KEY", "openrouter_api_key", "sk-s3cret", "sk-s3cret"), + ("OPENROUTER_MODEL", "BOT_OPENROUTER_MODEL", "openrouter_model", "a/model", "a/model"), + ("ADMIN_ONLY", "BOT_ADMIN_ONLY", "admin_only", "on", True), + ("ADMIN_CHAT_IDS", "BOT_ADMIN_CHAT_IDS", "admin_chat_ids", "5 -9", frozenset({5, -9})), + ("LOG_WIDTH", "BOT_LOG_WIDTH", "log_width", "80", 80), + ("WEATHER_MCP_URL", "BOT_MCP_URL", "mcp_url", "http://ecobot-mcp:8765/mcp", "http://ecobot-mcp:8765/mcp"), + ("TUYA_CLIENT_SECRET", "BOT_TUYA_CLIENT_SECRET", "tuya_client_secret", "tuya-s3cret", "tuya-s3cret"), + ("IRRIGATION_CHECK_HOUR", "BOT_IRRIGATION_CHECK_HOUR", "irrigation_check_hour", "7", 7), + ("TELEGRAM_PRELOAD_CHAT", "BOT_TELEGRAM_PRELOAD_CHAT", "telegram_preload_chat", "-100", -100)] + + +@pytest.mark.parametrize("old, new, attr, text, want", OLD_AND_NEW, ids=[row[0] for row in OLD_AND_NEW]) +def test_a_setting_is_read_by_its_new_name_or_its_old_one_with_a_warning(monkeypatch, tmp_path, caplog, old, new, attr, text, want): + bot_settings(monkeypatch, tmp_path) + monkeypatch.setenv(new, text) + caplog.clear() + assert getattr(Config.from_env(), attr) == want and "Old setting names" not in caplog.text + monkeypatch.delenv(new) + monkeypatch.setenv(old, text) + caplog.clear() + assert getattr(Config.from_env(), attr) == want + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING and "Old setting names" in r.getMessage()] + assert len(warnings) == 1 and f"{old} -> {new}" in warnings[0] and (len(text) < 5 or text not in warnings[0]) # (never the value) + assert env(new) == text.strip() # (the scripts' way in, old names too) + + +def test_the_old_names_are_one_warning_and_a_new_name_wins_over_its_old_one(monkeypatch, tmp_path, caplog): + monkeypatch.setenv("DATA_DIR", str(tmp_path)) + for old, value in (("TELEGRAM_BOT_TOKEN", "1:s3cret"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + monkeypatch.setenv(old, value) + monkeypatch.setenv("BOT_LOG_WIDTH", "30") + monkeypatch.setenv("LOG_WIDTH", "99") + cfg = Config.from_env() + assert cfg.telegram_token == "1:s3cret" and cfg.ecowitt and cfg.log_width == 30 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + renamed = [w for w in warnings if "Old setting names" in w] + assert len(renamed) == 1 and "TELEGRAM_BOT_TOKEN -> BOT_TELEGRAM_TOKEN" in renamed[0] and "ECOWITT_APP_KEY -> MCP_ECOWITT_APP_KEY" in renamed[0] + assert any("Ignoring LOG_WIDTH" in w for w in warnings) and "s3cret" not in caplog.text and "99" not in caplog.text + + +def test_a_value_an_old_name_gives_is_checked_under_that_name(monkeypatch, tmp_path, caplog): + bot_settings(monkeypatch, tmp_path) + monkeypatch.setenv("ADMIN_ONLY", "ture") + assert Config.from_env().admin_only is False and "ADMIN_ONLY: 'ture' is not on or off" in caplog.text + + +# ---------- the token ---------- +def test_ecobot_mcp_generates_a_token_once_keeps_it_private_and_says_where_never_what(tmp_path, caplog): + caplog.set_level("INFO") + cfg = config(tmp_path) + token = mcp_main.generated_token(cfg) + kept = tmp_path / "auth_token" + assert len(token) >= 40 and kept.read_text().strip() == token + assert stat.S_IMODE(kept.stat().st_mode) == 0o600 + assert mcp_main.generated_token(cfg) == token # used again at the next start + assert str(kept) in caplog.text and token not in caplog.text + assert [p.name for p in tmp_path.iterdir() if p.name.startswith(".auth_token")] == [] # (no file of its own left behind) + + +def test_an_empty_token_file_is_replaced_and_an_unwritable_folder_stops_ecobot_mcp_saying_why(tmp_path): + (tmp_path / "auth_token").write_text("\n") + token = auth_token.ensure(tmp_path) + assert token and auth_token.read(tmp_path) == token + if os.geteuid() != 0: # (root writes anywhere) + locked = tmp_path / "locked" + locked.mkdir(mode=0o500) + with pytest.raises(SystemExit, match="AUTH_TOKENS is not set"): + mcp_main.generated_token(config(locked)) + + +def test_the_bot_sends_the_first_of_auth_tokens_else_the_retired_one_else_the_generated_one(tmp_path, caplog): + assert ecobot.mcp_token(config(tmp_path, auth_tokens=("first", "second"))) == "first" + assert ecobot.mcp_token(config(tmp_path, auth_tokens=("first",), retired_mcp_token="old")) == "first" + assert "WEATHER_MCP_TOKEN is retired and ignored" in caplog.text + caplog.clear() + assert ecobot.mcp_token(config(tmp_path, retired_mcp_token="r3tired")) == "r3tired" + assert "move it into AUTH_TOKENS" in caplog.text and "r3tired" not in caplog.text + caplog.clear() + read = ecobot.mcp_token(config(tmp_path)) # ecobot-mcp hasn't written its token yet: said, and read again + assert callable(read) and read() is None and f"there is no token at {tmp_path / 'auth_token'}" in caplog.text + token = auth_token.ensure(tmp_path) + assert read() == token + caplog.clear() + assert ecobot.mcp_token(config(tmp_path))() == token and "no token" not in caplog.text diff --git a/tests/test_startup.py b/tests/test_startup.py index 16a92ee6..e0cd2119 100644 --- a/tests/test_startup.py +++ b/tests/test_startup.py @@ -99,7 +99,7 @@ async def stop_when_archived(): # the background archives finish, then we shut assert "/0 fetched/failed, " in final and "d held (5m/30m/4h/1d)" in final assert len(app.handlers) == 11 # start+help, reset, keyboard, alerts, usage, report, the one button handler, other updates, membership, messages, errors assert "Alerts NOT running" not in log - assert ecobot._format.width == 120 # LOG_WIDTH reaches the bot's own log lines + assert ecobot._format.width == 120 # BOT_LOG_WIDTH reaches the bot's own log lines assert buttons_not_drawn_ahead == [app.bot] # the keyboard's charts are drawn ahead once the sources are warm @@ -277,20 +277,20 @@ def test_the_time_zone_without_a_station_is_tz_else_the_one_etc_localtime_links_ def test_the_alert_cooldown_is_configurable_with_a_default_and_limits(monkeypatch): from lib.config import Config - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "t") - monkeypatch.setenv("OPENROUTER_API_KEY", "k") - monkeypatch.setenv("ECOWITT_API_KEY", "a") - monkeypatch.setenv("ECOWITT_APP_KEY", "b") - monkeypatch.delenv("ALERT_COOLDOWN_MINUTES", raising=False) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "t") + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", "k") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_ALERT_COOLDOWN_MINUTES", raising=False) assert Config.from_env().alert_cooldown_minutes == 60 for value, want in (("45", 45), ("1", 5), ("0", 5), ("-3", 5), ("999", 150), ("junk", 60)): # 0 is under 5 like 1 is - monkeypatch.setenv("ALERT_COOLDOWN_MINUTES", value) + monkeypatch.setenv("MCP_ALERT_COOLDOWN_MINUTES", value) assert Config.from_env().alert_cooldown_minutes == want, value def test_the_log_level_is_a_setting_and_a_typo_keeps_info_with_a_warning(monkeypatch, caplog): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) monkeypatch.delenv("LOG_LEVEL", raising=False) assert Config.from_env().log_level == "INFO" @@ -303,48 +303,48 @@ def test_the_log_level_is_a_setting_and_a_typo_keeps_info_with_a_warning(monkeyp def test_a_blank_setting_means_its_default_and_a_missing_key_says_which(monkeypatch, caplog): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", " t "), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", " t "), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - for k in ("OPENROUTER_MODEL", "OPENROUTER_BASE_URL", "PLACE", "POLLEN_DISTRICT", "TUYA_BASE_URL"): + for k in ("BOT_OPENROUTER_MODEL", "BOT_OPENROUTER_BASE_URL", "PLACE", "MCP_POLLEN_DISTRICT", "BOT_TUYA_BASE_URL"): monkeypatch.setenv(k, " ") monkeypatch.setenv("POLLEN", "enabled") cfg = Config.from_env() assert (cfg.telegram_token, cfg.openrouter_model, cfg.openrouter_base_url, cfg.place, cfg.pollen_district, cfg.tuya_base_url) == ( "t", "deepseek/deepseek-v4.1-flash-1017", "https://openrouter.ai/api/v1", "Melbourne", "Central", "https://openapi.tuyaeu.com") assert cfg.pollen is False and "POLLEN: 'enabled' is not on or off; keeping the default (off)" in caplog.text - monkeypatch.setenv("OPENROUTER_API_KEY", " ") + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", " ") assert Config.from_env().openrouter_api_key == "" # no model is allowed: the bot then answers only what it works out itself - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", " ") - with pytest.raises(SystemExit, match="TELEGRAM_BOT_TOKEN is not set"): + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", " ") + with pytest.raises(SystemExit, match="BOT_TELEGRAM_TOKEN is not set"): Config.from_env() def test_the_rain_quiet_hours_are_configurable(): from lib.config import _hours - hours = lambda text: _hours(text, (0, 6), "RAIN_QUIET_HOURS") + hours = lambda text: _hours(text, (0, 6), "MCP_RAIN_QUIET_HOURS") assert hours("") == (0, 6) and hours("22-6") == (22, 6) and hours("off") is None assert hours("junk") == (0, 6) and hours("6-6") == (0, 6) and hours("0-25") == (0, 6) def test_feels_like_in_chart_all_is_off_by_default_and_a_config_option_turns_it_on(monkeypatch): from lib.config import Config - monkeypatch.setenv("TELEGRAM_BOT_TOKEN", "t") - monkeypatch.setenv("OPENROUTER_API_KEY", "k") - monkeypatch.setenv("ECOWITT_API_KEY", "a") - monkeypatch.setenv("ECOWITT_APP_KEY", "b") - monkeypatch.delenv("CHART_ALL_FEELS_LIKE", raising=False) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "t") + monkeypatch.setenv("BOT_OPENROUTER_API_KEY", "k") + monkeypatch.setenv("MCP_ECOWITT_API_KEY", "a") + monkeypatch.setenv("MCP_ECOWITT_APP_KEY", "b") + monkeypatch.delenv("MCP_CHART_ALL_FEELS_LIKE", raising=False) assert Config.from_env().chart_all_feels_like is False - monkeypatch.setenv("CHART_ALL_FEELS_LIKE", "on") + monkeypatch.setenv("MCP_CHART_ALL_FEELS_LIKE", "on") assert Config.from_env().chart_all_feels_like is True def test_vpd_in_chart_all_is_off_by_default_and_a_config_option_turns_it_on(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("CHART_ALL_VPD", raising=False) + monkeypatch.delenv("MCP_CHART_ALL_VPD", raising=False) assert Config.from_env().chart_all_vpd is False - monkeypatch.setenv("CHART_ALL_VPD", "on") + monkeypatch.setenv("MCP_CHART_ALL_VPD", "on") assert Config.from_env().chart_all_vpd is True @@ -437,23 +437,23 @@ def test_a_traceback_is_logged_whole_after_its_message(): def test_the_log_width_is_24_unless_set_and_0_keeps_whole_messages(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("LOG_WIDTH", raising=False) + monkeypatch.delenv("BOT_LOG_WIDTH", raising=False) assert Config.from_env().log_width == 24 for value, want in (("120", 120), ("0", 0), ("junk", 24), ("-5", 24), ("7.5", 24), ("²", 24)): - monkeypatch.setenv("LOG_WIDTH", value) + monkeypatch.setenv("BOT_LOG_WIDTH", value) assert Config.from_env().log_width == want, value def test_the_preload_chat_is_a_chat_id_or_off(monkeypatch): from lib.config import Config - for k, v in (("TELEGRAM_BOT_TOKEN", "t"), ("OPENROUTER_API_KEY", "k"), ("ECOWITT_API_KEY", "a"), ("ECOWITT_APP_KEY", "b")): + for k, v in (("BOT_TELEGRAM_TOKEN", "t"), ("BOT_OPENROUTER_API_KEY", "k"), ("MCP_ECOWITT_API_KEY", "a"), ("MCP_ECOWITT_APP_KEY", "b")): monkeypatch.setenv(k, v) - monkeypatch.delenv("TELEGRAM_PRELOAD_CHAT", raising=False) + monkeypatch.delenv("BOT_TELEGRAM_PRELOAD_CHAT", raising=False) assert Config.from_env().telegram_preload_chat is None for value, want in (("-1001234567890", -1001234567890), ("42", 42), ("", None), ("junk", None)): - monkeypatch.setenv("TELEGRAM_PRELOAD_CHAT", value) + monkeypatch.setenv("BOT_TELEGRAM_PRELOAD_CHAT", value) assert Config.from_env().telegram_preload_chat == want, value @@ -481,5 +481,5 @@ async def initialize(self): monkeypatch.setattr(ecobot.Application, "builder", staticmethod(lambda: FakeBuilder(Rejecting()))) with pytest.raises(SystemExit) as stopped: await ecobot.main() - assert "TELEGRAM_BOT_TOKEN was rejected by Telegram" in str(stopped.value) and "SECRET" not in str(stopped.value) + assert "BOT_TELEGRAM_TOKEN was rejected by Telegram" in str(stopped.value) and "SECRET" not in str(stopped.value) assert stopped.value.__cause__ is None and stopped.value.__suppress_context__ From 3c794387e143f692db2514dbe6cde3b4c4bcebad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:14:48 +0000 Subject: [PATCH 079/125] Upgrading a systemd ecobot-mcp: copy its unit in again; an old unit still starts The ecobot-mcp.service copied into /etc/systemd/system before the rename runs python -m ecobot_service and unsets the bot's secrets only by their old names. README's systemd upgrade now copies the new unit in, reloads and restarts ecobot-mcp. Until then a small ecobot_service shim starts ecobot_mcp with a warning saying so, dropping the bot's secrets by their new names first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 9 +++++++++ ecobot_service/__main__.py | 29 +++++++++++++++++++++++++++++ tests/test_packaging.py | 23 +++++++++++++++++++++++ 3 files changed, 61 insertions(+) create mode 100644 ecobot_service/__main__.py diff --git a/README.md b/README.md index 1e616484..95cd1327 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,15 @@ sudo /opt/ecobot/.venv/bin/pip install -r /opt/ecobot/requirements.txt -r /opt/e sudo systemctl restart ecobot ``` +If you run [ecobot-mcp on its own](#ecobot-mcp-on-its-own-optional), copy its unit in again too, then restart it (before November +2026 the unit ran `python -m ecobot_service`, ecobot-mcp's old name, and dropped the bot's secrets only by their old names): + +``` +sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && sudo systemctl restart ecobot-mcp +``` + +An old unit not yet copied in still starts, with a warning in its log saying to copy the new one. + ### Docker ``` diff --git a/ecobot_service/__main__.py b/ecobot_service/__main__.py new file mode 100644 index 00000000..9f688bee --- /dev/null +++ b/ecobot_service/__main__.py @@ -0,0 +1,29 @@ +"""python -m ecobot_service: the old name of ecobot-mcp (python -m ecobot_mcp), kept so that an ecobot-mcp.service copied into +/etc/systemd/system before the rename keeps starting until the new unit is copied in (README, Upgrading > systemd). That old unit +drops the bot's secrets only by their old names (UnsetEnvironment=), so this drops them by their new ones too before ecobot-mcp +starts, and logs a warning saying what to do.""" + +import logging +import os + +# The bot's secrets by their new names, which the old unit's UnsetEnvironment= doesn't list (the new unit lists them itself) +BOT_SECRETS = ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "BOT_TUYA_CLIENT_ID", "BOT_TUYA_CLIENT_SECRET") + + +def drop_bot_secrets(environ=os.environ) -> None: + for name in BOT_SECRETS: + environ.pop(name, None) + + +def run(): + drop_bot_secrets() + from ecobot_mcp.__main__ import run as run_mcp + logging.getLogger("ecobot.mcp").warning( + "Started as python -m ecobot_service, ecobot-mcp's old name: copy the new unit in " + "(sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && " + "sudo systemctl restart ecobot-mcp), which runs python -m ecobot_mcp") + run_mcp() + + +if __name__ == "__main__": + run() diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 7ca3f75d..be081169 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -54,3 +54,26 @@ def test_the_ecobot_mcp_unit_drops_the_bots_secrets_by_their_new_and_old_names() for name in ("BOT_TELEGRAM_TOKEN", "BOT_OPENROUTER_API_KEY", "BOT_TUYA_CLIENT_ID", "BOT_TUYA_CLIENT_SECRET"): assert {name, by_env[name]} <= unset, name assert "AUTH_TOKENS" not in unset and "ExecStart=/opt/ecobot/.venv/bin/python -m ecobot_mcp" in text + + +def test_an_old_ecobot_service_unit_still_starts_ecobot_mcp_without_the_bots_secrets_by_their_new_names(monkeypatch): + # an ecobot-mcp.service copied in before the rename runs python -m ecobot_service and unsets the bot's secrets by their old names + import ecobot_mcp.__main__ + import ecobot_service.__main__ as old + unit = set(re.search(r"^UnsetEnvironment=(.*)$", (ROOT / "ecobot-mcp.service").read_text(), re.M)[1].split()) + assert set(old.BOT_SECRETS) <= unit + environ = {name: "secret" for name in old.BOT_SECRETS} | {"MCP_ECOWITT_API_KEY": "k", "AUTH_TOKENS": "t"} + old.drop_bot_secrets(environ) + assert environ == {"MCP_ECOWITT_API_KEY": "k", "AUTH_TOKENS": "t"} + ran = [] + monkeypatch.setattr(ecobot_mcp.__main__, "run", lambda: ran.append(True)) + monkeypatch.setenv("BOT_TELEGRAM_TOKEN", "secret") + old.run() + assert ran == [True] and "BOT_TELEGRAM_TOKEN" not in __import__("os").environ + + +def test_the_systemd_upgrade_copies_the_ecobot_mcp_unit_in_again(): + text = (ROOT / "README.md").read_text() + upgrade = text.split("### systemd", 2)[2].split("### Docker")[0] + assert "sudo cp /opt/ecobot/ecobot-mcp.service /etc/systemd/system/ && sudo systemctl daemon-reload && " \ + "sudo systemctl restart ecobot-mcp" in upgrade From 6da1a0c4bf8adaf939fe555703f80ab676923131 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:18:32 +0000 Subject: [PATCH 080/125] scripts/migrate_env.py renames an env file's settings; step 6 (the slim bot) in the plan; Docker upgrade removes ecobot-service first - migrate_env.py: old names to new from lib/config.py's text (no import, Python 3.9+, no packages), values/comments/order kept, WEATHER_MCP_TOKEN into AUTH_TOKENS first, ecobot-service hosts to ecobot-mcp, stops on a conflict; shows a masked diff, changes the file only with --write after a backup with the same owner and mode - README: the script under Renamed settings; the Docker upgrade command removes the old ecobot-service container first - docs/ecobot-mcp.md: step 6 is the slim bot (6a pictures from ecobot-mcp, 6b client only, 6c less code, 6d irrigation) - lib/upstream.py: says ecobot-mcp, not the service Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 31 +++++--- docs/ecobot-mcp.md | 48 +++++++++++- lib/upstream.py | 12 +-- scripts/migrate_env.py | 150 ++++++++++++++++++++++++++++++++++++++ tests/test_migrate_env.py | 74 +++++++++++++++++++ 5 files changed, 296 insertions(+), 19 deletions(-) create mode 100644 scripts/migrate_env.py create mode 100644 tests/test_migrate_env.py diff --git a/README.md b/README.md index 95cd1327..ea73f242 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,21 @@ Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) ar In November 2026 every setting got the name of the program that reads it: `MCP_` for ecobot-mcp's, `BOT_` for the bot's, and none for the few both read. The old names still work: when a new name is unset and its old one is set, the old one is used, and the log says -once at start which to rename (never their values). Rename them in `/etc/ecobot.env` when convenient: +once at start which to rename (never their values). Rename them in `/etc/ecobot.env` when convenient, by hand from the table, or with the script, which shows what it +would change (secrets masked) and changes the file only with `--write`, keeping a backup beside it: + +``` +sudo python3 /opt/ecobot/scripts/migrate_env.py /etc/ecobot.env +``` + +``` +sudo python3 /opt/ecobot/scripts/migrate_env.py /etc/ecobot.env --write +``` + +Then restart ecobot-mcp and the bot. Beyond the renames it moves `WEATHER_MCP_TOKEN` into `AUTH_TOKENS` (first, the token the bot +sends) and changes the old container name `ecobot-service` in a URL or allowed host to `ecobot-mcp`; it stops, changing nothing, where +an old and a new name are both set to different values. + | Old name | New name | |---|---| @@ -261,9 +275,12 @@ cd /opt/ecobot && sudo git pull ``` ``` -sudo docker compose up -d --build +sudo docker rm -f ecobot-service 2>/dev/null; sudo docker compose up -d --build ``` +(The first part removes the container ecobot-mcp had before November 2026, `ecobot-service`, which would keep port 8765; once it's gone +it does nothing.) + Compose replaces a container only if its image or settings changed. To remove the old images and build cache that upgrades leave behind: ``` @@ -271,15 +288,7 @@ sudo docker image prune -f && sudo docker builder prune -f ``` **From the layout with a container named `ecobot-service` (November 2026):** that container is now `ecobot-mcp`, from an image of -its own (`ecobot-mcp`; the bot's is still `ecobot`). Remove the old container first, or it keeps port 8765: - -``` -sudo docker rm -f ecobot-service -``` - -``` -sudo docker compose up -d --build -``` +its own (`ecobot-mcp`; the bot's is still `ecobot`). The command above removes the old container first, which would otherwise keep port 8765. Your token lines still work (`MCP_SERVICE_TOKENS` is read as `AUTH_TOKENS`, and `WEATHER_MCP_TOKEN` is ignored once that is set, with a warning): rename `MCP_SERVICE_TOKENS` to `AUTH_TOKENS` and delete `WEATHER_MCP_TOKEN`, or delete both to use the token ecobot-mcp diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index 57c1669a..ef0cf1cd 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -640,8 +640,52 @@ Each step ships on its own, with the tests and evals green and the bot working t byte for byte the bot's own, for a call and an alert's chart). - **Left: 5b**, the irrigation server in its own repository (3.9: its tools, the watchdog and the daily check, `irrigation://alerts`), the bot connecting to both and `lib/irrigation` going from here; and `show_request` and `report_inputs` as MCP clients. -6. **The bot retired** (section 4), its code and tests deleted; the repository is the service. The renderer stays, for the service's - chart images (3.7), and the gauges go with the bot unless they move to the service first. +6. **The slim bot** (decided November 2026, in place of retiring it: section 4 describes the bot as it was). The Telegram bot is kept, but only as a thin client of ecobot-mcp: it does what only a Telegram bot can do + (chats, buttons, pushing alerts), and everything about the weather, the air, the alerts' rules and the pictures comes from + ecobot-mcp over MCP. It never opens the readings file and draws nothing. Sub-steps, each its own change with the checks green: + + - **6a. Every picture from ecobot-mcp.** The charts in the model's answers and in the keyboard's answers come from ecobot-mcp as + images (request `_meta` `chart_image: "png"`): the bot keeps the image blocks and `ecobot/charts` (for the period buttons) and + gives the model only the text (`for_model`, as today). The dashboard's gauges move to ecobot-mcp the same way: a tool or resource + that returns the gauge sheet as a PNG, its figures as text. The bot then imports neither Pillow nor `lib/charts.py`, + `lib/draw.py` or `lib/gauges.py`. + - **6b. Client only.** `BOT_MCP_URL` is required: the in-process mode (`LocalWeather`, the bot starting the sources, the syncers, + the alert rules and the alert log itself) is deleted. Under systemd, `ecobot.service` wants and starts after `ecobot-mcp.service`; + in Docker this is already the layout. The bot's image installs only its own packages (python-telegram-bot, openai, mcp, httpx). + - **6c. Less code in the bot.** + - Typed shortcuts go: anything typed goes to the model (`lib/intent.py`'s pattern matching, `chart_call`, the dashboard and + report words). Buttons stay instant because each is a fixed call. + - `/report` becomes an ecobot-mcp prompt (`report`): the bot asks the model with it, and the model calls the tools. The + report written in code (`lib/report.py`, `lib/report_menu.py`) is deleted. + - The charts drawn ahead every 5 minutes go (`draw_buttons_ahead`). Kept: after a chart is sent, its other periods are fetched + (and, with `BOT_TELEGRAM_PRELOAD_CHAT`, uploaded) in the background, so its period buttons answer at once. A keyboard button's + first press waits for ecobot-mcp, about half a second. + - Without `BOT_OPENROUTER_API_KEY` the bot answers the buttons and sends alerts; a typed question gets one line saying the + model isn't set up (the no-model fallbacks go). + - The test-only oracles from step 3 (`tests/old_tools.py`, `tests/report_words.py`) are deleted. + - **6d. Irrigation** is step 5b's: its own repository and MCP server, which the bot connects to as a second server + (`BOT_IRRIGATION_MCP_URL`), listening for its alerts the same way. + + **What the bot keeps:** + - **Telegram:** who may use it (`BOT_ADMIN_ONLY`, `BOT_ADMIN_CHAT_IDS`, group admins), private and group chats, the keyboard, the + per-chat state (`bot_state.json`: chats, alert subscriptions and sound, each chart message's `drawn_by`, the last alert read). + - **Questions:** the model loop with ecobot-mcp's tools, its instructions (from discover) and a short persona prompt (tone, + Telegram formatting, group-chat names, the chart caption rule). + - **Alerts:** listening to `ecobot://alerts`, sending each to the chats subscribed to its kind with its picture, the alert menus + (on/off and sound per kind), 🔄 under an alert's chart. + - **Charts:** the keyboard's chart buttons (each a fixed call), the period buttons and 🔄 (replaying `drawn_by`), and Help from + `about`. + + **What it leaves:** about a fifth of today's bot code: `lib/bot.py` (much smaller), `lib/weather.py` (the remote half), + `lib/upstream.py`, `lib/model_tools.py`, `lib/llm.py`, `lib/prompt.py`, `lib/alerts/notify.py` and `menu.py`, `lib/periods.py` + (the buttons), `lib/templates.py` (the keyboard), `lib/admins.py`, `lib/buttons.py`, `lib/config.py` (its `BOT_` settings). + + **Gates:** the offline evals (every typed case now goes to the model: the "answered in code" cases become model cases, their + expected calls unchanged); a live eval run on the production model only after asking (the typed shortcuts' cases are the ones + that change); the remote-bot tests over uvicorn; a check that the bot imports no Pillow and no source module. + + **Risks:** a typed chart request ("rain chart 7d") now costs a model call and a second or two, where it was instant; a keyboard + button's first press waits for ecobot-mcp; the bot does nothing without ecobot-mcp (it says so, as today). ## 7. Testing diff --git a/lib/upstream.py b/lib/upstream.py index 58771a04..17f611e9 100644 --- a/lib/upstream.py +++ b/lib/upstream.py @@ -29,7 +29,7 @@ def http_transport(url: str, token: str | None = None, refused: dict | None = None): """The Streamable HTTP transport to ecobot-mcp, its bearer token sent with every request, its read timeout READ_SECONDS. - refused: given, its "status" is set to an HTTP error the service answered with (the SDK reports any of them as one message).""" + refused: given, its "status" is set to an HTTP error ecobot-mcp answered with (the SDK reports any of them as one message).""" import httpx2 from mcp.client.streamable_http import streamable_http_client from mcp.shared._httpx_utils import create_mcp_http_client @@ -63,13 +63,13 @@ class Upstream: def __init__(self, target, token=None, on_event=None, on_discover=None, on_listening=None, resources=None): """Callbacks: on_discover(DiscoverResult), each new connection's, before it is used; on_listening(), once its listen is acknowledged (what was missed is read from here: an event from now on isn't); on_event(event), each listen event. Async. - resources: the URIs listened to, of those the service lists (None: every one).""" + resources: the URIs listened to, of those ecobot-mcp lists (None: every one).""" self.target, self.token, self.resources = target, token, resources self.on_event, self.on_discover, self.on_listening = on_event, on_discover, on_listening self.client: Client | None = None self.connected = asyncio.Event() self.attempts = 0 - self.refused: dict = {} # the HTTP error the service last answered with + self.refused: dict = {} # the HTTP error ecobot-mcp last answered with def _client(self) -> Client: token = self.token() if callable(self.token) else self.token # (a function: read again for each connection) @@ -89,7 +89,7 @@ async def run(self): await self.on_discover(discovered) self.client, self.attempts = client, 0 self.connected.set() - log.info("ecobot-mcp: connected to %s", self.target if isinstance(self.target, str) else "the service") + log.info("ecobot-mcp: connected to %s", self.target if isinstance(self.target, str) else "in-process") await self._listen(client) log.warning("ecobot-mcp ended the listen; connecting again") except asyncio.CancelledError: @@ -109,7 +109,7 @@ async def run(self): self.attempts += 1 async def _listen(self, client: Client): - """Listen to every resource the service lists and its lists' changes, passing each event on, until the stream ends.""" + """Listen to every resource ecobot-mcp lists and its lists' changes, passing each event on, until the stream ends.""" uris = [r.uri for r in (await client.list_resources()).resources if self.resources is None or str(r.uri) in self.resources] async with client.listen(tools_list_changed=True, prompts_list_changed=True, resources_list_changed=True, resource_subscriptions=uris) as sub: @@ -120,7 +120,7 @@ async def _listen(self, client: Client): await self.on_event(event) async def get(self) -> Client: - """The connected client; refused (MCPError) when the service can't be reached within CONNECT_WAIT.""" + """The connected client; refused (MCPError) when ecobot-mcp can't be reached within CONNECT_WAIT.""" if self.client is None: try: await asyncio.wait_for(self.connected.wait(), CONNECT_WAIT) diff --git a/scripts/migrate_env.py b/scripts/migrate_env.py new file mode 100644 index 00000000..253f6bfb --- /dev/null +++ b/scripts/migrate_env.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Rename the settings in an environment file (/etc/ecobot.env) to their new names (docs/configuration.md, "Renamed settings"): +ecobot-mcp's are MCP_..., the bot's BOT_..., the shared ones unprefixed. Values, comments, blank lines and order are kept. + + sudo python3 scripts/migrate_env.py /etc/ecobot.env # show what would change (secrets masked); changes nothing + sudo python3 scripts/migrate_env.py /etc/ecobot.env --write # change it, after a backup beside it (same owner and mode) + +The old names still work (with a warning at start), so this is a tidy-up, not a must. It reads the renames from lib/config.py's text +(no import: any Python 3.9 or newer, no packages), so it works in a Docker install too. It can be run again: a renamed file is left +alone. It stops, changing nothing, where it can't tell what you meant: an old and a new name both set to different values. + +Beyond the plain renames: + - the bot's retired token, WEATHER_MCP_TOKEN, goes into AUTH_TOKENS (the shared list, was MCP_SERVICE_TOKENS) as its first token, + the one the bot sends; dropped if it is already there; + - the old container's name, ecobot-service, in a URL or an allowed host becomes ecobot-mcp's. +""" + +import argparse +import difflib +import os +import re +import shutil +import sys +import tempfile +from datetime import datetime +from pathlib import Path + +CONFIG = Path(__file__).resolve().parent.parent / "lib" / "config.py" +RETIRED_TOKEN, TOKENS = "WEATHER_MCP_TOKEN", "AUTH_TOKENS" +OLD_HOST, NEW_HOST = "ecobot-service", "ecobot-mcp" +SECRET = re.compile(r"TOKEN|KEY|SECRET|PASSWORD") +LINE = re.compile(r"^(\s*(?:export\s+)?)([A-Za-z_][A-Za-z0-9_]*)(\s*=\s*)(.*?)\s*$") + + +def renames(config: Path = CONFIG) -> dict[str, str]: + """{old name: new name}, from lib/config.py's _setting("NEW", ..., old="OLD") calls.""" + text = config.read_text() + found = dict((old, new) for new, old in re.findall(r'_setting\(\s*"([A-Z0-9_]+)"[^\n]*?old="([A-Z0-9_]+)"', text)) + if not found: + raise SystemExit(f"No renamed settings found in {config}: is this the ecobot checkout?") + return found + + +def unquoted(value: str) -> tuple[str, str]: + """(the value without its quotes, the quote it had).""" + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + return value[1:-1], value[0] + return value, "" + + +def migrate(lines: list[str], names: dict[str, str]) -> tuple[list[str], list[str]]: + """(the file's lines renamed, notes on what changed). SystemExit on a conflict.""" + parsed = [LINE.match(line.rstrip("\n")) for line in lines] + values: dict[str, str] = {} + for m in parsed: + if m and not m.group(2).startswith("#"): + values[m.group(2)] = unquoted(m.group(4))[0] + conflicts = [f"{old} and {new}" for old, new in names.items() + if old in values and new in values and values[old] != values[new]] + if conflicts: + raise SystemExit("Both an old and a new name are set, to different values (keep one, then run this again): " + "; ".join(conflicts)) + notes, out = [], [] + token = values.get(RETIRED_TOKEN, "") + tokens_at = next((i for i, m in enumerate(parsed) if m and names.get(m.group(2), m.group(2)) == TOKENS), None) + for i, (line, m) in enumerate(zip(lines, parsed)): + if not m: + out.append(line) + continue + lead, key, eq, raw = m.groups() + value, quote = unquoted(raw) + end = "\n" if line.endswith("\n") else "" + if key == RETIRED_TOKEN: + if tokens_at is None: # (no list yet: this becomes it) + out.append(f"{lead}{TOKENS}{eq}{raw}{end}") + notes.append(f"{RETIRED_TOKEN} -> {TOKENS}") + else: + notes.append(f"{RETIRED_TOKEN} removed: its token is the first of {TOKENS}, the one the bot sends") + continue + new = names.get(key) + if new and new in values: # (the new one is there already, with the same value: the old line goes) + notes.append(f"{key} removed: {new} is already set to the same value") + continue + name = new or key + if new: + notes.append(f"{key} -> {new}") + if name == TOKENS and token: + listed = [t.strip() for t in value.split(",") if t.strip()] + value = ",".join([token, *[t for t in listed if t != token]]) + if listed[:1] != [token]: + notes.append(f"{TOKENS}: {RETIRED_TOKEN}'s token put first, the one the bot sends") + if OLD_HOST in value and name in ("BOT_MCP_URL", "MCP_ALLOWED_HOSTS"): + value = value.replace(OLD_HOST, NEW_HOST) + notes.append(f"{name}: {OLD_HOST} -> {NEW_HOST} (the container's new name)") + out.append(f"{lead}{name}{eq}{quote}{value}{quote}{end}") + return out, notes + + +def masked(line: str) -> str: + m = LINE.match(line.rstrip("\n")) + if m and SECRET.search(m.group(2)) and m.group(4): + return f"{m.group(1)}{m.group(2)}{m.group(3)}****" + return line.rstrip("\n") + + +def write(path: Path, lines: list[str]) -> Path: + """The file replaced in one step, with its owner and mode; the old one kept beside it first. Returns the backup's path.""" + backup = path.with_name(f"{path.name}.bak-{datetime.now():%Y%m%d-%H%M%S}") + shutil.copy2(path, backup) + st = path.stat() + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") + try: + with os.fdopen(fd, "w") as f: + f.writelines(lines) + os.chmod(tmp, st.st_mode & 0o7777) + try: + os.chown(tmp, st.st_uid, st.st_gid) + except PermissionError: + pass # (not root: it is then the caller's own file) + os.replace(tmp, path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + return backup + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("path", type=Path, help="the environment file, e.g. /etc/ecobot.env") + ap.add_argument("--write", action="store_true", help="change the file (a backup is kept beside it); without it, only show") + args = ap.parse_args(argv) + lines = args.path.read_text().splitlines(keepends=True) + new, notes = migrate(lines, renames()) + if new == lines: + print(f"{args.path}: nothing to rename") + return 0 + for note in notes: + print(f" {note}") + print() + old_set, new_set = [masked(l) for l in lines], [masked(l) for l in new] + sys.stdout.writelines(l + "\n" for l in difflib.unified_diff(old_set, new_set, str(args.path), f"{args.path} (renamed)", lineterm="")) + if not args.write: + print("\nNothing changed. Run again with --write to change the file.") + return 0 + backup = write(args.path, new) + print(f"\nChanged {args.path}; the old file is {backup}. Restart ecobot-mcp and the bot to use it.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_migrate_env.py b/tests/test_migrate_env.py new file mode 100644 index 00000000..cda9a604 --- /dev/null +++ b/tests/test_migrate_env.py @@ -0,0 +1,74 @@ +"""scripts/migrate_env.py: an environment file's settings renamed to their new names, values, comments and order kept.""" + +import os +import stat +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) +import migrate_env # noqa: E402 + +from lib.config import Config # noqa: E402 +from dataclasses import fields # noqa: E402 + +OLD = """# keys +TELEGRAM_BOT_TOKEN=123:abc +export ECOWITT_API_KEY = "k e y" + +PLACE=Melbourne +WEATHER_MCP_URL=http://ecobot-service:8765/mcp +MCP_SERVICE_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-service +MCP_SERVICE_TOKENS=other,s3cret +WEATHER_MCP_TOKEN=s3cret +TZ=Australia/Melbourne +""" + + +def test_every_renamed_setting_is_found_from_the_configs_text(): + want = {f.metadata["old"]: f.metadata["env"] for f in fields(Config) if f.metadata.get("old")} + assert migrate_env.renames() == want + + +def test_a_file_is_renamed_keeping_values_comments_quotes_and_order_and_the_token_goes_first(): + out, notes = migrate_env.migrate(OLD.splitlines(keepends=True), migrate_env.renames()) + assert "".join(out) == """# keys +BOT_TELEGRAM_TOKEN=123:abc +export MCP_ECOWITT_API_KEY = "k e y" + +MCP_PLACE=Melbourne +BOT_MCP_URL=http://ecobot-mcp:8765/mcp +MCP_ALLOWED_HOSTS=127.0.0.1,localhost,ecobot-mcp +AUTH_TOKENS=s3cret,other +TZ=Australia/Melbourne +""" + assert any("put first" in n for n in notes) and any("WEATHER_MCP_TOKEN removed" in n for n in notes) + again, _ = migrate_env.migrate(out, migrate_env.renames()) + assert again == out # (run again: nothing changes) + + +def test_the_retired_token_alone_becomes_the_list(): + out, _ = migrate_env.migrate(["WEATHER_MCP_TOKEN=t0k\n"], migrate_env.renames()) + assert out == ["AUTH_TOKENS=t0k\n"] + + +def test_an_old_and_a_new_name_set_differently_stop_it_and_the_same_value_drops_the_old_line(): + with pytest.raises(SystemExit, match="PLACE and MCP_PLACE"): + migrate_env.migrate(["PLACE=a\n", "MCP_PLACE=b\n"], migrate_env.renames()) + out, _ = migrate_env.migrate(["PLACE=a\n", "MCP_PLACE=a\n"], migrate_env.renames()) + assert out == ["MCP_PLACE=a\n"] + + +def test_without_write_nothing_changes_and_secrets_are_masked_with_write_a_backup_keeps_mode(tmp_path, capsys): + env = tmp_path / "ecobot.env" + env.write_text(OLD) + os.chmod(env, 0o600) + assert migrate_env.main([str(env)]) == 0 + shown = capsys.readouterr().out + assert env.read_text() == OLD and "123:abc" not in shown and "s3cret" not in shown and "+BOT_TELEGRAM_TOKEN=****" in shown + assert migrate_env.main([str(env), "--write"]) == 0 + assert "BOT_TELEGRAM_TOKEN=123:abc" in env.read_text() and stat.S_IMODE(env.stat().st_mode) == 0o600 + backups = list(tmp_path.glob("ecobot.env.bak-*")) + assert len(backups) == 1 and backups[0].read_text() == OLD and stat.S_IMODE(backups[0].stat().st_mode) == 0o600 + assert migrate_env.main([str(env), "--write"]) == 0 and "nothing to rename" in capsys.readouterr().out From 36aaa4d8fe0ad67a9babde1b30262d2c85201f6d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 03:59:52 +0000 Subject: [PATCH 081/125] Bot: ecobot-mcp unreachable for a moment isn't a warning A start or restart of either takes a few seconds: failed attempts are logged at debug for QUIET_SECONDS (30 s), then warned about with how long it has been down, and the connection after says it was down that long. A refusal (token, Host, path) is still warned about at once. ecobot-mcp ending the listen (its restart) is info. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- lib/upstream.py | 23 ++++++++++++++++++++--- tests/test_mcp_listen.py | 24 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/lib/upstream.py b/lib/upstream.py index 17f611e9..6bbeb358 100644 --- a/lib/upstream.py +++ b/lib/upstream.py @@ -7,6 +7,7 @@ import asyncio import contextlib import logging +import time import mcp_types as types from mcp import Client @@ -18,6 +19,8 @@ READ_SECONDS = 45.0 # the HTTP read timeout: three of the server's 15-second pings, so a silently dead link is noticed CONNECT_WAIT = 10.0 # how long a request waits for ecobot-mcp to be reached before it is refused BACKOFF = (1, 2, 5, 10, 30) # seconds between attempts to reach it again, the last repeated +QUIET_SECONDS = 30.0 # how long it may be unreachable before that is a warning (a start or restart of either takes a few + # seconds); a refusal (a wrong token, Host or path) is one at once: it won't go away by itself REFUSED = {401: "401: the token the bot sends isn't one ecobot-mcp accepts: give both the same AUTH_TOKENS, or leave it unset in both " @@ -70,6 +73,8 @@ def __init__(self, target, token=None, on_event=None, on_discover=None, on_liste self.connected = asyncio.Event() self.attempts = 0 self.refused: dict = {} # the HTTP error ecobot-mcp last answered with + self.down_since: float | None = None # (monotonic) when it was last found unreachable, while it still is + self.warned = False # whether this time down has been warned about def _client(self) -> Client: token = self.token() if callable(self.token) else self.token # (a function: read again for each connection) @@ -89,9 +94,14 @@ async def run(self): await self.on_discover(discovered) self.client, self.attempts = client, 0 self.connected.set() - log.info("ecobot-mcp: connected to %s", self.target if isinstance(self.target, str) else "in-process") + target = self.target if isinstance(self.target, str) else "in-process" + if self.warned: + log.info("ecobot-mcp: connected to %s again, after %.0fs", target, time.monotonic() - self.down_since) + else: + log.info("ecobot-mcp: connected to %s", target) + self.down_since, self.warned = None, False await self._listen(client) - log.warning("ecobot-mcp ended the listen; connecting again") + log.info("ecobot-mcp ended the listen (a restart?); connecting again") except asyncio.CancelledError: raise except BaseException as e: # (a transport failure ends the whole client, as an exception group too) @@ -101,7 +111,14 @@ async def run(self): raise asyncio.CancelledError() from e # wrapped it (an exception group): stop all the same cause, status = _leaf(e), self.refused.get("status") why = (REFUSED.get(status, f"HTTP {status}") if status else f"{type(cause).__name__}: {cause}") - log.warning("ecobot-mcp at %s isn't reachable (%s); trying again", self.target, why) + now = time.monotonic() + self.down_since = self.down_since or now + if status or now - self.down_since >= QUIET_SECONDS: + log.warning("ecobot-mcp at %s isn't reachable (%s)%s; trying again", self.target, why, + f" for {now - self.down_since:.0f}s" if now - self.down_since >= 1 else "") + self.warned = True + else: + log.debug("ecobot-mcp at %s isn't reachable yet (%s); trying again", self.target, why) finally: self.client = None self.connected.clear() diff --git a/tests/test_mcp_listen.py b/tests/test_mcp_listen.py index 0cee84cc..006256a1 100644 --- a/tests/test_mcp_listen.py +++ b/tests/test_mcp_listen.py @@ -244,3 +244,27 @@ async def test_each_request_is_logged_with_who_asked_what_and_a_refusal_with_its assert any("refused: POST /mcp tools/list -> 401, no token, or one that isn't in AUTH_TOKENS" in line for line in lines), lines assert any("-> 421, its Host isn't in MCP_ALLOWED_HOSTS (Host 192.168.1.208:8765)" in line for line in lines), lines assert not any(TOKENS["bot"] in line or "wrong" in line for line in lines) + + +async def test_ecobot_mcp_down_for_a_moment_isnt_a_warning_but_down_for_longer_or_refusing_is(service, monkeypatch, caplog): + """A start or restart of either takes a few seconds: only QUIET_SECONDS of not reaching it is warned about, and the connection after + says how long it was down. A refusal (here the token) is warned about at once: it won't go away by itself.""" + caplog.set_level("DEBUG", logger="lib.upstream") + monkeypatch.setattr(upstream, "BACKOFF", (0.1,)) + monkeypatch.setattr(upstream, "QUIET_SECONDS", 0.6) + port = free_port() + task = asyncio.create_task(Upstream(f"http://127.0.0.1:{port}/mcp", TOKENS["bot"]).run()) # (nothing listens there yet) + await asyncio.sleep(0.3) + warned = lambda: [r.getMessage() for r in caplog.records if r.levelname == "WARNING" and r.name == "lib.upstream"] + assert not warned() and "isn't reachable yet" in caplog.text + await asyncio.sleep(0.6) + assert warned() and "for 0s" not in warned()[0] + async with Serving(http_app(service, tokens=TOKENS.values()), port): + for _ in range(100): + if "again, after" in caplog.text: + break + await asyncio.sleep(0.05) + assert f"connected to http://127.0.0.1:{port}/mcp again, after" in caplog.text + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task From a2a0715d4949bbefc4fefc0be413fc91e219e38f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:05:10 +0000 Subject: [PATCH 082/125] Bot: no 'no token yet' warning at a start of both; said only when ecobot-mcp can't be reached and there is no token At a first start ecobot-mcp writes its token a moment after the bot first looks; the bot reads it again for each connection. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- ecobot.py | 21 +++++++++++++++------ tests/test_settings.py | 8 +++++--- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/ecobot.py b/ecobot.py index 4dbf80e0..a88f83e3 100644 --- a/ecobot.py +++ b/ecobot.py @@ -115,7 +115,7 @@ def apply(zone): def mcp_token(cfg: Config): """The token the bot sends ecobot-mcp: the first of AUTH_TOKENS; else the retired WEATHER_MCP_TOKEN, with a warning; else the one ecobot-mcp generated in the data folder they share, read again for each connection (a function: ecobot-mcp may write it after the - bot starts), with a warning when it isn't there yet. Never logged: only where it is.""" + bot starts: at a start of both, the bot may look before ecobot-mcp has written it). Never logged: only where it is.""" if cfg.auth_tokens: if cfg.retired_mcp_token: log.warning("%s is retired and ignored: the bot sends the first of AUTH_TOKENS", RETIRED_TOKEN) @@ -125,19 +125,27 @@ def mcp_token(cfg: Config): "if it isn't there already)", RETIRED_TOKEN) return cfg.retired_mcp_token folder = cfg.state_path.parent - if auth_token.read(folder) is None: - log.warning("AUTH_TOKENS is not set and there is no token at %s (yet): ecobot-mcp writes it there at its first start, on the same " - "data folder. Until it can be read the bot sends none and is refused; set AUTH_TOKENS (the same in both) if ecobot-mcp " - "keeps another folder", auth_token.path(folder)) return lambda: auth_token.read(folder) +def no_token_yet(cfg: Config, token) -> bool: + """Said (a warning) when ecobot-mcp couldn't be reached in time and the bot has no token to send it: the generated one isn't in the + data folder. Only then: at a start of both, the file can appear a moment after the bot first looks.""" + if not callable(token) or token() is not None: + return False + log.warning("AUTH_TOKENS is not set and there is no token at %s: ecobot-mcp writes it there at its first start, on the same data " + "folder. Until it can be read the bot sends none and is refused; set AUTH_TOKENS (the same in both) if ecobot-mcp keeps " + "another folder", auth_token.path(cfg.state_path.parent)) + return True + + async def connect(cfg: Config, stack: contextlib.AsyncExitStack, state: AlertState) -> tuple[RemoteWeather, Config]: """The bot as ecobot-mcp's client (BOT_MCP_URL): the supervisor started (closed by `stack`), the first connection waited for up to STARTUP_WAIT seconds; the settings in the station's time zone once it has been read, else in the one last read (kept in bot_state.json), else in TZ's, with a warning. Read later, it is followed then (follow_zone).""" kept = _zone(state.zone) - weather = RemoteWeather(cfg.mcp_url, mcp_token(cfg), kept or cfg.tz) + token = mcp_token(cfg) + weather = RemoteWeather(cfg.mcp_url, token, kept or cfg.tz) supervisor = asyncio.create_task(weather.run()) async def stop(): @@ -148,6 +156,7 @@ async def stop(): try: await asyncio.wait_for(weather.listening.wait(), STARTUP_WAIT) except TimeoutError: + no_token_yet(cfg, token) log.warning("ecobot-mcp at %s isn't reachable yet: questions are told so until it is (the time zone is %s, %s, " "until its station is read)", cfg.mcp_url, "the station's last read" if kept else "TZ's", weather.tz) if str(weather.tz) != str(cfg.tz): diff --git a/tests/test_settings.py b/tests/test_settings.py index c737f158..100c9a1f 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -128,9 +128,11 @@ def test_the_bot_sends_the_first_of_auth_tokens_else_the_retired_one_else_the_ge assert ecobot.mcp_token(config(tmp_path, retired_mcp_token="r3tired")) == "r3tired" assert "move it into AUTH_TOKENS" in caplog.text and "r3tired" not in caplog.text caplog.clear() - read = ecobot.mcp_token(config(tmp_path)) # ecobot-mcp hasn't written its token yet: said, and read again - assert callable(read) and read() is None and f"there is no token at {tmp_path / 'auth_token'}" in caplog.text + read = ecobot.mcp_token(config(tmp_path)) # ecobot-mcp hasn't written its token yet: read again later, + assert callable(read) and read() is None and "no token" not in caplog.text # and not said at once (it may be a moment away) + assert ecobot.no_token_yet(config(tmp_path), read) and f"there is no token at {tmp_path / 'auth_token'}" in caplog.text # said + caplog.clear() # when ecobot-mcp can't be reached token = auth_token.ensure(tmp_path) - assert read() == token + assert read() == token and not ecobot.no_token_yet(config(tmp_path), read) and "no token" not in caplog.text caplog.clear() assert ecobot.mcp_token(config(tmp_path))() == token and "no token" not in caplog.text From 4eaed050acbc714cc11f5d6ae32ae2166eef3ffa Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:05:33 +0000 Subject: [PATCH 083/125] Plan: the bot stays as a slim client (step 6) everywhere the plan said it would be retired Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/ecobot-mcp.md | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index ef0cf1cd..ee630c49 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -8,16 +8,16 @@ The plan for turning this repository into a weather and air-quality service that any MCP client can use: the readings file, the syncers that fill it, and an MCP server over them. Claude Desktop, Claude Code, ChatGPT, Open WebUI or anyone's bot asks it questions -and gets answers it can pass on. Today's Telegram bot becomes the service's first client while the tools move over, and is retired -once another client does its job. Irrigation becomes a second MCP server in its own repository. This is a design and a sequence of +and gets answers it can pass on. Today's Telegram bot becomes ecobot-mcp's first client while the tools move over, and stays as a +slim client (step 6): Telegram's chats, buttons and alerts, with everything else from ecobot-mcp. Irrigation becomes a second MCP server in its own repository. This is a design and a sequence of steps, each shipped on its own, in the manner of [storage-plan.md](storage-plan.md). Decided: - **The end state is the service alone.** No bot of ours; nothing in the interface may assume one. - **Charts are data.** Tools return a chart's data; the client draws it (or its model does). - **Alerts are decided by the service and published over MCP only**, as a log clients listen to. -- **This repository becomes the service**, keeping its history; the bot keeps working as a client until it is retired, then its code - goes. Irrigation moves to its own repository and server. +- **This repository becomes ecobot-mcp**, keeping its history; the bot stays as a slim client of it (step 6), its in-process code + gone. Irrigation moves to its own repository and server. - **Separate hosts** are possible: the service runs near Home Assistant and the sensors; clients connect over the network. ## 1. Why @@ -339,14 +339,14 @@ every 60 seconds, particulates every 30 minutes and only then, since its two-rea pollen the end of its day, a forecast the day it is about), and `ecobot://alerts?since=` returns only unexpired alerts unless asked. A client back after a gap sends what is still true, never the morning's rain as news. - **Delivery is the client's.** A client listens, reads `ecobot://alerts?since=`, and sends each alert to whoever - it serves. Our bot does this for its subscribed chats until it is retired. + it serves. Our bot does this for its subscribed chats. - **The forecast alert is station-wide:** for today and tomorrow, it compares each new forecast with the first one fetched after 6am that day (its baseline), alerts when the maximum moves by more than 2°C or the chance of rain rises past 50% (or falls from there to 30% or less: the band keeps a chance hovering around 50% from alerting each way on every refresh), and makes the forecast it alerted on the new baseline. Its text says what changed ("The forecast for tomorrow has changed: was 24°C and dry, now 19°C with rain likely"), not "since I sent it", which only the bot could say. -- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open; once the bot is retired, alerts reach - no one unless a client that listens is running (a short script with the SDK, or Home Assistant). Section 8. +- **Only listening clients get alerts.** Most chat clients don't keep an MCP listen stream open: the bot is the client that listens + and delivers them (a short script with the SDK, or Home Assistant, could too). Section 8. ### 3.7 Charts @@ -441,7 +441,7 @@ station names one), `DATA_DIR`, the alert settings (cooldowns, quiet hours, thre `AUTH_TOKENS`, `MCP_BIND`, `MCP_ALLOWED_HOSTS`. The irrigation server: `IRRIGATION_*` (Tuya), `BOT_MCP_URL`, a token, its own `AUTH_TOKENS`. -## 4. The bot until it is retired +## 4. The bot (as it was before step 6) The bot is the service's first client, and the measure of each step: it keeps answering in Telegram while its insides move to the service. Beyond what the steps need, it gets no new features. While it lives it: @@ -457,9 +457,8 @@ service. Beyond what the steps need, it gets no new features. While it lives it: - keeps per-chat state: subscriptions, admins, and each chart's `drawn_by` behind its period buttons (a press replays it with a new `period`). -It is retired when a replacement does what you use it for: another client for questions (any MCP-capable assistant), and, for alerts, -a client that listens. Its code is then deleted from this repository: `lib/bot.py`, `lib/llm.py`, `lib/prompt.py`, `lib/intent.py`, -`lib/report.py`, the menus, the renderer and its tests and golden images. +The plan was to retire it once another client did its job; in November 2026 it was decided to keep it, slimmed down to a client of +ecobot-mcp alone: step 6 says what it keeps and what goes. ## 5. What does not change @@ -717,8 +716,8 @@ Each step ships on its own, with the tests and evals green and the bot working t ## 8. Risks -- **Alerts reach only listening clients.** With alerts over MCP only (3.6), once the bot is retired nobody gets them unless a client - that listens is running. Plan that client before step 6, or accept no alerts. +- **Alerts reach only listening clients.** With alerts over MCP only (3.6), nobody gets them unless a client that listens is running: + the bot, which stays (step 6), or another. - **Charts only where a client can draw.** A client that neither draws the chart data nor lets its model draw gets the figures without a picture. - **Models other than ours.** A client's model may be weaker, or tuned differently, than the one the evals were built on; some clients From 1acadf313b2975cf12c04a8cf66a0361d80a710c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 04:22:14 +0000 Subject: [PATCH 084/125] Plan: irrigation on its own is step 7 (was 5b, then 6d) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/ecobot-mcp.md | 10 +++++----- ecobot.py | 2 +- lib/weather.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index ee630c49..695a2687 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -618,7 +618,7 @@ Each step ships on its own, with the tests and evals green and the bot working t (`station_zone`), and a start while the service can't be reached runs in the zone last read, `TZ` only before any. A question's call waits up to 5 seconds while the client is being built again, a background one not at all; a question while the service can't be reached is answered that it can't (`bot.SERVICE_DOWN`), without the model. The bot's `warm_up` is its charts drawn ahead, every 5 minutes, quietly nothing while the - service is away; the poke of the sources is gone (there are none). Irrigation stays in the bot until 5b: its daily check reads the + service is away; the poke of the sources is gone (there are none). Irrigation stays in the bot until step 7: its daily check reads the measured rain from `summary {readings: ["rain"], period: "last 24 hours"}` (`ServiceRain`) and the forecast from `ecobot://forecast` (`ServiceForecast`, read again at each check and on each `ResourceUpdated`; the one last read stands when the service can't be reached). Tests: `tests/test_bot_remote.py` (the bot against the real server, in memory and under uvicorn: a question answered with @@ -637,8 +637,7 @@ Each step ships on its own, with the tests and evals green and the bot working t drawn by the bot. Tests: `tests/test_mcp_server.py` (in memory and under uvicorn: off unchanged, the URL's `?charts=png`, the per-call override both ways, without Pillow, no Pillow imported by the server), `tests/test_bot_remote.py` (the service's PNG byte for byte the bot's own, for a call and an alert's chart). - - **Left: 5b**, the irrigation server in its own repository (3.9: its tools, the watchdog and the daily check, `irrigation://alerts`), - the bot connecting to both and `lib/irrigation` going from here; and `show_request` and `report_inputs` as MCP clients. + - **Left:** the irrigation server, now step 7; and `show_request` and `report_inputs` as MCP clients. 6. **The slim bot** (decided November 2026, in place of retiring it: section 4 describes the bot as it was). The Telegram bot is kept, but only as a thin client of ecobot-mcp: it does what only a Telegram bot can do (chats, buttons, pushing alerts), and everything about the weather, the air, the alerts' rules and the pictures comes from ecobot-mcp over MCP. It never opens the readings file and draws nothing. Sub-steps, each its own change with the checks green: @@ -662,8 +661,6 @@ Each step ships on its own, with the tests and evals green and the bot working t - Without `BOT_OPENROUTER_API_KEY` the bot answers the buttons and sends alerts; a typed question gets one line saying the model isn't set up (the no-model fallbacks go). - The test-only oracles from step 3 (`tests/old_tools.py`, `tests/report_words.py`) are deleted. - - **6d. Irrigation** is step 5b's: its own repository and MCP server, which the bot connects to as a second server - (`BOT_IRRIGATION_MCP_URL`), listening for its alerts the same way. **What the bot keeps:** - **Telegram:** who may use it (`BOT_ADMIN_ONLY`, `BOT_ADMIN_CHAT_IDS`, group admins), private and group chats, the keyboard, the @@ -685,6 +682,9 @@ Each step ships on its own, with the tests and evals green and the bot working t **Risks:** a typed chart request ("rain chart 7d") now costs a model call and a second or two, where it was instant; a keyboard button's first press waits for ecobot-mcp; the bot does nothing without ecobot-mcp (it says so, as today). +7. **Irrigation on its own** (was 5b): the irrigation server in its own repository and MCP server (3.9: its tools, the watchdog and the + daily check, `irrigation://alerts`). The bot connects to it as a second server (`BOT_IRRIGATION_MCP_URL`) and listens for its alerts + the same way; `lib/irrigation` and the bot's `BOT_TUYA_*` and `BOT_IRRIGATION_CHECK_HOUR` go from here. ## 7. Testing diff --git a/ecobot.py b/ecobot.py index a88f83e3..aa8e8dd9 100644 --- a/ecobot.py +++ b/ecobot.py @@ -60,7 +60,7 @@ def start_alerts(cfg: Config, bot: Bot, notify: Notifier, tasks: Tasks, core: Co """In-process (`core`): hook up ecobot-mcp's alert rules over every source that started (core.start_alerts: they append to the alert log); the weather rules start in warm_up, once the station has been read. Remote (`weather`): the rules are ecobot-mcp's, and its alert log is read over MCP. Either way the bot delivers from the log (AlertDelivery), and runs the irrigation controller's check - and watchdog (sent by the bot itself until it is a server of its own, step 5b; remote, its rain and forecast are asked of + and watchdog (sent by the bot itself until it is a server of its own, step 7; remote, its rain and forecast are asked of ecobot-mcp). Returns the alert types now running here, the rules (None when remote), and what keeps the time zone (the delivery, the irrigation check: follow_zone).""" if core is not None: diff --git a/lib/weather.py b/lib/weather.py index 3b3611aa..6e34993f 100644 --- a/lib/weather.py +++ b/lib/weather.py @@ -21,7 +21,7 @@ (`chart_dark`: its DARKMODE, so its image cache's theme holds). A service that sends no image (no Pillow there) has its chart drawn here. -For the irrigation check while it is still the bot's (step 5b moves it to its own server): `ServiceRain` (the measured rain, from +For the irrigation check while it is still the bot's (step 7 moves it to its own server): `ServiceRain` (the measured rain, from `summary {readings: ["rain"], period: "last 24 hours"}`) and `ServiceForecast` (ecobot://forecast, the last read kept when the service can't be reached), docs 3.9.""" From 7a2330ec9f541478b56b8723e8647f0744fca0c3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 05:54:03 +0000 Subject: [PATCH 085/125] Prompts named so each can be a chat command: weather -> weather_chart, rain -> rainfall; plan step 6c: the bot offers them as Telegram commands The bot's own /weather and /rain are the keyboard's instant charts; a test keeps prompt names Telegram-valid and clear of them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- docs/ecobot-mcp.md | 19 ++++++++++++++----- lib/mcp_server.py | 9 +++++---- tests/test_mcp_server.py | 16 +++++++++++++--- 3 files changed, 32 insertions(+), 12 deletions(-) diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index 695a2687..8e24f184 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -319,9 +319,10 @@ the resource list gives. Only clients on the 2026-07-28 revision can listen; old ### 3.5 Prompts The service also offers MCP prompts, the templates clients show as commands or buttons, each a question in words with its period as an -argument: `now`, `report`, `will_it_rain`, `weather` (every reading, a panel each), `chart` (a reading and a period), `rain`, `air`. -They hold no logic: the client's model answers them with the tools, as any question. They replace the bot's keyboard and `/commands` -for clients that show prompts. +argument: `now`, `report`, `will_it_rain`, `weather_chart` (every reading, a panel each), `chart` (a reading and a period), +`rainfall`, `air`. They hold no logic: the client's model answers them with the tools, as any question. Their names are chat +commands too (step 6c: the bot offers each as a Telegram `/command`), so they keep to Telegram's form (lowercase letters, digits and +`_`, at most 32) and none takes the name of one of the bot's own commands (`/rain`, `/weather`, …: the keyboard's instant charts). ### 3.6 Alerts @@ -653,8 +654,16 @@ Each step ships on its own, with the tests and evals green and the bot working t - **6c. Less code in the bot.** - Typed shortcuts go: anything typed goes to the model (`lib/intent.py`'s pattern matching, `chart_call`, the dashboard and report words). Buttons stay instant because each is a fixed call. - - `/report` becomes an ecobot-mcp prompt (`report`): the bot asks the model with it, and the model calls the tools. The - report written in code (`lib/report.py`, `lib/report_menu.py`) is deleted. + - **ecobot-mcp's prompts become Telegram commands.** On connecting, the bot reads the prompt list and sets Telegram's command + menu (`setMyCommands`) to its own commands (`/start`, `/alerts`, `/usage`, `/keyboard`, `/reset`, and the keyboard's + instant charts: `/rain`, `/weather`, `/temperature`, …) and one command per prompt, with its description; again whenever + ecobot-mcp says its prompts changed (`PromptsListChanged`, which the bot already listens for). `/ ` gets the + prompt with the words after the command as its arguments, in order, the last taking the rest (`/chart rain 7d` is `chart` + with `reading` "rain" and `period` "7d"; `/rainfall last week` is `rainfall` with `period` "last week"; none: the + prompt's defaults), and asks the model with it, as a typed question. A prompt whose + name isn't a valid Telegram command, or is one of the bot's own, is left out with a warning. So a prompt added to ecobot-mcp + appears in Telegram, as in any other client, with no change to the bot. + - `/report` is the `report` prompt: the report written in code (`lib/report.py`, `lib/report_menu.py`) is deleted. - The charts drawn ahead every 5 minutes go (`draw_buttons_ahead`). Kept: after a chart is sent, its other periods are fetched (and, with `BOT_TELEGRAM_PRELOAD_CHAT`, uploaded) in the background, so its period buttons answer at once. A keyboard button's first press waits for ecobot-mcp, about half a second. diff --git a/lib/mcp_server.py b/lib/mcp_server.py index 7530244e..b184f977 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -99,20 +99,21 @@ # ---------- prompts (3.5) ---------- PERIOD = types.PromptArgument(name="period", description="The period in your own words (\"this week\", \"last 3 months\", \"yesterday\")", required=False) -PROMPTS = { # name: (description, arguments, the question: a format string over the arguments, with their defaults) +PROMPTS = { # name: (description, arguments, the question: a format string over the arguments, with their defaults). A name is also a + # chat command (Telegram's: lowercase, digits and _, at most 32), so none takes a bot command's name (lib/templates.COMMANDS) "now": ("The weather and the air now.", [], "How is it outside now?"), "report": ("A report: the readings now, today's forecast and the pollen.", [], "Give me a report: the readings now, today's forecast and the pollen."), "will_it_rain": ("Will it rain in the next few hours: the station's read and the forecast.", [], "Will it rain in the next few hours?"), - "weather": ("Every reading of the weather station over a period, a panel each.", [PERIOD], + "weather_chart": ("Every reading of the weather station over a period, a panel each.", [PERIOD], "Chart every weather reading, a panel each, over {period}."), "chart": ("A chart of a reading over a period.", [types.PromptArgument(name="reading", description="The reading (\"temperature\", \"pressure\", \"pm2.5\")", required=True), PERIOD], "Chart {reading} over {period}."), - "rain": ("How much rain fell over a period, and when.", [PERIOD], "How much rain fell over {period}?"), + "rainfall": ("How much rain fell over a period, and when.", [PERIOD], "How much rain fell over {period}?"), "air": ("The air quality, now or over a period.", [PERIOD], "How was the air quality over {period}?"), } -PROMPT_DEFAULTS = {"weather": {"period": "the last 7 days"}, "chart": {"period": "the last 24 hours"}, "rain": {"period": "today"}} +PROMPT_DEFAULTS = {"weather_chart": {"period": "the last 7 days"}, "chart": {"period": "the last 24 hours"}, "rainfall": {"period": "today"}} WITHOUT_ARGUMENTS = {"air": "How is the air quality now?"} # the question when no argument is sent diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index a707f097..cf75b6a2 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -251,16 +251,16 @@ async def test_a_new_alert_is_published_to_a_listener(tmp_path): async def test_the_prompts_are_questions_in_words_with_their_period_an_argument(world): async with Client(world.server) as client: listed = {p.name: p for p in (await client.list_prompts()).prompts} - assert list(listed) == ["now", "report", "will_it_rain", "weather", "chart", "rain", "air"] == list(PROMPTS) + assert list(listed) == ["now", "report", "will_it_rain", "weather_chart", "chart", "rainfall", "air"] == list(PROMPTS) assert [a.name for a in listed["chart"].arguments] == ["reading", "period"] and listed["chart"].arguments[0].required got = await client.get_prompt("chart", {"reading": "pressure", "period": "this week"}) assert got.messages[0].role == "user" and got.messages[0].content.text == "Chart pressure over this week." with pytest.raises(MCPError, match="needs reading"): await client.get_prompt("chart", {}) - assert prompt("rain").messages[0].content.text == "How much rain fell over today?" + assert prompt("rainfall").messages[0].content.text == "How much rain fell over today?" assert prompt("air").messages[0].content.text == "How is the air quality now?" assert prompt("air", {"period": "last week"}).messages[0].content.text == "How was the air quality over last week?" - assert prompt("weather").messages[0].content.text == "Chart every weather reading, a panel each, over the last 7 days." + assert prompt("weather_chart").messages[0].content.text == "Chart every weather reading, a panel each, over the last 7 days." with pytest.raises(MCPError, match="No prompt"): prompt("lightning") @@ -429,3 +429,13 @@ async def test_over_http_the_connections_url_asks_for_images_and_a_call_can_say_ for got in (without, plain): assert [b.type for b in got.content] == ["text"] and not ours(got) assert got.content[0].text == await world.service["summary"].call(CHARTED) + + +def test_every_prompt_name_is_a_telegram_command_and_none_is_one_of_the_bots_own(): + """The bot offers each prompt as a /command (docs/ecobot-mcp.md step 6c): Telegram's form, and no clash with the keyboard's.""" + import re + from lib import templates + from lib.mcp_server import PROMPTS + for name in PROMPTS: + assert re.fullmatch(r"[a-z0-9_]{1,32}", name), name + assert not set(PROMPTS) & (set(templates.COMMANDS) - {"report"}) # (/report becomes the report prompt, step 6c) From 819e3ca666f631e0515efeebed56f54c2af5b4a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 08:09:38 +0000 Subject: [PATCH 086/125] The gauges as a live web page: /dashboard beside /mcp in ecobot-mcp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /dashboard: a self-contained HTML5 page (no framework, nothing fetched from elsewhere) drawing the tiles as inline SVG with HTML titles and tables, in the PNG's colours and sizes; a script picks the columns that make the tiles largest with all of them on screen (480:575 tiles), re-laid out on resize or rotation, scrolling below a readable size. - GET /dashboard/data: gauge_sheet's tiles from current with context, as JSON, with as_of and the look. - GET /dashboard/events: Server-Sent Events, one when the gauges' readings change in the kept live reading (the server's change detection for ecobot://now/weather; nothing fetched for it); the page refetches and redraws in place, every 60 s regardless, and shows "updated hh:mm" / "reconnecting…". The streams end as uvicorn shuts down, so it doesn't wait on them. - Read-only: no token and no Host check for these routes; /mcp keeps both. MCP_DASHBOARD (on by default; off: 404). The request log logs them, a stream once as it opens. - lib/gauge_look.py: the gauges' colours and sizes, out of lib/gauges.py, shared by the PNG and the page (Pillow still not imported by ecobot-mcp until an image is asked for). - Tests under uvicorn, and the page in Chromium (Playwright, through node) at phone, tablet and desktop sizes; README, docs/configuration.md and docs/ecobot-mcp.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WBwHofjb1g9onaYRdLZMbf --- README.md | 14 ++ docs/configuration.md | 3 +- docs/ecobot-mcp.md | 5 + ecobot_mcp/__main__.py | 21 ++- lib/config.py | 1 + lib/gauge_look.py | 47 ++++++ lib/gauges.py | 26 +-- lib/mcp_server.py | 17 +- lib/web_dashboard.html | 280 +++++++++++++++++++++++++++++++++ lib/web_dashboard.py | 131 +++++++++++++++ tests/test_settings.py | 2 +- tests/test_web_dashboard.py | 221 ++++++++++++++++++++++++++ tests/web_dashboard_browser.js | 66 ++++++++ 13 files changed, 803 insertions(+), 31 deletions(-) create mode 100644 lib/gauge_look.py create mode 100644 lib/web_dashboard.html create mode 100644 lib/web_dashboard.py create mode 100644 tests/test_web_dashboard.py create mode 100644 tests/web_dashboard_browser.js diff --git a/README.md b/README.md index ea73f242..a6421a3b 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ A Telegram bot for your Ecowitt weather station and AirGradient air sensor. Ask - [Docker](#docker) - [Docker logging](#docker-logging) - [Docker networking](#docker-networking) +- [Web dashboard](#web-dashboard) - [Upgrading](#upgrading) - [Renamed settings](#renamed-settings) - [systemd](#systemd-1) @@ -30,6 +31,7 @@ A Telegram bot for your Ecowitt weather station and AirGradient air sensor. Ask - **Ask in plain words:** "how hot is it?", "will it rain?", "how many days was UV over 9 this year?" - **Charts on request:** any reading, with 1D, 7D, 1M, 3M and 1Y buttons to change the period, or two readings on one chart with a scale each. - **One-tap report:** `/report` shows weather, air quality, pollen and the forecast in one message, under gauges of the temperature, humidity and rain. `/dashboard` draws the station's gauges with the day's, month's and year's highs and lows. +- **Web dashboard:** the same gauges as a live page in any browser on your network, laid out to fill a phone, a tablet or a screen. - **Alerts:** rain, strong gusts, high UV, unhealthy air and temperature changes. Silent unless you turn sound on. - **Irrigation:** water or pause a Tuya controller from the chat, and have it paused automatically when rain has fallen or is forecast. - **Cheap to run:** most answers are worked out by the bot itself, and the AI model is only called when it's needed. @@ -195,6 +197,18 @@ echo "COMPOSE_FILE=compose.yaml:compose.host-network.yaml" | sudo tee -a /opt/ec `/opt/ecobot/.env` holds one `COMPOSE_FILE=` line: to use more than one of these files, list them all in it, separated by `:`. +## Web dashboard + +ecobot-mcp also serves the station's gauges as a live web page at `/dashboard` on its port, e.g. `http://deb1:8765/dashboard` +(your machine's name or IP address). It looks like `/dashboard` in the chat, drawn by the browser (plain HTML5, nothing fetched from +the internet), and fits every tile on the screen in portrait or landscape where they stay readable (on a phone it scrolls). It +updates by itself when a new reading arrives, and says "reconnecting…" while ecobot-mcp is away. + +It is read-only (the weather readings, nothing else), so it is open to anyone on your network: no token, and any name or address +in the URL (`MCP_ALLOWED_HOSTS` is only for `/mcp`, which keeps its token). ecobot-mcp has to listen beyond the machine itself: +Docker publishes port 8765 already; under systemd set `MCP_BIND=0.0.0.0:8765`. It is plain HTTP: keep it on your own network. To +turn it off, set `MCP_DASHBOARD=off`. + ## Upgrading Your keys in `/etc/ecobot.env` and the bot's data (`/var/lib/private/ecobot`) are kept; settings with an old name still work diff --git a/docs/configuration.md b/docs/configuration.md index 7094f907..1ef3b7bd 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -67,8 +67,9 @@ At least one of Ecowitt (cloud or Home Assistant) or AirGradient (cloud, local o |---|---|---| | `MCP_BIND` | `127.0.0.1:8765` | `host:port` it listens on (`[::1]:8765` for IPv6; Docker sets `0.0.0.0:8765`). Serve it to other machines through TLS (a reverse proxy such as Caddy) | | `MCP_ALLOWED_HOSTS` | none | More `Host` names it answers, besides `127.0.0.1`, `localhost` and its own hostname (in Docker, `ecobot-mcp`), any port unless one is given (`weather.lan`, `192.168.1.5:8765`); any other is refused (421), against DNS rebinding. Add the name or IP address a proxy or a LAN client uses | +| `MCP_DASHBOARD` | `on` | The gauges' live web page at `/dashboard` beside `/mcp` (`http://deb1:8765/dashboard`): read-only, so it needs no token and answers any `Host` (open it by the machine's name or address from the LAN); `/mcp` keeps both checks. `off`: `/dashboard`, `/dashboard/data` and `/dashboard/events` answer 404 | -Every request needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once. +Every request to `/mcp` needs a token (`AUTH_TOKENS`, below). Chart images are not a setting of ecobot-mcp but of each client: a client whose MCP URL ends `?charts=png` (`http://127.0.0.1:8765/mcp?charts=png`) gets each chart as a PNG beside the figures, drawn in `DARKMODE`'s theme; a call's request `_meta` `chart_image` (`"png"` or `"none"`) overrides its connection's ([ecobot-mcp.md](ecobot-mcp.md) 3.7). They need Pillow (`requirements-charts.txt`, in both Docker images): installed from `requirements-mcp.txt` alone ecobot-mcp answers with the charts' JSON and a note, and warns once. ## The bot's settings (`BOT_`) diff --git a/docs/ecobot-mcp.md b/docs/ecobot-mcp.md index 8e24f184..135ad1bb 100644 --- a/docs/ecobot-mcp.md +++ b/docs/ecobot-mcp.md @@ -648,6 +648,11 @@ Each step ships on its own, with the tests and evals green and the bot working t gives the model only the text (`for_model`, as today). The dashboard's gauges move to ecobot-mcp the same way: a tool or resource that returns the gauge sheet as a PNG, its figures as text. The bot then imports neither Pillow nor `lib/charts.py`, `lib/draw.py` or `lib/gauges.py`. + The gauges' live page is already ecobot-mcp's: `/dashboard` beside `/mcp` (`lib/web_dashboard.py`, `MCP_DASHBOARD`, on by + default) is a self-contained HTML5 page drawing the same tiles in the browser (inline SVG, `lib/gauge_look.py`'s colours and + sizes) from `/dashboard/data` (gauge_sheet's tiles from `current` with context) and redrawing them on each `/dashboard/events` + event (Server-Sent Events, on the gauges' readings changing in ecobot://now/weather's change detection). Read-only, so no token + and no Host check; `/mcp` keeps both. - **6b. Client only.** `BOT_MCP_URL` is required: the in-process mode (`LocalWeather`, the bot starting the sources, the syncers, the alert rules and the alert log itself) is deleted. Under systemd, `ecobot.service` wants and starts after `ecobot-mcp.service`; in Docker this is already the layout. The bot's image installs only its own packages (python-telegram-bot, openai, mcp, httpx). diff --git a/ecobot_mcp/__main__.py b/ecobot_mcp/__main__.py index d71d122b..70f7ef54 100644 --- a/ecobot_mcp/__main__.py +++ b/ecobot_mcp/__main__.py @@ -28,12 +28,23 @@ class Uvicorn(uvicorn.Server): """uvicorn's server, leaving SIGINT and SIGTERM to ecobot-mcp (which closes everything in order: uvicorn's own handling raises the - signal again once it has stopped, ending the process before the sources are closed).""" + signal again once it has stopped, ending the process before the sources are closed), and ending the dashboard's event streams as it + stops.""" @contextlib.contextmanager def capture_signals(self): yield + async def shutdown(self, sockets=None): + """uvicorn's graceful shutdown, the app's endless streams (the dashboard's events: `app.state.closing`) ended first, once no new + connection is accepted, so it doesn't wait on them.""" + for server in self.servers: + server.close() + closing = getattr(getattr(self.config.app, "state", None), "closing", None) + if closing is not None: + closing() + await super().shutdown(sockets) + def server_config(app, host: str, port: int) -> uvicorn.Config: """uvicorn's settings for the app: its lifespan on (the MCP session manager runs in it), its own access log off, and an open @@ -79,7 +90,8 @@ async def main(): stack.push_async_callback(source.warmer.stop) server = EcobotServer(core.ctx, core.alert_log, health=core.health.report, version=version()) hosts = tuple(dict.fromkeys(("127.0.0.1", "localhost", socket.gethostname(), *cfg.mcp_allowed_hosts))) # (its own name too: a container's hostname) - app = http_app(server, tokens=tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}") + app = http_app(server, tokens=tokens, allowed_hosts=hosts, issuer_url=f"http://{f'[{host}]' if ':' in host else host}:{port}", + dashboard=cfg.mcp_dashboard) core.log_startup() running = core.start_alerts() core.start_warmers() @@ -96,9 +108,12 @@ async def warm_up(): asyncio.get_running_loop().add_signal_handler(sig, stop.set) web = Uvicorn(server_config(app, host, port)) serving = asyncio.create_task(web.serve()) - log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", host if ":" not in host else f"[{host}]", port, + shown = host if ":" not in host else f"[{host}]" + log.info("MCP: http://%s:%d/mcp, %s; answering Host %s", shown, port, f"{len(tokens)} token(s) from AUTH_TOKENS" if cfg.auth_tokens else f"the token in {auth_token.path(cfg.state_path.parent)}", ", ".join(hosts)) + if cfg.mcp_dashboard: + log.info("Dashboard: http://%s:%d/dashboard (read-only, no token, any Host; MCP_DASHBOARD=off turns it off)", shown, port) waiting = asyncio.create_task(stop.wait()) await asyncio.wait({serving, waiting}, return_when=asyncio.FIRST_COMPLETED) server.listen.close() # (the listen streams end gracefully: their clients know to listen again) diff --git a/lib/config.py b/lib/config.py index b69fa712..d8e6eb1f 100644 --- a/lib/config.py +++ b/lib/config.py @@ -298,6 +298,7 @@ class Config: chart_all_vpd: bool = _setting("MCP_CHART_ALL_VPD", False, _flag, old="CHART_ALL_VPD") # "weather all week" also draws the vapour pressure deficit panel (off: it is temperature and humidity combined) mcp_bind: tuple[str, int] = _setting("MCP_BIND", ("127.0.0.1", 8765), _bind, old="MCP_SERVICE_BIND") # host:port ecobot-mcp listens on mcp_allowed_hosts: tuple[str, ...] = _setting("MCP_ALLOWED_HOSTS", ("127.0.0.1", "localhost"), _names, old="MCP_SERVICE_ALLOWED_HOSTS") # the Host names it answers (any port, unless one is given) + mcp_dashboard: bool = _setting("MCP_DASHBOARD", True, _flag) # the gauges' live web page at /dashboard beside /mcp: read-only, no token, any Host (off: 404) # The bot's (ecobot.py) telegram_token: str = _setting("BOT_TELEGRAM_TOKEN", "", old="TELEGRAM_BOT_TOKEN") # (REQUIRED_BY_BOT: it stops without it) telegram_preload_chat: int | None = _setting("BOT_TELEGRAM_PRELOAD_CHAT", None, _chat_id, old="TELEGRAM_PRELOAD_CHAT") # a chat the other periods of each chart are silently uploaded to ahead of the press (none: off) diff --git a/lib/gauge_look.py b/lib/gauge_look.py new file mode 100644 index 00000000..458469ba --- /dev/null +++ b/lib/gauge_look.py @@ -0,0 +1,47 @@ +"""How the gauges look: the dashboard's colours and the shapes' sizes, shared by the PNG (lib/gauges.py, drawn with Pillow) and the +live web page (lib/web_dashboard.py, drawn by the browser from these same figures). Sizes are pixels of a CELL_W by CELL_H tile, the +top left 0, 0. Nothing here imports Pillow.""" + +from dataclasses import asdict + +from .specs import Tile + +BG = "#14191D" +INK = "#E8EAED" # the titles, the figures +SOFT = "#B8BDC2" # scale numbers, outlines +CHIP = "#3A4046" # the row names' backing +MAX_CHIP, MIN_CHIP, TOTAL_CHIP = "#C62828", "#4FB3F6", "#5BC8F0" +CHIPS = {"Max": MAX_CHIP, "Min": MIN_CHIP, "Total": TOTAL_CHIP} +MARKS = {"Max": "▲", "Min": "▼", "Total": "+"} # in front of a column's name +FILL = "#D32F27" # the thermometer's mercury +TUBE_HALF, BULB_RADIUS = 28, 38 # the thermometer: half the tube's width, the bulb's radius (pixels, to the outline) +MERCURY_GAP = 7 # the gap between the outline and the red, the same round the bulb as up the tube +BAR_WIDTH, BAR_GAP = 13, 12 # the scale's coloured blocks beside a thermometer or beaker: how wide, and how far from its outline +RING_OUTER, BAND_WIDTH = 130, 22 # a dial's coloured scale: its outer radius and how wide it is (the outline is at 138) +LABEL_RADIUS = 84 # where a dial's numbers sit, just inside its scale +WATER = "#4FB3F6" # the rain beaker's water +NEEDLE = "#3E86C0" +CELL_W, CELL_H, MARGIN = 480, 575, 20 +FADE = 0.4 # how much of its colour a tile with no reading keeps +SWEEP, START = 250.0, 215.0 # the dial runs clockwise from START degrees (0 = right, 90 = up) through SWEEP degrees +ROWS = ("Daily", "Monthly", "Yearly") + + +def faded(tile: Tile) -> bool: + """A tile drawn dimmed (FADE): it has no reading now and no figure either.""" + return tile.value is None and not any(any(f is not None for f in figures) for figures in tile.rows.values()) + + +def look() -> dict: + """The figures above as JSON, for the web page to draw with.""" + return {"bg": BG, "ink": INK, "soft": SOFT, "chip": CHIP, "chips": CHIPS, "marks": MARKS, "fill": FILL, "water": WATER, + "needle": NEEDLE, "tube_half": TUBE_HALF, "bulb_radius": BULB_RADIUS, "mercury_gap": MERCURY_GAP, "bar_width": BAR_WIDTH, + "bar_gap": BAR_GAP, "ring_outer": RING_OUTER, "band_width": BAND_WIDTH, "label_radius": LABEL_RADIUS, "cell": [CELL_W, CELL_H], + "fade": FADE, "sweep": SWEEP, "start": START, "rows": list(ROWS)} + + +def tile_json(tile: Tile) -> dict: + """A tile as JSON: specs.Tile's fields, and whether it is dimmed.""" + out = asdict(tile) + out["rows"] = {name: list(figures) for name, figures in tile.rows.items()} + return {**out, "colours": list(tile.colours), "columns": list(tile.columns), "ticks": list(tile.ticks), "faded": faded(tile)} diff --git a/lib/gauges.py b/lib/gauges.py index 9d16fe4a..41d1f407 100644 --- a/lib/gauges.py +++ b/lib/gauges.py @@ -1,35 +1,19 @@ """The dashboard: the station's readings as gauges on a dark card, each with its highest and lowest of the day, month and year. A thermometer, a dial or a rain beaker per tile (specs.Tile), three tiles to a row, drawn on one canvas laid out in pixels (the top left -is 0, 0). A tile with no reading is dimmed. Safe to call from several threads, as charts.render is (they share its drawing lock). +is 0, 0), in lib/gauge_look.py's colours and sizes (the live web page, lib/web_dashboard.py, draws with them too). A tile with no reading +is dimmed. Safe to call from several threads, as charts.render is (they share its drawing lock). """ import math from .charts import _DRAWING, _blend from .draw import PT, Canvas, arc, clip_below, rounded_rect +from .gauge_look import (BAND_WIDTH, BAR_GAP, BAR_WIDTH, BG, BULB_RADIUS, CELL_H, CELL_W, CHIP, CHIPS, FADE, FILL, INK, LABEL_RADIUS, + MARGIN, MARKS, MERCURY_GAP, NEEDLE, RING_OUTER, ROWS, SOFT, START, SWEEP, TUBE_HALF, WATER, faded) from .specs import Dashboard, Tile -BG = "#14191D" -INK = "#E8EAED" # the titles, the figures -SOFT = "#B8BDC2" # scale numbers, outlines -CHIP = "#3A4046" # the row names' backing -MAX_CHIP, MIN_CHIP, TOTAL_CHIP = "#C62828", "#4FB3F6", "#5BC8F0" -CHIPS = {"Max": MAX_CHIP, "Min": MIN_CHIP, "Total": TOTAL_CHIP} -MARKS = {"Max": "▲", "Min": "▼", "Total": "+"} # in front of a column's name -FILL = "#D32F27" # the thermometer's mercury -TUBE_HALF, BULB_RADIUS = 28, 38 # the thermometer: half the tube's width, the bulb's radius (pixels, to the outline) -MERCURY_GAP = 7 # the gap between the outline and the red, the same round the bulb as up the tube -BAR_WIDTH, BAR_GAP = 13, 12 # the scale's coloured blocks beside a thermometer or beaker: how wide, and how far from its outline -RING_OUTER, BAND_WIDTH = 130, 22 # a dial's coloured scale: its outer radius and how wide it is (the outline is at 138) -LABEL_RADIUS = 84 # where a dial's numbers sit, just inside its scale -WATER = "#4FB3F6" # the rain beaker's water -NEEDLE = "#3E86C0" -CELL_W, CELL_H, MARGIN = 480, 575, 20 DPI = 100 -FADE = 0.4 # how much of its colour a tile with no reading keeps -SWEEP, START = 250.0, 215.0 # the dial runs clockwise from START degrees (0 = right, 90 = up) through SWEEP degrees -ROWS = ("Daily", "Monthly", "Yearly") def _lw(width: float) -> float: @@ -154,7 +138,7 @@ def _table(c: Canvas, tile: Tile, ox: float, oy: float, ink): def _tile(c: Canvas, tile: Tile, ox: float, oy: float): - keep = 1.0 if tile.value is not None or any(any(f is not None for f in figures) for figures in tile.rows.values()) else FADE + keep = FADE if faded(tile) else 1.0 ink = (lambda colour: _blend(colour, 1 - keep, BG)) if keep < 1 else (lambda colour: colour) # dimmed towards the card _text(c, ox + CELL_W / 2, oy + 38, tile.title, 38, ink(INK)) DRAW[tile.kind](c, tile, ox, oy, ink) diff --git a/lib/mcp_server.py b/lib/mcp_server.py index b184f977..a25ab9e7 100644 --- a/lib/mcp_server.py +++ b/lib/mcp_server.py @@ -21,7 +21,8 @@ - **Prompts** (3.5): PROMPTS, each a question in words with its period an argument; no logic. - **HTTP** (`http_app`): `streamable_http_app` at /mcp, its Host header checked against the allowed hosts (TransportSecuritySettings: 127.0.0.1 and localhost unless MCP_ALLOWED_HOSTS says), each request's bearer token against - AUTH_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). + AUTH_TOKENS (TokenCheck: a constant-time compare, one token per client, so one can be revoked alone). Beside it, unless MCP_DASHBOARD + is off, the gauges' live page at /dashboard (lib/web_dashboard.py): read-only, so neither the token nor the Host is asked. `EcobotServer(ctx, alert_log)` builds it over the service's Context; `run()` is its publishing, for as long as it runs. Nothing here fetches, alerts or writes: ecobot_mcp runs the sources and the rules.""" @@ -55,6 +56,7 @@ from .service.instructions import instructions from .service.names import AIR_DEVICE, STATION, Catalogue from .tools import json_result +from .web_dashboard import WebDashboard log = logging.getLogger(__name__) requests_log = logging.getLogger(__name__ + ".requests") # one line per HTTP request (RequestLog) @@ -546,14 +548,19 @@ def record(scope, asked: str, status: int, took: float): def http_app(server: EcobotServer, *, tokens=(), allowed_hosts=("127.0.0.1", "localhost"), issuer_url: str = "http://127.0.0.1:8765", - path: str = "/mcp"): - """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (AUTH_TOKENS), every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth - metadata is published (resource_server_url=None).""" + path: str = "/mcp", dashboard: bool = True): + """The Streamable HTTP app (Starlette) at `path`: the Host header checked against `allowed_hosts`, and, with `tokens` (AUTH_TOKENS), + every request's bearer token (TokenCheck). `issuer_url` is required by the SDK with auth but unused: no OAuth metadata is published + (resource_server_url=None). With `dashboard` (MCP_DASHBOARD), the gauges' live page beside it at /dashboard (lib/web_dashboard.py): + read-only, no token, any Host; `app.state.closing` ends its event streams at shutdown.""" check = TokenCheck(tokens) if tokens else None + web = WebDashboard(server, WEATHER_URI) if dashboard else None app = server.server.streamable_http_app( streamable_http_path=path, transport_security=host_settings(allowed_hosts), - auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None) if check else None, token_verifier=check) + auth=AuthSettings(issuer_url=issuer_url, resource_server_url=None) if check else None, token_verifier=check, + custom_starlette_routes=web.routes() if web else None) app.state.tokens = check + app.state.closing = web.close if web else None app.add_middleware(RequestLog) # (added last: outermost, so it sees the token's and the Host's refusals too) return app diff --git a/lib/web_dashboard.html b/lib/web_dashboard.html new file mode 100644 index 00000000..83dcd166 --- /dev/null +++ b/lib/web_dashboard.html @@ -0,0 +1,280 @@ + + + + + + + +Weather station + + + + +
+
+
loading…
+ + + diff --git a/lib/web_dashboard.py b/lib/web_dashboard.py new file mode 100644 index 00000000..4f8e9c42 --- /dev/null +++ b/lib/web_dashboard.py @@ -0,0 +1,131 @@ +"""The gauges as a live web page, served by ecobot-mcp beside /mcp (lib/mcp_server.py http_app), read-only and open to the LAN: + + - GET /dashboard: one self-contained HTML5 page (web_dashboard.html: no framework, nothing fetched from elsewhere) whose script draws + the gauges as inline SVG, with HTML titles and tables, in lib/gauge_look.py's colours and sizes, as the PNG (lib/gauges.py) has + them; its tiles laid out to fill the window, portrait or landscape; + - GET /dashboard/data: the tiles as JSON: the gauges' sheet (lib/gauge_sheet.py) from the service's `current` with context, as the bot + lays it out, each tile's specs.Tile fields and whether it is dimmed, with the time of the reading (`as_of`) and the look; + - GET /dashboard/events: Server-Sent Events, a `readings` event whenever the gauges' readings in the station's kept live reading + change, told by the server's own change detection for ecobot://now/weather (EcobotServer.publish_changes: nothing is fetched for + it), so the page fetches the data again and redraws in place. A comment every HEARTBEAT_SECONDS keeps a proxy from closing it. + +No token is asked for (it is the weather readings only) and the Host isn't checked: a browser opens it by the machine's name. The MCP +endpoint keeps both. MCP_DASHBOARD off: none of the three routes is served (404). `close()` ends the open streams, so uvicorn's +graceful shutdown doesn't wait on them (ecobot_mcp's Uvicorn calls it once it stops accepting connections).""" + +import asyncio +import json +import logging +from pathlib import Path + +from starlette.requests import Request +from starlette.responses import HTMLResponse, JSONResponse, StreamingResponse +from starlette.routing import Route + +from . import gauge_sheet +from .ecowitt.dashboard import GAUGES, live_value +from .gauge_look import look, tile_json + +log = logging.getLogger(__name__) + +PAGE = Path(__file__).with_name("web_dashboard.html") +HEARTBEAT_SECONDS = 25.0 # a comment on an idle stream this often +RETRY_MS = 5000 # how soon a browser connects again after its stream ends +QUEUED = 4 # events waiting on a stream that isn't read: more are dropped (one says it all: fetch again) +NOT_ANSWERING = "The weather station isn't answering right now." + + +def readings_of(live: dict | None) -> tuple | None: + """What the gauges show now of a live reading ({group: {field: {value, ...}}}): each gauge's reading, and the gust counted into the + wind's Max. None without one.""" + if not live: + return None + return tuple(live_value(live, where) for g in GAUGES for where in (g.live, *([g.counted] if g.counted else []))) + + +class WebDashboard: + """The page, its data and its event streams over an EcobotServer (its service's `current`, its bus and its context); `uri` the + resource whose updates are the live reading's (ecobot://now/weather).""" + + def __init__(self, server, uri: str = "ecobot://now/weather"): + self.server, self.uri = server, uri + self._streams: set[asyncio.Queue] = set() + self._shown = self._readings() + self.closed = False + server.bus.subscribe(self._on_event) + + # ---------- the data ---------- + async def data(self) -> dict: + """{as_of, tiles, look}, or with `unavailable` (and no tiles) when the station gives nothing.""" + tool = self.server.service.get("current") + result = json.loads(await tool.call(gauge_sheet.call(), {})) if tool else {"error": "no current"} + sheet = gauge_sheet.sheet(result) + out = {"as_of": result.get("as_of"), "tiles": [tile_json(t) for t in sheet.tiles] if sheet else [], "look": look()} + if sheet is None: + out["unavailable"] = (result.get("unavailable") or {}).get("station") or NOT_ANSWERING + return out + + # ---------- the events ---------- + def _readings(self): + try: + kept = getattr(self.server.ctx.eco, "_live", None) + return readings_of(kept[1] if kept else None) + except Exception as e: # (never stops the publishing) + log.warning("Dashboard: couldn't read the live reading: %s: %s", type(e).__name__, e) + return None + + def _on_event(self, event): + """The bus's listener (sync, on the event loop): a weather update whose gauges' readings changed goes to every stream.""" + if getattr(event, "uri", None) != self.uri: + return + now = self._readings() + if now is None or now == self._shown: + return + self._shown = now + for queue in list(self._streams): + if queue.qsize() < QUEUED: + queue.put_nowait("readings") + + def close(self): + """End every open stream (and answer a new one with just its retry), for the server's shutdown.""" + self.closed = True + for queue in list(self._streams): + queue.put_nowait(None) + + async def _stream(self, queue: asyncio.Queue): + try: + yield f"retry: {RETRY_MS}\n: ecobot dashboard\n\n" + while not self.closed: + try: + what = await asyncio.wait_for(queue.get(), HEARTBEAT_SECONDS) + except TimeoutError: + yield ": still here\n\n" + continue + if what is None: + break + yield f"event: {what}\ndata: {{}}\n\n" + finally: + self._streams.discard(queue) + + # ---------- the routes ---------- + async def page(self, request: Request): + return HTMLResponse(PAGE.read_text(encoding="utf-8"), headers={"Cache-Control": "no-cache"}) + + async def data_route(self, request: Request): + return JSONResponse(await self.data(), headers={"Cache-Control": "no-store"}) + + async def events(self, request: Request): + queue: asyncio.Queue = asyncio.Queue() + if self.closed: + queue.put_nowait(None) + else: + self._streams.add(queue) + return StreamingResponse(self._stream(queue), media_type="text/event-stream", + headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"}) + + def routes(self, path: str = "/dashboard") -> list[Route]: + return [Route(path, self.page, methods=["GET"]), Route(f"{path}/data", self.data_route, methods=["GET"]), + Route(f"{path}/events", self.events, methods=["GET"])] + + +__all__ = ["WebDashboard", "readings_of"] diff --git a/tests/test_settings.py b/tests/test_settings.py index 100c9a1f..6bdd91cc 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -19,7 +19,7 @@ MCP_ONLY = {"ecowitt_api_key", "ecowitt_app_key", "ecowitt_source", "airgradient_token", "airgradient_location", "airgradient_dashboard", "airgradient_local_url", "airgradient_source", "homeassistant_url", "homeassistant_token", "place", "pollen", "pollen_district", "forecast", "forecast_lat", "forecast_lon", "rain_quiet_hours", "alert_cooldown_minutes", "antispike_require_consecutive", - "chart_all_feels_like", "chart_all_vpd", "mcp_bind", "mcp_allowed_hosts"} + "chart_all_feels_like", "chart_all_vpd", "mcp_bind", "mcp_allowed_hosts", "mcp_dashboard"} def test_every_setting_is_named_for_the_program_that_reads_it(): diff --git a/tests/test_web_dashboard.py b/tests/test_web_dashboard.py new file mode 100644 index 00000000..88b02830 --- /dev/null +++ b/tests/test_web_dashboard.py @@ -0,0 +1,221 @@ +"""The gauges' live web page beside /mcp (lib/web_dashboard.py), under uvicorn as tests/test_mcp_listen.py serves the app: the page, its +data (the tiles gauge_sheet lays out from current with context), its events (one when the live reading's gauges change, from the +server's own change detection), no token and any Host for it while /mcp still asks for both, MCP_DASHBOARD off (404), the request log, +and a shutdown that doesn't wait on an open stream. Then the page in a browser (Playwright's Chromium, through node, skipped without +it) at a phone's, a tablet's and a desktop's sizes: every tile on the screen where the size allows, nothing wider than the window, no +console error. With ECOBOT_SCREENSHOTS set, its screenshots are kept in that folder.""" + +import asyncio +import json +import os +import shutil +import subprocess +import time +from pathlib import Path +from types import SimpleNamespace as NS + +import httpx +import pytest + +from lib import gauge_sheet +from lib.gauge_look import look, tile_json +from lib.mcp_server import EcobotServer, WEATHER_URI, http_app +from lib.service.context import Context +from lib.service.names import Catalogue +from lib.web_dashboard import readings_of +from tests.chart_samples import _station +from tests.fakes import TZ, StandInService, gauges_result +from tests.test_mcp_listen import Serving, free_port, until + +TOKEN = "s3cret" +AS_OF = {"text": "Tue 27 Oct 2026 6:42pm", "time": "2026-10-27T18:42:00+11:00"} +BROWSER = Path(__file__).with_name("web_dashboard_browser.js") + + +class Station: + """The fake station: its kept live reading (what ecobot://now/weather is compared from) and current's result with context over it + (the days' figures of chart_samples' October evening).""" + + def __init__(self): + self.live, self.values, self.today = _station() + self.eco = NS(_live=(time.time(), self.live), storage=None, tz=TZ) + + def current(self, args, meta): + assert args == gauge_sheet.call() and meta == {} # every gauge's reading, with context; the request's defaults + return {"as_of": AS_OF, **gauges_result(self.live, self.values, self.today)} + + def reads(self, group: str, field: str, value: str): + self.live = json.loads(json.dumps(self.live)) + self.live[group][field]["value"] = value + self.eco._live = (time.time(), self.live) + + +@pytest.fixture +def station(): + return Station() + + +@pytest.fixture +def server(station): + ctx = Context(eco=station.eco, tz=TZ) + ctx.catalogue = Catalogue([]) + server = EcobotServer(ctx, None) + server._service = StandInService(current=station.current) + return server + + +async def get(url: str, **headers) -> httpx.Response: + async with httpx.AsyncClient() as http: + return await http.get(url, headers=headers) + + +async def test_the_page_and_its_data_are_served_without_a_token_to_any_host_and_the_data_is_gauge_sheets_tiles(server, station): + port = free_port() + base = f"http://127.0.0.1:{port}" + async with Serving(http_app(server, tokens=(TOKEN,), allowed_hosts=("127.0.0.1",)), port): + page = await get(f"{base}/dashboard", Host="deb1:8765") # by the machine's name: not an allowed host + data = await get(f"{base}/dashboard/data", Host="deb1:8765") + mcp = await get(f"{base}/mcp", Host="deb1:8765", Authorization=f"Bearer {TOKEN}") + no_token = await get(f"{base}/mcp", Accept="text/event-stream") + assert page.status_code == 200 and page.headers["content-type"].startswith("text/html") + html = page.text + assert html.startswith("") and "