@astrofoundry/pi-astro 0.40.71 → 0.40.73
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 +1 -1
- package/agents/home.md +5 -3
- package/extensions/specialist-gate/approvals.test.ts +8 -0
- package/extensions/specialist-gate/index.ts +3 -2
- package/package.json +1 -1
- package/skills/home/SKILL.md +53 -2
- package/specialists/AGENTS.md +1 -1
- package/specialists/README.md +4 -3
- package/specialists/entry/remote/spc-home-entry.sh +93 -0
- package/specialists/home/run.ts +313 -47
- package/specialists/lib/home-assistant.test.ts +12 -1
- package/specialists/lib/home-assistant.ts +30 -0
- package/specialists/lib/home-files.test.ts +216 -0
- package/specialists/lib/home-files.ts +221 -0
- package/specialists/wrappers.test.ts +69 -1
package/specialists/home/run.ts
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
1
2
|
import { readConfig } from "../lib/config.ts";
|
|
2
3
|
import { ServiceError, UsageError } from "../lib/errors.ts";
|
|
3
|
-
import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
|
|
4
|
+
import { backupSummary, bounded, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, isReadCommand, openRepairs, pendingUpdates, tailLines } from "../lib/home-assistant.ts";
|
|
4
5
|
import type { HaCall, HomeSnapshot } from "../lib/home-assistant.ts";
|
|
6
|
+
import { REDACTED, SSH_ADDON, isPublicKey, isStamp, isYamlPath, pageLines, redactYaml, replaceOnce, withFileAccess } from "../lib/home-files.ts";
|
|
5
7
|
import { main } from "../lib/main.ts";
|
|
6
8
|
import { printJson, printRaw } from "../lib/output.ts";
|
|
7
|
-
import {
|
|
9
|
+
import { specialistsHome } from "../lib/paths.ts";
|
|
10
|
+
import { redactSecrets } from "../lib/sanitize.ts";
|
|
11
|
+
import { readSecret, secretPath } from "../lib/secrets.ts";
|
|
12
|
+
import { sshFixed } from "../lib/ssh.ts";
|
|
13
|
+
import type { SshTarget } from "../lib/ssh.ts";
|
|
8
14
|
|
|
9
15
|
const SERVICE = "home";
|
|
10
16
|
|
|
@@ -17,35 +23,71 @@ const SHAPE = { homeAssistantUrl: "string" } as const;
|
|
|
17
23
|
|
|
18
24
|
const MAX_ENTITIES = 200;
|
|
19
25
|
const MAX_LOG_LINES = 400;
|
|
26
|
+
/** The most JSON one generic answer prints; a longer list keeps its first items. */
|
|
27
|
+
const MAX_ANSWER_CHARS = 60_000;
|
|
20
28
|
const ENTITY_ID = /^[a-z0-9_]+\.[a-z0-9_]+$/;
|
|
21
29
|
const ACTION = /^[a-z0-9_]+\.[a-z0-9_]+$/;
|
|
22
30
|
const ADDON_SLUG = /^[a-z0-9_]+$/;
|
|
23
31
|
const ENTRY_ID = /^[0-9A-Za-z]{20,64}$/;
|
|
32
|
+
const WS_TYPE = /^[a-z0-9_]+(?:\/[a-z0-9_]+)*$/;
|
|
33
|
+
const SUPERVISOR_ENDPOINT = /^(?:\/[A-Za-z0-9_-][A-Za-z0-9_.-]*)+$/;
|
|
24
34
|
const LOG_SOURCES = ["core", "supervisor", "host"];
|
|
35
|
+
const WRITE_METHODS = ["post", "put", "delete"] as const;
|
|
36
|
+
type Method = "get" | (typeof WRITE_METHODS)[number];
|
|
25
37
|
|
|
26
|
-
const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API and
|
|
38
|
+
const HELP = `home specialist (Home Assistant at Mira, through its WebSocket API, REST API, and Supervisor)
|
|
27
39
|
|
|
28
40
|
status versions, Supervisor health, integrations that did not load, repairs, updates,
|
|
29
41
|
backups, disk, add-ons, and the number of unavailable entities
|
|
30
42
|
problems what needs a person, one line each; a part that cannot be read is a problem too
|
|
31
43
|
entities [--state <state>] [--domain <domain>] [--max N]
|
|
32
44
|
entity ids, names, and states (default: state unavailable, 50 of them)
|
|
45
|
+
integrations [--failed] every integration entry with its id, state, and reason
|
|
33
46
|
logs <core|supervisor|host> [lines]
|
|
34
47
|
logs addon <slug> [lines] the newest log lines (default 100, at most ${MAX_LOG_LINES})
|
|
35
|
-
|
|
48
|
+
check-config validate the configuration files
|
|
49
|
+
ws-read <type> [json] a WebSocket command that only reads: registries, lists, history, traces, dashboards
|
|
50
|
+
rest get <path> GET any route under /api/
|
|
51
|
+
supervisor get <endpoint> GET a Supervisor endpoint, such as /addons/core_matter_server/info
|
|
52
|
+
file-list the YAML files of the configuration folder
|
|
53
|
+
file-read <path> [first line]
|
|
54
|
+
one YAML file, such as configuration.yaml or packages/lights.yaml; values of
|
|
55
|
+
secret-named keys read as ${REDACTED}, and a long file continues from "next"
|
|
56
|
+
file-backups <path> the stamps of the copies kept of one file
|
|
57
|
+
|
|
58
|
+
Changes; each needs an owner's approval in chat:
|
|
36
59
|
integration-remove <entry_id> --confirm
|
|
37
60
|
delete one integration entry, with its devices and entities
|
|
38
61
|
update <update.entity_id> --confirm
|
|
39
62
|
install the update of one update entity
|
|
40
63
|
restart --confirm restart Home Assistant Core
|
|
41
64
|
action <domain.action> [json]
|
|
42
|
-
run any Home Assistant action with {"target": {...}, "data": {...}}
|
|
65
|
+
run any Home Assistant action with {"target": {...}, "data": {...}}
|
|
66
|
+
ws <type> [json] any WebSocket command, such as config/entity_registry/update or lovelace/config/save
|
|
67
|
+
rest <post|put|delete> <path> [json]
|
|
68
|
+
any other call under /api/, such as /api/config/automation/config/<id>
|
|
69
|
+
supervisor <post|put|delete> <endpoint> [json]
|
|
70
|
+
any other Supervisor call, such as /addons/<slug>/restart or /host/reboot
|
|
71
|
+
file-replace <path> <json> --confirm
|
|
72
|
+
replace one exact text in a YAML file: {"old": "...", "new": "..."}
|
|
73
|
+
file-write <path> <content> --confirm
|
|
74
|
+
write a whole YAML file
|
|
75
|
+
file-restore <path> <stamp> --confirm
|
|
76
|
+
put back one of the copies file-backups lists
|
|
77
|
+
file-remove <path> --confirm
|
|
78
|
+
delete a YAML file
|
|
79
|
+
files-setup <public key> [--no-password] --confirm
|
|
80
|
+
bind the specialist's SSH key to the file commands in the SSH add-on and start
|
|
81
|
+
it at boot; --no-password also turns the add-on's password login off
|
|
43
82
|
|
|
44
|
-
|
|
83
|
+
A file change keeps a copy of the previous file and runs check-config before and after; a change that makes
|
|
84
|
+
a valid configuration invalid is undone. It takes effect after a reload or a restart. The file commands never
|
|
85
|
+
reach secrets.yaml or hidden folders such as .storage.
|
|
86
|
+
Answers longer than ${MAX_ANSWER_CHARS} characters are cut, and values under secret-looking keys are redacted.`;
|
|
45
87
|
|
|
46
|
-
/** The Supervisor's answer to a
|
|
47
|
-
function
|
|
48
|
-
return call("supervisor/api", { endpoint, method:
|
|
88
|
+
/** The Supervisor's answer to a call, through Core's `supervisor/api` command. */
|
|
89
|
+
function supervisorCall(call: HaCall, method: Method, endpoint: string, data?: unknown): Promise<unknown> {
|
|
90
|
+
return call("supervisor/api", { endpoint, method, ...(data === undefined ? {} : { data }) });
|
|
49
91
|
}
|
|
50
92
|
|
|
51
93
|
async function snapshot(call: HaCall): Promise<HomeSnapshot> {
|
|
@@ -64,12 +106,12 @@ async function snapshot(call: HaCall): Promise<HomeSnapshot> {
|
|
|
64
106
|
read("integration list", call("config_entries/get")),
|
|
65
107
|
read("repair list", call("repairs/list_issues")),
|
|
66
108
|
read("backup list", call("backup/info")),
|
|
67
|
-
read("Supervisor state",
|
|
68
|
-
read("Core version",
|
|
69
|
-
read("operating system state",
|
|
70
|
-
read("host state",
|
|
71
|
-
read("Supervisor checks",
|
|
72
|
-
read("add-on list",
|
|
109
|
+
read("Supervisor state", supervisorCall(call, "get", "/supervisor/info")),
|
|
110
|
+
read("Core version", supervisorCall(call, "get", "/core/info")),
|
|
111
|
+
read("operating system state", supervisorCall(call, "get", "/os/info")),
|
|
112
|
+
read("host state", supervisorCall(call, "get", "/host/info")),
|
|
113
|
+
read("Supervisor checks", supervisorCall(call, "get", "/resolution/info")),
|
|
114
|
+
read("add-on list", supervisorCall(call, "get", "/addons")),
|
|
73
115
|
]);
|
|
74
116
|
return { config, states, entries, repairs, backups, supervisor, core, os, host, resolution, addons, unread };
|
|
75
117
|
}
|
|
@@ -161,19 +203,21 @@ function record(value: unknown, name: string): Record<string, unknown> | undefin
|
|
|
161
203
|
return value as Record<string, unknown>;
|
|
162
204
|
}
|
|
163
205
|
|
|
206
|
+
function parseJson(json: string | undefined): unknown {
|
|
207
|
+
if (json === undefined) return undefined;
|
|
208
|
+
try {
|
|
209
|
+
return JSON.parse(json) as unknown;
|
|
210
|
+
} catch {
|
|
211
|
+
throw new UsageError("the body must be JSON");
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
164
215
|
/** `action <domain.action> [json]`: the JSON may carry `target` and `data`, nothing else. */
|
|
165
216
|
export function parseAction(args: string[]): ActionCall {
|
|
166
217
|
const usage = 'action <domain.action> [{"target": {...}, "data": {...}}]';
|
|
167
218
|
const [name, json, ...extra] = args;
|
|
168
219
|
if (name === undefined || !ACTION.test(name) || extra.length > 0) throw new UsageError(usage);
|
|
169
|
-
|
|
170
|
-
if (json !== undefined) {
|
|
171
|
-
try {
|
|
172
|
-
body = record(JSON.parse(json) as unknown, "the body") ?? {};
|
|
173
|
-
} catch (err) {
|
|
174
|
-
throw err instanceof UsageError ? err : new UsageError("the body must be JSON");
|
|
175
|
-
}
|
|
176
|
-
}
|
|
220
|
+
const body = record(parseJson(json), "the body") ?? {};
|
|
177
221
|
if (Object.keys(body).some((key) => key !== "target" && key !== "data")) throw new UsageError(usage);
|
|
178
222
|
const [domain, service] = name.split(".");
|
|
179
223
|
const target = record(body.target, "target");
|
|
@@ -181,6 +225,47 @@ export function parseAction(args: string[]): ActionCall {
|
|
|
181
225
|
return { domain, service, ...(target ? { target } : {}), ...(data ? { data } : {}) };
|
|
182
226
|
}
|
|
183
227
|
|
|
228
|
+
/** `ws-read <type> [json]` and `ws <type> [json]`: the command and its fields, without the id the session adds. */
|
|
229
|
+
export function parseWs(args: string[], readOnly: boolean): { type: string; fields: Record<string, unknown> } {
|
|
230
|
+
const usage = `${readOnly ? "ws-read" : "ws"} <type> [json]`;
|
|
231
|
+
const [type, json, ...extra] = args;
|
|
232
|
+
if (type === undefined || !WS_TYPE.test(type) || type === "auth" || extra.length > 0) throw new UsageError(usage);
|
|
233
|
+
if (readOnly && !isReadCommand(type)) throw new UsageError(`${type} is not a known read command; send it with ws, which asks an owner`);
|
|
234
|
+
const fields = record(parseJson(json), "the fields") ?? {};
|
|
235
|
+
if ("id" in fields || "type" in fields) throw new UsageError("the fields must not carry id or type");
|
|
236
|
+
return { type, fields };
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function parseMethod(value: string | undefined, usage: string): Method {
|
|
240
|
+
if (value === "get") return "get";
|
|
241
|
+
const method = WRITE_METHODS.find((m) => m === value);
|
|
242
|
+
if (method === undefined) throw new UsageError(usage);
|
|
243
|
+
return method;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** `rest <get|post|put|delete> <path> [json]`: any route under /api/ of Home Assistant itself. */
|
|
247
|
+
export function parseRest(args: string[]): { method: Method; path: string; body?: unknown } {
|
|
248
|
+
const usage = "rest get <path> | rest <post|put|delete> <path> [json]";
|
|
249
|
+
const [verb, path, json, ...extra] = args;
|
|
250
|
+
const method = parseMethod(verb, usage);
|
|
251
|
+
if (path === undefined || extra.length > 0 || (method === "get" && json !== undefined)) throw new UsageError(usage);
|
|
252
|
+
if (!path.startsWith("/api/") || /\.\.|\\|%|\s/.test(path.split("?")[0]) || path.startsWith("/api/websocket")) throw new UsageError("the path must start with /api/ and hold no dot segments, backslashes, or escapes");
|
|
253
|
+
const body = parseJson(json);
|
|
254
|
+
return { method, path, ...(body === undefined ? {} : { body }) };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** `supervisor <get|post|put|delete> <endpoint> [json]`: one Supervisor endpoint; logs and downloads have their own commands. */
|
|
258
|
+
export function parseSupervisor(args: string[]): { method: Method; endpoint: string; body?: Record<string, unknown> } {
|
|
259
|
+
const usage = "supervisor get <endpoint> | supervisor <post|put|delete> <endpoint> [json]";
|
|
260
|
+
const [verb, endpoint, json, ...extra] = args;
|
|
261
|
+
const method = parseMethod(verb, usage);
|
|
262
|
+
if (endpoint === undefined || extra.length > 0 || (method === "get" && json !== undefined)) throw new UsageError(usage);
|
|
263
|
+
if (!SUPERVISOR_ENDPOINT.test(endpoint) || endpoint.includes("..")) throw new UsageError("the endpoint must look like /addons/<slug>/info");
|
|
264
|
+
if (method === "get" && /\/(?:logs|download)(?:\/|$)/.test(endpoint)) throw new UsageError("logs and downloads are not JSON: use the logs command");
|
|
265
|
+
const body = record(parseJson(json), "the body");
|
|
266
|
+
return { method, endpoint, ...(body === undefined ? {} : { body }) };
|
|
267
|
+
}
|
|
268
|
+
|
|
184
269
|
function callAction(call: HaCall, action: ActionCall): Promise<unknown> {
|
|
185
270
|
return call("call_service", { domain: action.domain, service: action.service, ...(action.target ? { target: action.target } : {}), ...(action.data ? { service_data: action.data } : {}) });
|
|
186
271
|
}
|
|
@@ -191,30 +276,186 @@ function confirmed(args: string[], usage: string): string[] {
|
|
|
191
276
|
return args.filter((a) => a !== "--confirm");
|
|
192
277
|
}
|
|
193
278
|
|
|
194
|
-
/**
|
|
195
|
-
async function
|
|
196
|
-
const url = new URL(
|
|
279
|
+
/** One call to Home Assistant's REST API; the answer is JSON when it parses, text otherwise. */
|
|
280
|
+
async function restRequest(config: HomeConfig, token: string, method: Method, path: string, body?: unknown): Promise<{ status: number; body: unknown }> {
|
|
281
|
+
const url = new URL(path, config.homeAssistantUrl);
|
|
282
|
+
const route = `${method.toUpperCase()} ${url.pathname}`;
|
|
197
283
|
let res: Response;
|
|
284
|
+
let text: string;
|
|
198
285
|
try {
|
|
199
|
-
res = await fetch(url, {
|
|
286
|
+
res = await fetch(url, {
|
|
287
|
+
method: method.toUpperCase(),
|
|
288
|
+
headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
289
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
290
|
+
signal: AbortSignal.timeout(60_000),
|
|
291
|
+
});
|
|
292
|
+
text = await res.text();
|
|
200
293
|
} catch (err) {
|
|
201
|
-
throw new ServiceError(`home assistant gave no answer to
|
|
294
|
+
throw new ServiceError(`home assistant gave no answer to ${route}: ${err instanceof Error ? err.message.slice(0, 200) : String(err)}`);
|
|
295
|
+
}
|
|
296
|
+
if (!res.ok) throw new ServiceError(`home assistant answered ${res.status} to ${route}${text.length > 0 ? `: ${text.slice(0, 300)}` : ""}`);
|
|
297
|
+
try {
|
|
298
|
+
return { status: res.status, body: JSON.parse(text) as unknown };
|
|
299
|
+
} catch {
|
|
300
|
+
return { status: res.status, body: text };
|
|
202
301
|
}
|
|
203
|
-
if (res.status === 404) throw new ServiceError(`home assistant knows no integration entry ${entryId}`);
|
|
204
|
-
if (!res.ok) throw new ServiceError(`home assistant answered ${res.status} to DELETE ${url.pathname}`);
|
|
205
|
-
return (await res.json()) as unknown;
|
|
206
302
|
}
|
|
207
303
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
304
|
+
/** What a generic answer prints: secret-looking values redacted, then cut to a readable size. */
|
|
305
|
+
function answer(value: unknown): unknown {
|
|
306
|
+
return bounded(redactSecrets(value), MAX_ANSWER_CHARS);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const FILE_COMMANDS = ["file-list", "file-read", "file-backups", "file-write", "file-replace", "file-restore", "file-remove", "files-setup"];
|
|
310
|
+
const COMMANDS = ["status", "problems", "entities", "integrations", "integration-remove", "logs", "check-config", "update", "restart", "action", "ws-read", "ws", "rest", "supervisor", ...FILE_COMMANDS];
|
|
311
|
+
const FILE_USAGE: Record<string, string> = {
|
|
312
|
+
"file-write": "file-write <path> <content> --confirm",
|
|
313
|
+
"file-replace": 'file-replace <path> {"old": "...", "new": "..."} --confirm',
|
|
314
|
+
"file-restore": "file-restore <path> <stamp> --confirm",
|
|
315
|
+
"file-remove": "file-remove <path> --confirm",
|
|
316
|
+
"files-setup": "files-setup <public key> [--no-password] --confirm",
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
export type FileCommand =
|
|
320
|
+
| { op: "list" }
|
|
321
|
+
| { op: "read"; path: string; from: number }
|
|
322
|
+
| { op: "backups"; path: string }
|
|
323
|
+
| { op: "write"; path: string; content: string }
|
|
324
|
+
| { op: "replace"; path: string; old: string; replacement: string }
|
|
325
|
+
| { op: "restore"; path: string; stamp: string }
|
|
326
|
+
| { op: "remove"; path: string }
|
|
327
|
+
| { op: "setup"; publicKey: string; keepPassword: boolean };
|
|
328
|
+
|
|
329
|
+
function yamlPath(path: string | undefined, usage: string): string {
|
|
330
|
+
if (path === undefined || !isYamlPath(path)) throw new UsageError(`${usage}: the path must be a YAML file below the configuration folder, not hidden, and not secrets.yaml`);
|
|
331
|
+
return path;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function unmasked(text: string, usage: string): string {
|
|
335
|
+
if (text.includes(REDACTED)) throw new UsageError(`${usage}: the text carries ${REDACTED}, a value file-read masked; change the lines around it with file-replace`);
|
|
336
|
+
return text;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The file commands; every one that changes something needs `--confirm`. */
|
|
340
|
+
export function parseFileCommand(name: string, args: string[]): FileCommand {
|
|
341
|
+
if (name === "file-list") {
|
|
342
|
+
if (args.length > 0) throw new UsageError("file-list takes no arguments");
|
|
343
|
+
return { op: "list" };
|
|
344
|
+
}
|
|
345
|
+
if (name === "file-read") {
|
|
346
|
+
if (args.length < 1 || args.length > 2) throw new UsageError("file-read <path> [first line]");
|
|
347
|
+
return { op: "read", path: yamlPath(args[0], "file-read <path> [first line]"), from: parseCount(args[1], "the first line", 10_000_000, 1) };
|
|
348
|
+
}
|
|
349
|
+
if (name === "file-backups") {
|
|
350
|
+
if (args.length !== 1) throw new UsageError("file-backups <path>");
|
|
351
|
+
return { op: "backups", path: yamlPath(args[0], "file-backups <path>") };
|
|
352
|
+
}
|
|
353
|
+
const usage = FILE_USAGE[name];
|
|
354
|
+
if (usage === undefined) throw new UsageError(`unknown command: ${name}`);
|
|
355
|
+
const rest = confirmed(args, usage);
|
|
356
|
+
if (name === "files-setup") {
|
|
357
|
+
const key = rest.filter((a) => a !== "--no-password");
|
|
358
|
+
if (key.length !== 1 || !isPublicKey(key[0])) throw new UsageError(`${usage}: give one ssh-ed25519 public key line`);
|
|
359
|
+
return { op: "setup", publicKey: key[0], keepPassword: key.length === rest.length };
|
|
360
|
+
}
|
|
361
|
+
const path = yamlPath(rest[0], usage);
|
|
362
|
+
if (name === "file-remove") {
|
|
363
|
+
if (rest.length !== 1) throw new UsageError(usage);
|
|
364
|
+
return { op: "remove", path };
|
|
365
|
+
}
|
|
366
|
+
if (rest.length !== 2) throw new UsageError(usage);
|
|
367
|
+
if (name === "file-restore") {
|
|
368
|
+
if (!isStamp(rest[1])) throw new UsageError(`${usage}: a stamp looks like 20261112T101500Z`);
|
|
369
|
+
return { op: "restore", path, stamp: rest[1] };
|
|
370
|
+
}
|
|
371
|
+
if (name === "file-write") return { op: "write", path, content: unmasked(rest[1], usage) };
|
|
372
|
+
const change = record(parseJson(rest[1]), "the change");
|
|
373
|
+
if (typeof change?.old !== "string" || typeof change.new !== "string" || Object.keys(change).length !== 2) throw new UsageError(usage);
|
|
374
|
+
return { op: "replace", path, old: unmasked(change.old, usage), replacement: unmasked(change.new, usage) };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
interface AddonInfo {
|
|
378
|
+
state?: unknown;
|
|
379
|
+
network?: Record<string, unknown> | null;
|
|
380
|
+
options?: { ssh?: { username?: unknown } };
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** One entry-script command; `input` becomes the remote command's stdin. */
|
|
384
|
+
type Entry = (remote: string, input?: string) => Promise<string>;
|
|
385
|
+
|
|
386
|
+
/** Entry-script calls through the specialist's key. The add-on tells its own port and user, once per process. */
|
|
387
|
+
function fileEntry(config: HomeConfig, call: HaCall): Entry {
|
|
388
|
+
let target: SshTarget | null = null;
|
|
389
|
+
return async (remote, input) => {
|
|
390
|
+
if (target === null) {
|
|
391
|
+
const info = (await supervisorCall(call, "get", `/addons/${SSH_ADDON}/info`)) as AddonInfo | null;
|
|
392
|
+
const port = info?.network?.["22/tcp"];
|
|
393
|
+
const user = info?.options?.ssh?.username;
|
|
394
|
+
if (info?.state !== "started") throw new ServiceError("the SSH add-on is not started; an owner runs files-setup first");
|
|
395
|
+
if (typeof port !== "number" || typeof user !== "string") throw new ServiceError("the SSH add-on reports no port or user name");
|
|
396
|
+
// The add-on lower-cases the user name before it creates the account (`init-ssh/run`).
|
|
397
|
+
target = { host: new URL(config.homeAssistantUrl).hostname, user: user.toLowerCase(), port, keyFile: secretPath(SERVICE, "SSH_KEY_HOME"), knownHostsFile: join(specialistsHome(), "config", "known_hosts") };
|
|
398
|
+
}
|
|
399
|
+
const result = await sshFixed(target, remote, 60_000, input);
|
|
400
|
+
if (result.code !== 0) throw new ServiceError(`the file command failed: ${(result.stderr.trim().split("\n").at(-1) ?? "").slice(0, 300) || `exit ${result.code}`}`);
|
|
401
|
+
return result.stdout;
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
async function configValid(config: HomeConfig, token: string): Promise<{ valid: boolean; errors: string | null }> {
|
|
406
|
+
const check = (await restRequest(config, token, "post", "/api/config/core/check_config")).body as { result?: unknown; errors?: unknown } | null;
|
|
407
|
+
return { valid: check?.result === "valid", errors: typeof check?.errors === "string" ? check.errors.slice(0, 1500) : null };
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Runs one changing entry command between two configuration checks. A change that turns a valid configuration
|
|
412
|
+
* invalid is undone from the copy the entry script kept; one made while the configuration was already invalid
|
|
413
|
+
* stays, because it may be part of the repair.
|
|
414
|
+
*/
|
|
415
|
+
async function changeChecked(run: Entry, config: HomeConfig, token: string, status: string, path: string, remote: string, input?: string): Promise<Record<string, unknown>> {
|
|
416
|
+
const before = await configValid(config, token);
|
|
417
|
+
const backup = /^backup (\S+)$/m.exec(await run(remote, input))?.[1];
|
|
418
|
+
if (backup === undefined) throw new ServiceError("the entry script named no backup");
|
|
419
|
+
const after = await configValid(config, token);
|
|
420
|
+
if (after.valid) return { status, path, backup, check: "valid" };
|
|
421
|
+
if (!before.valid) return { status, path, backup, check: "invalid before and after", errors: after.errors };
|
|
422
|
+
await run(backup === "none" ? `remove ${path}` : `restore ${path} ${backup}`);
|
|
423
|
+
return { status: "rolled back", path, check: "invalid", errors: after.errors };
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function wait(ms: number): Promise<void> {
|
|
427
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function fileCommand(config: HomeConfig, token: string, call: HaCall, cmd: FileCommand): Promise<Record<string, unknown>> {
|
|
431
|
+
const run = fileEntry(config, call);
|
|
432
|
+
const lines = (text: string): string[] => text.split("\n").filter((l) => l.length > 0);
|
|
433
|
+
if (cmd.op === "list") return { files: lines(await run("list")) };
|
|
434
|
+
if (cmd.op === "read") return { path: cmd.path, ...pageLines(redactYaml(await run(`read ${cmd.path}`)), cmd.from, MAX_ANSWER_CHARS) };
|
|
435
|
+
if (cmd.op === "backups") return { path: cmd.path, backups: lines(await run(`backups ${cmd.path}`)) };
|
|
436
|
+
if (cmd.op === "write") return changeChecked(run, config, token, "written", cmd.path, `write ${cmd.path}`, cmd.content);
|
|
437
|
+
if (cmd.op === "replace") {
|
|
438
|
+
const changed = replaceOnce(await run(`read ${cmd.path}`), cmd.old, cmd.replacement);
|
|
439
|
+
if (typeof changed !== "string") throw new ServiceError(`${cmd.path}: ${changed.error}`);
|
|
440
|
+
return changeChecked(run, config, token, "replaced", cmd.path, `write ${cmd.path}`, changed);
|
|
215
441
|
}
|
|
216
|
-
if (
|
|
217
|
-
return
|
|
442
|
+
if (cmd.op === "restore") return changeChecked(run, config, token, "restored", cmd.path, `restore ${cmd.path} ${cmd.stamp}`);
|
|
443
|
+
if (cmd.op === "remove") return changeChecked(run, config, token, "removed", cmd.path, `remove ${cmd.path}`);
|
|
444
|
+
// The add-on's options hold the owner's keys and password: they go back to the Supervisor and are never printed.
|
|
445
|
+
const info = (await supervisorCall(call, "get", `/addons/${SSH_ADDON}/info`)) as (AddonInfo & { options?: unknown }) | null;
|
|
446
|
+
const started = info?.state === "started";
|
|
447
|
+
await supervisorCall(call, "post", `/addons/${SSH_ADDON}/options`, { options: withFileAccess(info?.options, cmd.publicKey, cmd.keepPassword), boot: "auto" });
|
|
448
|
+
await supervisorCall(call, "post", `/addons/${SSH_ADDON}/${started ? "restart" : "start"}`);
|
|
449
|
+
let failure = "";
|
|
450
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
451
|
+
try {
|
|
452
|
+
return { status: "file access set up", addon: SSH_ADDON, was: started ? "started" : "stopped", boot: "auto", passwordLogin: cmd.keepPassword ? "unchanged" : "off", files: lines(await run("list")).length };
|
|
453
|
+
} catch (err) {
|
|
454
|
+
failure = err instanceof Error ? err.message : String(err);
|
|
455
|
+
await wait(5000);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
throw new ServiceError(`the add-on took the options, but the file commands do not answer: ${failure}`);
|
|
218
459
|
}
|
|
219
460
|
|
|
220
461
|
export async function command(args: string[]): Promise<number> {
|
|
@@ -223,28 +464,42 @@ export async function command(args: string[]): Promise<number> {
|
|
|
223
464
|
printRaw(HELP);
|
|
224
465
|
return 0;
|
|
225
466
|
}
|
|
226
|
-
|
|
467
|
+
if (!COMMANDS.includes(name)) throw new UsageError(`unknown command: ${name}`);
|
|
468
|
+
// Every argument is checked before config or secret is read, so a wrong call never opens a session.
|
|
227
469
|
const entityQuery = name === "entities" ? parseEntityQuery(rest) : null;
|
|
228
470
|
const logQuery = name === "logs" ? parseLogs(rest) : null;
|
|
229
471
|
const action = name === "action" ? parseAction(rest) : null;
|
|
472
|
+
const ws = name === "ws-read" || name === "ws" ? parseWs(rest, name === "ws-read") : null;
|
|
473
|
+
const restCall = name === "rest" ? parseRest(rest) : null;
|
|
474
|
+
const supervisor = name === "supervisor" ? parseSupervisor(rest) : null;
|
|
475
|
+
const file = FILE_COMMANDS.includes(name) ? parseFileCommand(name, rest) : null;
|
|
230
476
|
const updateTarget = name === "update" ? confirmed(rest, "update <update.entity_id> --confirm") : null;
|
|
231
477
|
if (updateTarget !== null && (updateTarget.length !== 1 || !ENTITY_ID.test(updateTarget[0]) || !updateTarget[0].startsWith("update."))) throw new UsageError("update <update.entity_id> --confirm");
|
|
232
478
|
if (name === "restart" && confirmed(rest, "restart --confirm").length > 0) throw new UsageError("restart --confirm");
|
|
233
479
|
const removeTarget = name === "integration-remove" ? confirmed(rest, "integration-remove <entry_id> --confirm") : null;
|
|
234
480
|
if (removeTarget !== null && (removeTarget.length !== 1 || !ENTRY_ID.test(removeTarget[0]))) throw new UsageError("integration-remove <entry_id> --confirm");
|
|
235
481
|
if (name === "integrations" && rest.some((a) => a !== "--failed")) throw new UsageError("integrations [--failed]");
|
|
236
|
-
if ((name === "status" || name === "problems") && rest.length > 0) throw new UsageError(`${name} takes no arguments`);
|
|
237
|
-
if (!["status", "problems", "entities", "integrations", "integration-remove", "logs", "update", "restart", "action"].includes(name)) throw new UsageError(`unknown command: ${name}`);
|
|
482
|
+
if ((name === "status" || name === "problems" || name === "check-config") && rest.length > 0) throw new UsageError(`${name} takes no arguments`);
|
|
238
483
|
|
|
239
484
|
const config = readConfig<HomeConfig>(SERVICE, SHAPE);
|
|
240
485
|
const token = readSecret(SERVICE, "HOMEASSISTANT_TOKEN");
|
|
241
486
|
if (logQuery !== null) {
|
|
242
|
-
|
|
487
|
+
const log = await restRequest(config, token, "get", `/api/hassio/${logQuery.path}?lines=${logQuery.lines}`);
|
|
488
|
+
printJson({ lines: tailLines(typeof log.body === "string" ? log.body : JSON.stringify(log.body), logQuery.lines) });
|
|
243
489
|
return 0;
|
|
244
490
|
}
|
|
245
491
|
if (removeTarget !== null) {
|
|
246
|
-
const
|
|
247
|
-
printJson({ status: "removed", entry_id: removeTarget[0], require_restart: (
|
|
492
|
+
const removed = await restRequest(config, token, "delete", `/api/config/config_entries/entry/${removeTarget[0]}`);
|
|
493
|
+
printJson({ status: "removed", entry_id: removeTarget[0], require_restart: (removed.body as { require_restart?: unknown } | null)?.require_restart === true });
|
|
494
|
+
return 0;
|
|
495
|
+
}
|
|
496
|
+
if (name === "check-config") {
|
|
497
|
+
printJson(answer((await restRequest(config, token, "post", "/api/config/core/check_config")).body));
|
|
498
|
+
return 0;
|
|
499
|
+
}
|
|
500
|
+
if (restCall !== null) {
|
|
501
|
+
const result = await restRequest(config, token, restCall.method, restCall.path, restCall.body);
|
|
502
|
+
printJson({ status: result.status, body: answer(result.body) });
|
|
248
503
|
return 0;
|
|
249
504
|
}
|
|
250
505
|
await haSession(config.homeAssistantUrl, token, async (call) => {
|
|
@@ -263,11 +518,22 @@ export async function command(args: string[]): Promise<number> {
|
|
|
263
518
|
await callAction(call, { domain: "update", service: "install", target: { entity_id: updateTarget[0] } });
|
|
264
519
|
printJson({ status: "update started", entity: updateTarget[0] });
|
|
265
520
|
} else if (name === "restart") {
|
|
266
|
-
|
|
521
|
+
try {
|
|
522
|
+
await callAction(call, { domain: "homeassistant", service: "restart" });
|
|
523
|
+
} catch (err) {
|
|
524
|
+
// Core closes the socket while it restarts, often before it sends the result (seen on 2026-11-12).
|
|
525
|
+
if (!(err instanceof ServiceError) || !err.message.includes("closed the connection")) throw err;
|
|
526
|
+
}
|
|
267
527
|
printJson({ status: "restart requested" });
|
|
268
528
|
} else if (action !== null) {
|
|
269
529
|
await callAction(call, action);
|
|
270
530
|
printJson({ status: "done", action: `${action.domain}.${action.service}` });
|
|
531
|
+
} else if (ws !== null) {
|
|
532
|
+
printJson({ result: answer(await call(ws.type, ws.fields)) });
|
|
533
|
+
} else if (supervisor !== null) {
|
|
534
|
+
printJson({ result: answer(await supervisorCall(call, supervisor.method, supervisor.endpoint, supervisor.body)) });
|
|
535
|
+
} else if (file !== null) {
|
|
536
|
+
printJson(await fileCommand(config, token, call, file));
|
|
271
537
|
}
|
|
272
538
|
});
|
|
273
539
|
return 0;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { backupSummary, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, openRepairs, pendingUpdates, tailLines } from "./home-assistant.ts";
|
|
2
|
+
import { backupSummary, bounded, diskUse, entitiesIn, failedIntegrations, haSession, homeProblems, integrationRows, isReadCommand, openRepairs, pendingUpdates, tailLines } from "./home-assistant.ts";
|
|
3
3
|
import type { HomeSnapshot } from "./home-assistant.ts";
|
|
4
4
|
|
|
5
5
|
type Listener = (event: { data?: string }) => void;
|
|
@@ -175,6 +175,17 @@ describe("home assistant findings", () => {
|
|
|
175
175
|
]);
|
|
176
176
|
});
|
|
177
177
|
|
|
178
|
+
it("knows which commands only read", () => {
|
|
179
|
+
for (const type of ["get_states", "config_entries/get", "config/device_registry/list", "repairs/list_issues", "backup/info", "lovelace/config", "trace/get", "person/list", "automation/config"]) expect(isReadCommand(type)).toBe(true);
|
|
180
|
+
for (const type of ["config/entity_registry/update", "lovelace/config/save", "backup/generate", "backup/config/info", "call_service", "application_credentials/list", "auth/refresh_tokens", "supervisor/api"]) expect(isReadCommand(type)).toBe(false);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("cuts a long answer and says how much it kept", () => {
|
|
184
|
+
expect(bounded({ a: 1 }, 100)).toEqual({ a: 1 });
|
|
185
|
+
expect(bounded(["aaaa", "bbbb", "cccc"], 16)).toEqual({ truncated: true, total: 3, shown: 2, items: ["aaaa", "bbbb"] });
|
|
186
|
+
expect(bounded({ text: "x".repeat(50) }, 20)).toEqual({ truncated: true, text: '{"text":"xxxxxxxxxxx' });
|
|
187
|
+
});
|
|
188
|
+
|
|
178
189
|
it("keeps the newest log lines", () => {
|
|
179
190
|
expect(tailLines("a\n\nb\nc\n", 2)).toEqual(["b", "c"]);
|
|
180
191
|
});
|
|
@@ -272,6 +272,36 @@ export function homeProblems(s: HomeSnapshot, now: number): string[] {
|
|
|
272
272
|
return out;
|
|
273
273
|
}
|
|
274
274
|
|
|
275
|
+
/**
|
|
276
|
+
* WebSocket commands that only read: lists, registries, history, traces, dashboards, and the helpers'
|
|
277
|
+
* `<domain>/list`. Commands that return credentials stay out (`backup/config/info` holds the backup
|
|
278
|
+
* password, `application_credentials/list` client secrets, `thread/get_dataset_tlv` the network key).
|
|
279
|
+
*/
|
|
280
|
+
const READ_COMMANDS =
|
|
281
|
+
/^(?:get_(?:states|config|services|panels)|config_entries\/(?:get|flow\/progress|subentries\/list)|config\/(?:entity|device|area|floor|label|category)_registry\/(?:list|get|get_entries|list_for_display)|repairs\/(?:list_issues|get_issue_data)|backup\/(?:info|details|agents\/info)|system_log\/list|logger\/log_info|logbook\/get_events|history\/history_during_period|recorder\/(?:info|list_statistic_ids|statistics_during_period|get_statistics_metadata)|trace\/(?:list|get|contexts)|lovelace\/(?:config|info|dashboards\/list|resources)|(?:automation|script)\/config|search\/related|blueprint\/list|update\/release_notes|manifest\/(?:list|get)|diagnostics\/list|energy\/get_prefs|[a-z_]+\/list)$/;
|
|
282
|
+
const NO_READ = /^(?:application_credentials|auth|cloud)\//;
|
|
283
|
+
|
|
284
|
+
/** True for a WebSocket command that changes nothing and returns no credential. */
|
|
285
|
+
export function isReadCommand(type: string): boolean {
|
|
286
|
+
return READ_COMMANDS.test(type) && !NO_READ.test(type);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** An answer cut to `maxChars` of JSON: a long list keeps its first items and says how many it had. */
|
|
290
|
+
export function bounded(value: unknown, maxChars: number): unknown {
|
|
291
|
+
if (JSON.stringify(value ?? null).length <= maxChars) return value;
|
|
292
|
+
if (Array.isArray(value)) {
|
|
293
|
+
const kept: unknown[] = [];
|
|
294
|
+
let size = 2;
|
|
295
|
+
for (const item of value) {
|
|
296
|
+
size += JSON.stringify(item ?? null).length + 1;
|
|
297
|
+
if (size > maxChars) break;
|
|
298
|
+
kept.push(item);
|
|
299
|
+
}
|
|
300
|
+
return { truncated: true, total: value.length, shown: kept.length, items: kept };
|
|
301
|
+
}
|
|
302
|
+
return { truncated: true, text: JSON.stringify(value).slice(0, maxChars) };
|
|
303
|
+
}
|
|
304
|
+
|
|
275
305
|
/** The newest `lines` lines of a log text, each cut to a readable width. */
|
|
276
306
|
export function tailLines(log: string, lines: number): string[] {
|
|
277
307
|
return log
|