@knowttl/ha-axi 0.0.0-stage → 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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -2
  3. package/artium-inventory.json +142 -0
  4. package/axi-credential.schema.json +91 -0
  5. package/dist/cli.js +73 -0
  6. package/dist/core/credentials/config.js +218 -0
  7. package/dist/core/credentials/errors.js +38 -0
  8. package/dist/core/credentials/paths.js +32 -0
  9. package/dist/core/credentials/private-file.js +278 -0
  10. package/dist/core/credentials/redact.js +127 -0
  11. package/dist/core/output/command.js +141 -0
  12. package/dist/core/registry/credential.js +21 -0
  13. package/dist/core/registry/types.js +31 -0
  14. package/dist/core/transport/mutate-ws.js +165 -0
  15. package/dist/core/transport/mutate.js +109 -0
  16. package/dist/core/transport/rest.js +68 -0
  17. package/dist/core/transport/ws.js +50 -0
  18. package/dist/core/writes/coordinator.js +236 -0
  19. package/dist/core/writes/digest.js +29 -0
  20. package/dist/core/writes/journal.js +123 -0
  21. package/dist/core/writes/passthrough.js +17 -0
  22. package/dist/features/actions/commands.js +254 -0
  23. package/dist/features/actions/feature.js +13 -0
  24. package/dist/features/core/commands.js +164 -0
  25. package/dist/features/core/feature.js +16 -0
  26. package/dist/features/core/home.js +56 -0
  27. package/dist/features/core/writes-status.js +51 -0
  28. package/dist/features/diagnostics/commands.js +168 -0
  29. package/dist/features/diagnostics/feature.js +11 -0
  30. package/dist/features/raw/classify.js +76 -0
  31. package/dist/features/raw/commands.js +135 -0
  32. package/dist/features/raw/feature.js +15 -0
  33. package/dist/features/states/commands.js +100 -0
  34. package/dist/features/states/feature.js +8 -0
  35. package/dist/generated/registry.js +159 -0
  36. package/package.json +62 -4
  37. package/skills/ha-axi/SKILL.md +130 -0
