From 12573832108c65008186bc596f8f43efea79fca6 Mon Sep 17 00:00:00 2001 From: chenliuyun Date: Fri, 20 Nov 2026 19:11:47 +0800 Subject: [PATCH] chore: release 3.11.0 --- CHANGELOG.md | 4 +- README.md | 7 +- docs/agent-guide.md | 9 +- docs/audit-log.md | 37 ++++---- docs/json-contract.md | 4 +- docs/openapi-alignment-ambiguities.md | 6 +- docs/policy-reference.md | 118 ++++++++++---------------- docs/schema-versioning.md | 14 +-- package-lock.json | 4 +- package.json | 2 +- src/commands/mcp.ts | 5 +- 11 files changed, 96 insertions(+), 114 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95383d6..59ca128 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ All notable changes to `@switchbot/openapi-cli` are documented in this file. The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [3.11.0] ### Added @@ -26,7 +26,7 @@ This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - CLI and MCP distinguish repeat safety from request-key deduplication. Unclear intent no longer generates a write; scoped replay and IR checks use the verified target. Legacy Luma overrides apply to Frame 2; DVD/Speaker discovery identifies undocumented DVD volume support. - Compact bootstrap no longer dumps the catalog on a cold cache. Single-model schemas narrow webhook results; help examples and byte budgets are exercised on cold and populated fixtures. -See the [pinned protocol notes](./docs/openapi-alignment-ambiguities.md). No new REST endpoint, CLI command, MCP tool or release version. +See the [pinned protocol notes](./docs/openapi-alignment-ambiguities.md). No new REST endpoint, CLI command or MCP tool. ## [3.10.0] diff --git a/README.md b/README.md index 919d3c7..00702cc 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ [![license](https://img.shields.io/npm/l/@switchbot/openapi-cli.svg)](./LICENSE) [![node](https://img.shields.io/node/v/@switchbot/openapi-cli.svg)](https://nodejs.org) [![CI](https://github.com/OpenWonderLabs/switchbot-openapi-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/OpenWonderLabs/switchbot-openapi-cli/actions/workflows/ci.yml) +[![Fully tested: 3300 tests](https://img.shields.io/badge/tests-3300-blue)](#development) SwitchBot smart home CLI — control devices, run scenes, stream events, and plug AI agents into your home via the built-in MCP server. @@ -66,7 +67,7 @@ Run `switchbot catalog show` for the effective catalog, including aliases and pe ### Device contract notes -**Unreleased OpenAPI update** (after CLI 3.10.0): +**OpenAPI changes in CLI 3.11.0:** - **Plug Mini (IT) and Outdoor Plug (EU):** `switchbot --json devices status ` reports `power` in watts and `usedElectricity` in watt-minutes for the day. Read `switchStatus` (0 off, 1 on) for the relay state. The two models have distinct webhook identities; their events do not report energy readings. - **Hub 4 and Vision Doorbell:** use `switchbot --json devices status ` rather than sending a command. Hub 4 reports motion and environmental readings and has webhook events. Vision Doorbell reports `version`, `battery`, and `online`; no webhook is documented. Unlike Video Doorbell, it has no motion-detection controls. Its inventory entry may include `lockDeviceId` (a linked lock ID or `null`). @@ -377,7 +378,7 @@ switchbot config list-profiles switchbot mcp serve # stdio — default 18 tools; readonly 15; --tools all 29 ``` -Read endpoints added in CLI 3.9.0: `mindclip transcript ` and `devices diary --start --end `. Both have readonly MCP equivalents; diary windows are limited to 31 days and embedded detail strings remain raw. +Read endpoints added in CLI 3.9.0: `mindclip transcript ` and `devices diary --start --end `. Both are available in the readonly MCP profile; diary windows are limited to 31 days and embedded detail strings remain raw. ### `webhook` @@ -470,7 +471,7 @@ switchbot completion bash/zsh/fish/powershell | Flag | Description | | --- | --- | | `--json` | Raw JSON output | -| `--format ` | `tsv` / `yaml` / `jsonl` / `id` | +| `--format ` | `table` (default), `json`, `jsonl`, `tsv`, `yaml`, `id`, or `markdown` | | `--fields ` | Comma-separated column filter | | `--dry-run` | Preview supported actions without applying changes; unsupported writes fail. Reads may consume quota. Use `rules simulate` for offline rule decisions. | | `--verbose` | Log HTTP request/response to stderr | diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 8e672ed..b31bdb2 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -9,7 +9,7 @@ If you're a human looking for a tour, start with the [top-level README](../READM > its Skill + MCP architecture and existing startup contract. > The documented CLI/MCP surfaces are the shared contract. Check offline > catalog/bootstrap compatibility with -> `switchbot doctor --json | jq '.data.checks[] | select(.name=="catalog-schema")'`. +> `switchbot doctor --section catalog-schema --json`. --- @@ -74,7 +74,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) ### Available tools (29, including 3 deprecated aliases) -The default profile exposes 18 tools; `--tools readonly` exposes 15. Policy, audit and rule-administration tools require `--tools all`. Installations keep the safe default rather than enabling all tools merely for onboarding. +`switchbot mcp serve` exposes 18 tools by default; `--tools readonly` exposes 15. Policy, audit and rule-administration tools require `--tools all`. To inspect a profile without starting the server, run `switchbot mcp tools --tools default --json` (or substitute `readonly` or `all`). Unlike `serve`, `mcp tools` lists all 29 when no profile is specified. | Tool | Purpose | Safety tier | | --- | --- | --- | @@ -88,6 +88,9 @@ The default profile exposes 18 tools; `--tools readonly` exposes 15. Policy, aud | `describe_device` | Catalog-derived capabilities + optional live status | read | | `account_overview` | Cold-start snapshot (devices/scenes/quota/cache/MQTT) | read | | `device_history` | Read locally-persisted history. mode: "raw" (latest + ring) / "query" (time-range JSONL) / "aggregate" (bucketed stats) | read | +| `get_device_history` | Deprecated; use `device_history` with `mode: "raw"` | read | +| `query_device_history` | Deprecated; use `device_history` with `mode: "query"` | read | +| `aggregate_device_history` | Deprecated; use `device_history` with `mode: "aggregate"` | read | | `mindclip_recordings` | AI MindClip recordings. action: `"list"`, `"get"` metadata, `"summary"`, or `"transcript"` transcription status/result | read | | `mindclip_list_todos` | List AI-extracted to-dos pulled from voice recordings | read | | `mindclip_recall` | AI-curated recall views. period: `"daily"` daily recall / `"weekly"` weekly summary / `"urgent_todos"` urgent to-dos | read | @@ -467,7 +470,7 @@ Each command entry carries: ### Model-specific boundaries -**Unreleased models** (after CLI 3.10.0): +**Model changes in CLI 3.11.0:** - For **Plug Mini (IT)** and **Outdoor Plug (EU)**, use `get_device_status` for `switchStatus` (0 off, 1 on), `power` (W), `electricCurrent` (mA), `voltage` (V), and daily `usedElectricity` (W·min). Their separate `changeReport` events expose `online`, `overTemperature`, `overload`, and `switchStatus`, not metering samples. - **Hub 4** is read-only. Use status for `moveDetected` and webhook `detectionState` for motion events. **Vision Doorbell** is also read-only (`version`, `battery`, `online`), with no documented webhook. `list_devices` may report `lockDeviceId` as a string or `null`, or omit it. It is inventory metadata, not a doorbell command target. Do not offer Video Doorbell's motion-detection controls. diff --git a/docs/audit-log.md b/docs/audit-log.md index db50806..4d04cea 100644 --- a/docs/audit-log.md +++ b/docs/audit-log.md @@ -1,8 +1,8 @@ # Audit Log Format -The SwitchBot CLI writes a JSONL audit record for every mutating device or -scene command when either `--audit-log` is passed or a profile sets -`defaults.flags` including `--audit-log`. +Pass `--audit-log` to record device commands. A device command with a +`planId` uses the default log even without the flag. Direct scene execution +does not write a command record. - **Default path:** `~/.switchbot/audit.log` - **Override:** `--audit-log-path ` @@ -12,7 +12,10 @@ scene command when either `--audit-log` is passed or a profile sets ## Schema -Every record is a JSON object with at least the following fields: +New records share `auditVersion`, `t`, and `kind`. The remaining fields below +describe command records; other kinds have different payloads. For example, +`rule-evaluate` has `rule`, `trigger`, `fireId`, `conditions`, `decision` and +`evaluationMs` instead of command fields. | Field | Type | Notes | | --- | --- | --- | @@ -21,12 +24,16 @@ Every record is a JSON object with at least the following fields: | `kind` | string | Record discriminator. Values: `command`, `rule-fire`, `rule-fire-dry`, `rule-throttled`, `rule-webhook-rejected`, `rule-notify`, `rule-evaluate`, `llm-suggest`, `llm-condition`, `llm-budget-exceeded`. | | `deviceId` | string | Target device ID. | | `command` | string | SwitchBot command name (e.g. `turnOn`, `setColor`). | -| `parameter` | string \| object | `command` records use the wire parameter. Rule-fire records retain the parameter string, including JSON whitespace; RGB values use `r:g:b`. Unused parameters are `"default"`. | +| `parameter` | JSON value | Device command parameter (for example, a string, number or object). Rule-fire records retain parsed command text, including JSON whitespace; RGB values use `r:g:b`. | | `commandType` | `"command" \| "customize"` | Matches the upstream SwitchBot API field. | | `dryRun` | boolean | `true` when the command was intercepted by `--dry-run` and never reached the network. | -| `result` | `"ok" \| "error"` | Optional — only present once the command completed (absent for `dryRun: true`). | +| `result` | `"ok"` \| `"error"` \| `"dry-run"` | Optional. An intercepted device command records `"dry-run"`; a successful `rule-fire-dry` records `"ok"`. | | `error` | string | Optional — populated when `result === "error"`. | +`llm-condition` is a declared kind. Do not expect a separate record for +each LLM call: the evaluator puts condition details in `rule-evaluate` +traces and writes `llm-budget-exceeded` on budget rejection. + ### Example ```json @@ -54,19 +61,17 @@ Every record is a JSON object with at least the following fields: ## `history verify` -`switchbot history verify` inspects the log and reports: - -- total / parsed / skipped / malformed line counts -- histogram of `auditVersion` values (`unversioned` for pre-v1 records) -- earliest / latest timestamp -- per-line problem details for anything that failed to parse +`switchbot history verify` ignores blank lines. Human output includes parsed +and malformed counts, an `auditVersion` histogram, earliest/latest timestamps +when available, and line numbers for malformed JSON. `--json` instead reports +`data.status`, `fileMissing`, `parsed`, `malformed`, `unversioned` and `message`. Exit codes: -| Code | Meaning | -|------|----------------------------------------------------------------------------------| -| 0 | Every line parsed; no malformed entries. | -| 1 | File missing OR one or more malformed lines. | +| Code | Meaning | +| --- | --- | +| 0 | No malformed or unversioned entries (`ok`), or file missing (`warn`). | +| 1 | At least one malformed or unversioned entry (`fail`). | ## Rotation diff --git a/docs/json-contract.md b/docs/json-contract.md index 1585916..f496867 100644 --- a/docs/json-contract.md +++ b/docs/json-contract.md @@ -34,7 +34,7 @@ query` emit one JSON envelope. outer success or error shape changes. A command payload can have an additional version inside `data`. -For example, schema discovery in CLI 3.10.0 is an envelope at `1.2`, an export +For example, schema discovery in CLI 3.11.0 is an envelope at `1.2`, an export at `2.0`, and a resource catalog at `2.0`: ~~~json @@ -95,7 +95,7 @@ displayed image remains and nothing was deleted. With both values `0`, the album was empty. Do not treat zero as missing. The count is for the **cloud album**, including images not downloaded to the frame. A successful deletion means the cloud removed the image and sent the instruction, not that the frame -has finished. See the [pinned device evidence](openapi-alignment-ambiguities.md#2026-11-20-upstream-snapshot-unreleased). +has finished. See the [pinned device evidence](openapi-alignment-ambiguities.md#2026-11-20-upstream-snapshot). ## 2. Streaming commands diff --git a/docs/openapi-alignment-ambiguities.md b/docs/openapi-alignment-ambiguities.md index 1725ca3..78ba7b4 100644 --- a/docs/openapi-alignment-ambiguities.md +++ b/docs/openapi-alignment-ambiguities.md @@ -1,6 +1,6 @@ # OpenAPI alignment ambiguities -The latest entries use the [2026-11-20 upstream snapshot](#2026-11-20-upstream-snapshot-unreleased) (`0db92c78`). The earlier entries below retain their own `dc9a6b0e` evidence links. Written contracts, reported payloads and unresolved server behavior are distinguished throughout. +The latest entries use the [2026-11-20 upstream snapshot](#2026-11-20-upstream-snapshot) (`0db92c78`). The earlier entries below retain their own `dc9a6b0e` evidence links. Written contracts, reported payloads and unresolved server behavior are distinguished throughout. - [MindClip](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/others/ai-mindclip.md): the CLI, library and MCP now require the documented list/todo/date/week query fields; missing fields fail before HTTP rather than relying on an unverified server default. Extra language/time/folder/category filters, legacy numeric bounds and completed/category value meanings still require upstream confirmation; mock responses do not establish them. - [Curtain and Blind Tilt](https://github.com/OpenWonderLabs/SwitchBotAPI/tree/dc9a6b0e4ad77882c72d186ecd5d134113acdad0/devices/curtains-blinds): scalar Curtain position, Blind Tilt/Roller Shade on/off, and fan toggle support are not tightened without pinned evidence. The documented spaced Blind Tilt form `up; 36` is accepted and normalized to `up;36`. @@ -46,10 +46,10 @@ It supplements, rather than replaces, the historical evidence above. Solar webhook `timeOfSample` is milliseconds, not the status URL expiry unit. -## 2026-11-20 upstream snapshot (unreleased) +## 2026-11-20 upstream snapshot [Official delta from `fa8f90c` to `0db92c7`](https://github.com/OpenWonderLabs/SwitchBotAPI/compare/fa8f90c661cfa183d633d87f18c04e0e5059fa74...0db92c78b56808f25b74c61535313f44bef4cd91). -The five additions below use existing REST operations. The evidence is the +CLI 3.11.0 supports the five additions below through existing REST operations. The evidence is the written OpenAPI contract, not a live-device or regional availability test. - [Plug Mini (IT)](https://github.com/OpenWonderLabs/SwitchBotAPI/blob/0db92c78b56808f25b74c61535313f44bef4cd91/devices/plugs-switches/plug-mini-it.md) diff --git a/docs/policy-reference.md b/docs/policy-reference.md index 7f07e6c..eef751d 100644 --- a/docs/policy-reference.md +++ b/docs/policy-reference.md @@ -27,8 +27,8 @@ Override order (first hit wins): 3. The default path above `switchbot policy new` writes to the resolved path; `switchbot policy -validate` reads from it; `switchbot policy migrate` reads, upgrades in -memory, and writes back. +validate` reads from it. `policy migrate` checks its declared version; there +is no upgrade path between two different versions in this release. --- @@ -41,8 +41,8 @@ The top-level `version` field is **required**. This CLI validates only v0.2; v0. | `"0.1"` | **Removed in v3.0** — migrate with `policy migrate` (CLI ≤2.15) | aliases, confirmations, quiet_hours, audit, cli | | `"0.2"` | **Current (required)** | typed `automation.rules[]` for the rules engine | -A file with anything other than `"0.2"` fails validation -with a named `unsupported-version` error. v0.2 is the default emitted +A file declaring a different version string fails validation +with an `unsupported-version` error. v0.2 is the default emitted by `switchbot policy new`. Existing v0.1 files must be migrated using CLI ≤2.15 before upgrading to v3.0+: @@ -51,10 +51,6 @@ CLI ≤2.15 before upgrading to v3.0+: switchbot policy migrate ``` -`policy migrate` applies additive changes only (new optional fields, -tighter types on reserved blocks), rewrites the `version` constant, and -refuses to migrate if any user edits would conflict (exit code 7). - ```yaml version: "0.2" # current default # version: "0.1" # legacy — upgrade with `switchbot policy migrate` @@ -71,7 +67,7 @@ defaults. | Block | Purpose | Default when missing | | --- | --- | --- | | `aliases` | Map user-spoken names to deviceIds | No aliases — name resolution falls through to the CLI's match strategies | -| `confirmations` | Override per-action confirmation policy | Default tier behaviour (see [Safety tiers](./audit-log.md)) | +| `confirmations` | Override per-action confirmation policy | Default tier behaviour (see [Safety rails](./agent-guide.md#safety-rails)) | | `quiet_hours` | Require confirmation during a daily window | No quiet hours | | `audit` | Where to write and how long to keep the audit log | `~/.switchbot/audit.log`, retention `90d` | | `automation` | Configure the v0.2 rule engine and its triggers, conditions, and actions | `enabled: false` | @@ -96,8 +92,8 @@ Rules: - Keys are free-form strings. Quote them if they contain spaces or non-ASCII characters. -- Values must match `^[A-Za-z0-9][A-Za-z0-9_-]{1,63}$` — also accepts - hex MAC format and hyphenated multi-segment IDs. +- Values must match `^[A-Za-z0-9][A-Za-z0-9_-]{1,63}$` and pass the + offline plausibility check for a hex MAC or hyphenated device ID. Get IDs from `switchbot devices list --format=tsv`. --- @@ -193,7 +189,7 @@ automation: evaluate_trace: sampled # full | sampled | off (default sampled) evaluate_retention_days: 7 # min 1 (default 7) llm_budget: - max_calls_per_hour: 60 # global limit across all LLM conditions (default 60) + max_calls_per_hour: 60 # fallback hourly cap for each LLM condition rules: - name: hallway motion at night # unique per file; audit label enabled: true # default true; false silences the rule @@ -215,12 +211,11 @@ automation: on_failure: log # log | retry | ignore throttle: max_per: "10m" # minimum spacing: \d+[smh] - dedupe_window: null # event deduplication window - cooldown: null # shorthand for throttle.max_per - requires_stable_for: null # hysteresis guard duration - maxFiringsPerHour: null # per-hour rate limit + dedupe_window: "5s" # optional event deduplication window + requires_stable_for: "10s" # optional hysteresis guard duration + maxFiringsPerHour: 6 # optional per-hour rate limit suppressIfAlreadyDesired: false # skip if device already in desired state - dry_run: true # default true in v0.2; writes audit but skips the API call + dry_run: true # set explicitly to skip action dispatch ``` #### Rule command parameters @@ -286,7 +281,7 @@ too. | Keyword | Meaning | Status | | --- | --- | --- | | `time_between` | `[HH:MM, HH:MM]` local-time window, `start > end` → overnight | active | -| `device_state` | `{ device, field, op, value }` read device status inline | active | +| `device`, `field`, `op`, `value` | Compare a device status field; use these four keys directly, without a `device_state` wrapper | active | | `event_count` | Count events in a rolling window over device history | active | | `all` | AND-join multiple sub-conditions | active | | `any` | OR-join multiple sub-conditions | active | @@ -300,7 +295,7 @@ conditions: - event_count: device: hallway-motion # alias or deviceId (required) event: motion.detected # MQTT event name; omit to count all - window: "5m" # rolling window: \d+[smh] (required) + window: "5m" # integer + ms, s, m, h or d (required) min: 3 # fire only if count >= min (required) max: 10 # optional upper bound (count <= max) ``` @@ -316,47 +311,32 @@ path: an "alarm if motion ≥3 times in 5m" guard does not need a model. conditions: - llm: prompt: "Is the temperature above normal comfort range?" - provider: auto # auto | openai | anthropic | local + provider: auto # auto | openai | anthropic timeout_ms: 5000 # 500–10000 (default 5000) cache_ttl: 5m # none | \d+[smh] (default 5m) - recent_events: 5 # 0–20 (default 5) — last N events of the - # trigger device included verbatim in prompt + recent_events: 5 # 0–20; matching history contributes to the cache key budget: - max_calls_per_hour: 10 # per-condition limit (default 10) - max_tokens_per_hour: 100000 # optional rolling 1h token cap - max_cost_per_day_usd: 1.00 # optional rolling 24h USD cap + max_calls_per_hour: 10 # per-condition call limit + max_tokens_per_hour: 100000 # optional hourly token cap + max_cost_per_day_usd: 1.00 # optional daily USD cap on_error: fail # fail | pass | skip (default fail) ``` -Set `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` for the cloud providers. -For `provider: local`, point `SWITCHBOT_LOCAL_LLM_URL` at any -OpenAI-compatible `/v1/chat/completions` endpoint (Ollama defaults -to `http://localhost:11434/v1`, llama.cpp / vLLM / LM Studio also -work). Models without tool-use call into a structured-output -fallback (JSON instruction prompt + lenient parser + one repair -retry); set `SWITCHBOT_LOCAL_LLM_TOOL_USE=1` if your local model -does support tool use. +Set `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` for the selected provider. +`provider: local` is not accepted by the policy schema. -`rules lint` flags misconfigured LLM conditions, including -`condition-llm-tokens-budget-zero` (token cap set to 0 — never -allowed) and `condition-llm-cost-without-known-model` (cost cap on a -model not in the pricing table — won't be enforced). +`rules lint` warns when a zero token cap forces the `on_error` path, or when +`provider: auto` makes cost accounting depend on the model selected at runtime. -The audit log records every LLM condition outcome as -`kind: llm-condition` with `usage: { tokensIn, tokensOut, costUsd? }` -and emits `kind: llm-budget-exceeded` with -`dimension: "calls" | "tokens" | "cost"` when a cap fires. +When evaluation tracing is enabled, an LLM condition can report token usage +in its `rule-evaluate` trace. A budget rejection writes `llm-budget-exceeded` +with `budgetDimension` (`calls`, `tokens` or `cost`), `budgetLimit`, and +`budgetObserved` when auditing is enabled. -Global LLM budget (applied across all LLM conditions, in addition to -each condition's per-rule budget): - -```yaml -automation: - llm_budget: - max_calls_per_hour: 60 # default 60 - max_tokens_per_hour: 1000000 # optional - max_cost_per_day_usd: 10.00 # optional -``` +In `rules run`, `automation.llm_budget.max_calls_per_hour` is a fallback per +condition, not an aggregate across rules. A condition's own call cap overrides +it. Set token and cost caps on `conditions[].llm.budget`; the engine does not +pass automation-level token or cost caps to the evaluator. **Destructive commands are refused.** The v0.2 validator rejects `lock`, `unlock`, `deadbolt`, `nightLatchUnlock`, `createKey`, `deleteKey`, @@ -381,8 +361,7 @@ windows. Rules are executed in the order declared; `on_error: stop` halts the remaining actions in a single rule's `then[]` but doesn't affect other rules. -See [`docs/design/phase4-rules.md`](./design/phase4-rules.md) for the -pipeline and [`examples/policies/automation.yaml`](../examples/policies/automation.yaml) +See [`examples/policies/automation.yaml`](../examples/policies/automation.yaml) for a working walkthrough. --- @@ -424,20 +403,13 @@ Exit codes: | Code | Meaning | | --- | --- | | 0 | File is valid and matches schema v0.2 | -| 1 | Schema violation (line-accurate error with hint) | +| 1 | Invalid policy (schema, semantics, or safety checks); also used for missing `--live` credentials | | 2 | File is missing | | 3 | YAML is malformed (parse error, with line/col) | | 4 | Internal error | -Every non-zero exit prints a compiler-style block: - -```text -policy.yaml:12:14 error lowercase deviceId - | -12 | "bedroom ac": "02-202502111234-abc123" - | ^^^^^^^^ - = hint: SwitchBot deviceIds are uppercase. Try "ABC123". -``` +Human output for an invalid policy includes diagnostics; file-loading errors +instead report why the file could not be read or parsed. For machine consumption, pass `--json`. Schema violations exit `1` with `data.valid: false` and `data.errors[]`; file/parse/internal failures use @@ -479,14 +451,14 @@ live inventory validation is explicitly requested. | `missing version` | Top-level `version` is absent | Add `version: "0.2"` | | `unsupported version` | `version` is not `"0.2"` | Use a supported policy schema; v0.1 requires a legacy CLI <=2.15 for migration | | `wrong version` | `version: "0.1"` on this CLI | Migrate with CLI <=2.15, then upgrade back | -| `lowercase deviceId` | `aliases` value doesn't match the accepted patterns | Copy the exact ID from `devices list` | +| `alias-device-id` | Alias value is not a plausible SwitchBot device ID | Copy the exact ID from `devices list` | | `destructive in never_confirm` | `lock`/`unlock`/etc in `confirmations.never_confirm` | Remove it; intentional by design | | `quiet_hours.start without end` | Only one of the two times is set | Set both, or remove the block | | `invalid retention` | `audit.retention` isn't `never` / `Nd` / `Nw` / `Nm` | Use one of the documented formats | | `unknown top-level key` | You misspelled a block (e.g. `alias:` not `aliases:`) | Check the spelling against this reference | -Every error includes the offending line and column, and most include a -machine-readable `rule` field so tooling can suggest fixes. +Validation errors include a machine-readable `keyword` and can include a +source `line`, `col` and a suggested `hint`. --- @@ -499,14 +471,12 @@ v0.2 is the current required schema. This CLI cannot migrate v0.1. Use CLI <=2.1 switchbot policy migrate ``` -`policy migrate`: - -1. Detects your current `version` field. -2. Applies additive changes only (new optional fields, tighter types on - reserved blocks). -3. Rewrites the file with the new `version` constant. -4. Refuses to migrate if any user edits conflict, and explains what - conflicts (exit code 7). +On the current CLI, a v0.2 file targeting v0.2 returns `already-current` +without rewriting or validating the file. A missing or non-string version +returns `no-version-field` (exit 0, no write). An unsupported source or +target version exits 6. File-not-found, YAML parse and internal loading errors +exit 2, 3 and 4 respectively. Exit 7 is reserved for a migration that fails +prevalidation; with only one supported version there is no such upgrade here. After migrating, run `switchbot policy validate` to confirm the file is valid before using the rules engine. diff --git a/docs/schema-versioning.md b/docs/schema-versioning.md index c5e7e68..c88be82 100644 --- a/docs/schema-versioning.md +++ b/docs/schema-versioning.md @@ -3,14 +3,14 @@ SwitchBot CLI has separate machine-readable contracts. A version in one contract does not change the version of another contract. -## Current versions for CLI 3.10.0 +## Current versions for CLI 3.11.0 | Contract | Location | Version | What it versions | | --- | --- | --- | --- | | JSON envelope | top-level JSON success and error output | `1.2` | `{ schemaVersion, data }` and `{ schemaVersion, error }` | | Discovery export | `schema export` data `version` | `2.0` | the discoverable catalog payload, including resources | -| Resource catalog | `schema export` data `resources.version` | `2.0` | scenes, webhooks, and keypad resource metadata | -| Device entry shape | each item in `schema export` data `types` | `1.0` | device command and status-field descriptors | +| Resource catalog | non-compact `schema export` data `resources.version` | `2.0` | scenes, webhooks, and keypad resource metadata | +| Device entry shape | `schema export` data `types` (no per-entry version field) | `1.0` | device command and status-field descriptors | | Event payload | streaming event data `payloadVersion` | `1` | normalized event record inside the JSON envelope | The top-level JSON envelope remains `1.2`. Its version does not mean that @@ -42,9 +42,9 @@ audit records. Account switching can reject an obsolete in-flight operation or require an MQTT subscription restart; payload-version stability does not remove those behavioral boundaries. -### Unreleased OpenAPI alignment after 3.10.0 +### OpenAPI alignment in CLI 3.11.0 -The [pinned upstream delta](openapi-alignment-ambiguities.md#2026-11-20-upstream-snapshot-unreleased) +The [pinned upstream delta](openapi-alignment-ambiguities.md#2026-11-20-upstream-snapshot) adds catalog entries and commands, not descriptor fields. `AI Art Frame 2` is the canonical discovery value; `AI Art Frame Luma` remains a lookup alias. Consumers enumerating catalog values should not assume a fixed set of names @@ -106,5 +106,5 @@ JSON envelopes at `schemaVersion` `1.2`. Their `data.payloadVersion` is `1`. The payload version applies to the normalized event record, not to the outer JSON envelope or the upstream raw payload. -A historical `batch.summary.schemaVersion` remains a compatibility field. -Prefer the top-level envelope version for CLI output parsing. +For `batch` output, read the top-level envelope version; do not require a +`schemaVersion` inside `data.summary`. diff --git a/package-lock.json b/package-lock.json index 8ee1558..6680e66 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,13 @@ { "name": "@switchbot/openapi-cli", - "version": "3.10.0", + "version": "3.11.0", "lockfileVersion": 3, "requires": true, "dev": true, "packages": { "": { "name": "@switchbot/openapi-cli", - "version": "3.10.0", + "version": "3.11.0", "license": "MIT", "workspaces": [ "packages/*" diff --git a/package.json b/package.json index 0def90d..0f79896 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@switchbot/openapi-cli", - "version": "3.10.0", + "version": "3.11.0", "description": "SwitchBot smart home CLI — control devices, run scenes, stream real-time events, and integrate AI agents via MCP. Full API v1.1 coverage.", "keywords": [ "switchbot", diff --git a/src/commands/mcp.ts b/src/commands/mcp.ts index 0b73475..e39dc2e 100644 --- a/src/commands/mcp.ts +++ b/src/commands/mcp.ts @@ -2645,13 +2645,16 @@ export function registerMcpCommand(program: Command): void { - list_devices fetch all physical + IR devices - get_device_status live status for a physical device - device_diary Kata diary reads over integer-millisecond windows up to 31 days - - send_command control a device (destructive commands need confirm:true) + - send_command control a device (destructive writes require a reviewed plan by default) - list_scenes list all manual scenes - run_scene execute a manual scene - search_catalog offline catalog search by type/alias - describe_device metadata + commands + (optionally) live status for one device - account_overview single cold-start snapshot: devices + scenes + quota + cache + MQTT state - device_history read locally-persisted device history (mode: "raw" | "query" | "aggregate") + - get_device_history deprecated: use device_history with mode "raw" + - query_device_history deprecated: use device_history with mode "query" + - aggregate_device_history deprecated: use device_history with mode "aggregate" - mindclip_recordings AI MindClip recordings (action: "list" | "get" | "summary" | "transcript") - mindclip_list_todos list AI-extracted to-dos (filters: completion, category, source recording, time range) - mindclip_recall AI-curated assistant views (period: "daily" | "weekly" | "urgent_todos")