@knowttl/ha-axi 0.1.0-alpha.0 → 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -2
- package/artium-inventory.json +38 -1
- package/dist/cli.js +16 -6
- package/dist/core/output/command.js +91 -1
- package/dist/core/transport/rest.js +23 -1
- package/dist/core/transport/ws.js +8 -2
- package/dist/core/writes/coordinator.js +10 -7
- package/dist/features/actions/commands.js +254 -0
- package/dist/features/actions/feature.js +13 -0
- package/dist/features/core/home.js +56 -0
- package/dist/features/diagnostics/commands.js +1 -8
- package/dist/features/raw/commands.js +4 -37
- package/dist/features/states/commands.js +100 -0
- package/dist/features/states/feature.js +8 -0
- package/dist/generated/registry.js +43 -0
- package/package.json +1 -1
- package/skills/ha-axi/SKILL.md +56 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Home Assistant OS core admin AXI CLI for agents (strict TypeScript, standalone and via artium-axi).
|
|
4
4
|
|
|
5
|
-
`ha-axi` gives an AI agent UI-free command-line access to Home Assistant OS core commands, diagnostics and raw REST and WebSocket fallbacks.
|
|
5
|
+
`ha-axi` gives an AI agent UI-free command-line access to Home Assistant OS core commands, diagnostics, states, actions, events and raw REST and WebSocket fallbacks.
|
|
6
6
|
It follows the AXI Credential Standard v2 (with one approved standalone deviation for local LAN HTTP) and sends no telemetry.
|
|
7
7
|
|
|
8
8
|
## Status
|
|
@@ -14,7 +14,8 @@ Unit `S1d` adds the WebSocket transport and the raw `ws` fallback.
|
|
|
14
14
|
Unit `S1e` adds the [dedicated write coordinator](docs/design/design.md#write-lifecycle-preview-confirmation-pre-dispatch-intent-and-crash-recovery) and local write journal inspection.
|
|
15
15
|
Unit `S1f` (`ha-axi` side) names the npm package `@knowttl/ha-axi` and ships the [hosted integration artifacts](docs/design/design.md#artium-hosted-contract-s1f).
|
|
16
16
|
Unit `S2` adds [diagnostics commands](skills/ha-axi/SKILL.md#commands) for logs, repairs, integrations, templates, history and logbook.
|
|
17
|
-
|
|
17
|
+
Unit `S3` adds the bare `ha-axi` home summary, `states list`, `states get` and `actions list`, and the dedicated `states set`, `actions call` and `events fire` writes.
|
|
18
|
+
The package is published to npm as `@knowttl/ha-axi`; see [Release](#release).
|
|
18
19
|
More Home Assistant commands arrive in later units; see the [implementation plan](docs/design/implementation-plan.md).
|
|
19
20
|
|
|
20
21
|
## Setup
|
|
@@ -57,14 +58,42 @@ node dist/cli.js api GET /api/calendars --profile home
|
|
|
57
58
|
node dist/cli.js ws get_config --profile home
|
|
58
59
|
node dist/cli.js logs list --level warning --profile home
|
|
59
60
|
node dist/cli.js history get sun.sun --since 1h --profile home
|
|
61
|
+
node dist/cli.js --profile home
|
|
62
|
+
node dist/cli.js states list --domain light --profile home
|
|
63
|
+
node dist/cli.js actions list --domain light --profile home
|
|
60
64
|
```
|
|
61
65
|
|
|
66
|
+
To try a dedicated write, first preview the action.
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
echo '{"target":{"entity_id":"light.porch"}}' | node dist/cli.js actions call light.toggle --stdin --profile home
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
To apply it using the example profile above, save that profile again with the `actions.call` grant and replace `'<digest>'` with the preview's `confirm` value.
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
node dist/cli.js profile set home --origin https://ha.example.com:8123 --token-env HA_AXI_TOKEN --allow-writes --allow-op actions.call
|
|
76
|
+
echo '{"target":{"entity_id":"light.porch"}}' | node dist/cli.js actions call light.toggle --stdin --execute --confirm '<digest>' --profile home
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
See the [command reference](skills/ha-axi/SKILL.md#commands) for state, action and event payloads and readback outcomes.
|
|
62
80
|
The [packaged agent skill](skills/ha-axi/SKILL.md#credentials) explains profile selection, credential paths and the standalone LAN HTTP option.
|
|
63
81
|
The [raw fallback contract](docs/design/design.md#raw-api-fallbacks-passthrough-policy-single-classifier) explains which `api` and `ws` calls can write and how to enable read-only mode.
|
|
64
82
|
|
|
65
83
|
Use `node dist/cli.js writes pending` to find writes that need reconciliation, then run `node dist/cli.js writes status <entryId>` for the entry and its guidance.
|
|
66
84
|
See the [write journal inspection contract](docs/design/design.md#write-journal-inspection).
|
|
67
85
|
|
|
86
|
+
## Release
|
|
87
|
+
|
|
88
|
+
Releases are automated by [Release Please](https://github.com/googleapis/release-please) in [`.github/workflows/release-please.yml`](.github/workflows/release-please.yml).
|
|
89
|
+
npm trusted publishing is configured for that workflow filename.
|
|
90
|
+
The workflow runs on each push to `main` and opens or updates a release pull request when it finds releasable Conventional Commits since the last release.
|
|
91
|
+
Merging that pull request tags the release.
|
|
92
|
+
The publish job installs dependencies from the frozen lockfile and runs `pnpm run check` before publishing the public package with provenance through npm trusted publishing, which requires no npm token secret.
|
|
93
|
+
If the publish job fails, use GitHub Actions' **Re-run failed jobs** to retry it with the release tag from the successful job.
|
|
94
|
+
Versions stay on the `alpha` pre-release line (`0.1.0-alpha.1` follows `0.1.0-alpha.0`) and publish under the `next` dist-tag; a stable version publishes under `latest`.
|
|
95
|
+
Do not edit `CHANGELOG.md` or the version in `package.json` by hand.
|
|
96
|
+
|
|
68
97
|
## Documentation
|
|
69
98
|
|
|
70
99
|
- [Design](docs/design/design.md), including the 2026-11-30 amendments (public MIT repository, raw passthrough policy, WSL development).
|
package/artium-inventory.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"tool": "ha-axi",
|
|
3
3
|
"commands": [
|
|
4
|
+
{
|
|
5
|
+
"name": "actions list",
|
|
6
|
+
"effect": "read",
|
|
7
|
+
"summary": "List actions (services) with name, description, fields and target schema, optionally for one --domain"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"name": "actions call",
|
|
11
|
+
"effect": "write",
|
|
12
|
+
"grantId": "actions.call",
|
|
13
|
+
"summary": "Call an action with an optional target and data, reading back targeted entities; hassio actions, restart and stop are refused"
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"name": "events fire",
|
|
17
|
+
"effect": "write",
|
|
18
|
+
"grantId": "events.fire",
|
|
19
|
+
"summary": "Fire a custom event with optional event data; Home Assistant only acknowledges it"
|
|
20
|
+
},
|
|
4
21
|
{
|
|
5
22
|
"name": "help",
|
|
6
23
|
"effect": "read",
|
|
@@ -95,9 +112,29 @@
|
|
|
95
112
|
"name": "ws",
|
|
96
113
|
"effect": "passthrough",
|
|
97
114
|
"summary": "Send a WebSocket command; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused"
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
"name": "states list",
|
|
118
|
+
"effect": "read",
|
|
119
|
+
"summary": "List entity states with entity ID, state, friendly name and last change, optionally for one --domain"
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
"name": "states get",
|
|
123
|
+
"effect": "read",
|
|
124
|
+
"summary": "Show one entity's state, attributes and last change"
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"name": "states set",
|
|
128
|
+
"effect": "write",
|
|
129
|
+
"grantId": "states.set",
|
|
130
|
+
"summary": "Set an entity's state and attributes in Home Assistant's state machine, with readback"
|
|
98
131
|
}
|
|
99
132
|
],
|
|
100
|
-
"confirmedWrites": [
|
|
133
|
+
"confirmedWrites": [
|
|
134
|
+
"actions.call",
|
|
135
|
+
"events.fire",
|
|
136
|
+
"states.set"
|
|
137
|
+
],
|
|
101
138
|
"blockedCommands": [
|
|
102
139
|
"profile set",
|
|
103
140
|
"profile remove"
|
package/dist/cli.js
CHANGED
|
@@ -8,12 +8,21 @@ import { currentHost } from "./core/credentials/paths.js";
|
|
|
8
8
|
import { PrivateFiles } from "./core/credentials/private-file.js";
|
|
9
9
|
import { Redactor } from "./core/credentials/redact.js";
|
|
10
10
|
import { errorOutput, refusedFlag, render } from "./core/output/command.js";
|
|
11
|
+
import { handlers as actionsHandlers } from "./features/actions/commands.js";
|
|
11
12
|
import { handlers as coreHandlers } from "./features/core/commands.js";
|
|
13
|
+
import { home } from "./features/core/home.js";
|
|
12
14
|
import { handlers as diagnosticsHandlers } from "./features/diagnostics/commands.js";
|
|
13
15
|
import { handlers as rawHandlers } from "./features/raw/commands.js";
|
|
16
|
+
import { handlers as statesHandlers } from "./features/states/commands.js";
|
|
14
17
|
import { registry } from "./generated/registry.js";
|
|
15
18
|
const packageSchema = z.object({ version: z.string() });
|
|
16
|
-
const handlers = {
|
|
19
|
+
const handlers = {
|
|
20
|
+
...coreHandlers,
|
|
21
|
+
...diagnosticsHandlers,
|
|
22
|
+
...statesHandlers,
|
|
23
|
+
...actionsHandlers,
|
|
24
|
+
...rawHandlers,
|
|
25
|
+
};
|
|
17
26
|
function version() {
|
|
18
27
|
const raw = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
19
28
|
return packageSchema.parse(raw).version;
|
|
@@ -24,12 +33,12 @@ function help() {
|
|
|
24
33
|
tool: "ha-axi",
|
|
25
34
|
description: "Home Assistant OS core admin AXI CLI",
|
|
26
35
|
commands,
|
|
27
|
-
help: ["Run `ha-axi --version` to print the installed version"],
|
|
36
|
+
help: ["Run `ha-axi` with no command for a home summary", "Run `ha-axi --version` to print the installed version"],
|
|
28
37
|
});
|
|
29
38
|
}
|
|
30
39
|
async function main(args) {
|
|
31
40
|
const [first, ...rest] = args;
|
|
32
|
-
if (rest.length === 0 && (first ===
|
|
41
|
+
if (rest.length === 0 && (first === "help" || first === "--help" || first === "-h")) {
|
|
33
42
|
process.stdout.write(`${help()}\n`);
|
|
34
43
|
return 0;
|
|
35
44
|
}
|
|
@@ -40,15 +49,16 @@ async function main(args) {
|
|
|
40
49
|
const redactor = new Redactor();
|
|
41
50
|
const name = Object.keys(handlers).find((key) => key.split(" ").every((word, index) => args[index] === word));
|
|
42
51
|
try {
|
|
43
|
-
const
|
|
44
|
-
|
|
52
|
+
const bare = first === undefined || first.startsWith("-");
|
|
53
|
+
const handler = name === undefined ? (bare ? home : undefined) : handlers[name];
|
|
54
|
+
if (handler === undefined) {
|
|
45
55
|
const flag = args.slice(0, 2).find((arg) => arg.startsWith("-"));
|
|
46
56
|
if (flag !== undefined)
|
|
47
57
|
throw refusedFlag(flag);
|
|
48
58
|
throw new AxiError("INVALID_ARGUMENT", "Unknown command", ["Run `ha-axi --help` to list commands"]);
|
|
49
59
|
}
|
|
50
60
|
const context = { host: currentHost(), files: new PrivateFiles(), redactor, userAgent: `ha-axi/${version()}`, stdin: () => buffer(process.stdin) };
|
|
51
|
-
process.stdout.write(render(await handler(args.slice(name.split(" ").length), context), redactor));
|
|
61
|
+
process.stdout.write(render(await handler(args.slice(name === undefined ? 0 : name.split(" ").length), context), redactor));
|
|
52
62
|
return 0;
|
|
53
63
|
}
|
|
54
64
|
catch (error) {
|
|
@@ -1,9 +1,16 @@
|
|
|
1
|
+
import { isUtf8 } from "node:buffer";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
1
3
|
import { parseArgs } from "node:util";
|
|
2
4
|
import { encode } from "@toon-format/toon";
|
|
3
|
-
import {
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { AxiError, errnoCode } from "../credentials/errors.js";
|
|
4
7
|
const SECRET_NAME = /token|secret|passw|key|credential|bearer|auth/i;
|
|
8
|
+
const ENTITY_ID = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*\.[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
|
|
9
|
+
const DOMAIN = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
|
|
10
|
+
const jsonObjectSchema = z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value));
|
|
5
11
|
export const CONFIG = { config: { type: "string" } };
|
|
6
12
|
export const SELECT = { ...CONFIG, profile: { type: "string" } };
|
|
13
|
+
export const PAYLOAD = { "payload-file": { type: "string" }, stdin: { type: "boolean" } };
|
|
7
14
|
export const secretName = (name) => SECRET_NAME.test(name);
|
|
8
15
|
export function refusedFlag(arg) {
|
|
9
16
|
const flag = arg.split("=")[0] ?? arg;
|
|
@@ -44,6 +51,89 @@ export const selector = (values) => ({
|
|
|
44
51
|
...(values.config === undefined ? {} : { config: values.config }),
|
|
45
52
|
...(values.profile === undefined ? {} : { profile: values.profile }),
|
|
46
53
|
});
|
|
54
|
+
const SHELL_SAFE = /^[\w@%+=:,./-]+$/;
|
|
55
|
+
const shellQuote = (value) => (SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`);
|
|
56
|
+
export const selectorFlags = (values) => `${values.profile === undefined ? "" : ` --profile=${shellQuote(values.profile)}`}${values.config === undefined ? "" : ` --config=${shellQuote(values.config)}`}`;
|
|
57
|
+
export const isEntityId = (value) => ENTITY_ID.test(value);
|
|
58
|
+
export const isDomain = (value) => DOMAIN.test(value);
|
|
59
|
+
function normalizeZero(value) {
|
|
60
|
+
if (value === 0)
|
|
61
|
+
return 0;
|
|
62
|
+
if (Array.isArray(value))
|
|
63
|
+
return value.map(normalizeZero);
|
|
64
|
+
if (typeof value === "object" && value !== null) {
|
|
65
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, normalizeZero(item)]));
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
export const stateSchema = z.object({
|
|
70
|
+
entity_id: z.string().refine(isEntityId, "Expected an entity ID"),
|
|
71
|
+
state: z.string(),
|
|
72
|
+
attributes: z.record(z.string(), z.unknown().transform(normalizeZero)),
|
|
73
|
+
last_changed: z.iso.datetime({ offset: true }),
|
|
74
|
+
});
|
|
75
|
+
export const stateFor = (entity) => stateSchema.refine(({ entity_id }) => entity_id === entity, { path: ["entity_id"], error: "Does not match the requested entity" });
|
|
76
|
+
export function entityId(value, flag) {
|
|
77
|
+
if (!isEntityId(value))
|
|
78
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must be an entity ID such as sun.sun`);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
export const listing = (name, rows, empty) => rows.length > 0 ? { count: rows.length, [name]: rows } : { count: 0, [name]: `0 results: ${empty}` };
|
|
82
|
+
export function readInput(path, flag) {
|
|
83
|
+
try {
|
|
84
|
+
return readFileSync(path);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} ${path} cannot be read (${errnoCode(error) ?? "unknown error"})`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function decimalValue(source) {
|
|
91
|
+
const [coefficient = "", exponent = "0"] = source.toLowerCase().split("e");
|
|
92
|
+
const [integer = "", fraction = ""] = coefficient.replace(/^-/, "").split(".");
|
|
93
|
+
const digits = (integer + fraction).replace(/^0+/, "");
|
|
94
|
+
if (digits === "")
|
|
95
|
+
return "0";
|
|
96
|
+
const significant = digits.replace(/0+$/, "");
|
|
97
|
+
const scale = BigInt(exponent) + BigInt(digits.length - significant.length - fraction.length);
|
|
98
|
+
return `${coefficient.startsWith("-") ? "-" : ""}${significant}e${String(scale)}`;
|
|
99
|
+
}
|
|
100
|
+
export async function payload(values, stdin, mode = "write") {
|
|
101
|
+
const file = values["payload-file"];
|
|
102
|
+
if (file !== undefined && values.stdin === true)
|
|
103
|
+
throw new AxiError("INVALID_ARGUMENT", "Use at most one of --payload-file and --stdin");
|
|
104
|
+
const source = file !== undefined ? readInput(file, "--payload-file") : values.stdin === true ? await stdin() : undefined;
|
|
105
|
+
if (source === undefined)
|
|
106
|
+
return undefined;
|
|
107
|
+
const flag = file !== undefined ? "--payload-file" : "--stdin";
|
|
108
|
+
if (!isUtf8(source))
|
|
109
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid UTF-8`);
|
|
110
|
+
let json;
|
|
111
|
+
try {
|
|
112
|
+
json = JSON.parse(source.toString("utf8"), mode === "raw" ? undefined : (key, value, context) => {
|
|
113
|
+
if (!key.isWellFormed() || (typeof value === "string" && !value.isWellFormed())) {
|
|
114
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must contain only well-formed Unicode in JSON keys and strings`);
|
|
115
|
+
}
|
|
116
|
+
if (typeof value !== "number")
|
|
117
|
+
return value;
|
|
118
|
+
if (!Number.isFinite(value)) {
|
|
119
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must contain only finite numbers`);
|
|
120
|
+
}
|
|
121
|
+
if (context?.source !== undefined && decimalValue(context.source) !== decimalValue(JSON.stringify(value))) {
|
|
122
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} contains a number that cannot be sent without rounding`);
|
|
123
|
+
}
|
|
124
|
+
return value === 0 ? 0 : value;
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error instanceof AxiError)
|
|
129
|
+
throw error;
|
|
130
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid JSON`);
|
|
131
|
+
}
|
|
132
|
+
const parsed = jsonObjectSchema.safeParse(json);
|
|
133
|
+
if (!parsed.success)
|
|
134
|
+
throw new AxiError("INVALID_ARGUMENT", `${flag} must contain a JSON object`);
|
|
135
|
+
return parsed.data;
|
|
136
|
+
}
|
|
47
137
|
export const render = (value, redactor) => `${redactor.output(encode(value))}\n`;
|
|
48
138
|
export const errorOutput = (error) => ({
|
|
49
139
|
error: { code: error.code, message: error.message },
|
|
@@ -22,7 +22,29 @@ export function statusError(status, text, label, forbiddenHelp = "Use a token fr
|
|
|
22
22
|
}
|
|
23
23
|
export async function readJson(session, request, schema) {
|
|
24
24
|
const response = await readRest(session, { ...request, maxBytes: request.maxBytes ?? MAX_JSON_RESPONSE_BYTES });
|
|
25
|
-
|
|
25
|
+
return parseJsonResponse(response, schema, `${request.method} ${request.path}`);
|
|
26
|
+
}
|
|
27
|
+
function isEntityNotFound(response) {
|
|
28
|
+
if (response.truncated)
|
|
29
|
+
return false;
|
|
30
|
+
let body;
|
|
31
|
+
try {
|
|
32
|
+
body = JSON.parse(response.text);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
return typeof body === "object" && body !== null && "message" in body && body.message === "Entity not found.";
|
|
38
|
+
}
|
|
39
|
+
export async function readEntityState(session, entity, schema, timeoutMs) {
|
|
40
|
+
const path = `/api/states/${entity}`;
|
|
41
|
+
const response = await readRest(session, { method: "GET", path, maxBytes: MAX_JSON_RESPONSE_BYTES, ...(timeoutMs === undefined ? {} : { timeoutMs }) });
|
|
42
|
+
const label = `GET ${path}`;
|
|
43
|
+
if (response.status === 404 && !isEntityNotFound(response))
|
|
44
|
+
throw new AxiError("UPSTREAM_ERROR", `${label} returned HTTP 404`);
|
|
45
|
+
return parseJsonResponse(response, schema, label);
|
|
46
|
+
}
|
|
47
|
+
function parseJsonResponse(response, schema, label) {
|
|
26
48
|
if (response.status < 200 || response.status > 299)
|
|
27
49
|
throw statusError(response.status, response.text, label);
|
|
28
50
|
if (response.truncated)
|
|
@@ -37,8 +37,14 @@ export async function readWsJson(session, request, schema, redactor) {
|
|
|
37
37
|
const reply = await readWs(session, request);
|
|
38
38
|
if (reply.success)
|
|
39
39
|
return validate(reply.result, schema, label);
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
throw wsFailure(label, reply.error, redactor);
|
|
41
|
+
}
|
|
42
|
+
export function wsFailure(label, error, redactor) {
|
|
43
|
+
const message = `${label} failed (${redactor.text(error.code)}): ${redactor.text(error.message)}`;
|
|
44
|
+
if (error.code === "not_found")
|
|
45
|
+
return new AxiError("NOT_FOUND", message);
|
|
46
|
+
const denied = error.code === "unauthorized" || (error.code === "home_assistant_error" && error.message === "Unauthorized");
|
|
47
|
+
return denied
|
|
42
48
|
? new AxiError("FORBIDDEN", message, ["Use a token from a Home Assistant administrator account"])
|
|
43
49
|
: new AxiError("UPSTREAM_ERROR", message);
|
|
44
50
|
}
|
|
@@ -4,6 +4,7 @@ import { redactPayload } from "../credentials/redact.js";
|
|
|
4
4
|
import { mutateRest, outcomeUnknown, UNKNOWN_OUTCOME } from "../transport/mutate.js";
|
|
5
5
|
import { mutateWs } from "../transport/mutate-ws.js";
|
|
6
6
|
import { statusError } from "../transport/rest.js";
|
|
7
|
+
import { wsFailure } from "../transport/ws.js";
|
|
7
8
|
import { canonicalJson, CONFIRMATION_TTL_SECONDS, confirmationToken, parseToken, sha256, stateHash, STATELESS, } from "./digest.js";
|
|
8
9
|
import { Journal } from "./journal.js";
|
|
9
10
|
export const WRITE_OPTIONS = {
|
|
@@ -55,8 +56,8 @@ function replay(entry) {
|
|
|
55
56
|
}
|
|
56
57
|
return { outcome: outcome.outcome, entryId: intent.entryId, grantId: intent.grantId, target: intent.target, replayed: true, help: [statusHelp(intent.entryId)] };
|
|
57
58
|
}
|
|
58
|
-
|
|
59
|
-
return
|
|
59
|
+
function baseStateHash(before) {
|
|
60
|
+
return before === undefined ? STATELESS : stateHash(before.snapshot);
|
|
60
61
|
}
|
|
61
62
|
const confirmationMismatch = () => new AxiError("CONFIRMATION_MISMATCH", "The confirmation does not match this write or the current Home Assistant state", [
|
|
62
63
|
"Run the preview again and review the changes before executing",
|
|
@@ -77,17 +78,17 @@ async function confirm(plan, input, token) {
|
|
|
77
78
|
throw new AxiError("CONFIRMATION_REQUIRED", `${plan.grantId} needs --confirm <digest> from a preview`, ["Run without --execute to preview the write and get a digest"]);
|
|
78
79
|
}
|
|
79
80
|
checkConfirmationAge(parsed.issuedAtEpoch);
|
|
80
|
-
const beforeHash = await
|
|
81
|
+
const beforeHash = baseStateHash(await plan.before?.());
|
|
81
82
|
checkConfirmationAge(parsed.issuedAtEpoch);
|
|
82
83
|
if (confirmationToken({ ...input, baseStateHash: beforeHash }, parsed.issuedAtEpoch) !== token)
|
|
83
84
|
throw confirmationMismatch();
|
|
84
85
|
return token;
|
|
85
86
|
}
|
|
86
|
-
async function dispatch(plan, session) {
|
|
87
|
+
async function dispatch(plan, session, redactor) {
|
|
87
88
|
if ("ws" in plan) {
|
|
88
89
|
const result = await mutateWs(session, plan.ws, "write");
|
|
89
90
|
if (!result.success)
|
|
90
|
-
throw
|
|
91
|
+
throw wsFailure(`WebSocket command ${plan.ws.type}`, result.error, redactor);
|
|
91
92
|
return await readback(() => plan.verify(result));
|
|
92
93
|
}
|
|
93
94
|
const response = await mutateRest(session, plan.rest, "write");
|
|
@@ -119,7 +120,7 @@ async function execute(plan, journal, intent, { session, redactor }) {
|
|
|
119
120
|
};
|
|
120
121
|
let result;
|
|
121
122
|
try {
|
|
122
|
-
result = await dispatch(plan, session);
|
|
123
|
+
result = await dispatch(plan, session, redactor);
|
|
123
124
|
}
|
|
124
125
|
catch (error) {
|
|
125
126
|
if (!(error instanceof AxiError) || outcomeUnknown(error)) {
|
|
@@ -182,13 +183,15 @@ async function coordinate(request, options, context) {
|
|
|
182
183
|
const input = { grantId: plan.grantId, origin: session.origin, normalizedRequest: normalized(plan) };
|
|
183
184
|
if (options.execute !== true) {
|
|
184
185
|
const issuedAtEpoch = nowEpoch();
|
|
185
|
-
const
|
|
186
|
+
const before = await plan.before?.();
|
|
187
|
+
const token = confirmationToken({ ...input, baseStateHash: baseStateHash(before) }, issuedAtEpoch);
|
|
186
188
|
return {
|
|
187
189
|
outcome: "preview",
|
|
188
190
|
grantId: plan.grantId,
|
|
189
191
|
target: plan.target,
|
|
190
192
|
confirm: token,
|
|
191
193
|
expiresAt: new Date((issuedAtEpoch + CONFIRMATION_TTL_SECONDS) * 1000).toISOString(),
|
|
194
|
+
...(before === undefined ? {} : { changes: redactPayload(before.changes, redactor) }),
|
|
192
195
|
help: [`Run the same command with --execute --confirm ${token} within ${String(CONFIRMATION_TTL_SECONDS / 60)} minutes to apply it`],
|
|
193
196
|
};
|
|
194
197
|
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
5
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
6
|
+
import { redactPayload } from "../../core/credentials/redact.js";
|
|
7
|
+
import { isDomain, isEntityId, listing, parse, PAYLOAD, payload, SELECT, selector, selectorFlags, stateFor } from "../../core/output/command.js";
|
|
8
|
+
import { connect, readEntityState } from "../../core/transport/rest.js";
|
|
9
|
+
import { readWsJson } from "../../core/transport/ws.js";
|
|
10
|
+
import { runWrite, WRITE_OPTIONS } from "../../core/writes/coordinator.js";
|
|
11
|
+
const SLUG = /^[\p{Nd}a-z_]+$/u;
|
|
12
|
+
const SELECTOR_UNICODE_SPACE = /\p{White_Space}/u;
|
|
13
|
+
const DENIED_EVENTS = new Set([
|
|
14
|
+
"*",
|
|
15
|
+
"call_service",
|
|
16
|
+
"component_loaded",
|
|
17
|
+
"core_config_updated",
|
|
18
|
+
"labs_updated",
|
|
19
|
+
"logbook_entry",
|
|
20
|
+
"logging_changed",
|
|
21
|
+
"lovelace_updated",
|
|
22
|
+
"panels_updated",
|
|
23
|
+
"recorder_5min_statistics_generated",
|
|
24
|
+
"recorder_hourly_statistics_generated",
|
|
25
|
+
"service_registered",
|
|
26
|
+
"service_removed",
|
|
27
|
+
"shopping_list_updated",
|
|
28
|
+
"state_changed",
|
|
29
|
+
"state_reported",
|
|
30
|
+
"themes_updated",
|
|
31
|
+
]);
|
|
32
|
+
const DENIED_ACTIONS = new Set(["homeassistant.restart", "homeassistant.stop"]);
|
|
33
|
+
const DENIED_DOMAINS = new Set(["hassio"]);
|
|
34
|
+
const READBACK_WAIT_MS = 2_000;
|
|
35
|
+
const READBACK_POLL_MS = 250;
|
|
36
|
+
const fieldSectionSchema = z.object({ fields: z.record(z.string(), z.unknown()) });
|
|
37
|
+
const servicesSchema = z.record(z.string(), z.record(z.string(), z.object({
|
|
38
|
+
name: z.string().optional(),
|
|
39
|
+
description: z.string().optional(),
|
|
40
|
+
fields: z.record(z.string(), z.unknown()).optional(),
|
|
41
|
+
target: z.unknown().optional(),
|
|
42
|
+
})));
|
|
43
|
+
const targetId = z.union([z.string(), z.array(z.string())]).nullable().optional();
|
|
44
|
+
const targetSelectors = { device_id: targetId, area_id: targetId, floor_id: targetId, label_id: targetId };
|
|
45
|
+
const excludedEntityId = z.string().refine(isEntityId);
|
|
46
|
+
const excludeSchema = z.strictObject({
|
|
47
|
+
...targetSelectors,
|
|
48
|
+
entity_id: z.union([excludedEntityId, z.array(excludedEntityId)]).nullable().optional(),
|
|
49
|
+
});
|
|
50
|
+
const targetEntityId = z.string().refine((id) => isEntityId(id.toLowerCase()));
|
|
51
|
+
function isSelectorSpace(character) {
|
|
52
|
+
const code = character.charCodeAt(0);
|
|
53
|
+
return (code >= 0x1c && code <= 0x1f) || SELECTOR_UNICODE_SPACE.test(character);
|
|
54
|
+
}
|
|
55
|
+
function trimSelector(id) {
|
|
56
|
+
let start = 0;
|
|
57
|
+
let end = id.length;
|
|
58
|
+
while (start < end && isSelectorSpace(id.charAt(start)))
|
|
59
|
+
start++;
|
|
60
|
+
while (end > start && isSelectorSpace(id.charAt(end - 1)))
|
|
61
|
+
end--;
|
|
62
|
+
return id.slice(start, end);
|
|
63
|
+
}
|
|
64
|
+
const scalarEntityIds = (value) => value.split(",").map((id) => trimSelector(id).toLowerCase());
|
|
65
|
+
const targetSchema = z.strictObject({
|
|
66
|
+
...targetSelectors,
|
|
67
|
+
entity_id: z.union([
|
|
68
|
+
z.string().refine((ids) => /^(?:all|none)$/i.test(ids) || scalarEntityIds(ids).every(isEntityId)),
|
|
69
|
+
z.array(targetEntityId),
|
|
70
|
+
]).optional(),
|
|
71
|
+
exclude: excludeSchema.optional(),
|
|
72
|
+
});
|
|
73
|
+
const callPayloadSchema = z.strictObject({
|
|
74
|
+
target: targetSchema.optional(),
|
|
75
|
+
data: z.record(z.string(), z.unknown()).optional(),
|
|
76
|
+
});
|
|
77
|
+
const responseSchema = z.object({ response: z.unknown() });
|
|
78
|
+
const eventReplySchema = z.object({ message: z.string() });
|
|
79
|
+
function open(values, context) {
|
|
80
|
+
const { host, files, redactor, userAgent } = context;
|
|
81
|
+
const selection = selectProfile(selector(values), host, files);
|
|
82
|
+
return { host, files, redactor, selection, session: connect(selection, host, files, redactor, userAgent) };
|
|
83
|
+
}
|
|
84
|
+
function entityIds(value) {
|
|
85
|
+
const list = Array.isArray(value) ? value : [];
|
|
86
|
+
const ids = typeof value === "string" ? scalarEntityIds(value) : list.filter((item) => typeof item === "string").map((item) => item.toLowerCase());
|
|
87
|
+
return [...new Set(ids.filter(isEntityId))].sort();
|
|
88
|
+
}
|
|
89
|
+
async function readState(session, entity, timeoutMs) {
|
|
90
|
+
const { entity_id, state, attributes } = await readEntityState(session, entity, stateFor(entity), timeoutMs);
|
|
91
|
+
return { entity_id, state, attributes };
|
|
92
|
+
}
|
|
93
|
+
async function observe(session, before) {
|
|
94
|
+
const deadline = performance.now() + READBACK_WAIT_MS;
|
|
95
|
+
let changed = false;
|
|
96
|
+
const watch = async (base) => {
|
|
97
|
+
let latest;
|
|
98
|
+
while (!changed) {
|
|
99
|
+
const remaining = deadline - performance.now();
|
|
100
|
+
if (remaining <= 0)
|
|
101
|
+
break;
|
|
102
|
+
try {
|
|
103
|
+
const value = await readState(session, base.entity_id, Math.ceil(remaining));
|
|
104
|
+
if (performance.now() >= deadline)
|
|
105
|
+
break;
|
|
106
|
+
latest = { status: "fulfilled", value };
|
|
107
|
+
if (!isDeepStrictEqual(value, base))
|
|
108
|
+
changed = true;
|
|
109
|
+
}
|
|
110
|
+
catch (reason) {
|
|
111
|
+
if (reason instanceof AxiError && reason.code === "NOT_FOUND" && performance.now() < deadline) {
|
|
112
|
+
latest = { status: "fulfilled", value: null };
|
|
113
|
+
changed = true;
|
|
114
|
+
}
|
|
115
|
+
else if (latest === undefined || (latest.status === "rejected" && !(reason instanceof AxiError && reason.code === "UPSTREAM_TIMEOUT"))) {
|
|
116
|
+
latest = { status: "rejected", reason };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const wait = Math.min(READBACK_POLL_MS, deadline - performance.now());
|
|
120
|
+
if (changed || wait <= 0)
|
|
121
|
+
break;
|
|
122
|
+
await delay(Math.ceil(wait));
|
|
123
|
+
}
|
|
124
|
+
return latest;
|
|
125
|
+
};
|
|
126
|
+
const after = await Promise.all(before.map(watch));
|
|
127
|
+
return { changed, after };
|
|
128
|
+
}
|
|
129
|
+
const actionsList = async (args, context) => {
|
|
130
|
+
const { values } = parse(args, { ...SELECT, domain: { type: "string" } }, 0);
|
|
131
|
+
const domain = values.domain;
|
|
132
|
+
if (domain !== undefined && !isDomain(domain))
|
|
133
|
+
throw new AxiError("INVALID_ARGUMENT", "--domain must be a domain such as light or input_boolean");
|
|
134
|
+
const { session } = open(values, context);
|
|
135
|
+
const { redactor } = context;
|
|
136
|
+
const services = await readWsJson(session, { type: "get_services", payload: {} }, servicesSchema, redactor);
|
|
137
|
+
const rows = Object.entries(services)
|
|
138
|
+
.filter(([name]) => domain === undefined || name === domain)
|
|
139
|
+
.flatMap(([name, actions]) => Object.entries(actions).map(([service, action]) => ({
|
|
140
|
+
action: redactor.text(`${name}.${service}`),
|
|
141
|
+
name: action.name === undefined ? null : redactor.text(action.name),
|
|
142
|
+
description: action.description === undefined ? null : redactor.text(action.description),
|
|
143
|
+
fields: Object.entries(action.fields ?? {}).flatMap(([field, metadata]) => {
|
|
144
|
+
const section = fieldSectionSchema.safeParse(metadata);
|
|
145
|
+
return section.success ? Object.keys(section.data.fields) : [field];
|
|
146
|
+
}).map((field) => redactor.text(field)),
|
|
147
|
+
target: redactPayload(action.target ?? null, redactor),
|
|
148
|
+
})))
|
|
149
|
+
.sort((a, b) => (a.action < b.action ? -1 : a.action > b.action ? 1 : 0));
|
|
150
|
+
const scope = domain === undefined ? "" : ` in domain ${domain}`;
|
|
151
|
+
return {
|
|
152
|
+
...listing("actions", rows, `no actions${scope}`),
|
|
153
|
+
...(rows.length > 0 ? { help: [`Run \`ha-axi actions call <domain.action> --payload-file <path>${selectorFlags(values)}\` to preview a call`] } : {}),
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
function action(raw) {
|
|
157
|
+
const name = raw.toLowerCase();
|
|
158
|
+
const [domain = "", service = "", ...rest] = name.split(".");
|
|
159
|
+
if (rest.length > 0 || !isDomain(domain) || !SLUG.test(service)) {
|
|
160
|
+
throw new AxiError("INVALID_ARGUMENT", "<action> must be <domain>.<action>, such as light.turn_on");
|
|
161
|
+
}
|
|
162
|
+
if (DENIED_DOMAINS.has(domain) || DENIED_ACTIONS.has(name)) {
|
|
163
|
+
throw new AxiError("WRITE_DISABLED", `${name} is refused: ha-axi actions call never sends hassio actions, homeassistant.restart or homeassistant.stop; nothing was sent`, [
|
|
164
|
+
"Restart or stop Home Assistant from its own interface",
|
|
165
|
+
]);
|
|
166
|
+
}
|
|
167
|
+
return { domain, service };
|
|
168
|
+
}
|
|
169
|
+
const actionsCall = async (args, context) => {
|
|
170
|
+
const { values, positionals } = parse(args, { ...SELECT, ...PAYLOAD, ...WRITE_OPTIONS, "return-response": { type: "boolean" } }, 1);
|
|
171
|
+
const { domain, service } = action(positionals[0] ?? "");
|
|
172
|
+
const parsed = callPayloadSchema.safeParse((await payload(values, context.stdin)) ?? {});
|
|
173
|
+
if (!parsed.success) {
|
|
174
|
+
throw new AxiError("INVALID_ARGUMENT", "Use a JSON object with optional target and data objects. Target accepts entity_id, device_id, area_id, floor_id, label_id, and an exclude object with the same selectors.");
|
|
175
|
+
}
|
|
176
|
+
const { target, data } = parsed.data;
|
|
177
|
+
const returnResponse = values["return-response"] === true;
|
|
178
|
+
const write = open(values, context);
|
|
179
|
+
const effective = { ...data, ...target };
|
|
180
|
+
const exclusion = Object.hasOwn(effective, "exclude");
|
|
181
|
+
const entities = exclusion ? [] : entityIds(effective["entity_id"]);
|
|
182
|
+
let baseline = [];
|
|
183
|
+
const before = async () => {
|
|
184
|
+
baseline = await Promise.all(entities.map((entity) => readState(write.session, entity)));
|
|
185
|
+
return { snapshot: baseline, changes: { before: baseline.map(({ entity_id, state }) => ({ entity_id, state })) } };
|
|
186
|
+
};
|
|
187
|
+
const verify = async (result) => {
|
|
188
|
+
const reply = responseSchema.safeParse(result.success ? result.result : undefined);
|
|
189
|
+
const response = returnResponse && reply.success && reply.data.response !== undefined ? { response: reply.data.response } : {};
|
|
190
|
+
if (entities.length === 0) {
|
|
191
|
+
const readback = exclusion ? "exclusions are not resolved locally" : "no entity target";
|
|
192
|
+
return { outcome: "executed_unverified", details: { ...response, readback } };
|
|
193
|
+
}
|
|
194
|
+
const observed = await observe(write.session, baseline);
|
|
195
|
+
const states = baseline.map(({ entity_id, state }, index) => {
|
|
196
|
+
const read = observed.after[index];
|
|
197
|
+
const current = read?.status === "fulfilled" ? read.value : undefined;
|
|
198
|
+
return { entity_id, before: state, after: current?.state ?? null, ...(current === null ? { absent: true } : {}) };
|
|
199
|
+
});
|
|
200
|
+
const failure = observed.after.find((read) => read?.status === "rejected");
|
|
201
|
+
const error = failure?.reason;
|
|
202
|
+
const reason = error instanceof AxiError ? `${error.code}: ${error.message}` : "unexpected error";
|
|
203
|
+
return {
|
|
204
|
+
outcome: observed.changed ? "executed_verified" : "executed_unverified",
|
|
205
|
+
details: { ...response, states, ...(failure === undefined ? {} : { readback: `failed (${reason})` }) },
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const payloadFields = {
|
|
209
|
+
domain,
|
|
210
|
+
service,
|
|
211
|
+
...(data === undefined ? {} : { service_data: data }),
|
|
212
|
+
...(target === undefined ? {} : { target }),
|
|
213
|
+
...(returnResponse ? { return_response: true } : {}),
|
|
214
|
+
};
|
|
215
|
+
return await runWrite({
|
|
216
|
+
grantId: "actions.call",
|
|
217
|
+
target: entities.length === 0 ? `${domain}.${service}` : `${domain}.${service} on ${entities.join(", ")}`,
|
|
218
|
+
ws: { type: "call_service", payload: payloadFields },
|
|
219
|
+
...(entities.length === 0 ? {} : { before }),
|
|
220
|
+
verify,
|
|
221
|
+
}, values, write);
|
|
222
|
+
};
|
|
223
|
+
const eventsFire = async (args, context) => {
|
|
224
|
+
const { values, positionals } = parse(args, { ...SELECT, ...PAYLOAD, ...WRITE_OPTIONS }, 1);
|
|
225
|
+
const eventType = positionals[0] ?? "";
|
|
226
|
+
if (eventType === "" || Array.from(eventType).length > 64 || eventType === "." || eventType === "..") {
|
|
227
|
+
throw new AxiError("INVALID_ARGUMENT", "<event_type> must be 1 to 64 characters and cannot be . or ..");
|
|
228
|
+
}
|
|
229
|
+
if (eventType.startsWith("homeassistant_") || eventType.endsWith("_registry_updated") || DENIED_EVENTS.has(eventType)) {
|
|
230
|
+
throw new AxiError("WRITE_DISABLED", `${eventType} is reserved by Home Assistant; nothing was sent`);
|
|
231
|
+
}
|
|
232
|
+
const data = (await payload(values, context.stdin)) ?? {};
|
|
233
|
+
const write = open(values, context);
|
|
234
|
+
const verify = (response) => {
|
|
235
|
+
let json;
|
|
236
|
+
try {
|
|
237
|
+
json = JSON.parse(response.text);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
json = undefined;
|
|
241
|
+
}
|
|
242
|
+
const reply = eventReplySchema.safeParse(json);
|
|
243
|
+
return Promise.resolve({
|
|
244
|
+
outcome: "executed_unverified",
|
|
245
|
+
...(reply.success ? { details: { message: reply.data.message } } : {}),
|
|
246
|
+
});
|
|
247
|
+
};
|
|
248
|
+
return await runWrite({ grantId: "events.fire", target: eventType, rest: { method: "POST", path: `/api/events/${encodeURIComponent(eventType)}`, body: Buffer.from(JSON.stringify(data)) }, verify }, values, write);
|
|
249
|
+
};
|
|
250
|
+
export const handlers = {
|
|
251
|
+
"actions list": actionsList,
|
|
252
|
+
"actions call": actionsCall,
|
|
253
|
+
"events fire": eventsFire,
|
|
254
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "actions",
|
|
3
|
+
commands: [
|
|
4
|
+
{ name: "actions list", effect: "read", summary: "List actions (services) with name, description, fields and target schema, optionally for one --domain" },
|
|
5
|
+
{
|
|
6
|
+
name: "actions call",
|
|
7
|
+
effect: "write",
|
|
8
|
+
grantId: "actions.call",
|
|
9
|
+
summary: "Call an action with an optional target and data, reading back targeted entities; hassio actions, restart and stop are refused",
|
|
10
|
+
},
|
|
11
|
+
{ name: "events fire", effect: "write", grantId: "events.fire", summary: "Fire a custom event with optional event data; Home Assistant only acknowledges it" },
|
|
12
|
+
],
|
|
13
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
3
|
+
import { parse, SELECT, selector, selectorFlags, stateSchema } from "../../core/output/command.js";
|
|
4
|
+
import { connect, readJson } from "../../core/transport/rest.js";
|
|
5
|
+
import { readWsJson } from "../../core/transport/ws.js";
|
|
6
|
+
const WARNING_LEVELS = new Set(["WARNING", "ERROR", "CRITICAL"]);
|
|
7
|
+
const RECENT_WARNINGS = 3;
|
|
8
|
+
const configSchema = z.object({ version: z.string(), state: z.string(), location_name: z.string() });
|
|
9
|
+
const statesSchema = z.array(stateSchema.pick({ entity_id: true }));
|
|
10
|
+
const repairsSchema = z.object({ issues: z.array(z.object({ ignored: z.boolean() })) });
|
|
11
|
+
const systemLogSchema = z.array(z.object({
|
|
12
|
+
message: z.tuple([z.string()], z.string()),
|
|
13
|
+
level: z.string(),
|
|
14
|
+
source: z.tuple([z.string(), z.number()]),
|
|
15
|
+
timestamp: z.number(),
|
|
16
|
+
}));
|
|
17
|
+
export const home = async (args, { host, files, redactor, userAgent }) => {
|
|
18
|
+
const { values } = parse(args, SELECT, 0);
|
|
19
|
+
const flags = selectorFlags(values);
|
|
20
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
21
|
+
const [config, states, repairs, log] = await Promise.all([
|
|
22
|
+
readJson(session, { method: "GET", path: "/api/config" }, configSchema),
|
|
23
|
+
readJson(session, { method: "GET", path: "/api/states" }, statesSchema),
|
|
24
|
+
readWsJson(session, { type: "repairs/list_issues", payload: {} }, repairsSchema, redactor),
|
|
25
|
+
readWsJson(session, { type: "system_log/list", payload: {} }, systemLogSchema, redactor),
|
|
26
|
+
]);
|
|
27
|
+
const counts = new Map();
|
|
28
|
+
for (const { entity_id } of states) {
|
|
29
|
+
const domain = entity_id.split(".", 1)[0] ?? "";
|
|
30
|
+
counts.set(domain, (counts.get(domain) ?? 0) + 1);
|
|
31
|
+
}
|
|
32
|
+
const domains = [...counts].map(([domain, count]) => ({ domain, count }))
|
|
33
|
+
.sort((a, b) => b.count - a.count || (a.domain < b.domain ? -1 : 1));
|
|
34
|
+
const activeRepairs = repairs.issues.filter((issue) => !issue.ignored).length;
|
|
35
|
+
const warnings = log.filter((entry) => WARNING_LEVELS.has(entry.level.toUpperCase())).sort((a, b) => b.timestamp - a.timestamp);
|
|
36
|
+
const recent = warnings.slice(0, RECENT_WARNINGS).map((entry) => ({
|
|
37
|
+
level: redactor.text(entry.level),
|
|
38
|
+
source: `${redactor.text(entry.source[0])}:${String(entry.source[1])}`,
|
|
39
|
+
lastOccurred: new Date(Math.round(entry.timestamp * 1_000)).toISOString(),
|
|
40
|
+
messageSample: redactor.text(entry.message.reduce((_, message) => message)),
|
|
41
|
+
}));
|
|
42
|
+
return {
|
|
43
|
+
homeAssistant: { version: redactor.text(config.version), state: redactor.text(config.state), location: redactor.text(config.location_name) },
|
|
44
|
+
entities: states.length,
|
|
45
|
+
domains: domains.length > 0 ? domains : "0 results: no entities",
|
|
46
|
+
activeRepairs,
|
|
47
|
+
warnings: warnings.length,
|
|
48
|
+
recentWarnings: recent.length > 0 ? recent : "0 results: no warnings or errors in the system log",
|
|
49
|
+
help: [
|
|
50
|
+
`Run \`ha-axi states list --domain <domain>${flags}\` to list a domain's entities`,
|
|
51
|
+
...(activeRepairs > 0 ? [`Run \`ha-axi repairs list${flags}\` to see the active repair issues`] : []),
|
|
52
|
+
...(warnings.length > 0 ? [`Run \`ha-axi logs list --level warning${flags}\` for every warning and error`] : []),
|
|
53
|
+
"Run `ha-axi --help` to list every command",
|
|
54
|
+
],
|
|
55
|
+
};
|
|
56
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { selectProfile } from "../../core/credentials/config.js";
|
|
3
3
|
import { AxiError } from "../../core/credentials/errors.js";
|
|
4
|
-
import { parse, SELECT, selector } from "../../core/output/command.js";
|
|
4
|
+
import { entityId, listing, parse, SELECT, selector } from "../../core/output/command.js";
|
|
5
5
|
import { connect, readJson, readRest, statusError } from "../../core/transport/rest.js";
|
|
6
6
|
import { readWsJson } from "../../core/transport/ws.js";
|
|
7
7
|
const LEVELS = ["debug", "info", "warning", "error", "critical"];
|
|
@@ -9,7 +9,6 @@ const DURATION = /^([1-9]\d*)([smhd])$/;
|
|
|
9
9
|
const DAY_MS = 86_400_000;
|
|
10
10
|
const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000, d: DAY_MS };
|
|
11
11
|
const MAX_WINDOW_MS = 365 * DAY_MS;
|
|
12
|
-
const ENTITY_ID = /^[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*\.[\p{Nd}a-z]+(?:_[\p{Nd}a-z]+)*$/u;
|
|
13
12
|
const MAX_TEMPLATE_BYTES = 16 * 1024 * 1024;
|
|
14
13
|
const systemLogSchema = z.array(z.object({
|
|
15
14
|
message: z.tuple([z.string()], z.string()),
|
|
@@ -40,12 +39,6 @@ const logbookSchema = z.array(z.object({
|
|
|
40
39
|
function open(values, { host, files, redactor, userAgent }) {
|
|
41
40
|
return connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
42
41
|
}
|
|
43
|
-
const listing = (name, rows, empty) => rows.length > 0 ? { count: rows.length, [name]: rows } : { count: 0, [name]: `0 results: ${empty}` };
|
|
44
|
-
function entityId(value, flag) {
|
|
45
|
-
if (!ENTITY_ID.test(value))
|
|
46
|
-
throw new AxiError("INVALID_ARGUMENT", `${flag} must be an entity ID such as sun.sun`);
|
|
47
|
-
return value;
|
|
48
|
-
}
|
|
49
42
|
function window(since) {
|
|
50
43
|
const match = DURATION.exec(since ?? "");
|
|
51
44
|
const ms = match === null ? 0 : Number(match[1]) * (UNIT_MS[match[2] ?? ""] ?? 0);
|
|
@@ -1,11 +1,8 @@
|
|
|
1
|
-
import { isUtf8 } from "node:buffer";
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
3
1
|
import { StringDecoder } from "node:string_decoder";
|
|
4
|
-
import { z } from "zod";
|
|
5
2
|
import { selectProfile } from "../../core/credentials/config.js";
|
|
6
|
-
import { AxiError
|
|
3
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
7
4
|
import { redactPayload } from "../../core/credentials/redact.js";
|
|
8
|
-
import { parse, SELECT, secretName, selector } from "../../core/output/command.js";
|
|
5
|
+
import { parse, PAYLOAD, payload as readPayload, readInput, SELECT, secretName, selector } from "../../core/output/command.js";
|
|
9
6
|
import { connect, MAX_REST_RESPONSE_BYTES, readRest } from "../../core/transport/rest.js";
|
|
10
7
|
import { readWs } from "../../core/transport/ws.js";
|
|
11
8
|
import { passthroughRest, passthroughWs } from "../../core/writes/passthrough.js";
|
|
@@ -16,8 +13,7 @@ const FORBIDDEN_HEADERS = new Set([
|
|
|
16
13
|
const HTTP_TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
17
14
|
const DEFAULT_MAX_BYTES = 512 * 1024;
|
|
18
15
|
const MAX_TIMEOUT_MS = 600_000;
|
|
19
|
-
const
|
|
20
|
-
const WS_OPTIONS = { ...SELECT, "payload-file": { type: "string" }, stdin: { type: "boolean" }, timeout: { type: "string" } };
|
|
16
|
+
const WS_OPTIONS = { ...SELECT, ...PAYLOAD, timeout: { type: "string" } };
|
|
21
17
|
const OPTIONS = {
|
|
22
18
|
...SELECT,
|
|
23
19
|
query: { type: "string", multiple: true },
|
|
@@ -59,31 +55,6 @@ function integer(value, flag, max) {
|
|
|
59
55
|
throw new AxiError("INVALID_ARGUMENT", `${flag} must be an integer from 1 to ${String(max)}`);
|
|
60
56
|
return parsed;
|
|
61
57
|
}
|
|
62
|
-
function readInput(path, flag) {
|
|
63
|
-
try {
|
|
64
|
-
return readFileSync(path);
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
throw new AxiError("INVALID_ARGUMENT", `${flag} ${path} cannot be read (${errnoCode(error) ?? "unknown error"})`);
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
function wsPayload(source, flag) {
|
|
71
|
-
if (source === undefined)
|
|
72
|
-
return {};
|
|
73
|
-
if (!isUtf8(source))
|
|
74
|
-
throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid UTF-8`);
|
|
75
|
-
let json;
|
|
76
|
-
try {
|
|
77
|
-
json = JSON.parse(source.toString("utf8"));
|
|
78
|
-
}
|
|
79
|
-
catch {
|
|
80
|
-
throw new AxiError("INVALID_ARGUMENT", `${flag} is not valid JSON`);
|
|
81
|
-
}
|
|
82
|
-
const parsed = payloadSchema.safeParse(json);
|
|
83
|
-
if (!parsed.success)
|
|
84
|
-
throw new AxiError("INVALID_ARGUMENT", `${flag} must contain a JSON object`);
|
|
85
|
-
return parsed.data;
|
|
86
|
-
}
|
|
87
58
|
function vendorBody(response, redactor) {
|
|
88
59
|
const mediaType = response.contentType.split(";", 1)[0]?.trim().toLowerCase();
|
|
89
60
|
if (mediaType === "application/json" || mediaType?.endsWith("+json")) {
|
|
@@ -141,11 +112,7 @@ const api = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
|
141
112
|
const ws = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
142
113
|
const { values, positionals } = parse(args, WS_OPTIONS, 1);
|
|
143
114
|
const [type = ""] = positionals;
|
|
144
|
-
const
|
|
145
|
-
if (file !== undefined && values.stdin === true)
|
|
146
|
-
throw new AxiError("INVALID_ARGUMENT", "Use at most one of --payload-file and --stdin");
|
|
147
|
-
const source = file !== undefined ? readInput(file, "--payload-file") : values.stdin === true ? await stdin() : undefined;
|
|
148
|
-
const payload = wsPayload(source, file !== undefined ? "--payload-file" : "--stdin");
|
|
115
|
+
const payload = (await readPayload(values, stdin, "raw")) ?? {};
|
|
149
116
|
const target = classifyWs(type, payload);
|
|
150
117
|
const timeoutMs = integer(values.timeout, "--timeout", MAX_TIMEOUT_MS);
|
|
151
118
|
const selection = selectProfile(selector(values), host, files);
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { selectProfile } from "../../core/credentials/config.js";
|
|
4
|
+
import { AxiError } from "../../core/credentials/errors.js";
|
|
5
|
+
import { redactPayload } from "../../core/credentials/redact.js";
|
|
6
|
+
import { entityId, isDomain, listing, parse, PAYLOAD, payload, SELECT, selector, selectorFlags, stateFor, stateSchema } from "../../core/output/command.js";
|
|
7
|
+
import { connect, readEntityState, readJson } from "../../core/transport/rest.js";
|
|
8
|
+
import { runWrite, WRITE_OPTIONS } from "../../core/writes/coordinator.js";
|
|
9
|
+
const STATE_VALUE = /^[\s\S]{0,255}$/u;
|
|
10
|
+
const row = (state, redactor) => {
|
|
11
|
+
const name = state.attributes["friendly_name"];
|
|
12
|
+
return {
|
|
13
|
+
entity_id: redactor.text(state.entity_id),
|
|
14
|
+
state: redactor.text(state.state),
|
|
15
|
+
friendly_name: typeof name === "string" ? redactor.text(name) : null,
|
|
16
|
+
last_changed: redactor.text(state.last_changed),
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
async function readState(session, entity) {
|
|
20
|
+
try {
|
|
21
|
+
return await readEntityState(session, entity, stateFor(entity));
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error instanceof AxiError && error.code === "NOT_FOUND")
|
|
25
|
+
return null;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const statesList = async (args, { host, files, redactor, userAgent }) => {
|
|
30
|
+
const { values } = parse(args, { ...SELECT, domain: { type: "string" } }, 0);
|
|
31
|
+
const domain = values.domain;
|
|
32
|
+
if (domain !== undefined && !isDomain(domain))
|
|
33
|
+
throw new AxiError("INVALID_ARGUMENT", "--domain must be a domain such as light or sensor");
|
|
34
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
35
|
+
const states = await readJson(session, { method: "GET", path: "/api/states" }, z.array(stateSchema));
|
|
36
|
+
const rows = states
|
|
37
|
+
.filter((state) => domain === undefined || state.entity_id.startsWith(`${domain}.`))
|
|
38
|
+
.sort((a, b) => (a.entity_id < b.entity_id ? -1 : a.entity_id > b.entity_id ? 1 : 0))
|
|
39
|
+
.map((state) => row(state, redactor));
|
|
40
|
+
const scope = domain === undefined ? "" : ` in domain ${domain}`;
|
|
41
|
+
return {
|
|
42
|
+
...listing("states", rows, `no entities${scope}`),
|
|
43
|
+
...(rows.length > 0
|
|
44
|
+
? { help: [`Run \`ha-axi states get <entity_id>${selectorFlags(values)}\` for one entity's attributes`] }
|
|
45
|
+
: domain === undefined ? {} : { help: [`Run \`ha-axi states list${selectorFlags(values)}\` without --domain to see every domain`] }),
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
const statesGet = async (args, { host, files, redactor, userAgent }) => {
|
|
49
|
+
const { values, positionals } = parse(args, SELECT, 1);
|
|
50
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
51
|
+
const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
|
|
52
|
+
const state = await readState(session, entity);
|
|
53
|
+
if (state === null) {
|
|
54
|
+
throw new AxiError("NOT_FOUND", `Entity ${entity} was not found`, [`Run \`ha-axi states list${selectorFlags(values)}\` to see the entity IDs Home Assistant knows`]);
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
...row(state, redactor),
|
|
58
|
+
attributes: redactPayload(state.attributes, redactor),
|
|
59
|
+
};
|
|
60
|
+
};
|
|
61
|
+
const statesSet = async (args, { host, files, redactor, userAgent, stdin }) => {
|
|
62
|
+
const { values, positionals } = parse(args, { ...SELECT, ...PAYLOAD, ...WRITE_OPTIONS }, 2);
|
|
63
|
+
const entity = entityId(positionals[0] ?? "", "<entity_id>");
|
|
64
|
+
const value = positionals[1] ?? "";
|
|
65
|
+
if (!STATE_VALUE.test(value))
|
|
66
|
+
throw new AxiError("INVALID_ARGUMENT", "<state> must be at most 255 characters");
|
|
67
|
+
const attributes = await payload(values, stdin);
|
|
68
|
+
const selection = selectProfile(selector(values), host, files);
|
|
69
|
+
const session = connect(selection, host, files, redactor, userAgent);
|
|
70
|
+
const path = `/api/states/${entity}`;
|
|
71
|
+
const before = async () => {
|
|
72
|
+
const observed = await readState(session, entity);
|
|
73
|
+
const current = observed === null ? null : { state: observed.state, attributes: observed.attributes };
|
|
74
|
+
const clearsAttributes = current !== null && Object.keys(current.attributes).length > 0 && Object.keys(attributes ?? {}).length === 0;
|
|
75
|
+
return {
|
|
76
|
+
snapshot: current === null ? null : { entity_id: entity, ...current },
|
|
77
|
+
changes: {
|
|
78
|
+
before: current,
|
|
79
|
+
after: { state: value, attributes: attributes ?? {} },
|
|
80
|
+
...(clearsAttributes ? { warning: "Home Assistant will clear the entity's existing attributes" } : {}),
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
const verify = async () => {
|
|
85
|
+
const observed = await readState(session, entity);
|
|
86
|
+
if (observed === null)
|
|
87
|
+
return { outcome: "executed_mismatch" };
|
|
88
|
+
const matches = observed.state === value && isDeepStrictEqual(observed.attributes, attributes ?? {});
|
|
89
|
+
return { outcome: matches ? "executed_verified" : "executed_mismatch", details: { state: observed.state } };
|
|
90
|
+
};
|
|
91
|
+
const body = Buffer.from(JSON.stringify({ state: value, ...(attributes === undefined ? {} : { attributes }) }));
|
|
92
|
+
return await runWrite({ grantId: "states.set", target: entity, rest: { method: "POST", path, body }, before, verify }, values, {
|
|
93
|
+
host, files, redactor, selection, session,
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
export const handlers = {
|
|
97
|
+
"states list": statesList,
|
|
98
|
+
"states get": statesGet,
|
|
99
|
+
"states set": statesSet,
|
|
100
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const feature = {
|
|
2
|
+
name: "states",
|
|
3
|
+
commands: [
|
|
4
|
+
{ name: "states list", effect: "read", summary: "List entity states with entity ID, state, friendly name and last change, optionally for one --domain" },
|
|
5
|
+
{ name: "states get", effect: "read", summary: "Show one entity's state, attributes and last change" },
|
|
6
|
+
{ name: "states set", effect: "write", grantId: "states.set", summary: "Set an entity's state and attributes in Home Assistant's state machine, with readback" },
|
|
7
|
+
],
|
|
8
|
+
};
|
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
export const registry = {
|
|
2
2
|
"features": [
|
|
3
|
+
{
|
|
4
|
+
"name": "actions",
|
|
5
|
+
"commands": [
|
|
6
|
+
{
|
|
7
|
+
"name": "actions list",
|
|
8
|
+
"effect": "read",
|
|
9
|
+
"summary": "List actions (services) with name, description, fields and target schema, optionally for one --domain"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"name": "actions call",
|
|
13
|
+
"effect": "write",
|
|
14
|
+
"grantId": "actions.call",
|
|
15
|
+
"summary": "Call an action with an optional target and data, reading back targeted entities; hassio actions, restart and stop are refused"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"name": "events fire",
|
|
19
|
+
"effect": "write",
|
|
20
|
+
"grantId": "events.fire",
|
|
21
|
+
"summary": "Fire a custom event with optional event data; Home Assistant only acknowledges it"
|
|
22
|
+
}
|
|
23
|
+
]
|
|
24
|
+
},
|
|
3
25
|
{
|
|
4
26
|
"name": "core",
|
|
5
27
|
"commands": [
|
|
@@ -111,6 +133,27 @@ export const registry = {
|
|
|
111
133
|
"summary": "Send a WebSocket command; writes pass through unless HA_AXI_READ_ONLY=true, deferred v2 families are refused"
|
|
112
134
|
}
|
|
113
135
|
]
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"name": "states",
|
|
139
|
+
"commands": [
|
|
140
|
+
{
|
|
141
|
+
"name": "states list",
|
|
142
|
+
"effect": "read",
|
|
143
|
+
"summary": "List entity states with entity ID, state, friendly name and last change, optionally for one --domain"
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
"name": "states get",
|
|
147
|
+
"effect": "read",
|
|
148
|
+
"summary": "Show one entity's state, attributes and last change"
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
"name": "states set",
|
|
152
|
+
"effect": "write",
|
|
153
|
+
"grantId": "states.set",
|
|
154
|
+
"summary": "Set an entity's state and attributes in Home Assistant's state machine, with readback"
|
|
155
|
+
}
|
|
156
|
+
]
|
|
114
157
|
}
|
|
115
158
|
]
|
|
116
159
|
};
|
package/package.json
CHANGED
package/skills/ha-axi/SKILL.md
CHANGED
|
@@ -7,11 +7,14 @@ description: Manage a Home Assistant OS instance from the command line through t
|
|
|
7
7
|
|
|
8
8
|
`ha-axi` is an Agent eXperience Interface (AXI) CLI for Home Assistant OS core administration.
|
|
9
9
|
The npm package is `@knowttl/ha-axi` and its command is `ha-axi`.
|
|
10
|
-
The package is awaiting its first npm release.
|
|
11
10
|
Output is TOON by default; errors are printed to stdout in the same structured format with a non-zero exit code.
|
|
12
11
|
|
|
13
12
|
## Commands
|
|
14
13
|
|
|
14
|
+
- `ha-axi [--profile <name>] [--config <path>]` prints a home summary with the Home Assistant version, state and location, entity counts by domain, the active repair count, and next steps.
|
|
15
|
+
Recent warning rows report the log group's `lastOccurred` time and a `messageSample` from the group.
|
|
16
|
+
It counts warning, error and critical log entries together and shows up to three of the most recent entries.
|
|
17
|
+
The suggested commands that contact Home Assistant retain any explicit profile and config selections.
|
|
15
18
|
- `ha-axi help` (or `ha-axi --help`): list every command with its effect (`read`, `write` or `passthrough`).
|
|
16
19
|
- `ha-axi --version`: print the installed version.
|
|
17
20
|
- `ha-axi auth status [--profile <name>] [--config <path>]`: show the selected profile, how it was selected, the origin, the token source (`env:<VAR>` or `file:<path>`), file protection, read-only state and write grants. It resolves the token but never prints it.
|
|
@@ -43,12 +46,63 @@ Output is TOON by default; errors are printed to stdout in the same structured f
|
|
|
43
46
|
Both commands take `--since` as a positive integer without leading zeroes followed by `s`, `m`, `h` or `d`, from 1 second to 365 days.
|
|
44
47
|
- Every diagnostics command accepts `--profile <name>` and `--config <path>`.
|
|
45
48
|
An empty list prints `count: 0` and replaces the rows with `0 results: <context>`.
|
|
49
|
+
- `ha-axi states list [--domain <domain>]`: list entities sorted by ID with `entity_id`, `state`, `friendly_name` and `last_changed`.
|
|
50
|
+
- `ha-axi states get <entity_id>` shows the same fields as `states list` and includes redacted attributes.
|
|
51
|
+
Home Assistant's entity-not-found response returns `NOT_FOUND`, and other HTTP 404 responses return `UPSTREAM_ERROR`.
|
|
52
|
+
- `ha-axi actions list [--domain <domain>]`: list actions as `<domain>.<action>` with name, description, field names and target schema.
|
|
53
|
+
`actions list --domain` and the domain part of `actions call` use Home Assistant's domain grammar, the same as `states list --domain`.
|
|
54
|
+
Fields grouped in a service section are listed by their callable names.
|
|
55
|
+
- Every `states`, `actions` and `events` command accepts `--profile <name>` and `--config <path>`.
|
|
56
|
+
Empty lists use the same `0 results` format as diagnostics.
|
|
57
|
+
The navigation hints from `states list`, `states get` and `actions list` retain any explicit profile and config selections.
|
|
58
|
+
- The dedicated write commands below accept `--execute --confirm <digest>` and an optional `--request-id <id>` during execution.
|
|
59
|
+
Their JSON input comes from either `--payload-file <path>` or `--stdin` and must be one JSON object.
|
|
60
|
+
A number that cannot be sent without changing its value returns `INVALID_ARGUMENT` before preview.
|
|
61
|
+
JSON keys and string values must contain well-formed Unicode.
|
|
62
|
+
See the [safety model](#safety-model) for preview and replay.
|
|
63
|
+
- `ha-axi states set <entity_id> <state> [--payload-file <path> | --stdin]` (grant `states.set`): post the state to Home Assistant's state machine, with the optional JSON object as the entity's attributes.
|
|
64
|
+
A state longer than 255 characters returns `INVALID_ARGUMENT` before credentials are resolved, matching Home Assistant's limit.
|
|
65
|
+
The preview shows the redacted current and requested state and attributes under `changes`, and warns when an empty or omitted payload will clear existing attributes.
|
|
66
|
+
Home Assistant replaces the entity's attributes with the ones sent, so include every attribute to keep.
|
|
67
|
+
The readback reports `executed_verified` when the state and the complete attribute map match the request, or `READBACK_MISMATCH` when they differ, an unsent attribute remains or the entity is missing.
|
|
68
|
+
Other readback failures report `executed_unverified`.
|
|
69
|
+
- `ha-axi actions call <domain.action> [--payload-file <path> | --stdin] [--return-response]` (grant `actions.call`): send `call_service` with the payload's optional `target` and `data` objects (no other keys).
|
|
70
|
+
Preview and execute validate `target` before resolving credentials.
|
|
71
|
+
Its selectors are `entity_id`, `device_id`, `area_id`, `floor_id`, and `label_id`, and `exclude` accepts those same selector keys.
|
|
72
|
+
Selectors take strings or lists of strings, and all except the top-level `entity_id` also accept `null`.
|
|
73
|
+
The top-level `entity_id` accepts comma-separated IDs in a single string or the special values `all` and `none`.
|
|
74
|
+
Excluded entity IDs must already be lowercase and contain no surrounding whitespace.
|
|
75
|
+
Home Assistant receives `data` as `service_data`.
|
|
76
|
+
For readback, `target` overrides `data` by key, including `entity_id` and `exclude`.
|
|
77
|
+
The CLI lowercases entity IDs for reads and trims each ID in a scalar `entity_id` string using Home Assistant's whitespace rules.
|
|
78
|
+
Array entries keep their whitespace, and a byte order mark in a scalar ID is treated as part of the ID during validation.
|
|
79
|
+
An `exclude` key in the effective target skips both the preview snapshot and readback, even if its value is empty.
|
|
80
|
+
In that case, the write target label shows only the service, and an acknowledged call returns `executed_unverified` with a readback note.
|
|
81
|
+
When direct entity IDs remain eligible, the preview shows their current states under `changes`, and the command polls each of them independently until it observes a change or reaches the shared 2-second deadline after the call.
|
|
82
|
+
Readback reports each `before` state and the latest `after` state read within the deadline.
|
|
83
|
+
A confirmed disappearance has `after: null` and `absent: true`.
|
|
84
|
+
An unavailable observation has only `after: null`.
|
|
85
|
+
If a read fails and there is no successful observation for that entity, `details.readback` can report the failure, including when a later poll times out.
|
|
86
|
+
Home Assistant's entity-not-found response counts as a disappearance and verifies a change.
|
|
87
|
+
An observed change to any entity's state or attributes returns `executed_verified`.
|
|
88
|
+
If no change was observed or there are no entity IDs, the command returns `executed_unverified`.
|
|
89
|
+
`--return-response` asks Home Assistant for the action's response data and prints it as `details.response`.
|
|
90
|
+
`hassio` actions, `homeassistant.restart` and `homeassistant.stop` return `WRITE_DISABLED` in any letter case before credentials are resolved, including on preview.
|
|
91
|
+
- `ha-axi events fire <event_type> [--payload-file <path> | --stdin]` (grant `events.fire`): post a custom event with the optional JSON object as event data.
|
|
92
|
+
Event names must be 1 to 64 characters, excluding `.` and `..`, and are encoded as one REST path segment.
|
|
93
|
+
Reserved names return `WRITE_DISABLED` before credentials are resolved, including on preview.
|
|
94
|
+
This covers the `*` wildcard, names starting with `homeassistant_`, names ending in `_registry_updated`, and specific core events such as `state_changed` and `call_service`.
|
|
95
|
+
Integration event names such as `timer.finished` are allowed when they pass these checks.
|
|
96
|
+
An acknowledgement returns `executed_unverified` and shows the Home Assistant message as `details.message`.
|
|
46
97
|
- `ha-axi api <METHOD> <path> [--query <key>=<value>]... [--header <name>:<value>]... [--body-file <path> | --stdin] [--max-bytes <n>] [--timeout <ms>] [--profile <name>] [--config <path>]`: send a raw REST request under `/api/` and print the HTTP status and redacted vendor body.
|
|
47
98
|
- `ha-axi ws <type> [--payload-file <path> | --stdin] [--timeout <ms>] [--profile <name>] [--config <path>]`: send one raw WebSocket command with an optional JSON object payload and print `success` with the redacted `result` or vendor `error`.
|
|
48
99
|
ha-axi sets the envelope `id` and `type`, so leave them out of the payload.
|
|
49
100
|
- `ha-axi writes status <entryId>` and `ha-axi writes pending` inspect the local journal. See the [journal command contract](https://github.com/knowttl/ha-axi/blob/main/docs/design/design.md#write-journal-inspection).
|
|
50
101
|
|
|
51
|
-
|
|
102
|
+
Read commands expecting JSON, including `doctor`, `status`, `config check` and the JSON diagnostics reads, return `INVALID_RESPONSE` when a successful upstream response has invalid JSON or an unexpected shape.
|
|
103
|
+
State detail and readback responses must contain valid entity IDs, states, attribute objects and `last_changed` timestamps with offsets.
|
|
104
|
+
A single-entity response must match the requested ID.
|
|
105
|
+
`states list` validates the same fields, while the home summary uses only `entity_id` from each state response.
|
|
52
106
|
More command groups arrive unit by unit; `ha-axi --help` is always the authoritative list.
|
|
53
107
|
|
|
54
108
|
## Credentials
|