@@ -0,0 +1,123 @@
1
+ import { closeSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { z } from "zod";
5
+ import { AxiError, errnoCode } from "../credentials/errors.js";
6
+ import { defaultWriteLog, writeLogPath } from "../credentials/paths.js";
7
+ import { redactPayload } from "../credentials/redact.js";
8
+ const LOCK_WAIT_MS = 10_000;
9
+ const LOCK_RETRY_MS = 25;
10
+ export const OUTCOMES = ["executed_verified", "executed_unverified", "executed_mismatch", "unknown_outcome", "failed"];
11
+ const intentSchema = z.object({
12
+ kind: z.literal("intent"),
13
+ entryId: z.string(),
14
+ requestId: z.string().optional(),
15
+ grantId: z.string(),
16
+ target: z.string(),
17
+ origin: z.string(),
18
+ requestHash: z.string(),
19
+ digest: z.string(),
20
+ timestamp: z.string(),
21
+ });
22
+ const outcomeSchema = z.object({
23
+ kind: z.literal("outcome"),
24
+ entryId: z.string(),
25
+ outcome: z.enum(OUTCOMES),
26
+ code: z.string().optional(),
27
+ message: z.string().optional(),
28
+ timestamp: z.string(),
29
+ });
30
+ const entrySchema = z.discriminatedUnion("kind", [intentSchema, outcomeSchema]);
31
+ export class Journal {
32
+ path;
33
+ #defaultDirectory;
34
+ #files;
35
+ #redactor;
36
+ constructor(host, files, redactor) {
37
+ this.path = writeLogPath(host);
38
+ this.#defaultDirectory = defaultWriteLog(host);
39
+ this.#files = files;
40
+ this.#redactor = redactor;
41
+ }
42
+ entries() {
43
+ const records = (this.#files.read(this.path, "secret", true) ?? "").split("\n").flatMap((line) => {
44
+ try {
45
+ const parsed = entrySchema.safeParse(JSON.parse(line));
46
+ return parsed.success ? [parsed.data] : [];
47
+ }
48
+ catch {
49
+ return [];
50
+ }
51
+ });
52
+ const outcomes = new Map(records.flatMap((record) => (record.kind === "outcome" ? [[record.entryId, record]] : [])));
53
+ return records.flatMap((record) => {
54
+ if (record.kind !== "intent")
55
+ return [];
56
+ const outcome = outcomes.get(record.entryId);
57
+ return [outcome === undefined ? { intent: record } : { intent: record, outcome }];
58
+ });
59
+ }
60
+ append(record) {
61
+ this.#files.append(this.path, this.#defaultDirectory, JSON.stringify(redactPayload(record, this.#redactor)));
62
+ }
63
+ async locked(action) {
64
+ const lock = `${this.path}.lock`;
65
+ this.#files.ensureDirectory(dirname(this.path), this.#defaultDirectory);
66
+ const deadline = Date.now() + LOCK_WAIT_MS;
67
+ for (;;) {
68
+ const holder = acquire(lock);
69
+ if (holder === undefined)
70
+ break;
71
+ if (holder !== "unknown" && !alive(holder)) {
72
+ rmSync(lock, { force: true });
73
+ continue;
74
+ }
75
+ if (Date.now() >= deadline) {
76
+ throw new AxiError("WRITE_DISABLED", `${lock} is held by another ha-axi write${holder === "unknown" ? "" : ` (process ${String(holder)})`}; nothing was sent`, [
77
+ "Wait for that write to finish, or remove the lock file once no ha-axi process is running",
78
+ ]);
79
+ }
80
+ await delay(LOCK_RETRY_MS);
81
+ }
82
+ try {
83
+ return await action();
84
+ }
85
+ finally {
86
+ rmSync(lock, { force: true });
87
+ }
88
+ }
89
+ }
90
+ function acquire(lock) {
91
+ let fd;
92
+ try {
93
+ fd = openSync(lock, "wx", 0o600);
94
+ }
95
+ catch (error) {
96
+ if (errnoCode(error) !== "EEXIST") {
97
+ throw new AxiError("CONFIG_INSECURE", `${lock} could not be created (${errnoCode(error) ?? "unknown error"}); nothing was sent`);
98
+ }
99
+ try {
100
+ const pid = Number(readFileSync(lock, "utf8"));
101
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : "unknown";
102
+ }
103
+ catch {
104
+ return "unknown";
105
+ }
106
+ }
107
+ try {
108
+ writeSync(fd, String(process.pid));
109
+ }
110
+ finally {
111
+ closeSync(fd);
112
+ }
113
+ return undefined;
114
+ }
115
+ function alive(pid) {
116
+ try {
117
+ process.kill(pid, 0);
118
+ return true;
119
+ }
120
+ catch (error) {
121
+ return errnoCode(error) === "EPERM";
122
+ }
123
+ }
@@ -0,0 +1,17 @@
1
+ import { AxiError } from "../credentials/errors.js";
2
+ import { mutateRest } from "../transport/mutate.js";
3
+ import { mutateWs } from "../transport/mutate-ws.js";
4
+ function requireWriteEnabled(readOnly, label) {
5
+ if (readOnly)
6
+ throw new AxiError("WRITE_DISABLED", `${label} is a raw write and HA_AXI_READ_ONLY is true; nothing was sent`, [
7
+ "Raw reads on the read-safe allowlist still work while HA_AXI_READ_ONLY is true",
8
+ ]);
9
+ }
10
+ export async function passthroughRest(session, readOnly, request) {
11
+ requireWriteEnabled(readOnly, `${request.method} ${request.path}`);
12
+ return await mutateRest(session, request, "write");
13
+ }
14
+ export async function passthroughWs(session, readOnly, request) {
15
+ requireWriteEnabled(readOnly, `WebSocket command ${request.type}`);
16
+ return await mutateWs(session, request, "write");
17
+ }
@@ -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,164 @@
1
+ import { z } from "zod";
2
+ import { DEFAULT_TOKEN, loadConfig, removeProfile, resolveToken, secretSource, selectProfile, setProfile, } from "../../core/credentials/config.js";
3
+ import { AxiError } from "../../core/credentials/errors.js";
4
+ import { configPath, writeLogPath } from "../../core/credentials/paths.js";
5
+ import { CONFIG, parse, SELECT, selector } from "../../core/output/command.js";
6
+ import { grantIdSchema } from "../../core/registry/types.js";
7
+ import { connect, readJson } from "../../core/transport/rest.js";
8
+ import { handlers as writesHandlers } from "./writes-status.js";
9
+ const INSECURE_HTTP_WARNING = "allowInsecureHttp is on: the token travels unencrypted over the LAN; prefer an https:// origin";
10
+ const NEXT_STEPS = ["Run `ha-axi status` for instance details", "Run `ha-axi config check` to validate the configuration"];
11
+ const coreConfigSchema = z.object({
12
+ version: z.string(),
13
+ state: z.string(),
14
+ location_name: z.string(),
15
+ time_zone: z.string(),
16
+ config_source: z.string(),
17
+ components: z.array(z.string()),
18
+ });
19
+ const checkConfigSchema = z.object({
20
+ result: z.enum(["valid", "invalid"]),
21
+ errors: z.string().nullable(),
22
+ warnings: z.string().nullable(),
23
+ });
24
+ const authStatus = (args, { host, files, redactor }) => {
25
+ const { values } = parse(args, SELECT, 0);
26
+ const selection = selectProfile(selector(values), host, files);
27
+ resolveToken(selection.token, host, files, redactor, true);
28
+ const fileProtection = selection.fromFile || "file" in selection.token
29
+ ? host.platform === "win32" ? "windows-dacl-verified" : "posix-owner-and-mode"
30
+ : "none";
31
+ return {
32
+ profile: selection.name,
33
+ selectedBy: selection.selectedBy,
34
+ config: selection.config.path,
35
+ origin: selection.origin,
36
+ token: secretSource(selection.token),
37
+ fileProtection,
38
+ readOnly: selection.readOnly,
39
+ writes: selection.writes,
40
+ ...(selection.allowInsecureHttp ? { warnings: [INSECURE_HTTP_WARNING] } : {}),
41
+ };
42
+ };
43
+ const profileList = (args, { host, files }) => {
44
+ const { values } = parse(args, CONFIG, 0);
45
+ const location = configPath(host, values.config);
46
+ const config = loadConfig(location, files, host.platform);
47
+ const profiles = Object.entries(config.profiles).map(([name, profile]) => ({
48
+ name,
49
+ origin: profile.origin,
50
+ token: secretSource(profile.token ?? DEFAULT_TOKEN),
51
+ default: config.defaultProfile === name,
52
+ allowWrites: profile.writes?.allowWrites ?? false,
53
+ }));
54
+ const help = profiles.length === 0 ? ["Run `ha-axi profile set <name> --origin <url> --token-env <VAR>` to add a profile"] : [];
55
+ return { config: location.path, count: profiles.length, profiles, ...(help.length > 0 ? { help } : {}) };
56
+ };
57
+ const profileSet = (args, { host, files }) => {
58
+ const options = {
59
+ ...CONFIG,
60
+ origin: { type: "string" },
61
+ "token-env": { type: "string" },
62
+ "token-file": { type: "string" },
63
+ "allow-insecure-http": { type: "boolean" },
64
+ "allow-writes": { type: "boolean" },
65
+ "allow-op": { type: "string", multiple: true },
66
+ };
67
+ const { values, positionals } = parse(args, options, 1);
68
+ const [name = ""] = positionals;
69
+ if (values.origin === undefined)
70
+ throw new AxiError("INVALID_ARGUMENT", "--origin <url> is required");
71
+ const tokenEnv = values["token-env"];
72
+ const tokenFile = values["token-file"];
73
+ const token = tokenEnv !== undefined && tokenFile === undefined ? { env: tokenEnv }
74
+ : tokenFile !== undefined && tokenEnv === undefined ? { file: tokenFile } : undefined;
75
+ if (token === undefined) {
76
+ throw new AxiError("INVALID_ARGUMENT", "Use exactly one of --token-env and --token-file");
77
+ }
78
+ const operations = values["allow-op"] ?? [];
79
+ for (const operation of operations) {
80
+ if (!grantIdSchema.safeParse(operation).success) {
81
+ throw new AxiError("INVALID_ARGUMENT", `--allow-op ${operation} is not a write grant ID`, [`Grant IDs: ${grantIdSchema.options.join(", ")}`]);
82
+ }
83
+ }
84
+ const allowWrites = values["allow-writes"] ?? false;
85
+ const profile = {
86
+ origin: values.origin,
87
+ token,
88
+ ...(values["allow-insecure-http"] === true ? { allowInsecureHttp: true } : {}),
89
+ ...(allowWrites || operations.length > 0 ? { writes: { allowWrites, operations } } : {}),
90
+ };
91
+ const location = setProfile(selector(values), name, profile, host, files);
92
+ return {
93
+ profile: name,
94
+ config: location.path,
95
+ origin: profile.origin,
96
+ token: secretSource(token),
97
+ ...(profile.allowInsecureHttp === true ? { warnings: [INSECURE_HTTP_WARNING] } : {}),
98
+ help: [`Run \`ha-axi auth status --profile ${name}\` to check it`],
99
+ };
100
+ };
101
+ const profileRemove = (args, { host, files }) => {
102
+ const { values, positionals } = parse(args, CONFIG, 1);
103
+ const [name = ""] = positionals;
104
+ const location = removeProfile(selector(values), name, host, files);
105
+ return { removed: name, config: location.path };
106
+ };
107
+ const configPathCommand = (args, { host }) => {
108
+ const { values } = parse(args, CONFIG, 0);
109
+ const location = configPath(host, values.config);
110
+ return { config: location.path, source: location.source, writeLog: writeLogPath(host) };
111
+ };
112
+ async function instance(args, { host, files, redactor, userAgent }) {
113
+ const { values } = parse(args, SELECT, 0);
114
+ const selection = selectProfile(selector(values), host, files);
115
+ const session = connect(selection, host, files, redactor, userAgent);
116
+ return { selection, config: await readJson(session, { method: "GET", path: "/api/config" }, coreConfigSchema) };
117
+ }
118
+ const doctor = async (args, context) => {
119
+ const { selection, config } = await instance(args, context);
120
+ const warnings = [
121
+ ...(selection.allowInsecureHttp ? [INSECURE_HTTP_WARNING] : []),
122
+ ...(config.state === "RUNNING" ? [] : [`Home Assistant reports state ${config.state}, not RUNNING`]),
123
+ ];
124
+ return {
125
+ profile: selection.name,
126
+ origin: selection.origin,
127
+ token: secretSource(selection.token),
128
+ homeAssistant: { version: config.version, state: config.state, components: config.components.length },
129
+ ...(warnings.length > 0 ? { warnings } : {}),
130
+ help: NEXT_STEPS,
131
+ };
132
+ };
133
+ const status = async (args, context) => {
134
+ const { config } = await instance(args, context);
135
+ return {
136
+ version: config.version,
137
+ state: config.state,
138
+ location: config.location_name,
139
+ timeZone: config.time_zone,
140
+ configSource: config.config_source,
141
+ components: config.components.length,
142
+ help: ["Run `ha-axi config check` to validate the configuration"],
143
+ };
144
+ };
145
+ const configCheck = async (args, { host, files, redactor, userAgent }) => {
146
+ const { values } = parse(args, SELECT, 0);
147
+ const session = connect(selectProfile(selector(values), host, files), host, files, redactor, userAgent);
148
+ const check = await readJson(session, { method: "POST", path: "/api/config/core/check_config" }, checkConfigSchema);
149
+ return {
150
+ ...check,
151
+ ...(check.result === "invalid" ? { help: ["Fix the reported errors, then run `ha-axi config check` again"] } : {}),
152
+ };
153
+ };
154
+ export const handlers = {
155
+ doctor,
156
+ status,
157
+ "config check": configCheck,
158
+ "auth status": authStatus,
159
+ "profile list": profileList,
160
+ "profile set": profileSet,
161
+ "profile remove": profileRemove,
162
+ "config path": configPathCommand,
163
+ ...writesHandlers,
164
+ };
@@ -0,0 +1,16 @@
1
+ export const feature = {
2
+ name: "core",
3
+ commands: [
4
+ { name: "help", effect: "read", summary: "List every ha-axi command with its effect" },
5
+ { name: "auth status", effect: "read", summary: "Show the selected profile, origin and token source without contacting Home Assistant" },
6
+ { name: "profile list", effect: "read", summary: "List the profiles in config.json" },
7
+ { name: "profile set", effect: "read", hosted: "blocked", summary: "Create or replace a local profile in config.json; sends no Home Assistant request" },
8
+ { name: "profile remove", effect: "read", hosted: "blocked", summary: "Remove a local profile from config.json; sends no Home Assistant request" },
9
+ { name: "config path", effect: "read", summary: "Print the config.json and writes.log paths" },
10
+ { name: "doctor", effect: "read", summary: "Check the profile and credentials with one bounded GET /api/config" },
11
+ { name: "status", effect: "read", summary: "Show the Home Assistant version, state, location and component count" },
12
+ { name: "config check", effect: "read", summary: "Validate the Home Assistant configuration (read-only POST)" },
13
+ { name: "writes status", effect: "read", summary: "Show one writes.log entry and its outcome, with reconciliation guidance when the outcome is unknown" },
14
+ { name: "writes pending", effect: "read", summary: "List journaled writes whose outcome is pending or unknown" },
15
+ ],
16
+ };
@@ -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
+ };