hactl 0.9.0 → 0.10.0

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 (3) hide show
  1. package/README.md +70 -10
  2. package/dist/cli.js +1927 -730
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -41,11 +41,11 @@ function convertKebabCaseToCamelCase(str) {
41
41
  function convertCamelCaseToKebabCase(name) {
42
42
  return Array.from(name).map((char, i) => {
43
43
  const upper = char.toUpperCase();
44
- const lower = char.toLowerCase();
45
- if (i === 0 || upper !== char || upper === lower) {
44
+ const lower2 = char.toLowerCase();
45
+ if (i === 0 || upper !== char || upper === lower2) {
46
46
  return char;
47
47
  }
48
- return `-${lower}`;
48
+ return `-${lower2}`;
49
49
  }).join("");
50
50
  }
51
51
  function newSparseMatrix(defaultValue) {
@@ -2271,7 +2271,7 @@ async function run(app2, inputs, context) {
2271
2271
  // package.json
2272
2272
  var package_default = {
2273
2273
  name: "hactl",
2274
- version: "0.9.0",
2274
+ version: "0.10.0",
2275
2275
  description: "Manage Home Assistant instances from the command line",
2276
2276
  license: "MIT",
2277
2277
  repository: {
@@ -2977,8 +2977,8 @@ function sethole1sll4ir138426n() {
2977
2977
  return true;
2978
2978
  }
2979
2979
 
2980
- // arktype:~arktype/rv4jgg08c1b48-tm9ovh0ab6yu7
2981
- var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection1r95ni81xgl88zValidator, intersection8yr2o71ja81ufValidator, intersection1mu7oxs0oq1x2nValidator, intersectionq8a1jl15p5kbrValidator, union214vmt0pwa2fdValidator, intersection17r4na700khzejValidator, intersection1649hnt0ixrxb1Validator, intersection15ttlhb0m0yhovValidator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersection3rk9um0b729ivValidator, intersection1dmk4z81d1f8mlValidator, intersection1tagcym1fnxkeyValidator, intersection1rp35ue1fi65ccValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2980
+ // arktype:~arktype/nnl38h0p7fqv6-1yxzlu30ali9ye
2981
+ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, intersection6w7z2u03slcwpValidator, intersection1lvjdu61ps4xl0Validator, intersection1ieh53x1r06da7Validator, intersection1kfvut30tftkihValidator, intersection1y5nwst153l9s2Validator, intersection1r95ni81xgl88zValidator, intersection8yr2o71ja81ufValidator, intersection1mu7oxs0oq1x2nValidator, intersectionq8a1jl15p5kbrValidator, union214vmt0pwa2fdValidator, intersection17r4na700khzejValidator, intersection15ttlhb0m0yhovValidator, intersection10qmong0na8e8rValidator, intersection1nv9uj515bs7itValidator, intersection3rk9um0b729ivValidator, intersection16hnzan16c9ou0Validator, intersection1tagcym1fnxkeyValidator, intersection1rp35ue1fi65ccValidator, intersection128bswg1yy3khmValidator, intersection1etdk1h0e9wp9wValidator, intersection1kkjjod0jxg0s5Validator, intersectionyxcocr0wxdk22Validator, intersectionm0h7h61efcs6aValidator, intersection150ify80evssmcValidator, intersection1649hnt0ixrxb1Validator, intersectionax9iml0n3vs6rValidator, intersection1v7qsxg01pq0unValidator, intersection1vhhd710xh4d2c, intersection1r8kxb1yxb7ek, intersectiongn35sl1ajga14] = (
2982
2982
  /* @__NOINLINE__ */
2983
2983
  (() => {
2984
2984
  const create1sex1811cremth2 = (({ 0: allows, 1: apply }) => {
@@ -3093,6 +3093,43 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3093
3093
  }
3094
3094
  return true;
3095
3095
  }
3096
+ function structure1pu25bs17d9ig3Allows(data, ctx) {
3097
+ const keys = Object.keys(data);
3098
+ const isArray2 = Array.isArray(data);
3099
+ for (let i = 0; i < keys.length; i++) {
3100
+ const k = keys[i];
3101
+ if (
3102
+ /* @__NOINLINE__ */
3103
+ domainwf1rf311hsq3lAllows(k)
3104
+ ) {
3105
+ if (!/* @__NOINLINE__ */
3106
+ intersection1kfvut30tftkihAllows(data[k])) {
3107
+ return false;
3108
+ }
3109
+ }
3110
+ }
3111
+ return true;
3112
+ }
3113
+ function structure1idajgl04py4nuApply$1(data, ctx) {
3114
+ const keys = Object.keys(data);
3115
+ const isArray2 = Array.isArray(data);
3116
+ for (let i = 0; i < keys.length; i++) {
3117
+ const k = keys[i];
3118
+ if (
3119
+ /* @__NOINLINE__ */
3120
+ domainwf1rf311hsq3lAllows(k, ctx)
3121
+ ) {
3122
+ if (!/* @__NOINLINE__ */
3123
+ intersectionc5cirx0ys2jaeAllows(data[k], ctx) && ctx._k(intersectionc5cirx0ys2jaeAllows, data, isArray2 ? (
3124
+ /* @__NOINLINE__ */
3125
+ intersection1in70h716rkr52R1(k)
3126
+ ) : k)) {
3127
+ return false;
3128
+ }
3129
+ }
3130
+ }
3131
+ return true;
3132
+ }
3096
3133
  function intersection1h3a6wa0xeftl5Allows(data, ctx) {
3097
3134
  for (; ; ) {
3098
3135
  if (!(Number.isFinite(data.id) && ("result" in data && !!/* @__NOINLINE__ */
@@ -3151,14 +3188,14 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3151
3188
  }
3152
3189
  return false;
3153
3190
  }
3154
- function intersection15l8ulg0cdy2drAllows(data, ctx) {
3191
+ function intersection6aeab31tdpfdtAllows(data, ctx) {
3155
3192
  for (; ; ) {
3156
3193
  if (!Array.isArray(data)) {
3157
3194
  break;
3158
3195
  }
3159
3196
  for (let i = 0; i < data.length; i++) {
3160
3197
  if (!/* @__NOINLINE__ */
3161
- intersection1r8kxb1yxb7ekAllows(data[i])) {
3198
+ intersectiong1m2lv14ljv26Allows(data[i])) {
3162
3199
  return false;
3163
3200
  }
3164
3201
  }
@@ -3166,14 +3203,29 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3166
3203
  }
3167
3204
  return false;
3168
3205
  }
3169
- function intersection6aeab31tdpfdtAllows(data, ctx) {
3206
+ function intersection15t5mdk0e0pwczAllows(data, ctx) {
3170
3207
  for (; ; ) {
3171
3208
  if (!Array.isArray(data)) {
3172
3209
  break;
3173
3210
  }
3174
3211
  for (let i = 0; i < data.length; i++) {
3175
3212
  if (!/* @__NOINLINE__ */
3176
- intersectiong1m2lv14ljv26Allows(data[i])) {
3213
+ intersectionp6z1tl0i351sdAllows(data[i])) {
3214
+ return false;
3215
+ }
3216
+ }
3217
+ return true;
3218
+ }
3219
+ return false;
3220
+ }
3221
+ function intersection15l8ulg0cdy2drAllows(data, ctx) {
3222
+ for (; ; ) {
3223
+ if (!Array.isArray(data)) {
3224
+ break;
3225
+ }
3226
+ for (let i = 0; i < data.length; i++) {
3227
+ if (!/* @__NOINLINE__ */
3228
+ intersection1r8kxb1yxb7ekAllows(data[i])) {
3177
3229
  return false;
3178
3230
  }
3179
3231
  }
@@ -3481,6 +3533,18 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3481
3533
  }
3482
3534
  return true;
3483
3535
  }
3536
+ function intersection15t5mdk0e0pwczApply(data, ctx) {
3537
+ if (!Array.isArray(data)) {
3538
+ return !ctx._e(data, "proto", "an array");
3539
+ }
3540
+ for (let i = 0; i < data.length; i++) {
3541
+ if (!/* @__NOINLINE__ */
3542
+ intersectionp6z1tl0i351sdAllows(data[i], ctx) && ctx._k(intersectionp6z1tl0i351sdApply, data, i)) {
3543
+ return false;
3544
+ }
3545
+ }
3546
+ return true;
3547
+ }
3484
3548
  function intersection1wvfn2n0l491ckApply(data, ctx) {
3485
3549
  if (!Array.isArray(data)) {
3486
3550
  return !ctx._e(data, "proto", "an array");
@@ -3565,9 +3629,13 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3565
3629
  if (!isObjectData(data)) return notObjectData(data, ctx);
3566
3630
  return data.optional === false || data.optional === true || !failsKey(ctx, data, "optional", "discriminant", "boolean");
3567
3631
  }
3568
- function intersectione4pcj513cxhmdApply(data, ctx) {
3632
+ function intersection1d09i901hcco3uApply(data, ctx) {
3633
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3634
+ return (typeof data.area_id === "string" || !fails0(ctx, data, "area_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("floor_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "floor_id")) && (!("labels" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "labels")) && (!("aliases" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "aliases"));
3635
+ }
3636
+ function intersectionp6z1tl0i351sdApply(data, ctx) {
3569
3637
  if (!isObjectData(data)) return notObjectData(data, ctx);
3570
- return (typeof data.area_id === "string" || !fails0(ctx, data, "area_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("floor_id" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "floor_id")) && (!("labels" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "labels"));
3638
+ return (typeof data.domain === "string" || !fails0(ctx, data, "domain")) && (typeof data.issue_id === "string" || !fails0(ctx, data, "issue_id")) && (!("severity" in data) || !(!(typeof data.severity === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "severity"))) && (!("is_fixable" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "is_fixable")) && (!("ignored" in data) || !ctx._k(union1jlxhky12plhj9Apply, data, "ignored")) && (!("created" in data) || !(!(typeof data.created === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "created"))) && (!("translation_key" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "translation_key")) && (!("translation_placeholders" in data) || !ctx._k(union12poedh18834r8Apply, data, "translation_placeholders"));
3571
3639
  }
3572
3640
  function intersection1idvyi512mjtrzApply(data, ctx) {
3573
3641
  if (!isObjectData(data)) return notObjectData(data, ctx);
@@ -3585,6 +3653,10 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3585
3653
  if (!isObjectData(data)) return notObjectData(data, ctx);
3586
3654
  return (typeof data.entity_id === "string" || !fails0(ctx, data, "entity_id")) && (typeof data.state === "string" || !fails0(ctx, data, "state")) && !ctx._k(intersection1in70h716rkr52Apply, data, "attributes", "an object") && (typeof data.last_changed === "string" || !fails0(ctx, data, "last_changed"));
3587
3655
  }
3656
+ function intersection9mjaub0dojaqnApply(data, ctx) {
3657
+ if (!isObjectData(data)) return notObjectData(data, ctx);
3658
+ return (typeof data.entry_id === "string" || !fails0(ctx, data, "entry_id")) && (typeof data.domain === "string" || !fails0(ctx, data, "domain")) && (!("title" in data) || !(!(typeof data.title === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "title"))) && (!("state" in data) || !(!(typeof data.state === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "state"))) && (!("reason" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "reason")) && (!("source" in data) || !(!(typeof data.source === "string") && ctx._k((data2, ctx2) => !ctx2._e(data2, "domain", "a string"), data, "source"))) && (!("supports_unload" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "supports_unload")) && (!("supports_reconfigure" in data) || !ctx._k(unionlgje2o0lqtbj0Apply, data, "supports_reconfigure")) && (!("disabled_by" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "disabled_by"));
3659
+ }
3588
3660
  function intersectionadina16r612gApply(data, ctx) {
3589
3661
  if (!isObjectData(data)) return notObjectData(data, ctx);
3590
3662
  return (typeof data.floor_id === "string" || !fails0(ctx, data, "floor_id")) && (typeof data.name === "string" || !fails0(ctx, data, "name")) && (!("level" in data) || !ctx._k(union1cy4v7a1543qpiApply, data, "level")) && (!("aliases" in data) || !ctx._k(intersection1kfvut30tftkihApply, data, "aliases")) && (!("icon" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "icon"));
@@ -3776,6 +3848,15 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3776
3848
  return true;
3777
3849
  }
3778
3850
  }
3851
+ function union12poedh18834r8Apply(data, ctx) {
3852
+ if (typeof data === "object" ? data !== null : typeof data === "function") {
3853
+ return structure1idajgl04py4nuApply$1(data, ctx);
3854
+ }
3855
+ if (data === null) {
3856
+ return true;
3857
+ }
3858
+ return !ctx._e(data, "discriminant", "an object or null");
3859
+ }
3779
3860
  function unionufj73n0jxns2oApply(data, ctx) {
3780
3861
  if (typeof data === "object" ? data !== null : typeof data === "function") {
3781
3862
  {
@@ -3799,6 +3880,18 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3799
3880
  }
3800
3881
  return false;
3801
3882
  }
3883
+ function union12poedh18834r8Allows(data, ctx) {
3884
+ if (data === null) {
3885
+ return true;
3886
+ }
3887
+ if (
3888
+ /* @__NOINLINE__ */
3889
+ intersection1in70h716rkr52Allows(data)
3890
+ ) {
3891
+ return true;
3892
+ }
3893
+ return false;
3894
+ }
3802
3895
  function intersectiont0fgct0m9vuomApply(data, ctx) {
3803
3896
  return (Number.isFinite(data.id) || !failsKey(ctx, data, "id", "domain", "a number")) && (data.success === false || !failsKey(ctx, data, "success", "unit", "false")) && !ctx._k(intersectionpk5ov80e6ufcoApply, data, "error", "an object");
3804
3897
  }
@@ -3829,7 +3922,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3829
3922
  function domainwf1rf311hsq3lAllows(data, ctx) {
3830
3923
  return typeof data === "string";
3831
3924
  }
3832
- function intersectione4pcj513cxhmdAllows(data, ctx) {
3925
+ function intersection1d09i901hcco3uAllows(data, ctx) {
3833
3926
  switch (data) {
3834
3927
  case null:
3835
3928
  case void 0:
@@ -3837,7 +3930,8 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3837
3930
  default:
3838
3931
  data.area_id;
3839
3932
  if ((data instanceof Object || Object(data) === data) && (typeof data.area_id === "string" && typeof data.name === "string" && (!("floor_id" in data) || !!(typeof data.floor_id === "string" || data.floor_id === null)) && (!("labels" in data) || !!/* @__NOINLINE__ */
3840
- intersection1kfvut30tftkihAllows(data.labels)))) {
3933
+ intersection1kfvut30tftkihAllows(data.labels)) && (!("aliases" in data) || !!/* @__NOINLINE__ */
3934
+ intersection1kfvut30tftkihAllows(data.aliases)))) {
3841
3935
  return true;
3842
3936
  }
3843
3937
  }
@@ -3942,6 +4036,20 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
3942
4036
  }
3943
4037
  return false;
3944
4038
  }
4039
+ function intersectionp6z1tl0i351sdAllows(data, ctx) {
4040
+ switch (data) {
4041
+ case null:
4042
+ case void 0:
4043
+ break;
4044
+ default:
4045
+ data.is_fixable;
4046
+ if ((data instanceof Object || Object(data) === data) && ((!("is_fixable" in data) || !!(data.is_fixable === false || data.is_fixable === null || data.is_fixable === true)) && (!("ignored" in data) || !!(data.ignored === false || data.ignored === true)) && typeof data.domain === "string" && typeof data.issue_id === "string" && (!("severity" in data) || !!(typeof data.severity === "string")) && (!("created" in data) || !!(typeof data.created === "string")) && (!("translation_key" in data) || !!(typeof data.translation_key === "string" || data.translation_key === null)) && (!("translation_placeholders" in data) || !!/* @__NOINLINE__ */
4047
+ union12poedh18834r8Allows(data.translation_placeholders)))) {
4048
+ return true;
4049
+ }
4050
+ }
4051
+ return false;
4052
+ }
3945
4053
  function intersectioncvon2w1hep5foAllows(data, ctx) {
3946
4054
  switch (data) {
3947
4055
  case null:
@@ -4096,6 +4204,19 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4096
4204
  }
4097
4205
  return false;
4098
4206
  }
4207
+ function intersection9mjaub0dojaqnAllows(data, ctx) {
4208
+ switch (data) {
4209
+ case null:
4210
+ case void 0:
4211
+ break;
4212
+ default:
4213
+ data.supports_unload;
4214
+ if ((data instanceof Object || Object(data) === data) && ((!("supports_unload" in data) || !!(data.supports_unload === false || data.supports_unload === null || data.supports_unload === true)) && (!("supports_reconfigure" in data) || !!(data.supports_reconfigure === false || data.supports_reconfigure === null || data.supports_reconfigure === true)) && typeof data.entry_id === "string" && typeof data.domain === "string" && (!("title" in data) || !!(typeof data.title === "string")) && (!("state" in data) || !!(typeof data.state === "string")) && (!("reason" in data) || !!(typeof data.reason === "string" || data.reason === null)) && (!("source" in data) || !!(typeof data.source === "string")) && (!("disabled_by" in data) || !!(typeof data.disabled_by === "string" || data.disabled_by === null)))) {
4215
+ return true;
4216
+ }
4217
+ }
4218
+ return false;
4219
+ }
4099
4220
  function unionlgje2o0lqtbj0Apply(data, ctx) {
4100
4221
  switch (data) {
4101
4222
  case false:
@@ -4233,6 +4354,21 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4233
4354
  }, function(data, ctx) {
4234
4355
  if (!isObjectData(data)) return notObjectData(data, ctx);
4235
4356
  return !ctx._k(intersectionyqw5ji14ai0asApply, data, "data", "an object") && !ctx._k(intersection15cfdd30ejztvcApply, data, "context", "an object");
4357
+ }]), create1sex1811cremth2([function(data, ctx) {
4358
+ switch (data) {
4359
+ case null:
4360
+ case void 0:
4361
+ break;
4362
+ default:
4363
+ data.result;
4364
+ if ((data instanceof Object || Object(data) === data) && ((data.result === "invalid" || data.result === "valid") && (!("errors" in data) || !!(typeof data.errors === "string" || data.errors === null)) && (!("warnings" in data) || !!(typeof data.warnings === "string" || data.warnings === null)))) {
4365
+ return true;
4366
+ }
4367
+ }
4368
+ return false;
4369
+ }, function(data, ctx) {
4370
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4371
+ return (data.result === "invalid" || data.result === "valid" || !failsKey(ctx, data, "result", "discriminant", '"invalid" or "valid"')) && (!("errors" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "errors")) && (!("warnings" in data) || !ctx._k(union1jkn5x91bzd348Apply, data, "warnings"));
4236
4372
  }]), create1sex1811cremth2([intersection1kfvut30tftkihAllows, intersection1kfvut30tftkihApply]), create1sex1811cremth2([function(data, ctx) {
4237
4373
  switch (data) {
4238
4374
  case null:
@@ -4359,31 +4495,6 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4359
4495
  }, function(data, ctx) {
4360
4496
  if (!isObjectData(data)) return notObjectData(data, ctx);
4361
4497
  return "response" in data ? !ctx._k(intersectionc5cirx0ys2jaeAllows, data, "response") : !failsKey(ctx, data, "response", "required", "present");
4362
- }]), create1sex1811cremth2([function(data, ctx) {
4363
- for (; ; ) {
4364
- if (!(typeof data === "string")) {
4365
- break;
4366
- }
4367
- if (!literal0.test(data)) {
4368
- break;
4369
- }
4370
- if (!/* @__NOINLINE__ */
4371
- intersection1649hnt0ixrxb1R3(data)) {
4372
- break;
4373
- }
4374
- return true;
4375
- }
4376
- return false;
4377
- }, function(data, ctx) {
4378
- if (!(typeof data === "string")) {
4379
- return !ctx._e(data, "domain", "a string");
4380
- }
4381
- if (!literal0.test(data)) {
4382
- return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4383
- }
4384
- {
4385
- return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4386
- }
4387
4498
  }]), create1sex1811cremth2([function(data, ctx) {
4388
4499
  switch (data) {
4389
4500
  case null:
@@ -4482,7 +4593,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4482
4593
  }
4483
4594
  for (let i = 0; i < data.length; i++) {
4484
4595
  if (!/* @__NOINLINE__ */
4485
- intersectione4pcj513cxhmdAllows(data[i])) {
4596
+ intersection1d09i901hcco3uAllows(data[i])) {
4486
4597
  return false;
4487
4598
  }
4488
4599
  }
@@ -4495,7 +4606,7 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4495
4606
  }
4496
4607
  for (let i = 0; i < data.length; i++) {
4497
4608
  if (!/* @__NOINLINE__ */
4498
- intersectione4pcj513cxhmdAllows(data[i], ctx) && ctx._k(intersectione4pcj513cxhmdApply, data, i)) {
4609
+ intersection1d09i901hcco3uAllows(data[i], ctx) && ctx._k(intersection1d09i901hcco3uApply, data, i)) {
4499
4610
  return false;
4500
4611
  }
4501
4612
  }
@@ -4600,6 +4711,121 @@ var [intersectionwidg351n2f7o4Validator, intersectionegwyf90w1alu2Validator, int
4600
4711
  }, function(data, ctx) {
4601
4712
  if (!isObjectData(data)) return notObjectData(data, ctx);
4602
4713
  return !ctx._k(intersection1wj0gg91b5c2hlApply, data, "resources", "an object");
4714
+ }]), create1sex1811cremth2([function(data, ctx) {
4715
+ for (; ; ) {
4716
+ if (!Array.isArray(data)) {
4717
+ break;
4718
+ }
4719
+ for (let i = 0; i < data.length; i++) {
4720
+ if (!/* @__NOINLINE__ */
4721
+ intersection9mjaub0dojaqnAllows(data[i])) {
4722
+ return false;
4723
+ }
4724
+ }
4725
+ return true;
4726
+ }
4727
+ return false;
4728
+ }, function(data, ctx) {
4729
+ if (!Array.isArray(data)) {
4730
+ return !ctx._e(data, "proto", "an array");
4731
+ }
4732
+ for (let i = 0; i < data.length; i++) {
4733
+ if (!/* @__NOINLINE__ */
4734
+ intersection9mjaub0dojaqnAllows(data[i], ctx) && ctx._k(intersection9mjaub0dojaqnApply, data, i)) {
4735
+ return false;
4736
+ }
4737
+ }
4738
+ return true;
4739
+ }]), create1sex1811cremth2([function(data, ctx) {
4740
+ switch (data) {
4741
+ case null:
4742
+ case void 0:
4743
+ break;
4744
+ default:
4745
+ data.issues;
4746
+ if ((data instanceof Object || Object(data) === data) && /* @__NOINLINE__ */
4747
+ intersection15t5mdk0e0pwczAllows(data.issues)) {
4748
+ return true;
4749
+ }
4750
+ }
4751
+ return false;
4752
+ }, function(data, ctx) {
4753
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4754
+ return !ctx._k(intersection15t5mdk0e0pwczApply, data, "issues", "an array");
4755
+ }]), create1sex1811cremth2([function(data, ctx) {
4756
+ for (; ; ) {
4757
+ if (!(data !== null && (typeof data === "object" || typeof data === "function"))) {
4758
+ break;
4759
+ }
4760
+ if (!/* @__NOINLINE__ */
4761
+ structure1pu25bs17d9ig3Allows(data)) {
4762
+ break;
4763
+ }
4764
+ return true;
4765
+ }
4766
+ return false;
4767
+ }, function(data, ctx) {
4768
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4769
+ {
4770
+ const keys = Object.keys(data);
4771
+ const isArray2 = Array.isArray(data);
4772
+ for (let i = 0; i < keys.length; i++) {
4773
+ const k = keys[i];
4774
+ if (
4775
+ /* @__NOINLINE__ */
4776
+ domainwf1rf311hsq3lAllows(k, ctx)
4777
+ ) {
4778
+ if (!/* @__NOINLINE__ */
4779
+ intersection1kfvut30tftkihAllows(data[k], ctx) && ctx._k(intersection1kfvut30tftkihApply, data, isArray2 ? (
4780
+ /* @__NOINLINE__ */
4781
+ intersection1in70h716rkr52R1(k)
4782
+ ) : k)) {
4783
+ return false;
4784
+ }
4785
+ }
4786
+ }
4787
+ return true;
4788
+ }
4789
+ }]), create1sex1811cremth2([function(data, ctx) {
4790
+ switch (data) {
4791
+ case null:
4792
+ case void 0:
4793
+ break;
4794
+ default:
4795
+ data.version;
4796
+ if ((data instanceof Object || Object(data) === data) && (typeof data.version === "string" && typeof data.state === "string")) {
4797
+ return true;
4798
+ }
4799
+ }
4800
+ return false;
4801
+ }, function(data, ctx) {
4802
+ if (!isObjectData(data)) return notObjectData(data, ctx);
4803
+ return (typeof data.version === "string" || !fails0(ctx, data, "version")) && (typeof data.state === "string" || !fails0(ctx, data, "state"));
4804
+ }]), create1sex1811cremth2([function(data, ctx) {
4805
+ for (; ; ) {
4806
+ if (!(typeof data === "string")) {
4807
+ break;
4808
+ }
4809
+ if (!literal0.test(data)) {
4810
+ break;
4811
+ }
4812
+ if (!/* @__NOINLINE__ */
4813
+ intersection1649hnt0ixrxb1R3(data)) {
4814
+ break;
4815
+ }
4816
+ return true;
4817
+ }
4818
+ return false;
4819
+ }, function(data, ctx) {
4820
+ if (!(typeof data === "string")) {
4821
+ return !ctx._e(data, "domain", "a string");
4822
+ }
4823
+ if (!literal0.test(data)) {
4824
+ return !ctx._e(data, "pattern", "an HTTP or HTTPS URL");
4825
+ }
4826
+ {
4827
+ return !!intersection1649hnt0ixrxb1R3(data, ctx) || !ctx._e(data, "predicate", "an HTTP or HTTPS URL");
4828
+ }
4603
4829
  }]), create1sex1811cremth2([function(data, ctx) {
4604
4830
  switch (data) {
4605
4831
  case null:
@@ -4659,7 +4885,7 @@ var create1sfgs3s1wvt6nb = (({ 0: allows, 1: apply }) => {
4659
4885
  return validator;
4660
4886
  });
4661
4887
 
4662
- // arktype:~arktype/141z4sf0c2cbgh-xin31g1b340jz
4888
+ // arktype:~arktype/141z4sf0c2cbgh-rf7kfa08h9f7r
4663
4889
  var created4;
4664
4890
  var factory1 = ((p0, p1) => {
4665
4891
  checkHeld(p0);
@@ -4682,24 +4908,26 @@ var held = (validator, ...inputs) => {
4682
4908
  // src/errors.ts
4683
4909
  var errorMeanings = {
4684
4910
  usage_error: "Wrong command, flag or argument",
4685
- config_error: "A config file is invalid or unreadable; the message names its path",
4911
+ config_error: "A config file is invalid, or a settings file cannot be read; the message names its path",
4686
4912
  context_not_found: "The selected or named context is not defined",
4687
4913
  no_context: "No context is selected",
4688
- token_missing: "The active context has no stored token",
4689
- keychain_unavailable: "The keychain tool is missing or failed",
4690
- unreachable: "The URL does not answer, or redirects",
4691
- timeout: "A service call or template took too long or got no answer",
4914
+ token_missing: "The active context has no keychain token or applicable HACTL_TOKEN",
4915
+ keychain_unavailable: "The OS keychain is unsupported, its tool is missing, or an operation failed; HACTL_TOKEN bypasses it",
4916
+ unreachable: "A connection failed or closed, or a URL did not answer as needed (including redirects)",
4917
+ timeout: "A service call, template or configuration check took too long or got no answer",
4692
4918
  unauthorized: "Home Assistant rejected the token",
4919
+ config_invalid: "Home Assistant reported the YAML configuration invalid",
4693
4920
  ha_error: "Home Assistant returned an error or an unexpected response",
4694
- ssh_not_configured: "The command needs SSH, but the context has no SSH target",
4695
- ssh_failed: "SSH could not connect or log in without a prompt",
4921
+ ssh_not_configured: "An SSH target is missing (reserved; ctx verify skips SSH when none is set)",
4922
+ ssh_failed: "The ssh executable is missing, or SSH failed to connect or authenticate",
4696
4923
  install_mismatch: "The context's install type does not match what Home Assistant reports",
4697
4924
  container_not_running: "The Docker container is not running, or the SSH user cannot run docker",
4698
4925
  config_dir_missing: "The config folder has no readable .HA_VERSION",
4699
4926
  not_found: "A named thing does not exist, such as an entity, area, service, app or release",
4700
- not_a_binary: "`hactl upgrade` was run from source, not from a release binary",
4927
+ not_a_binary: "`hactl upgrade` was run from npm or source, not from a release binary",
4701
4928
  upgrade_not_writable: "`hactl upgrade` cannot stage or replace the binary",
4702
- download_failed: "The downloaded binary failed its digest or version check"
4929
+ download_failed: "The binary could not be downloaded or failed its digest or version check",
4930
+ internal_error: "An unexpected error occurred; the hint links to the issue tracker"
4703
4931
  };
4704
4932
  var HactlError = class extends Error {
4705
4933
  hint;
@@ -4739,9 +4967,14 @@ var TimeoutError = class extends HactlError {
4739
4967
  var UnauthorizedError = class extends HactlError {
4740
4968
  code = "unauthorized";
4741
4969
  };
4970
+ var ConfigInvalidError = class extends HactlError {
4971
+ code = "config_invalid";
4972
+ };
4742
4973
  var HaError = class extends HactlError {
4743
4974
  code = "ha_error";
4744
4975
  };
4976
+ var AdminRequiredError = class extends HaError {
4977
+ };
4745
4978
  var HaCommandError = class extends HaError {
4746
4979
  haCode;
4747
4980
  translationKey;
@@ -4900,18 +5133,40 @@ function parseContextName(input) {
4900
5133
  if (!contextNamePattern.test(input)) {
4901
5134
  throw new UsageError(
4902
5135
  `invalid context name "${input}"`,
4903
- "Use lowercase letters, digits and dashes."
5136
+ "Start with a lowercase letter or digit; use only lowercase letters, digits and dashes."
4904
5137
  );
4905
5138
  }
4906
5139
  return input;
4907
5140
  }
4908
5141
 
4909
- // src/settings.ts
4910
- import { stat } from "node:fs/promises";
4911
- import { dirname as dirname2, join as join3 } from "node:path";
4912
- var projectFileName = ".hactl.json";
4913
- async function findProjectFile(cwd) {
4914
- for (let folder = cwd; ; folder = dirname2(folder)) {
5142
+ // src/secret.ts
5143
+ import { inspect } from "node:util";
5144
+ var redacted = "<redacted>";
5145
+ var Secret = class {
5146
+ #value;
5147
+ constructor(value) {
5148
+ this.#value = value;
5149
+ }
5150
+ reveal() {
5151
+ return this.#value;
5152
+ }
5153
+ toString() {
5154
+ return redacted;
5155
+ }
5156
+ toJSON() {
5157
+ return redacted;
5158
+ }
5159
+ [inspect.custom]() {
5160
+ return redacted;
5161
+ }
5162
+ };
5163
+
5164
+ // src/settings.ts
5165
+ import { stat } from "node:fs/promises";
5166
+ import { dirname as dirname2, join as join3 } from "node:path";
5167
+ var projectFileName = ".hactl.json";
5168
+ async function findProjectFile(cwd) {
5169
+ for (let folder = cwd; ; folder = dirname2(folder)) {
4915
5170
  const path = join3(folder, projectFileName);
4916
5171
  try {
4917
5172
  if ((await stat(path)).isFile()) {
@@ -4937,24 +5192,28 @@ async function loadSettingsFile(path) {
4937
5192
  throw exc instanceof ConfigError ? exc : settingsIoError(path, exc);
4938
5193
  }
4939
5194
  }
5195
+ function selectionSource(selection) {
5196
+ return selection.source === "env" ? "HACTL_CONTEXT" : selection.path ?? "";
5197
+ }
4940
5198
  async function loadSelection(environment, planned) {
5199
+ const fromEnv = environment.env["HACTL_CONTEXT"];
5200
+ if (fromEnv !== void 0 && fromEnv !== "") {
5201
+ return { name: fromEnv, source: "env" };
5202
+ }
4941
5203
  const projectPath = planned?.source === "project" ? planned.path : await findProjectFile(environment.cwd);
4942
- const files = [
4943
- ...projectPath === void 0 ? [] : [{ source: "project", path: projectPath }],
4944
- {
4945
- source: "global",
4946
- path: globalSettingsPath(configFolder(environment.env, environment.homedir))
5204
+ const globalPath = globalSettingsPath(configFolder(environment.env, environment.homedir));
5205
+ const load = async (source, path) => {
5206
+ if (path === void 0) {
5207
+ return void 0;
4947
5208
  }
4948
- ];
4949
- const names = await Promise.all(
4950
- files.map(
4951
- async (file2) => planned?.source === file2.source ? planned.name : (await loadSettingsFile(file2.path))?.context
4952
- )
4953
- );
4954
- const index = names.findIndex((name2) => name2 !== void 0);
4955
- const file = files[index];
4956
- const name = names[index];
4957
- return file === void 0 || name === void 0 ? void 0 : { name, ...file };
5209
+ const name = planned?.source === source ? planned.name : (await loadSettingsFile(path))?.context;
5210
+ return name === void 0 ? void 0 : { name, source, path };
5211
+ };
5212
+ const [project, global] = await Promise.all([
5213
+ load("project", projectPath),
5214
+ load("global", globalPath)
5215
+ ]);
5216
+ return project ?? global;
4958
5217
  }
4959
5218
  async function setGlobalContext(folder, name) {
4960
5219
  await writeJsonFile(globalSettingsPath(folder), name === void 0 ? {} : { context: name });
@@ -4973,7 +5232,20 @@ async function clearGlobalContext(folder, name) {
4973
5232
  }
4974
5233
 
4975
5234
  // src/active.ts
5235
+ function envToken(env, name) {
5236
+ const token = env["HACTL_TOKEN"];
5237
+ return env["HACTL_CONTEXT"] === name && token !== void 0 && token !== "" ? new Secret(token.replace(/\r?\n$/, "")) : void 0;
5238
+ }
5239
+ function unauthorizedHint(active) {
5240
+ return active.source === "env" ? "The token in HACTL_TOKEN was rejected; set a new one." : `Store a new token with \`hactl ctx token-set ${active.context.name}\`.`;
5241
+ }
4976
5242
  async function resolveActiveContext(environment) {
5243
+ if ((environment.env["HACTL_TOKEN"] ?? "") !== "" && (environment.env["HACTL_CONTEXT"] ?? "") === "") {
5244
+ throw new UsageError(
5245
+ "HACTL_TOKEN is set without HACTL_CONTEXT",
5246
+ "HACTL_TOKEN only applies to the context HACTL_CONTEXT names. Set both, or neither."
5247
+ );
5248
+ }
4977
5249
  const selection = await loadSelection(environment);
4978
5250
  if (selection === void 0) {
4979
5251
  const contexts2 = await loadContexts(configFolder(environment.env, environment.homedir));
@@ -4983,15 +5255,19 @@ async function resolveActiveContext(environment) {
4983
5255
  );
4984
5256
  }
4985
5257
  const contexts = await loadContexts(configFolder(environment.env, environment.homedir));
4986
- const definition = requireContext(contexts, selection.name, selection.path);
5258
+ const definition = requireContext(contexts, selection.name, selectionSource(selection));
5259
+ const fromEnv = envToken(environment.env, definition.name);
5260
+ if (fromEnv !== void 0) {
5261
+ return { context: definition, token: fromEnv, source: "env" };
5262
+ }
4987
5263
  const token = await environment.keychain.get(definition.name);
4988
5264
  if (token === void 0) {
4989
5265
  throw new TokenMissingError(
4990
5266
  `no token is stored for context "${definition.name}"`,
4991
- `Run \`hactl ctx token-set ${definition.name}\`.`
5267
+ `Store one with \`hactl ctx token-set ${definition.name}\`, or set HACTL_TOKEN with HACTL_CONTEXT.`
4992
5268
  );
4993
5269
  }
4994
- return { context: definition, token };
5270
+ return { context: definition, token, source: "keychain" };
4995
5271
  }
4996
5272
 
4997
5273
  // src/context.ts
@@ -5017,7 +5293,8 @@ async function findOnPath(tool, env) {
5017
5293
  }
5018
5294
  function runTool(path, args, env, input) {
5019
5295
  return new Promise((resolve, reject) => {
5020
- const child = spawn(path, args, { env, stdio: ["pipe", "pipe", "pipe"] });
5296
+ const { HACTL_TOKEN: _token, ...childEnv } = env;
5297
+ const child = spawn(path, args, { env: childEnv, stdio: ["pipe", "pipe", "pipe"] });
5021
5298
  let stdout = "";
5022
5299
  let stderr = "";
5023
5300
  let stdinError = false;
@@ -5042,34 +5319,12 @@ function runTool(path, args, env, input) {
5042
5319
  });
5043
5320
  }
5044
5321
 
5045
- // src/secret.ts
5046
- import { inspect } from "node:util";
5047
- var redacted = "<redacted>";
5048
- var Secret = class {
5049
- #value;
5050
- constructor(value) {
5051
- this.#value = value;
5052
- }
5053
- reveal() {
5054
- return this.#value;
5055
- }
5056
- toString() {
5057
- return redacted;
5058
- }
5059
- toJSON() {
5060
- return redacted;
5061
- }
5062
- [inspect.custom]() {
5063
- return redacted;
5064
- }
5065
- };
5066
-
5067
5322
  // src/keychain/run.ts
5068
5323
  function toolFailed(tool, action, result) {
5069
5324
  const detail = result.stderr.trim();
5070
5325
  return new KeychainUnavailableError(
5071
5326
  `\`${tool}\` failed to ${action} (exit ${result.code}${detail === "" ? "" : `: ${detail}`})`,
5072
- "Unlock the keychain and allow hactl to use it."
5327
+ "Unlock the keychain and allow hactl to use it, or set HACTL_CONTEXT and HACTL_TOKEN."
5073
5328
  );
5074
5329
  }
5075
5330
 
@@ -5151,9 +5406,9 @@ function macosKeychain(path, env) {
5151
5406
  if (!tokenPattern.test(value)) {
5152
5407
  throw new UsageError("the token contains characters a Home Assistant token never has");
5153
5408
  }
5154
- const command5 = `add-generic-password -U -s hactl -a ${context} -w ${value}
5409
+ const command2 = `add-generic-password -U -s hactl -a ${context} -w ${value}
5155
5410
  `;
5156
- const result = await runTool(path, ["-i"], env, command5);
5411
+ const result = await runTool(path, ["-i"], env, command2);
5157
5412
  if (result.code !== 0 || result.stderr.trim() !== "") {
5158
5413
  throw toolFailed("security", "store the token", result);
5159
5414
  }
@@ -5187,13 +5442,16 @@ function createKeychain(platform, env) {
5187
5442
  })();
5188
5443
  const resolve = async () => {
5189
5444
  if (backend === void 0) {
5190
- throw new NoKeychainError(`storing tokens is not supported on ${platform}`);
5445
+ throw new NoKeychainError(
5446
+ `storing tokens is not supported on ${platform}`,
5447
+ "Or set HACTL_CONTEXT and HACTL_TOKEN to work without a keychain."
5448
+ );
5191
5449
  }
5192
5450
  const path = await findOnPath(backend.tool, env);
5193
5451
  if (path === void 0) {
5194
5452
  throw new NoKeychainError(
5195
5453
  `\`${backend.tool}\` was not found on PATH`,
5196
- backend.tool === "secret-tool" ? "Install `libsecret-tools`." : void 0
5454
+ backend.tool === "secret-tool" ? "Install `libsecret-tools`, or set HACTL_CONTEXT and HACTL_TOKEN." : "Set HACTL_CONTEXT and HACTL_TOKEN to work without a keychain."
5197
5455
  );
5198
5456
  }
5199
5457
  return backend.build(path, env);
@@ -5595,7 +5853,7 @@ function createLineRedactor(token) {
5595
5853
 
5596
5854
  // src/ssh.ts
5597
5855
  var sshFailure = 255;
5598
- function sshArgs(target, command5) {
5856
+ function sshArgs(target, command2) {
5599
5857
  return [
5600
5858
  "-o",
5601
5859
  "BatchMode=yes",
@@ -5605,23 +5863,23 @@ function sshArgs(target, command5) {
5605
5863
  "ConnectTimeout=10",
5606
5864
  "--",
5607
5865
  target,
5608
- command5
5866
+ command2
5609
5867
  ];
5610
5868
  }
5611
5869
  function createSshRunner(env) {
5612
- return async (target, command5) => {
5870
+ return async (target, command2) => {
5613
5871
  const path = await findOnPath("ssh", env);
5614
5872
  if (path === void 0) {
5615
5873
  throw new SshFailedError(`ssh to ${target} failed: \`ssh\` was not found on PATH`);
5616
5874
  }
5617
- return runTool(path, sshArgs(target, command5), env);
5875
+ return runTool(path, sshArgs(target, command2), env);
5618
5876
  };
5619
5877
  }
5620
5878
  function shellQuote(value) {
5621
5879
  return `'${value.replaceAll("'", `'\\''`)}'`;
5622
5880
  }
5623
- async function runRemote(ssh, target, command5, token) {
5624
- const result = await ssh(target, command5);
5881
+ async function runRemote(ssh, target, command2, token) {
5882
+ const result = await ssh(target, command2);
5625
5883
  if (result.code !== sshFailure) {
5626
5884
  return result;
5627
5885
  }
@@ -5747,7 +6005,8 @@ function printJson(context, value) {
5747
6005
  function webSocketUrl(context) {
5748
6006
  return `${baseUrl(context).replace(/^http/, "ws")}/api/websocket`;
5749
6007
  }
5750
- function openHa(connect, context, token, timeoutMs2 = 1e4) {
6008
+ function openHa(connect, active, timeoutMs2 = 1e4) {
6009
+ const { context, token } = active;
5751
6010
  const url2 = webSocketUrl(context);
5752
6011
  const pending = /* @__PURE__ */ new Map();
5753
6012
  const timers = /* @__PURE__ */ new Set();
@@ -5782,20 +6041,20 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5782
6041
  const unreachable = (reason) => new UnreachableError(`cannot reach ${url2}: ${reason}`);
5783
6042
  const notHa2 = (value) => {
5784
6043
  const id = typeof value === "object" && value !== null && "id" in value ? value.id : void 0;
5785
- const command5 = typeof id === "number" ? (pending.get(id) ?? listeners.get(id))?.command : void 0;
6044
+ const command2 = typeof id === "number" ? (pending.get(id) ?? listeners.get(id))?.command : void 0;
5786
6045
  return new HaError(
5787
- `${url2} did not answer like Home Assistant${command5 === void 0 ? "" : ` for ${command5}`}`
6046
+ `${url2} did not answer like Home Assistant${command2 === void 0 ? "" : ` for ${command2}`}`
5788
6047
  );
5789
6048
  };
5790
- const send = (command5, parameters, listener) => new Promise((resolve, reject) => {
6049
+ const send = (command2, parameters, listener) => new Promise((resolve, reject) => {
5791
6050
  if (finished) {
5792
6051
  reject(lost ?? unreachable("the connection is closed"));
5793
6052
  return;
5794
6053
  }
5795
6054
  const id = nextId++;
5796
6055
  const timer = timeout(() => {
5797
- const reason = `no answer to ${command5} within ${timeoutMs2 / 1e3} seconds`;
5798
- if (command5 === "call_service") {
6056
+ const reason = `no answer to ${command2} within ${timeoutMs2 / 1e3} seconds`;
6057
+ if (command2 === "call_service") {
5799
6058
  fail(
5800
6059
  new TimeoutError(
5801
6060
  `the call was sent, but there was ${reason}`,
@@ -5804,12 +6063,12 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5804
6063
  );
5805
6064
  } else {
5806
6065
  fail(
5807
- command5 === "render_template" ? new TimeoutError(`there was ${reason}`) : unreachable(reason)
6066
+ command2 === "render_template" ? new TimeoutError(`there was ${reason}`) : unreachable(reason)
5808
6067
  );
5809
6068
  }
5810
6069
  });
5811
6070
  pending.set(id, {
5812
- command: command5,
6071
+ command: command2,
5813
6072
  resolve: (result) => {
5814
6073
  clearTimeout(timer);
5815
6074
  timers.delete(timer);
@@ -5822,17 +6081,17 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5822
6081
  }
5823
6082
  });
5824
6083
  if (listener !== void 0) {
5825
- listeners.set(id, { command: command5, listener });
6084
+ listeners.set(id, { command: command2, listener });
5826
6085
  }
5827
- socket?.send(JSON.stringify({ ...parameters, id, type: command5 }));
6086
+ socket?.send(JSON.stringify({ ...parameters, id, type: command2 }));
5828
6087
  });
5829
6088
  const session = {
5830
- send: (command5, parameters) => send(command5, parameters),
6089
+ send: (command2, parameters) => send(command2, parameters),
5831
6090
  subscribe: async (eventType, listener) => {
5832
6091
  await send("subscribe_events", { event_type: eventType }, listener);
5833
6092
  },
5834
- stream: async (command5, parameters, listener) => {
5835
- await send(command5, parameters, listener);
6093
+ stream: async (command2, parameters, listener) => {
6094
+ await send(command2, parameters, listener);
5836
6095
  },
5837
6096
  lost: () => new Promise((_, reject) => {
5838
6097
  if (finished) {
@@ -5901,7 +6160,7 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5901
6160
  fail(
5902
6161
  new UnauthorizedError(
5903
6162
  `the token for context "${context.name}" was rejected`,
5904
- `Store a new token with \`hactl ctx token-set ${context.name}\`.`
6163
+ unauthorizedHint(active)
5905
6164
  )
5906
6165
  );
5907
6166
  return;
@@ -5950,26 +6209,32 @@ function openHa(connect, context, token, timeoutMs2 = 1e4) {
5950
6209
 
5951
6210
  // src/commands/get/read.ts
5952
6211
  async function withHa(context, use) {
5953
- const { context: target, token } = await resolveActiveContext(context);
5954
- const session = await openHa(context.connect, target, token);
6212
+ const active = await resolveActiveContext(context);
6213
+ const { token } = active;
6214
+ const session = await openHa(context.connect, active);
5955
6215
  try {
5956
6216
  return { value: await use(session, token), token };
5957
6217
  } finally {
5958
6218
  session.close();
5959
6219
  }
5960
6220
  }
5961
- var readHa = (context, commands3) => withHa(context, (session) => Promise.all(commands3.map((command5) => session.send(command5))));
5962
- function parseResult(schema, data, command5, token) {
6221
+ var readHa = (context, commands4) => withHa(context, (session) => Promise.all(commands4.map((command2) => session.send(command2))));
6222
+ function parseResult(schema, data, command2, token) {
5963
6223
  const result = schema(data);
5964
6224
  if (result instanceof Issues) {
5965
6225
  throw new HaError(
5966
- `${command5} returned an unexpected result: ${redactText(result.summary, token)}`
6226
+ `${command2} returned an unexpected result: ${redactText(result.summary, token)}`
5967
6227
  );
5968
6228
  }
5969
6229
  return result;
5970
6230
  }
5971
- function printItems(context, items, id, kind, summary, token) {
5972
- const found = id === void 0 ? items.map(summary) : findById(items, id, kind);
6231
+ function printItems(context, items, id, kind, summary, token, { count, limit } = {}) {
6232
+ if (count === true) {
6233
+ printJson(context, { count: items.length });
6234
+ return;
6235
+ }
6236
+ const list = limit === void 0 ? items : items.slice(0, limit);
6237
+ const found = id === void 0 ? list.map(summary) : findById(items, id, kind);
5973
6238
  printJson(context, redactData(found, token));
5974
6239
  }
5975
6240
  function findById(items, id, kind) {
@@ -5986,6 +6251,45 @@ function pick(item, keys) {
5986
6251
  }
5987
6252
  var idParameter = (brief) => ({ brief, placeholder: "id", parse: String, optional: true });
5988
6253
  var filterFlag = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
6254
+ function parseLimit(input) {
6255
+ const limit = Number(input);
6256
+ if (!/^\d+$/.test(input) || !Number.isSafeInteger(limit) || limit < 1) {
6257
+ throw new UsageError("--limit must be a whole number, 1 or more");
6258
+ }
6259
+ return limit;
6260
+ }
6261
+ var listFlags = {
6262
+ limit: {
6263
+ kind: "parsed",
6264
+ parse: parseLimit,
6265
+ optional: true,
6266
+ brief: "Print at most this many items (positive whole number)",
6267
+ placeholder: "n"
6268
+ },
6269
+ count: { kind: "boolean", optional: true, brief: 'Print {"count": n} instead of the items' }
6270
+ };
6271
+ function checkListFlags(flags, id) {
6272
+ if (flags.limit !== void 0 && flags.count === true) {
6273
+ throw new UsageError("--limit and --count cannot be combined");
6274
+ }
6275
+ if (id !== void 0 && (flags.limit !== void 0 || flags.count === true)) {
6276
+ throw new UsageError("--limit and --count apply to a list, not to an id");
6277
+ }
6278
+ }
6279
+ function refused(error) {
6280
+ return error instanceof UnauthorizedError || error instanceof AdminRequiredError || error instanceof HaCommandError && (error.haCode === "unauthorized" || error.haCode === "not_found" || error.haCode === "unknown_command");
6281
+ }
6282
+ async function optionalRead(names, name, read) {
6283
+ try {
6284
+ return await read();
6285
+ } catch (error) {
6286
+ if (!refused(error)) {
6287
+ throw error;
6288
+ }
6289
+ names.add(name);
6290
+ return void 0;
6291
+ }
6292
+ }
5989
6293
 
5990
6294
  // src/resources.ts
5991
6295
  function compact(value) {
@@ -6073,6 +6377,44 @@ function toEntities(current, registry, devices, options) {
6073
6377
  });
6074
6378
  }).sort(byId);
6075
6379
  }
6380
+ function toIntegrations(entries) {
6381
+ return entries.map(
6382
+ (entry) => compact({
6383
+ id: entry.entry_id,
6384
+ domain: entry.domain,
6385
+ title: entry.title,
6386
+ state: entry.state,
6387
+ reason: text2(entry.reason),
6388
+ disabled: flag(entry.disabled_by),
6389
+ source: entry.source,
6390
+ supportsUnload: entry.supports_unload ?? void 0,
6391
+ supportsReconfigure: entry.supports_reconfigure ?? void 0
6392
+ })
6393
+ ).sort(byId);
6394
+ }
6395
+ function isUnhealthyEntry(entry) {
6396
+ return entry.state !== "loaded" && entry.disabled_by !== "user";
6397
+ }
6398
+ function toRepairs(file) {
6399
+ return file.issues.map(
6400
+ (issue) => compact({
6401
+ id: `${issue.domain}/${issue.issue_id}`,
6402
+ domain: issue.domain,
6403
+ issueId: issue.issue_id,
6404
+ severity: issue.severity,
6405
+ isFixable: issue.is_fixable ?? void 0,
6406
+ ignored: issue.ignored,
6407
+ created: issue.created,
6408
+ translationKey: text2(issue.translation_key),
6409
+ translationPlaceholders: issue.translation_placeholders ?? void 0
6410
+ })
6411
+ ).sort(byId);
6412
+ }
6413
+ function toRelated(result) {
6414
+ return Object.fromEntries(
6415
+ Object.entries(result).map(([kind, ids]) => [kind, [...ids].sort()]).sort(([a], [b]) => a.localeCompare(b))
6416
+ );
6417
+ }
6076
6418
  function toServices(registry, texts = {}) {
6077
6419
  return Object.entries(registry).flatMap(
6078
6420
  ([domain, entries]) => Object.entries(entries).map(([name, service]) => {
@@ -6139,11 +6481,11 @@ function buildServiceData(flags) {
6139
6481
  }
6140
6482
  function readOnce(session) {
6141
6483
  const sent = /* @__PURE__ */ new Map();
6142
- return (command5) => {
6143
- let result = sent.get(command5);
6484
+ return (command2) => {
6485
+ let result = sent.get(command2);
6144
6486
  if (result === void 0) {
6145
- result = session.send(command5);
6146
- sent.set(command5, result);
6487
+ result = session.send(command2);
6488
+ sent.set(command2, result);
6147
6489
  }
6148
6490
  return result;
6149
6491
  };
@@ -6166,11 +6508,11 @@ async function checkTargets(read, flags, token) {
6166
6508
  throw new NotFoundError(`${kind} "${missing}" does not exist`);
6167
6509
  }
6168
6510
  };
6169
- const list = async (schema, command5) => parseResult(schema, await read(command5), command5, token);
6511
+ const list = async (schema, command2) => parseResult(schema, await read(command2), command2, token);
6170
6512
  const entities = (flags.entity ?? []).filter((id) => id !== "all" && id !== "none");
6171
6513
  const [states, areas, devices, floors, labels] = await inOrder([
6172
6514
  entities.length > 0 ? list(intersection10qmong0na8e8rValidator, "get_states") : Promise.resolve([]),
6173
- flags.area !== void 0 ? list(intersection1dmk4z81d1f8mlValidator, "config/area_registry/list") : Promise.resolve([]),
6515
+ flags.area !== void 0 ? list(intersection16hnzan16c9ou0Validator, "config/area_registry/list") : Promise.resolve([]),
6174
6516
  flags.device !== void 0 ? list(intersection3rk9um0b729ivValidator, "config/device_registry/list") : Promise.resolve([]),
6175
6517
  flags.floor !== void 0 ? list(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list") : Promise.resolve([]),
6176
6518
  flags.label !== void 0 ? list(intersection1rp35ue1fi65ccValidator, "config/label_registry/list") : Promise.resolve([])
@@ -6365,27 +6707,28 @@ async function callAndWatch(session, { domain, service }, data, seconds, targete
6365
6707
  }
6366
6708
  var callCommand = buildCommand({
6367
6709
  docs: {
6368
- brief: "Call a service and print the states it changed",
6369
- fullDescription: `Call a service and print the states it changed
6710
+ brief: "Call a service and report observed state changes",
6711
+ fullDescription: `Call a service and report observed state changes
6370
6712
 
6371
6713
  Calls <domain>.<service> on the active context. It never asks for confirmation.
6372
6714
  List services with \`hactl get services\`, and a service's fields with
6373
- \`hactl get services <id>\`. A service whose "response" is "required" only returns data: run
6374
- it with \`hactl query\`, as call refuses it.
6715
+ \`hactl get services <id>\`. If Home Assistant marks the response as "required", use
6716
+ \`hactl query\` instead; call refuses these services.
6375
6717
 
6376
6718
  Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
6377
6719
  key in --data. A target flag naming something that does not exist fails with not_found and
6378
- nothing is called. Ids in --data are not checked: Home Assistant ignores unknown ones. A lone --entity all targets every entity of
6379
- the service's domain: \`light.turn_off --entity all\` turns off every light. The
6380
- homeassistant.turn_on, turn_off and toggle services reject all.
6720
+ nothing is called. Ids in the --data JSON object are passed through without validation.
6721
+ Use --entity all on its own to pass Home Assistant's special all selector, e.g.
6722
+ \`light.turn_off --entity all\`. Not every service accepts it.
6381
6723
 
6382
6724
  Output: [{"id", "state", "attributes"}] of what changed, "attributes" holding only the
6383
- changed ones (null when removed) and left out when none did. Changes are collected for --wait seconds after Home
6384
- Assistant replies. The whole time is always waited; there is no maximum.
6725
+ changed ones (null when removed) and left out when none did. Results are sorted by entity id.
6726
+ Changes are collected from the time the call is sent until --wait seconds after Home
6727
+ Assistant replies (default ${defaultWaitSeconds}, capped at about 24.9 days).
6385
6728
  [] means no change was seen in time, not that nothing changed.
6386
6729
  A change counts when Home Assistant attributes it to this call or it is on a targeted
6387
- entity, including members of targeted groups and scenes. Home Assistant attributes for
6388
- 5 seconds after commanding a device, so slower changes of untargeted devices are missed.
6730
+ entity, including members of targeted groups and scenes. Unrelated changes on targeted
6731
+ entities can appear; changes on other entities are missed unless attributed to the call.
6389
6732
  Removed states are ignored. With --wait 0, only explicitly named entities and changes Home
6390
6733
  Assistant attributes to the call count, even before the reply.
6391
6734
 
@@ -6448,9 +6791,10 @@ returns at once.
6448
6791
  if (flags.dryRun === true && flags.response === true) {
6449
6792
  throw new UsageError("--dry-run cannot be combined with --response");
6450
6793
  }
6451
- const { context, token } = await resolveActiveContext(this);
6794
+ const active = await resolveActiveContext(this);
6795
+ const { token } = active;
6452
6796
  const data = buildServiceData(flags);
6453
- const session = await openHa(this.connect, context, token);
6797
+ const session = await openHa(this.connect, active);
6454
6798
  const id = `${service.domain}.${service.service}`;
6455
6799
  try {
6456
6800
  const read = readOnce(session);
@@ -6459,7 +6803,10 @@ returns at once.
6459
6803
  const [, , targeted, log] = await inOrder([
6460
6804
  responseSupport(read, service, token).then((support) => {
6461
6805
  if (support === "required") {
6462
- throw new UsageError(`"${id}" only returns data`, `Run it with \`hactl query ${id}\`.`);
6806
+ throw new UsageError(
6807
+ `"${id}" requires a response`,
6808
+ `Run it with \`hactl query ${id}\`.`
6809
+ );
6463
6810
  }
6464
6811
  if (support === void 0 && flags.dryRun === true) {
6465
6812
  throw new NotFoundError(`service "${id}" does not exist`);
@@ -6495,9 +6842,147 @@ returns at once.
6495
6842
  }
6496
6843
  });
6497
6844
 
6845
+ // src/ha.ts
6846
+ var timeoutMs = 1e4;
6847
+ function describeCause(exc, ms) {
6848
+ if (exc instanceof Error && exc.name === "TimeoutError") {
6849
+ return `no answer within ${ms / 1e3} seconds`;
6850
+ }
6851
+ return causeMessage(exc instanceof Error && exc.cause instanceof Error ? exc.cause : exc);
6852
+ }
6853
+ function transportError(exc, active, method, path, url2, ms, onTimeout) {
6854
+ const cause = describeCause(exc, ms);
6855
+ if (onTimeout === "timeout" && exc instanceof Error && exc.name === "TimeoutError") {
6856
+ return new TimeoutError(`${method} ${path} gave no answer within ${ms / 1e3} seconds`);
6857
+ }
6858
+ return new UnreachableError(
6859
+ `cannot reach ${url2}: ${redactText(cause, active.token)}`,
6860
+ /redirect/i.test(cause) ? `Set the final URL with \`hactl ctx set ${active.context.name} --url <url>\`.` : void 0
6861
+ );
6862
+ }
6863
+ async function getJson(fetchFn, active, path, request = {}) {
6864
+ const { context, token } = active;
6865
+ const { method = "GET", body, timeoutMs: ms = timeoutMs, onTimeout = "unreachable" } = request;
6866
+ const url2 = `${baseUrl(context)}${path}`;
6867
+ let response;
6868
+ try {
6869
+ response = await fetchFn(url2, {
6870
+ method,
6871
+ headers: {
6872
+ Authorization: `Bearer ${token.reveal()}`,
6873
+ ...body === void 0 ? {} : { "content-type": "application/json" }
6874
+ },
6875
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
6876
+ // A redirect could hand the token to another URL than the context's own.
6877
+ redirect: "error",
6878
+ signal: AbortSignal.timeout(ms)
6879
+ });
6880
+ } catch (exc) {
6881
+ throw transportError(exc, active, method, path, url2, ms, onTimeout);
6882
+ }
6883
+ if (response.status === 401) {
6884
+ throw new UnauthorizedError(
6885
+ `the token for context "${context.name}" was rejected (HTTP 401)`,
6886
+ unauthorizedHint(active)
6887
+ );
6888
+ }
6889
+ if (!response.ok) {
6890
+ throw new HaError(`${method} ${path} returned HTTP ${response.status}`);
6891
+ }
6892
+ let text5;
6893
+ try {
6894
+ text5 = await response.text();
6895
+ } catch (exc) {
6896
+ throw transportError(exc, active, method, path, url2, ms, onTimeout);
6897
+ }
6898
+ try {
6899
+ return JSON.parse(text5);
6900
+ } catch {
6901
+ throw notHa(context, path);
6902
+ }
6903
+ }
6904
+ function notHa(context, path) {
6905
+ return new HaError(`${baseUrl(context)}${path} did not answer like Home Assistant`);
6906
+ }
6907
+ async function getConfig(fetchFn, active) {
6908
+ const body = intersection15ttlhb0m0yhovValidator(await getJson(fetchFn, active, "/api/config"));
6909
+ if (body instanceof Issues) {
6910
+ throw notHa(active.context, "/api/config");
6911
+ }
6912
+ return body;
6913
+ }
6914
+
6915
+ // src/commands/check.ts
6916
+ var checkTimeoutMs = 6e4;
6917
+ var checkCommand = buildCommand({
6918
+ docs: {
6919
+ brief: "Have Home Assistant check its YAML configuration as it would load it on restart",
6920
+ fullDescription: `Have Home Assistant check its YAML configuration as it would load it on restart
6921
+
6922
+ Covers YAML (including includes, packages and \`!secret\`), not config entries or
6923
+ integration runtime setup. Use \`hactl diagnose\` for runtime health. This check needs
6924
+ the config integration and an admin token. It does not reload or restart Home Assistant.
6925
+ If Home Assistant does not respond to the validation request within 60 seconds,
6926
+ the command fails with timeout.
6927
+
6928
+ On success, prints {"valid": true} as JSON, adding "warnings" as a string if non-empty.
6929
+ An invalid configuration fails with config_invalid and no standard output, with any
6930
+ error text from Home Assistant on standard error. Use && to run a reload only on success:
6931
+
6932
+ hactl check && hactl call homeassistant.reload_all --wait 0
6933
+
6934
+ Reload an integration's YAML with its reload service, such as \`hactl call automation.reload\`.
6935
+ For changes that require a full restart, use \`hactl call homeassistant.restart\`.
6936
+
6937
+ Credentials in HA's error and warning text are printed as REDACTED; a secret without a
6938
+ recognizable name or shape cannot be caught.
6939
+
6940
+ hactl check`
6941
+ },
6942
+ parameters: {},
6943
+ async func() {
6944
+ const active = await resolveActiveContext(this);
6945
+ const { token } = active;
6946
+ const config = await getConfig(this.fetch, active);
6947
+ if (!config.components.includes("config")) {
6948
+ throw new HaError("the instance has no `config` integration, so it cannot check its YAML");
6949
+ }
6950
+ let body;
6951
+ try {
6952
+ body = await getJson(this.fetch, active, "/api/config/core/check_config", {
6953
+ method: "POST",
6954
+ timeoutMs: checkTimeoutMs,
6955
+ onTimeout: "timeout"
6956
+ });
6957
+ } catch (error) {
6958
+ throw error instanceof UnauthorizedError ? new AdminRequiredError(
6959
+ "the configuration check needs the token of an admin user",
6960
+ active.source === "env" ? "Set HACTL_TOKEN to a long-lived access token from an admin user." : `Store an admin token with \`hactl ctx token-set ${active.context.name}\`.`
6961
+ ) : error;
6962
+ }
6963
+ const result = intersection1ieh53x1r06da7Validator(body);
6964
+ if (result instanceof Issues) {
6965
+ throw new HaError("/api/config/core/check_config did not answer like Home Assistant");
6966
+ }
6967
+ if (result.result === "invalid") {
6968
+ throw new ConfigInvalidError(
6969
+ result.errors ? `the configuration is not valid: ${redactText(result.errors, token)}` : "the configuration is not valid",
6970
+ "Fix the YAML configuration and run `hactl check` again."
6971
+ );
6972
+ }
6973
+ printJson(this, {
6974
+ valid: true,
6975
+ ...result.warnings ? { warnings: redactText(result.warnings, token) } : {}
6976
+ });
6977
+ }
6978
+ });
6979
+
6498
6980
  // src/entry.ts
6499
- async function tokenState(keychain, name) {
6981
+ async function tokenState(keychain, env, name) {
6500
6982
  try {
6983
+ if (envToken(env, name) !== void 0) {
6984
+ return "env";
6985
+ }
6501
6986
  return await keychain.has(name) ? "set" : "missing";
6502
6987
  } catch {
6503
6988
  return "unknown";
@@ -6511,12 +6996,17 @@ function contextEntry(definition, state) {
6511
6996
  install: definition.install,
6512
6997
  ...definition.ssh === void 0 ? {} : { ssh: definition.ssh },
6513
6998
  token: state.token,
6514
- ...selection?.name === definition.name ? { active: { source: selection.source, path: selection.path } } : {}
6999
+ ...selection?.name === definition.name ? {
7000
+ active: {
7001
+ source: selection.source,
7002
+ ...selection.path === void 0 ? {} : { path: selection.path }
7003
+ }
7004
+ } : {}
6515
7005
  };
6516
7006
  }
6517
7007
  async function loadEntry(environment, definition) {
6518
7008
  return contextEntry(definition, {
6519
- token: await tokenState(environment.keychain, definition.name),
7009
+ token: await tokenState(environment.keychain, environment.env, definition.name),
6520
7010
  selection: await loadSelection(environment)
6521
7011
  });
6522
7012
  }
@@ -6576,12 +7066,12 @@ Prints an array of contexts, in the shape \`hactl ctx --help\` describes.`
6576
7066
  const contexts = await loadContexts(configFolder(this.env, this.homedir));
6577
7067
  const selection = await loadSelection(this);
6578
7068
  if (selection !== void 0) {
6579
- requireContext(contexts, selection.name, selection.path);
7069
+ requireContext(contexts, selection.name, selectionSource(selection));
6580
7070
  }
6581
7071
  const entries = await Promise.all(
6582
7072
  contexts.map(
6583
7073
  async (definition) => contextEntry(definition, {
6584
- token: await tokenState(this.keychain, definition.name),
7074
+ token: await tokenState(this.keychain, this.env, definition.name),
6585
7075
  selection
6586
7076
  })
6587
7077
  )
@@ -6592,15 +7082,15 @@ Prints an array of contexts, in the shape \`hactl ctx --help\` describes.`
6592
7082
 
6593
7083
  // src/commands/ctx/set.ts
6594
7084
  var text3 = (brief, placeholder) => ({ kind: "parsed", parse: String, optional: true, brief, placeholder });
6595
- function buildInstall(flags, existing) {
6596
- const kind = flags.install ?? existing?.install.type;
7085
+ function buildInstall(flags, existing2) {
7086
+ const kind = flags.install ?? existing2?.install.type;
6597
7087
  if (kind === "haos") {
6598
7088
  if (flags.container !== void 0) {
6599
7089
  throw new UsageError("--container only applies to docker contexts");
6600
7090
  }
6601
7091
  return { type: "haos" };
6602
7092
  }
6603
- const container = flags.container ?? (existing?.install.type === "docker" ? existing.install.container : void 0);
7093
+ const container = flags.container ?? (existing2?.install.type === "docker" ? existing2.install.container : void 0);
6604
7094
  if (container === void 0) {
6605
7095
  throw new UsageError("docker contexts require --container");
6606
7096
  }
@@ -6612,10 +7102,14 @@ var setCommand = buildCommand({
6612
7102
  fullDescription: `Create a context, or update the given fields of an existing one (does not switch to it)
6613
7103
 
6614
7104
  Creating requires --url and --install, and --container for docker. Updating changes only
6615
- the flags given. Context names use lowercase letters, digits and dashes.
7105
+ the flags given. Context names use lowercase letters, digits and dashes, but cannot
7106
+ start with a dash.
6616
7107
  --url must be an HTTP or HTTPS base URL, optionally with a path, but without credentials,
6617
7108
  a query, or a fragment.
6618
- Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
7109
+ Use --no-ssh to remove an existing SSH target; it cannot be combined with --ssh.
7110
+ Prints the context as JSON. If the token is missing, prints a hint on standard error.
7111
+ Store the token with \`hactl ctx token-set <name>\` and select it with \`hactl ctx use <name>\`.
7112
+ For a headless run, set HACTL_CONTEXT and HACTL_TOKEN instead.
6619
7113
 
6620
7114
  hactl ctx set home --url https://ha.example.ts.net --install haos --ssh root@ha.local
6621
7115
  hactl ctx set lab --url http://server:8123 --install docker --container homeassistant`
@@ -6625,7 +7119,7 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6625
7119
  url: text3("Home Assistant base URL", "url"),
6626
7120
  install: { kind: "enum", values: ["haos", "docker"], optional: true, brief: "Install type" },
6627
7121
  container: text3("Home Assistant container name (docker only, required there)", "name"),
6628
- ssh: text3("SSH target, user@host (without it, the context has no SSH access)", "target"),
7122
+ ssh: text3("Optional target for SSH verification, e.g. user@host", "target"),
6629
7123
  noSsh: { kind: "boolean", optional: true, brief: "Remove the SSH target" }
6630
7124
  },
6631
7125
  positional: {
@@ -6636,8 +7130,8 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6636
7130
  async func(flags, name) {
6637
7131
  const folder = configFolder(this.env, this.homedir);
6638
7132
  const contexts = await loadContexts(folder);
6639
- const existing = findContext(contexts, name);
6640
- if (existing === void 0) {
7133
+ const existing2 = findContext(contexts, name);
7134
+ if (existing2 === void 0) {
6641
7135
  const missing = [
6642
7136
  flags.url === void 0 ? "--url" : void 0,
6643
7137
  flags.install === void 0 ? "--install" : void 0
@@ -6649,11 +7143,11 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6649
7143
  if (flags.noSsh === true && flags.ssh !== void 0) {
6650
7144
  throw new UsageError("--ssh and --no-ssh cannot be combined");
6651
7145
  }
6652
- const ssh = flags.noSsh === true ? void 0 : flags.ssh ?? existing?.ssh;
7146
+ const ssh = flags.noSsh === true ? void 0 : flags.ssh ?? existing2?.ssh;
6653
7147
  const definition = contextDefinition({
6654
7148
  name,
6655
- url: flags.url ?? existing?.url,
6656
- install: buildInstall(flags, existing),
7149
+ url: flags.url ?? existing2?.url,
7150
+ install: buildInstall(flags, existing2),
6657
7151
  ...ssh === void 0 ? {} : { ssh }
6658
7152
  });
6659
7153
  if (definition instanceof Issues) {
@@ -6662,15 +7156,15 @@ Prints the context. Store its token next with \`hactl ctx token-set <name>\`.
6662
7156
  const selection = await loadSelection(this);
6663
7157
  await saveContexts(
6664
7158
  folder,
6665
- existing === void 0 ? [...contexts, definition] : contexts.map((context) => context.name === name ? definition : context)
7159
+ existing2 === void 0 ? [...contexts, definition] : contexts.map((context) => context.name === name ? definition : context)
6666
7160
  );
6667
7161
  const entry = contextEntry(definition, {
6668
7162
  selection,
6669
- token: await tokenState(this.keychain, name)
7163
+ token: await tokenState(this.keychain, this.env, name)
6670
7164
  });
6671
7165
  printJson(this, entry);
6672
7166
  if (entry.token === "missing") {
6673
- this.process.stderr.write(`next: run \`hactl ctx token-set ${name}\`
7167
+ this.process.stderr.write(`hint: Store a token with \`hactl ctx token-set ${name}\`.
6674
7168
  `);
6675
7169
  }
6676
7170
  }
@@ -6682,12 +7176,15 @@ var tokenSetCommand = buildCommand({
6682
7176
  brief: "Store a context's token in the OS keychain, read from a hidden prompt or standard input",
6683
7177
  fullDescription: `Store a context's token in the OS keychain, read from a hidden prompt or standard input
6684
7178
 
6685
- The token is a long-lived access token, created in your Home Assistant profile.
6686
- On a terminal it is read from a hidden prompt, otherwise from standard input:
7179
+ Create a long-lived access token in your Home Assistant profile. This replaces the token
7180
+ for an existing context without checking it against Home Assistant.
7181
+ On a terminal it reads from a hidden prompt; with redirected input it reads to EOF:
6687
7182
 
6688
7183
  printf %s "$TOKEN" | hactl ctx token-set home
6689
7184
 
6690
- Prints the context.`
7185
+ Prints the context as JSON, without the token. Use \`hactl ctx verify\` to test the token
7186
+ after selecting the context. If HACTL_TOKEN applies, verification still uses it instead
7187
+ of the token just stored. Unset HACTL_TOKEN to test the keychain token.`
6691
7188
  },
6692
7189
  parameters: {
6693
7190
  flags: {
@@ -6721,7 +7218,10 @@ Prints the context.`
6721
7218
  await this.keychain.set(name, new Secret(token));
6722
7219
  printJson(
6723
7220
  this,
6724
- contextEntry(definition, { selection, token: await tokenState(this.keychain, name) })
7221
+ contextEntry(definition, {
7222
+ selection,
7223
+ token: await tokenState(this.keychain, this.env, name)
7224
+ })
6725
7225
  );
6726
7226
  }
6727
7227
  });
@@ -6729,12 +7229,14 @@ Prints the context.`
6729
7229
  // src/commands/ctx/use.ts
6730
7230
  var useCommand = buildCommand({
6731
7231
  docs: {
6732
- brief: "Select a context globally (a project's .hactl.json still wins where it sets one)",
6733
- fullDescription: `Select a context globally (a project's .hactl.json still wins where it sets one)
7232
+ brief: "Select a context globally (a project's .hactl.json or HACTL_CONTEXT still wins where it sets one)",
7233
+ fullDescription: `Select a context globally (a project's .hactl.json or HACTL_CONTEXT still wins where it sets one)
6734
7234
 
6735
- With --project it writes ./.hactl.json, which applies to this folder and everything below.
6736
- Warns on standard error when another file keeps a different context active here.
6737
- Prints the context.
7235
+ With --project it writes ./.hactl.json, which applies here and in subfolders unless a
7236
+ nearer .hactl.json overrides it. This does not change the global selection.
7237
+ A non-empty HACTL_CONTEXT overrides both selection files for this process.
7238
+ Warns on standard error if a project file or HACTL_CONTEXT keeps another context active.
7239
+ Prints the named context as JSON, even if another one stays active.
6738
7240
 
6739
7241
  hactl ctx use home
6740
7242
  hactl ctx use home --project`
@@ -6759,86 +7261,26 @@ Prints the context.
6759
7261
  if (flags.project === true) {
6760
7262
  selection = await setProjectContext(this, name);
6761
7263
  } else {
6762
- selection = await loadSelection(this, {
6763
- name,
6764
- source: "global",
6765
- path: globalSettingsPath(folder)
6766
- });
7264
+ selection = await loadSelection(this, { name, source: "global" });
6767
7265
  await setGlobalContext(folder, name);
6768
7266
  }
6769
7267
  if (selection !== void 0 && selection.name !== name) {
6770
7268
  this.process.stderr.write(
6771
- `warning: "${selection.name}" stays active here because of ${selection.path}
7269
+ selection.source === "env" ? `warning: "${selection.name}" stays active because of HACTL_CONTEXT
7270
+ ` : `warning: "${selection.name}" stays active here because of ${selection.path}
6772
7271
  `
6773
7272
  );
6774
7273
  }
6775
7274
  printJson(
6776
7275
  this,
6777
7276
  contextEntry(definition, {
6778
- token: await tokenState(this.keychain, name),
7277
+ token: await tokenState(this.keychain, this.env, name),
6779
7278
  selection
6780
7279
  })
6781
7280
  );
6782
7281
  }
6783
7282
  });
6784
7283
 
6785
- // src/ha.ts
6786
- var timeoutMs = 1e4;
6787
- function describeCause(exc) {
6788
- if (exc instanceof Error && exc.name === "TimeoutError") {
6789
- return `no answer within ${timeoutMs / 1e3} seconds`;
6790
- }
6791
- return causeMessage(exc instanceof Error && exc.cause instanceof Error ? exc.cause : exc);
6792
- }
6793
- async function getJson(fetchFn, context, token, path) {
6794
- const url2 = `${baseUrl(context)}${path}`;
6795
- let response;
6796
- try {
6797
- response = await fetchFn(url2, {
6798
- headers: { Authorization: `Bearer ${token.reveal()}` },
6799
- // A redirect could hand the token to another URL than the context's own.
6800
- redirect: "error",
6801
- signal: AbortSignal.timeout(timeoutMs)
6802
- });
6803
- } catch (exc) {
6804
- const cause = describeCause(exc);
6805
- throw new UnreachableError(
6806
- `cannot reach ${url2}: ${redactText(cause, token)}`,
6807
- /redirect/i.test(cause) ? `Set the final URL with \`hactl ctx set ${context.name} --url <url>\`.` : void 0
6808
- );
6809
- }
6810
- if (response.status === 401) {
6811
- throw new UnauthorizedError(
6812
- `the token for context "${context.name}" was rejected (HTTP 401)`,
6813
- `Store a new token with \`hactl ctx token-set ${context.name}\`.`
6814
- );
6815
- }
6816
- if (!response.ok) {
6817
- throw new HaError(`GET ${path} returned HTTP ${response.status}`);
6818
- }
6819
- let body;
6820
- try {
6821
- body = await response.text();
6822
- } catch (exc) {
6823
- throw new UnreachableError(`cannot reach ${url2}: ${describeCause(exc)}`);
6824
- }
6825
- try {
6826
- return JSON.parse(body);
6827
- } catch {
6828
- throw notHa(context, path);
6829
- }
6830
- }
6831
- function notHa(context, path) {
6832
- return new HaError(`${baseUrl(context)}${path} did not answer like Home Assistant`);
6833
- }
6834
- async function getConfig(fetchFn, context, token) {
6835
- const body = intersection15ttlhb0m0yhovValidator(await getJson(fetchFn, context, token, "/api/config"));
6836
- if (body instanceof Issues) {
6837
- throw notHa(context, "/api/config");
6838
- }
6839
- return body;
6840
- }
6841
-
6842
7284
  // src/commands/ctx/verify.ts
6843
7285
  function checkInstall(context, config) {
6844
7286
  const supervised = config.components.includes("hassio");
@@ -6864,7 +7306,7 @@ async function checkSsh(ssh, context, target, token) {
6864
7306
  const detail = redactText(inspect2.stderr.trim(), token);
6865
7307
  throw new ContainerNotRunningError(
6866
7308
  `container "${install.container}" is not running on ${target}${detail === "" ? "" : `: ${detail}`}`,
6867
- `Start it, or fix the name with \`hactl ctx set ${context.name} --container <name>\`.`
7309
+ `Check that it is running and the SSH user can run docker. To correct its name, use \`hactl ctx set ${context.name} --container <name>\`.`
6868
7310
  );
6869
7311
  }
6870
7312
  const read2 = await runRemote(
@@ -6876,7 +7318,7 @@ async function checkSsh(ssh, context, target, token) {
6876
7318
  if (read2.code !== 0) {
6877
7319
  throw new ConfigDirMissingError(
6878
7320
  `container "${install.container}" on ${target} has no readable ${versionFile}`,
6879
- `Fix the name with \`hactl ctx set ${context.name} --container <name>\`.`
7321
+ `Check that /config is readable. If this is not the Home Assistant container, use \`hactl ctx set ${context.name} --container <name>\`.`
6880
7322
  );
6881
7323
  }
6882
7324
  return;
@@ -6891,22 +7333,32 @@ async function checkSsh(ssh, context, target, token) {
6891
7333
  }
6892
7334
  var verifyCommand = buildCommand({
6893
7335
  docs: {
6894
- brief: "Check that the active context works: URL, token, install type and SSH access",
6895
- fullDescription: `Check that the active context works: URL, token, install type and SSH access
6896
-
6897
- Checks that the URL answers and accepts the token, and that the install type matches.
6898
- With an SSH target, also checks SSH login, the container (docker) and /config.
6899
- Prints {"version", "state"} of Home Assistant.`
7336
+ brief: "Check that the active context works: URL, token, install type, WebSocket and SSH access",
7337
+ fullDescription: `Check that the active context works: URL, token, install type, WebSocket and SSH access
7338
+
7339
+ Checks that /api/config answers and accepts the token. Expects the hassio component for
7340
+ haos and its absence for docker; a mismatch fails with install_mismatch. Then opens a
7341
+ WebSocket connection and authenticates with the token, and closes it.
7342
+ With an SSH target, also checks noninteractive SSH login and a readable /config/.HA_VERSION
7343
+ (inside the running container for docker). If no SSH target is set, those checks are skipped.
7344
+ Checks stop at the first failure. Prints {"http": true, "websocket": true} as JSON,
7345
+ plus "ssh": true when SSH is configured. Use \`hactl overview\` for the instance's state.`
6900
7346
  },
6901
7347
  parameters: {},
6902
7348
  async func() {
6903
- const { context, token } = await resolveActiveContext(this);
6904
- const config = await getConfig(this.fetch, context, token);
7349
+ const active = await resolveActiveContext(this);
7350
+ const { context, token } = active;
7351
+ const config = await getConfig(this.fetch, active);
6905
7352
  checkInstall(context, config);
7353
+ (await openHa(this.connect, active)).close();
6906
7354
  if (context.ssh !== void 0) {
6907
7355
  await checkSsh(this.ssh, context, context.ssh, token);
6908
7356
  }
6909
- printJson(this, redactData({ version: config.version, state: config.state }, token));
7357
+ printJson(this, {
7358
+ http: true,
7359
+ websocket: true,
7360
+ ...context.ssh === void 0 ? {} : { ssh: true }
7361
+ });
6910
7362
  }
6911
7363
  });
6912
7364
 
@@ -6924,68 +7376,661 @@ var ctxRoutes = buildRouteMap({
6924
7376
  brief: "Manage contexts: the Home Assistant instances hactl can talk to",
6925
7377
  fullDescription: `Manage contexts: the Home Assistant instances hactl can talk to
6926
7378
 
6927
- A context is one Home Assistant instance: its name, URL, install type (haos or docker), and
6928
- optionally the SSH target of its host. Every command that talks to Home Assistant uses the
6929
- active context.
7379
+ A context is a named connection profile for a Home Assistant instance: its URL, install type
7380
+ (haos or docker), and optionally an SSH target. Commands that talk to Home Assistant use the
7381
+ active context. Use \`hactl ctx verify\` to check its connection.
6930
7382
 
6931
7383
  Install types:
6932
7384
  haos Home Assistant OS. Over SSH, the add-on must expose the config at /config.
6933
7385
  docker A container, named with --container. Over SSH, hactl reads /config inside it.
6934
7386
 
6935
- Without an SSH target, commands that need SSH fail with ssh_not_configured.
7387
+ SSH is optional. If configured, \`hactl ctx verify\` checks it using noninteractive login
7388
+ and a known host key.
6936
7389
 
6937
- Which context is active, from the first file that sets it:
6938
- 1. the nearest .hactl.json, searching upward from the current folder
6939
- 2. the global config.json
7390
+ Which context is active, from the first that sets it:
7391
+ 1. a non-empty HACTL_CONTEXT in the environment
7392
+ 2. the nearest .hactl.json, searching upward from the current folder
7393
+ 3. the global config.json
6940
7394
 
6941
- A .hactl.json looks like this; any other key is a config_error:
7395
+ HACTL_CONTEXT selects an existing context for this process. If it is set and non-empty,
7396
+ selection files are not read. Otherwise, an empty project settings object ({}) falls
7397
+ back to the global selection, not to another ancestor's .hactl.json.
7398
+ A .hactl.json can contain this entry; any other key is a config_error:
6942
7399
  {"context": "home"}
6943
7400
 
6944
- It can only select a context, never define one, so a cloned repository cannot redirect
6945
- your token.
7401
+ It can only select a name, not define the context or change where its token is sent.
7402
+ Use \`hactl ctx list\` to see what selected the active context.
6946
7403
 
6947
7404
  Files, in $XDG_CONFIG_HOME/hactl or else ~/.config/hactl:
6948
7405
  contexts.json the context definitions
6949
7406
  config.json the globally selected context
6950
7407
 
6951
- Tokens live only in the OS keychain (macOS Keychain, or the Linux Secret Service through
6952
- secret-tool). They are never written to a file, printed, or passed as an argument.
7408
+ Tokens are stored in the OS keychain, not in these files. Linux requires both secret-tool
7409
+ (libsecret-tools on Debian and Ubuntu) and a working Secret Service. macOS uses Keychain.
7410
+ Give the token to \`hactl ctx token-set\` by prompt or standard input, not as an argument.
7411
+
7412
+ A non-empty HACTL_TOKEN replaces the keychain token only for the context named by
7413
+ HACTL_CONTEXT. Without HACTL_CONTEXT, commands that need a token fail with usage_error.
7414
+ Empty values for either variable count as unset. Keep HACTL_TOKEN in your CI secret store:
7415
+ anything that can read the process environment can read it. hactl removes HACTL_TOKEN
7416
+ from the environment of subprocesses it starts.
6953
7417
 
6954
7418
  A context is printed as:
6955
7419
  {"name", "url", "install": {"type", "container"}, "ssh", "token", "active": {"source", "path"}}
6956
- "token" is set, missing or unknown (no keychain). "active" is only on the active context:
6957
- "source" is project or global, and "path" is the file that selects it.`
7420
+ "token" is "set", "missing", "unknown" (keychain unavailable or failed) or "env"
7421
+ (HACTL_TOKEN applies). "active" is only on the active context: "source" is env, project or global,
7422
+ and "path" is the file that selects it, omitted for env.`
6958
7423
  }
6959
7424
  });
6960
7425
 
6961
- // src/commands/get/areas.ts
6962
- var command = "config/area_registry/list";
6963
- var areasCommand = buildCommand({
6964
- docs: {
6965
- brief: "List areas, or show one",
6966
- fullDescription: `List areas, or show one
6967
-
6968
- Fields: "id", "name", "floor". An id adds "labels".
6969
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6970
- caught.`
6971
- },
6972
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Area id")] } },
6973
- async func(_flags, id) {
6974
- const {
6975
- value: [registry],
6976
- token
6977
- } = await readHa(this, [command]);
6978
- printItems(
6979
- this,
6980
- toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, registry, command, token)),
6981
- id,
6982
- "area",
6983
- (area) => pick(area, ["id", "name", "floor"]),
6984
- token
7426
+ // src/commands/logs.ts
7427
+ var sourceLines = 100;
7428
+ var firstEventMs = 1e4;
7429
+ function parseLines(input) {
7430
+ const lines = Number(input);
7431
+ if (!/^\d+$/.test(input) || !Number.isSafeInteger(lines) || lines < 1) {
7432
+ throw new UsageError("--lines must be a whole number, 1 or more");
7433
+ }
7434
+ return lines;
7435
+ }
7436
+ var adminNeeded = () => new AdminRequiredError("Home Assistant refused the log: logs need the token of an admin user");
7437
+ function print(context, lines) {
7438
+ if (lines.length > 0) {
7439
+ context.process.stdout.write(`${lines.join("\n")}
7440
+ `);
7441
+ }
7442
+ }
7443
+ function subscribeCoreLog(session, integration, token, listen, onError) {
7444
+ return session.stream(
7445
+ "system_log/subscribe_raw",
7446
+ integration === void 0 ? {} : { integration },
7447
+ (event) => {
7448
+ try {
7449
+ listen(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw", token));
7450
+ } catch (error) {
7451
+ onError(error);
7452
+ }
7453
+ }
7454
+ );
7455
+ }
7456
+ async function coreLogTail(session, integration, token) {
7457
+ const redact = createLineRedactor(token);
7458
+ const first = Promise.withResolvers();
7459
+ void subscribeCoreLog(
7460
+ session,
7461
+ integration,
7462
+ token,
7463
+ (lines) => first.resolve(redact(lines)),
7464
+ first.reject
7465
+ ).then(void 0, first.reject);
7466
+ return await Promise.race([
7467
+ first.promise,
7468
+ session.wait(firstEventMs).then(() => {
7469
+ throw new HaError("system_log/subscribe_raw sent no log");
7470
+ })
7471
+ ]);
7472
+ }
7473
+ async function coreLog(context, active, flags, closed) {
7474
+ const { token } = active;
7475
+ const connecting = openHa(context.connect, active);
7476
+ const session = await Promise.race([connecting, closed]);
7477
+ if (session === void 0) {
7478
+ void connecting.then(
7479
+ (connection) => connection.close(),
7480
+ () => void 0
6985
7481
  );
7482
+ return;
6986
7483
  }
6987
- });
6988
-
7484
+ const redact = createLineRedactor(token);
7485
+ let first = true;
7486
+ const tail = Promise.withResolvers();
7487
+ tail.promise.catch(() => void 0);
7488
+ const listen = (lines) => {
7489
+ const text5 = redact(lines);
7490
+ if (first) {
7491
+ first = false;
7492
+ print(context, flags.lines === void 0 ? text5 : text5.slice(-flags.lines));
7493
+ tail.resolve();
7494
+ } else if (flags.follow === true) {
7495
+ print(context, text5);
7496
+ }
7497
+ };
7498
+ try {
7499
+ const { integration } = flags;
7500
+ const subscribed = subscribeCoreLog(session, integration, token, listen, tail.reject);
7501
+ await Promise.race([subscribed, closed]);
7502
+ const receivedTail = await Promise.race([
7503
+ closed,
7504
+ tail.promise.then(() => true),
7505
+ session.wait(firstEventMs).then(() => {
7506
+ throw new HaError("system_log/subscribe_raw sent no log");
7507
+ })
7508
+ ]);
7509
+ if (receivedTail && flags.follow === true) {
7510
+ session.keepAlive();
7511
+ await Promise.race([closed, session.lost()]);
7512
+ }
7513
+ } catch (error) {
7514
+ throw explain2(error, flags);
7515
+ } finally {
7516
+ session.close();
7517
+ }
7518
+ }
7519
+ function explain2(error, { integration }) {
7520
+ if (!(error instanceof HaCommandError)) {
7521
+ return error;
7522
+ }
7523
+ if (error.haCode === "unauthorized") {
7524
+ return adminNeeded();
7525
+ }
7526
+ if (error.haCode === "not_found" && integration !== void 0) {
7527
+ return new NotFoundError(`integration "${integration}" does not exist`);
7528
+ }
7529
+ return error;
7530
+ }
7531
+ async function checkApp(session, slug, token) {
7532
+ const result = await session.send("supervisor/api", { endpoint: "/addons", method: "get" });
7533
+ const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons", token);
7534
+ if (!addons.some((app2) => app2.slug === slug)) {
7535
+ throw new NotFoundError(`app "${slug}" is not installed`);
7536
+ }
7537
+ }
7538
+ async function openLog(context, active, path) {
7539
+ const { context: target, token } = active;
7540
+ const url2 = `${baseUrl(target)}${path}`;
7541
+ let response;
7542
+ try {
7543
+ response = await context.httpStream(url2, { Authorization: `Bearer ${token.reveal()}` });
7544
+ } catch (error) {
7545
+ throw new UnreachableError(`cannot reach ${url2}: ${redactText(causeMessage(error), token)}`);
7546
+ }
7547
+ const { status } = response;
7548
+ if (status >= 200 && status < 300) {
7549
+ return response;
7550
+ }
7551
+ response.close();
7552
+ if (status === 401) {
7553
+ throw adminNeeded();
7554
+ }
7555
+ if (status >= 300 && status < 400) {
7556
+ throw new UnreachableError(
7557
+ `cannot reach ${url2}: it redirects`,
7558
+ `Set the final URL with \`hactl ctx set ${target.name} --url <url>\`.`
7559
+ );
7560
+ }
7561
+ throw new HaError(`GET ${path} returned HTTP ${status}`);
7562
+ }
7563
+ async function checkSupervisor(context, active, source) {
7564
+ const config = await getConfig(context.fetch, active);
7565
+ if (!config.components.includes("hassio")) {
7566
+ throw new HaError(`the log of "${source}" needs Supervisor, which this instance does not have`);
7567
+ }
7568
+ }
7569
+ async function checkAppOnSession(context, active, source, flags) {
7570
+ const { token } = active;
7571
+ const session = await openHa(context.connect, active);
7572
+ try {
7573
+ await checkApp(session, source, token);
7574
+ } catch (error) {
7575
+ throw explain2(error, flags);
7576
+ } finally {
7577
+ session.close();
7578
+ }
7579
+ }
7580
+ async function sourceLog(context, active, source, flags, closed) {
7581
+ const { context: target, token } = active;
7582
+ const follow = flags.follow === true;
7583
+ const wanted = flags.lines ?? sourceLines;
7584
+ const root2 = source === "supervisor" ? "supervisor" : `addons/${encodeURIComponent(source)}`;
7585
+ const path = `/api/hassio/${root2}/logs${follow ? "/follow" : ""}?lines=${Math.max(wanted, 2)}`;
7586
+ const opening = openLog(context, active, path);
7587
+ const startup = Promise.allSettled([
7588
+ checkSupervisor(context, active, source),
7589
+ source === "supervisor" ? Promise.resolve() : checkAppOnSession(context, active, source, flags),
7590
+ opening
7591
+ ]);
7592
+ const settled = await Promise.race([startup, closed]);
7593
+ if (settled === void 0) {
7594
+ void opening.then(
7595
+ (response2) => response2.close(),
7596
+ () => void 0
7597
+ );
7598
+ return;
7599
+ }
7600
+ const [config, app2, opened] = settled;
7601
+ for (const check2 of [config, app2]) {
7602
+ if (check2.status === "rejected") {
7603
+ if (opened.status === "fulfilled") {
7604
+ opened.value.close();
7605
+ }
7606
+ throw check2.reason;
7607
+ }
7608
+ }
7609
+ if (opened.status === "rejected") {
7610
+ throw opened.reason;
7611
+ }
7612
+ const response = opened.value;
7613
+ const redact = createLineRedactor(token);
7614
+ let stopped = false;
7615
+ void closed.then(() => {
7616
+ stopped = true;
7617
+ response.close();
7618
+ });
7619
+ let partial = "";
7620
+ let skip = follow && wanted === 1 ? 1 : 0;
7621
+ const collected = [];
7622
+ const take = (lines) => {
7623
+ if (!follow) {
7624
+ collected.push(...lines);
7625
+ return;
7626
+ }
7627
+ print(context, lines.slice(skip));
7628
+ skip = Math.max(0, skip - lines.length);
7629
+ };
7630
+ const lost = (reason) => new UnreachableError(`lost the log from ${baseUrl(target)}: ${reason}`);
7631
+ try {
7632
+ for await (const chunk of response.body) {
7633
+ const lines = `${partial}${chunk}`.split("\n");
7634
+ partial = lines.pop() ?? "";
7635
+ if (lines.length > 0) {
7636
+ take(redact(lines));
7637
+ }
7638
+ }
7639
+ if (partial !== "") {
7640
+ take(redact([partial]));
7641
+ }
7642
+ } catch (error) {
7643
+ if (!stopped) {
7644
+ throw lost(redactText(causeMessage(error), token));
7645
+ }
7646
+ } finally {
7647
+ response.close();
7648
+ }
7649
+ if (!follow) {
7650
+ print(context, collected.slice(-wanted));
7651
+ } else if (!stopped) {
7652
+ throw lost("the stream ended");
7653
+ }
7654
+ }
7655
+ var logsCommand = buildCommand({
7656
+ docs: {
7657
+ brief: "Print or follow the log of Home Assistant, Supervisor or an app",
7658
+ fullDescription: `Print or follow the log of Home Assistant, Supervisor or an app
7659
+
7660
+ Sources:
7661
+ (none) the Core log, on every install type
7662
+ supervisor the Supervisor's log
7663
+ <app slug> that app's (add-on's) log, e.g. core_mosquitto
7664
+ supervisor and apps need an instance with Supervisor. An app that is not installed is not_found.
7665
+ Every source needs the token of an admin user. SSH is not used.
7666
+
7667
+ Output is plain text, not JSON, oldest line first, without color codes. A record spanning
7668
+ several lines counts as that many. Which levels are logged is up to Home Assistant's logger
7669
+ settings.
7670
+
7671
+ Existing lines: Home Assistant offers the last 100 lines of the Core log, or up to 5000 with
7672
+ --integration, going back only to its last start; a larger --lines prints what there is.
7673
+ Other sources print 100 lines unless --lines says otherwise.
7674
+ --lines accepts only digits, up to 9007199254740991. Core must send its initial tail
7675
+ within 10 seconds of accepting the subscription, even if the tail is empty.
7676
+ Supervisor and app sources have a 10-second header deadline, but no body deadline.
7677
+
7678
+ --follow keeps printing new lines and normally never ends by itself. Press Ctrl+C to exit
7679
+ successfully; a write to a closed output pipe also stops the command. If the connection is lost,
7680
+ such as when Home Assistant restarts, it fails with unreachable after the lines already
7681
+ printed. It does not reconnect.
7682
+
7683
+ --integration limits the Core log to one integration and the libraries it uses. It cannot
7684
+ be combined with a source. An unknown integration is not_found.
7685
+
7686
+ Credentials are printed as REDACTED. Redaction cannot catch every secret in free text: one
7687
+ without a recognizable name or shape is printed.
7688
+
7689
+ hactl logs --lines 20
7690
+ hactl logs --integration zha --follow
7691
+ hactl logs supervisor`
7692
+ },
7693
+ parameters: {
7694
+ flags: {
7695
+ lines: {
7696
+ kind: "parsed",
7697
+ parse: parseLines,
7698
+ optional: true,
7699
+ brief: "Print at most this many existing lines",
7700
+ placeholder: "n"
7701
+ },
7702
+ follow: {
7703
+ kind: "boolean",
7704
+ optional: true,
7705
+ brief: "Keep printing new lines until interrupted"
7706
+ },
7707
+ integration: {
7708
+ kind: "parsed",
7709
+ parse: String,
7710
+ optional: true,
7711
+ brief: "Only this integration (Core log only)",
7712
+ placeholder: "domain"
7713
+ }
7714
+ },
7715
+ positional: {
7716
+ kind: "tuple",
7717
+ parameters: [
7718
+ { brief: "supervisor or an app slug", placeholder: "source", parse: String, optional: true }
7719
+ ]
7720
+ }
7721
+ },
7722
+ async func(flags, source) {
7723
+ if (source !== void 0 && flags.integration !== void 0) {
7724
+ throw new UsageError("--integration only applies to the Core log, without a source");
7725
+ }
7726
+ const active = await resolveActiveContext(this);
7727
+ let stopListening;
7728
+ const closed = flags.follow === true ? Promise.race([
7729
+ this.stdoutClosed(),
7730
+ new Promise((resolve) => stopListening = this.onInterrupt(resolve))
7731
+ ]) : this.stdoutClosed();
7732
+ try {
7733
+ await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
7734
+ } finally {
7735
+ stopListening?.();
7736
+ }
7737
+ }
7738
+ });
7739
+
7740
+ // src/commands/related.ts
7741
+ var entityKinds = ["automation", "script", "scene"];
7742
+ var kinds = ["entity", "device", "area", "floor", "label", ...entityKinds];
7743
+ var registryCommand = {
7744
+ device: "config/device_registry/list",
7745
+ area: "config/area_registry/list",
7746
+ floor: "config/floor_registry/list",
7747
+ label: "config/label_registry/list"
7748
+ };
7749
+ function parseKind(input) {
7750
+ if (!kinds.includes(input)) {
7751
+ throw new UsageError(`<kind> must be one of ${kinds.join(", ")}, not "${input}"`);
7752
+ }
7753
+ return input;
7754
+ }
7755
+ async function existing(session, kind, token) {
7756
+ if (kind === "entity" || entityKinds.includes(kind)) {
7757
+ const [current, registry] = await Promise.all([
7758
+ session.send("get_states"),
7759
+ session.send("config/entity_registry/list")
7760
+ ]);
7761
+ return /* @__PURE__ */ new Set([
7762
+ ...parseResult(intersection10qmong0na8e8rValidator, current, "get_states", token).map((state) => state.entity_id),
7763
+ ...parseResult(intersection1nv9uj515bs7itValidator, registry, "config/entity_registry/list", token).map(
7764
+ (entry) => entry.entity_id
7765
+ )
7766
+ ]);
7767
+ }
7768
+ const command2 = registryCommand[kind];
7769
+ const result = await session.send(command2);
7770
+ let ids;
7771
+ if (kind === "device") {
7772
+ ids = parseResult(intersection3rk9um0b729ivValidator, result, command2, token).map((device) => device.id);
7773
+ } else if (kind === "area") {
7774
+ ids = parseResult(intersection16hnzan16c9ou0Validator, result, command2, token).map((area) => area.area_id);
7775
+ } else if (kind === "floor") {
7776
+ ids = parseResult(intersection1tagcym1fnxkeyValidator, result, command2, token).map((floor) => floor.floor_id);
7777
+ } else {
7778
+ ids = parseResult(intersection1rp35ue1fi65ccValidator, result, command2, token).map((label) => label.label_id);
7779
+ }
7780
+ return new Set(ids);
7781
+ }
7782
+ async function relatedOf(session, token, itemType, itemId) {
7783
+ const command2 = "search/related";
7784
+ const result = await session.send(command2, { item_type: itemType, item_id: itemId });
7785
+ return toRelated(parseResult(intersectionm0h7h61efcs6aValidator, result, command2, token));
7786
+ }
7787
+ var relatedCommand = buildCommand({
7788
+ docs: {
7789
+ brief: "List the resources related to an entity, device, area, floor, label, automation, script or scene",
7790
+ fullDescription: `List the resources related to an entity, device, area, floor, label, automation, script or scene
7791
+
7792
+ Asks Home Assistant which resources relate to <kind> <id> and prints one JSON object
7793
+ mapping each kind to a sorted array of its related ids; kinds without related resources
7794
+ are omitted, and an item with no relations prints {}. automation, script and scene take
7795
+ an entity id like automation.evening_lights; the id's domain must match the kind. An
7796
+ unsupported kind fails with usage_error, an unknown id with not_found.
7797
+
7798
+ Only reads: it changes nothing and needs no SSH.
7799
+
7800
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7801
+ caught.
7802
+
7803
+ hactl related entity light.kitchen
7804
+ hactl related device 8f3c
7805
+ hactl related automation automation.evening_lights`
7806
+ },
7807
+ parameters: {
7808
+ positional: {
7809
+ kind: "tuple",
7810
+ parameters: [
7811
+ {
7812
+ brief: "entity, device, area, floor, label, automation, script or scene",
7813
+ placeholder: "kind",
7814
+ parse: parseKind
7815
+ },
7816
+ { brief: "The resource id to inspect", placeholder: "id", parse: String }
7817
+ ]
7818
+ }
7819
+ },
7820
+ async func(_flags, kind, id) {
7821
+ if (entityKinds.includes(kind) && !id.startsWith(`${kind}.`)) {
7822
+ throw new UsageError(`the id of a ${kind} is an entity id like ${kind}.name`);
7823
+ }
7824
+ const active = await resolveActiveContext(this);
7825
+ const { token } = active;
7826
+ const session = await openHa(this.connect, active);
7827
+ try {
7828
+ if (!(await existing(session, kind, token)).has(id)) {
7829
+ throw new NotFoundError(`${kind} "${id}" does not exist`);
7830
+ }
7831
+ const related = await relatedOf(session, token, kind, id);
7832
+ printJson(
7833
+ this,
7834
+ redactData(
7835
+ Object.fromEntries(Object.entries(related).filter(([, ids]) => ids.length > 0)),
7836
+ token
7837
+ )
7838
+ );
7839
+ } finally {
7840
+ session.close();
7841
+ }
7842
+ }
7843
+ });
7844
+
7845
+ // src/commands/diagnose.ts
7846
+ var defaultLimit = 25;
7847
+ var errorLines = /\b(?:ERROR|WARNING)\b/;
7848
+ async function diagnoseTarget(session, token, target, limit, optional2) {
7849
+ let entity;
7850
+ let device;
7851
+ let domains2 = [];
7852
+ if (target.kind === "entity") {
7853
+ const commands4 = [
7854
+ "get_states",
7855
+ "config/entity_registry/list",
7856
+ "config/device_registry/list"
7857
+ ];
7858
+ const [current, registry, devices] = await Promise.all(
7859
+ commands4.map((command2) => session.send(command2))
7860
+ );
7861
+ const deviceFile = parseResult(intersection3rk9um0b729ivValidator, devices, commands4[2], token);
7862
+ entity = findById(
7863
+ toEntities(
7864
+ parseResult(intersection10qmong0na8e8rValidator, current, commands4[0], token),
7865
+ parseResult(intersection1nv9uj515bs7itValidator, registry, commands4[1], token),
7866
+ deviceFile,
7867
+ { all: true }
7868
+ ),
7869
+ target.id,
7870
+ "entity"
7871
+ );
7872
+ const deviceId = entity.device;
7873
+ device = deviceId === void 0 ? void 0 : toDevices(deviceFile).find((item) => item.id === deviceId);
7874
+ domains2 = entity.integration === void 0 ? [] : [entity.integration];
7875
+ } else if (target.kind === "device") {
7876
+ const deviceFile = parseResult(
7877
+ intersection3rk9um0b729ivValidator,
7878
+ await session.send("config/device_registry/list"),
7879
+ "config/device_registry/list",
7880
+ token
7881
+ );
7882
+ device = findById(toDevices(deviceFile), target.id, "device");
7883
+ domains2 = device.integrations;
7884
+ } else {
7885
+ domains2 = [target.id];
7886
+ }
7887
+ const domain = domains2[0];
7888
+ const entryFile = await optional2("integrations", () => session.send("config_entries/get"));
7889
+ const entries = entryFile === void 0 ? void 0 : parseResult(intersection1kkjjod0jxg0s5Validator, entryFile, "config_entries/get", token);
7890
+ let integration;
7891
+ if (entries !== void 0) {
7892
+ if (target.kind === "integration") {
7893
+ const own2 = entries.filter((entry) => entry.domain === target.id);
7894
+ if (own2.length === 0) {
7895
+ throw new NotFoundError(`integration "${target.id}" does not exist`);
7896
+ }
7897
+ }
7898
+ const linked = entries.filter((entry) => domains2.includes(entry.domain));
7899
+ integration = domain === void 0 ? void 0 : { domain, entries: toIntegrations(linked) };
7900
+ }
7901
+ const issueFile = await optional2("repairs", () => session.send("repairs/list_issues"));
7902
+ const repairs = issueFile === void 0 ? void 0 : toRepairs(parseResult(intersectionyxcocr0wxdk22Validator, issueFile, "repairs/list_issues", token)).filter(
7903
+ (issue) => domains2.includes(issue.domain)
7904
+ );
7905
+ const related = await optional2("related", async () => {
7906
+ if (entity !== void 0) {
7907
+ return relatedOf(session, token, "entity", entity.id);
7908
+ }
7909
+ if (device !== void 0) {
7910
+ return relatedOf(session, token, "device", device.id);
7911
+ }
7912
+ const perEntry = await Promise.all(
7913
+ (integration?.entries ?? []).map(
7914
+ (entry) => relatedOf(session, token, "config_entry", entry.id)
7915
+ )
7916
+ );
7917
+ const merged = /* @__PURE__ */ new Map();
7918
+ for (const each of perEntry) {
7919
+ for (const [kind, ids] of Object.entries(each)) {
7920
+ const bucket = merged.get(kind) ?? /* @__PURE__ */ new Set();
7921
+ ids.forEach((id) => bucket.add(id));
7922
+ merged.set(kind, bucket);
7923
+ }
7924
+ }
7925
+ return Object.fromEntries(
7926
+ [...merged.entries()].map(([kind, ids]) => [kind, [...ids].sort()]).sort(([a], [b]) => a.localeCompare(b))
7927
+ );
7928
+ });
7929
+ const logs = domain === void 0 ? void 0 : await optional2(
7930
+ "logs",
7931
+ async () => (await coreLogTail(session, domain, token)).slice(-limit)
7932
+ );
7933
+ return {
7934
+ ...entity === void 0 ? {} : { entity },
7935
+ ...device === void 0 ? {} : { device },
7936
+ ...integration === void 0 ? {} : { integration },
7937
+ ...repairs === void 0 ? {} : { repairs },
7938
+ ...related === void 0 ? {} : { related },
7939
+ ...logs === void 0 ? {} : { logs }
7940
+ };
7941
+ }
7942
+ async function diagnoseInstance(session, token, limit, optional2) {
7943
+ const current = parseResult(intersection10qmong0na8e8rValidator, await session.send("get_states"), "get_states", token);
7944
+ const unavailableEntities = current.filter((state) => state.state === "unavailable").map((state) => state.entity_id).sort().slice(0, limit);
7945
+ const entryFile = await optional2("integrations", () => session.send("config_entries/get"));
7946
+ const unhealthy = entryFile === void 0 ? void 0 : toIntegrations(
7947
+ parseResult(intersection1kkjjod0jxg0s5Validator, entryFile, "config_entries/get", token).filter(
7948
+ isUnhealthyEntry
7949
+ )
7950
+ ).slice(0, limit);
7951
+ const issueFile = await optional2("repairs", () => session.send("repairs/list_issues"));
7952
+ const repairs = issueFile === void 0 ? void 0 : toRepairs(parseResult(intersectionyxcocr0wxdk22Validator, issueFile, "repairs/list_issues", token)).filter((issue) => issue.ignored !== true).slice(0, limit);
7953
+ const recentErrors = await optional2(
7954
+ "logs",
7955
+ async () => (await coreLogTail(session, void 0, token)).filter((line) => errorLines.test(line)).slice(-limit)
7956
+ );
7957
+ return {
7958
+ ...unhealthy === void 0 ? {} : { unhealthyIntegrations: unhealthy },
7959
+ unavailableEntities,
7960
+ ...repairs === void 0 ? {} : { repairs },
7961
+ ...recentErrors === void 0 ? {} : { recentErrors }
7962
+ };
7963
+ }
7964
+ var diagnoseCommand = buildCommand({
7965
+ docs: {
7966
+ brief: "Print a read-only troubleshooting bundle for an entity, device, integration or the instance",
7967
+ fullDescription: `Print a read-only troubleshooting bundle for an entity, device, integration or the instance
7968
+
7969
+ Prints one JSON object. <id> (an entity id), --device and --integration are mutually
7970
+ exclusive. Use \`hactl get entities\`, \`hactl get devices\` or \`hactl get integrations\`
7971
+ to find entity IDs, device IDs or integration domains.
7972
+
7973
+ With a target, the bundle can include "entity", "device", "integration" (domain and
7974
+ matching config entries), "repairs" (matching issues, including ignored ones), "related"
7975
+ (resource IDs by kind) and "logs" (recent Core lines for the first matching domain).
7976
+ --limit caps only "logs" in this mode. An unknown entity or device fails with not_found;
7977
+ so does an integration domain with no matching entries, if entries could be read.
7978
+
7979
+ Without a target, the bundle includes "unavailableEntities" (IDs in state "unavailable")
7980
+ and, when accessible, "unhealthyIntegrations" (not loaded and not manually disabled),
7981
+ "repairs" (non-ignored issues) and "recentErrors" (Core lines containing ERROR or WARNING).
7982
+ --limit caps each of those arrays. The default in both modes is ${defaultLimit}.
7983
+
7984
+ Only reads: it changes nothing and needs no SSH. Use \`hactl check\` to validate YAML.
7985
+ If access to an optional read is denied (Core logs need an admin token) or Home Assistant
7986
+ reports it missing or unsupported, its output is omitted. "unavailable" lists the skipped
7987
+ reads: "integrations", "repairs", "related" or "logs". Other errors fail the command.
7988
+
7989
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7990
+ caught.
7991
+
7992
+ hactl diagnose sensor.kitchen_temp
7993
+ hactl diagnose --device <device-id>
7994
+ hactl diagnose --integration mqtt
7995
+ hactl diagnose`
7996
+ },
7997
+ parameters: {
7998
+ flags: {
7999
+ device: filterFlag("Diagnose this device by id", "id"),
8000
+ integration: filterFlag("Diagnose this integration by domain, e.g. mqtt", "domain"),
8001
+ limit: {
8002
+ ...listFlags.limit,
8003
+ brief: `Cap log lines for a target or each list for the instance (default ${defaultLimit})`
8004
+ }
8005
+ },
8006
+ positional: { kind: "tuple", parameters: [idParameter("Entity id to diagnose")] }
8007
+ },
8008
+ async func(flags, entityId2) {
8009
+ const target = entityId2 !== void 0 ? { kind: "entity", id: entityId2 } : flags.device !== void 0 ? { kind: "device", id: flags.device } : flags.integration !== void 0 ? { kind: "integration", id: flags.integration } : void 0;
8010
+ if ([entityId2, flags.device, flags.integration].filter((chosen) => chosen !== void 0).length > 1) {
8011
+ throw new UsageError("pass only one of an entity id, --device or --integration");
8012
+ }
8013
+ const limit = flags.limit ?? defaultLimit;
8014
+ const active = await resolveActiveContext(this);
8015
+ const { token } = active;
8016
+ const unavailable = /* @__PURE__ */ new Set();
8017
+ const optional2 = (name, read) => optionalRead(unavailable, name, read);
8018
+ const session = await openHa(this.connect, active);
8019
+ try {
8020
+ const bundle = target === void 0 ? await diagnoseInstance(session, token, limit, optional2) : await diagnoseTarget(session, token, target, limit, optional2);
8021
+ printJson(
8022
+ this,
8023
+ redactData(
8024
+ unavailable.size === 0 ? bundle : { ...bundle, unavailable: [...unavailable].sort() },
8025
+ token
8026
+ )
8027
+ );
8028
+ } finally {
8029
+ session.close();
8030
+ }
8031
+ }
8032
+ });
8033
+
6989
8034
  // src/commands/get/devices.ts
6990
8035
  var commands = ["config/device_registry/list", "config/area_registry/list"];
6991
8036
  var devicesCommand = buildCommand({
@@ -6994,23 +8039,26 @@ var devicesCommand = buildCommand({
6994
8039
  fullDescription: `List devices, or show one
6995
8040
 
6996
8041
  Fields: "id", "name" when available, "area", "manufacturer", "model", "integrations". An id adds
6997
- "labels" and "disabled". An unknown --area is not_found.
8042
+ "labels" and "disabled". An unknown --area is not_found. --limit caps the sorted list;
8043
+ --count prints {"count": n} for all matches. Neither can be used with an id, and they
8044
+ cannot be combined.
6998
8045
  Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
6999
8046
  caught.
7000
8047
 
7001
8048
  hactl get devices --area kitchen`
7002
8049
  },
7003
8050
  parameters: {
7004
- flags: { area: filterFlag("Only devices in this area", "id") },
8051
+ flags: { area: filterFlag("Only devices in this area", "id"), ...listFlags },
7005
8052
  positional: { kind: "tuple", parameters: [idParameter("Device id")] }
7006
8053
  },
7007
8054
  async func(flags, id) {
8055
+ checkListFlags(flags, id);
7008
8056
  const {
7009
8057
  value: [registry, areas],
7010
8058
  token
7011
8059
  } = await readHa(this, commands);
7012
8060
  if (flags.area !== void 0) {
7013
- findById(toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, areas, commands[1], token)), flags.area, "area");
8061
+ findById(toAreas(parseResult(intersection16hnzan16c9ou0Validator, areas, commands[1], token)), flags.area, "area");
7014
8062
  }
7015
8063
  const devices = toDevices(parseResult(intersection3rk9um0b729ivValidator, registry, commands[0], token)).filter(
7016
8064
  (device) => flags.area === void 0 || device.area === flags.area
@@ -7021,7 +8069,8 @@ caught.
7021
8069
  id,
7022
8070
  "device",
7023
8071
  (device) => pick(device, ["id", "name", "area", "manufacturer", "model", "integrations"]),
7024
- token
8072
+ token,
8073
+ flags
7025
8074
  );
7026
8075
  }
7027
8076
  });
@@ -7035,20 +8084,33 @@ var commands2 = [
7035
8084
  "config/floor_registry/list",
7036
8085
  "config/label_registry/list"
7037
8086
  ];
8087
+ function matchesSearch(entity, search) {
8088
+ const needle = search.toLowerCase();
8089
+ return [entity.id, entity.name, entity.area, entity.integration].some(
8090
+ (field) => field?.toLowerCase().includes(needle) === true
8091
+ );
8092
+ }
7038
8093
  var entitiesCommand = buildCommand({
7039
8094
  docs: {
7040
8095
  brief: "List entities with a state, or show one",
7041
8096
  fullDescription: `List entities with a state, or show one
7042
8097
 
7043
8098
  Lists entities that have a state, hidden ones included. --all adds registry-only entities,
7044
- which have no "state". Only entities marked disabled have "disabled": true.
7045
- Filters combine. An unknown --area, --device, --floor
7046
- or --label is not_found; a domain without entities gives [].
8099
+ which have no "state". An exact entity id can find a registry-only entity without --all.
8100
+ Only entities marked disabled have "disabled": true. All filters must match, even with
8101
+ an exact id. An unknown --area, --device, --floor or --label is not_found; a domain without
8102
+ entities gives [] when listing.
7047
8103
 
7048
8104
  --floor keeps entities whose "area" is on that floor. --label keeps entities that carry the
7049
8105
  label themselves, not through their device or area. A \`hactl call\` targeting a floor or
7050
8106
  label can therefore reach other entities than these filters list.
7051
8107
 
8108
+ --state keeps entities whose printed (redacted) state exactly matches the given value,
8109
+ e.g. unavailable. --search keeps entities whose id, name, area or integration contains
8110
+ the text, ignoring case.
8111
+ --limit caps the sorted list; --count prints {"count": n} for all matches. Neither can be
8112
+ used with an id, and they cannot be combined.
8113
+
7052
8114
  Fields: "id", "name" when available, "state", "area", "areaFrom", "device", "integration", "disabled".
7053
8115
  An id adds "labels", "attributes", "lastChanged" and "hidden". Credentials anywhere in the
7054
8116
  output, such as camera access tokens and password states, are printed as REDACTED; a secret
@@ -7056,6 +8118,7 @@ without a recognizable name or shape cannot be caught.
7056
8118
  "area" is the entity's own area, else its device's; "areaFrom" says which (entity, device).
7057
8119
 
7058
8120
  hactl get entities --domain light --area kitchen
8121
+ hactl get entities --state unavailable
7059
8122
  hactl get entities light.kitchen`
7060
8123
  },
7061
8124
  parameters: {
@@ -7065,16 +8128,20 @@ without a recognizable name or shape cannot be caught.
7065
8128
  device: filterFlag("Only entities of this device", "id"),
7066
8129
  floor: filterFlag("Only entities in an area on this floor", "id"),
7067
8130
  label: filterFlag("Only entities with this label", "id"),
7068
- all: { kind: "boolean", optional: true, brief: "Also list registry-only entities" }
8131
+ state: filterFlag("Only entities in this exact state, e.g. unavailable", "state"),
8132
+ search: filterFlag("Only entities whose id, name, area or integration contains this", "text"),
8133
+ all: { kind: "boolean", optional: true, brief: "Also list registry-only entities" },
8134
+ ...listFlags
7069
8135
  },
7070
8136
  positional: { kind: "tuple", parameters: [idParameter("Entity id")] }
7071
8137
  },
7072
8138
  async func(flags, id) {
8139
+ checkListFlags(flags, id);
7073
8140
  const { value: results, token } = await readHa(this, commands2);
7074
8141
  const current = parseResult(intersection10qmong0na8e8rValidator, results[0], commands2[0], token);
7075
8142
  const registry = parseResult(intersection1nv9uj515bs7itValidator, results[1], commands2[1], token);
7076
8143
  const devices = parseResult(intersection3rk9um0b729ivValidator, results[2], commands2[2], token);
7077
- const areas = toAreas(parseResult(intersection1dmk4z81d1f8mlValidator, results[3], commands2[3], token));
8144
+ const areas = toAreas(parseResult(intersection16hnzan16c9ou0Validator, results[3], commands2[3], token));
7078
8145
  const { area, device, floor, label } = flags;
7079
8146
  if (area !== void 0) {
7080
8147
  findById(areas, area, "area");
@@ -7104,7 +8171,7 @@ without a recognizable name or shape cannot be caught.
7104
8171
  // A single id is found whether or not it is disabled.
7105
8172
  { all: flags.all === true || id !== void 0 }
7106
8173
  ).filter(
7107
- (entity) => (flags.domain === void 0 || entity.id.startsWith(`${flags.domain}.`)) && (area === void 0 || entity.area === area) && (device === void 0 || entity.device === device) && (floor === void 0 || entity.area !== void 0 && onFloor.has(entity.area)) && (label === void 0 || entity.labels?.includes(label) === true)
8174
+ (entity) => (flags.domain === void 0 || entity.id.startsWith(`${flags.domain}.`)) && (area === void 0 || entity.area === area) && (device === void 0 || entity.device === device) && (floor === void 0 || entity.area !== void 0 && onFloor.has(entity.area)) && (label === void 0 || entity.labels?.includes(label) === true) && (flags.state === void 0 || redactData(entity.state, token) === flags.state) && (flags.search === void 0 || matchesSearch(entity, flags.search))
7108
8175
  );
7109
8176
  printItems(
7110
8177
  this,
@@ -7121,445 +8188,367 @@ without a recognizable name or shape cannot be caught.
7121
8188
  "integration",
7122
8189
  "disabled"
7123
8190
  ]),
7124
- token
8191
+ token,
8192
+ flags
7125
8193
  );
7126
8194
  }
7127
8195
  });
7128
8196
 
7129
- // src/commands/get/floors.ts
7130
- var command2 = "config/floor_registry/list";
7131
- var floorsCommand = buildCommand({
8197
+ // src/commands/get/integrations.ts
8198
+ var integrationsCommand = buildCommand({
7132
8199
  docs: {
7133
- brief: "List floors, or show one",
7134
- fullDescription: `List floors, or show one
8200
+ brief: "List integration config entries and their states, or show one entry",
8201
+ fullDescription: `List integration config entries and their states, or show one entry
7135
8202
 
7136
- Fields: "id", "name", "level". An id adds "aliases" and "icon".
7137
- Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7138
- caught.`
7139
- },
7140
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Floor id")] } },
7141
- async func(_flags, id) {
7142
- const {
7143
- value: [registry],
7144
- token
7145
- } = await readHa(this, [command2]);
7146
- printItems(
7147
- this,
7148
- toFloors(parseResult(intersection1tagcym1fnxkeyValidator, registry, command2, token)),
7149
- id,
7150
- "floor",
7151
- (floor) => pick(floor, ["id", "name", "level"]),
7152
- token
7153
- );
7154
- }
7155
- });
8203
+ Prints a JSON array sorted by config entry id. An integration can have multiple entries.
8204
+ Fields: "id", "domain", "title", "state", "reason" and "disabled", when available.
8205
+ With an entry id, prints one object and adds "source", "supportsUnload" and
8206
+ "supportsReconfigure". An id not found after filtering fails with not_found.
7156
8207
 
7157
- // src/commands/get/labels.ts
7158
- var command3 = "config/label_registry/list";
7159
- var labelsCommand = buildCommand({
7160
- docs: {
7161
- brief: "List labels, or show one",
7162
- fullDescription: `List labels, or show one
8208
+ --domain and --status match exact values and can be combined. No matches give [] in
8209
+ list mode. --limit caps the sorted list; --count prints {"count": n} for all matches.
8210
+ Neither can be used with an id, and they cannot be combined.
7163
8211
 
7164
- Fields: "id", "name", "description". An id adds "color" and "icon".
7165
8212
  Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7166
- caught.`
8213
+ caught.
8214
+
8215
+ hactl get integrations --status setup_error
8216
+ hactl get integrations --domain mqtt --count`
7167
8217
  },
7168
- parameters: { positional: { kind: "tuple", parameters: [idParameter("Label id")] } },
7169
- async func(_flags, id) {
7170
- const {
7171
- value: [registry],
7172
- token
7173
- } = await readHa(this, [command3]);
8218
+ parameters: {
8219
+ flags: {
8220
+ domain: filterFlag("Only entries of this integration domain, e.g. mqtt", "domain"),
8221
+ status: filterFlag("Only entries in this state, e.g. loaded, setup_error", "state"),
8222
+ ...listFlags
8223
+ },
8224
+ positional: { kind: "tuple", parameters: [idParameter("Config entry id")] }
8225
+ },
8226
+ async func(flags, id) {
8227
+ checkListFlags(flags, id);
8228
+ const { value: results, token } = await readHa(this, ["config_entries/get"]);
8229
+ const entries = toIntegrations(
8230
+ parseResult(intersection1kkjjod0jxg0s5Validator, results[0], "config_entries/get", token)
8231
+ ).filter(
8232
+ (entry) => (flags.domain === void 0 || entry.domain === flags.domain) && (flags.status === void 0 || entry.state === flags.status)
8233
+ );
7174
8234
  printItems(
7175
8235
  this,
7176
- toLabels(parseResult(intersection1rp35ue1fi65ccValidator, registry, command3, token)),
8236
+ entries,
7177
8237
  id,
7178
- "label",
7179
- (label) => pick(label, ["id", "name", "description"]),
7180
- token
8238
+ "integration",
8239
+ (entry) => pick(entry, ["id", "domain", "title", "state", "reason", "disabled"]),
8240
+ token,
8241
+ flags
7181
8242
  );
7182
8243
  }
7183
8244
  });
7184
8245
 
7185
- // src/commands/get/services.ts
7186
- var command4 = "get_services";
7187
- var translationCommand = "frontend/get_translations";
7188
- async function serviceTexts(session, token) {
7189
- try {
7190
- const result = await session.send(translationCommand, { language: "en", category: "services" });
7191
- return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand, token).resources;
7192
- } catch (error) {
7193
- if (error instanceof HaCommandError) {
7194
- return {};
8246
+ // src/commands/get/registries.ts
8247
+ function registryCommand2(label, schema, convert, fields, details) {
8248
+ const kind = label.toLowerCase();
8249
+ const command2 = `config/${kind}_registry/list`;
8250
+ const brief = `List ${kind}s, or show one`;
8251
+ return buildCommand({
8252
+ docs: {
8253
+ brief,
8254
+ fullDescription: `${brief}
8255
+
8256
+ Fields: ${fields.map((field) => `"${String(field)}"`).join(", ")}. An id adds ${details}.
8257
+ --limit caps the sorted list; --count prints {"count": n}. Neither can be used with an id,
8258
+ and they cannot be combined.
8259
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8260
+ caught.`
8261
+ },
8262
+ parameters: {
8263
+ flags: { ...listFlags },
8264
+ positional: { kind: "tuple", parameters: [idParameter(`${label} id`)] }
8265
+ },
8266
+ async func(flags, id) {
8267
+ checkListFlags(flags, id);
8268
+ const {
8269
+ value: [registry],
8270
+ token
8271
+ } = await readHa(this, [command2]);
8272
+ const items = convert(parseResult(schema, registry, command2, token));
8273
+ printItems(this, items, id, kind, (item) => pick(item, fields), token, flags);
7195
8274
  }
7196
- throw error;
7197
- }
8275
+ });
7198
8276
  }
7199
- var servicesCommand = buildCommand({
8277
+ var registryRoutes = {
8278
+ areas: registryCommand2("Area", intersection16hnzan16c9ou0Validator, toAreas, ["id", "name", "floor"], '"labels"'),
8279
+ floors: registryCommand2(
8280
+ "Floor",
8281
+ intersection1tagcym1fnxkeyValidator,
8282
+ toFloors,
8283
+ ["id", "name", "level"],
8284
+ '"aliases" and "icon"'
8285
+ ),
8286
+ labels: registryCommand2(
8287
+ "Label",
8288
+ intersection1rp35ue1fi65ccValidator,
8289
+ toLabels,
8290
+ ["id", "name", "description"],
8291
+ '"color" and "icon"'
8292
+ )
8293
+ };
8294
+
8295
+ // src/commands/get/repairs.ts
8296
+ var repairsCommand = buildCommand({
7200
8297
  docs: {
7201
- brief: "List services, or show one with its fields",
7202
- fullDescription: `List services, or show one with its fields
8298
+ brief: "List Repairs issues, or show one",
8299
+ fullDescription: `List Repairs issues, or show one
7203
8300
 
7204
- The id is <domain>.<service>, as \`hactl call\` takes it. A list has "id", "name" and
7205
- "description", in English; some services and fields have neither.
8301
+ Prints a JSON array of Repairs issues, including ignored ones, sorted by "id".
8302
+ With an id (<domain>/<issue_id>), prints one object with the same fields.
8303
+ Fields: "id", "domain", "issueId", "severity", "isFixable",
8304
+ "ignored", "created", "translationKey", "translationPlaceholders" (absent fields omitted).
7206
8305
 
7207
- An id adds:
7208
- "target" true when the service takes --entity, --area or --device
7209
- "response" when it returns data: required (use \`hactl query\`) or optional
7210
- (\`hactl call --response\`)
7211
- "fields" the keys --data takes: "id", "name", "description", "required", "example"
7212
- and "selector" (the type and limits of the value)
8306
+ --domain and --severity can be combined. An id not found after filtering fails with
8307
+ not_found. --limit caps the sorted list; --count prints {"count": n} for all matches.
8308
+ Neither can be used with an id, and they cannot be combined.
7213
8309
 
7214
8310
  Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
7215
8311
  caught.
7216
8312
 
7217
- hactl get services --domain light
7218
- hactl get services light.turn_on`
8313
+ hactl get repairs --severity critical
8314
+ hactl get repairs mqtt/broker_deprecated`
7219
8315
  },
7220
8316
  parameters: {
7221
- flags: { domain: filterFlag("Only services in this domain, e.g. light", "domain") },
7222
- positional: { kind: "tuple", parameters: [idParameter("Service id, e.g. light.turn_on")] }
7223
- },
7224
- async func(flags, id) {
7225
- const {
7226
- value: [result, texts],
7227
- token
7228
- } = await withHa(
7229
- this,
7230
- async (session, activeToken) => Promise.all([session.send(command4), serviceTexts(session, activeToken)])
7231
- );
7232
- const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command4, token), texts);
7233
- if (id !== void 0 && all.some((service) => service.id.startsWith(`${id}.`))) {
7234
- throw new NotFoundError(
7235
- `service "${id}" does not exist`,
7236
- `"${id}" is a domain: use \`--domain ${id}\`.`
7237
- );
7238
- }
7239
- const found = all.filter(
7240
- (service) => flags.domain === void 0 || service.id.startsWith(`${flags.domain}.`)
7241
- );
7242
- printItems(
7243
- this,
7244
- found,
7245
- id,
7246
- "service",
7247
- (service) => pick(service, ["id", "name", "description"]),
7248
- token
7249
- );
7250
- }
7251
- });
7252
-
7253
- // src/commands/get/index.ts
7254
- var getRoutes = buildRouteMap({
7255
- routes: {
7256
- entities: entitiesCommand,
7257
- devices: devicesCommand,
7258
- areas: areasCommand,
7259
- floors: floorsCommand,
7260
- labels: labelsCommand,
7261
- services: servicesCommand
7262
- },
7263
- docs: {
7264
- brief: "Read entities, devices, areas, floors, labels and services from Home Assistant",
7265
- fullDescription: `Read entities, devices, areas, floors, labels and services from Home Assistant
7266
-
7267
- Reads from the active context over the WebSocket API; SSH is not needed.
7268
- Without an id a command prints an array sorted by "id". With an id it prints that one item
7269
- in full. Items refer to each other by id, so an "area", "device", "floor" or "labels" value
7270
- can be passed to another command. Zones are entities: \`get entities --domain zone\`.`
7271
- }
7272
- });
7273
-
7274
- // src/commands/logs.ts
7275
- var sourceLines = 100;
7276
- var firstEventMs = 1e4;
7277
- function parseLines(input) {
7278
- const lines = Number(input);
7279
- if (!/^\d+$/.test(input) || !Number.isSafeInteger(lines) || lines < 1) {
7280
- throw new UsageError("--lines must be a whole number, 1 or more");
7281
- }
7282
- return lines;
7283
- }
7284
- var adminNeeded = () => new HaError("Home Assistant refused the log: logs need the token of an admin user");
7285
- function print(context, lines) {
7286
- if (lines.length > 0) {
7287
- context.process.stdout.write(`${lines.join("\n")}
7288
- `);
7289
- }
7290
- }
7291
- async function coreLog(context, { context: target, token }, flags, closed) {
7292
- const connecting = openHa(context.connect, target, token);
7293
- const session = await Promise.race([connecting, closed]);
7294
- if (session === void 0) {
7295
- void connecting.then(
7296
- (connection) => connection.close(),
7297
- () => void 0
7298
- );
7299
- return;
7300
- }
7301
- const redact = createLineRedactor(token);
7302
- let first = true;
7303
- let received = () => void 0;
7304
- let failed = () => void 0;
7305
- const tail = new Promise((resolve, reject) => {
7306
- received = resolve;
7307
- failed = reject;
7308
- });
7309
- tail.catch(() => void 0);
7310
- const listen = (event) => {
7311
- try {
7312
- const lines = redact(parseResult(intersection1kfvut30tftkihValidator, event, "system_log/subscribe_raw", token));
7313
- if (first) {
7314
- first = false;
7315
- print(context, flags.lines === void 0 ? lines : lines.slice(-flags.lines));
7316
- received();
7317
- } else if (flags.follow === true) {
7318
- print(context, lines);
7319
- }
7320
- } catch (error) {
7321
- failed(error);
7322
- }
7323
- };
7324
- try {
7325
- const { integration } = flags;
7326
- const subscribed = session.stream(
7327
- "system_log/subscribe_raw",
7328
- integration === void 0 ? {} : { integration },
7329
- listen
7330
- );
7331
- await Promise.race([subscribed, closed]);
7332
- const receivedTail = await Promise.race([
7333
- closed,
7334
- tail.then(() => true),
7335
- session.wait(firstEventMs).then(() => {
7336
- throw new HaError("system_log/subscribe_raw sent no log");
7337
- })
7338
- ]);
7339
- if (receivedTail && flags.follow === true) {
7340
- session.keepAlive();
7341
- await Promise.race([closed, session.lost()]);
7342
- }
7343
- } catch (error) {
7344
- throw explain2(error, flags);
7345
- } finally {
7346
- session.close();
7347
- }
7348
- }
7349
- function explain2(error, { integration }) {
7350
- if (!(error instanceof HaCommandError)) {
7351
- return error;
7352
- }
7353
- if (error.haCode === "unauthorized") {
7354
- return adminNeeded();
7355
- }
7356
- if (error.haCode === "not_found" && integration !== void 0) {
7357
- return new NotFoundError(`integration "${integration}" does not exist`);
7358
- }
7359
- return error;
7360
- }
7361
- async function checkApp(session, slug, token) {
7362
- const result = await session.send("supervisor/api", { endpoint: "/addons", method: "get" });
7363
- const { addons } = parseResult(intersection1y5nwst153l9s2Validator, result, "supervisor/api /addons", token);
7364
- if (!addons.some((app2) => app2.slug === slug)) {
7365
- throw new NotFoundError(`app "${slug}" is not installed`);
7366
- }
7367
- }
7368
- async function openLog(context, { context: target, token }, path) {
7369
- const url2 = `${baseUrl(target)}${path}`;
7370
- let response;
7371
- try {
7372
- response = await context.httpStream(url2, { Authorization: `Bearer ${token.reveal()}` });
7373
- } catch (error) {
7374
- throw new UnreachableError(`cannot reach ${url2}: ${redactText(causeMessage(error), token)}`);
7375
- }
7376
- const { status } = response;
7377
- if (status >= 200 && status < 300) {
7378
- return response;
7379
- }
7380
- response.close();
7381
- if (status === 401) {
7382
- throw adminNeeded();
7383
- }
7384
- if (status >= 300 && status < 400) {
7385
- throw new UnreachableError(
7386
- `cannot reach ${url2}: it redirects`,
7387
- `Set the final URL with \`hactl ctx set ${target.name} --url <url>\`.`
7388
- );
7389
- }
7390
- throw new HaError(`GET ${path} returned HTTP ${status}`);
7391
- }
7392
- async function checkSupervisor(context, { context: target, token }, source) {
7393
- const config = await getConfig(context.fetch, target, token);
7394
- if (!config.components.includes("hassio")) {
7395
- throw new HaError(`the log of "${source}" needs Supervisor, which this instance does not have`);
7396
- }
7397
- }
7398
- async function checkAppOnSession(context, { context: target, token }, source, flags) {
7399
- const session = await openHa(context.connect, target, token);
7400
- try {
7401
- await checkApp(session, source, token);
7402
- } catch (error) {
7403
- throw explain2(error, flags);
7404
- } finally {
7405
- session.close();
7406
- }
7407
- }
7408
- async function sourceLog(context, active, source, flags, closed) {
7409
- const { context: target, token } = active;
7410
- const follow = flags.follow === true;
7411
- const wanted = flags.lines ?? sourceLines;
7412
- const root2 = source === "supervisor" ? "supervisor" : `addons/${encodeURIComponent(source)}`;
7413
- const path = `/api/hassio/${root2}/logs${follow ? "/follow" : ""}?lines=${Math.max(wanted, 2)}`;
7414
- const opening = openLog(context, active, path);
7415
- const startup = Promise.allSettled([
7416
- checkSupervisor(context, active, source),
7417
- source === "supervisor" ? Promise.resolve() : checkAppOnSession(context, active, source, flags),
7418
- opening
7419
- ]);
7420
- const settled = await Promise.race([startup, closed]);
7421
- if (settled === void 0) {
7422
- void opening.then(
7423
- (response2) => response2.close(),
7424
- () => void 0
7425
- );
7426
- return;
7427
- }
7428
- const [config, app2, opened] = settled;
7429
- for (const check2 of [config, app2]) {
7430
- if (check2.status === "rejected") {
7431
- if (opened.status === "fulfilled") {
7432
- opened.value.close();
7433
- }
7434
- throw check2.reason;
7435
- }
7436
- }
7437
- if (opened.status === "rejected") {
7438
- throw opened.reason;
8317
+ flags: {
8318
+ domain: filterFlag("Only issues of this domain, e.g. mqtt", "domain"),
8319
+ severity: {
8320
+ kind: "enum",
8321
+ values: ["warning", "error", "critical"],
8322
+ optional: true,
8323
+ brief: "Only issues of this severity"
8324
+ },
8325
+ ...listFlags
8326
+ },
8327
+ positional: { kind: "tuple", parameters: [idParameter("Issue id, <domain>/<issue_id>")] }
8328
+ },
8329
+ async func(flags, id) {
8330
+ checkListFlags(flags, id);
8331
+ const { value: results, token } = await readHa(this, ["repairs/list_issues"]);
8332
+ const issues = toRepairs(
8333
+ parseResult(intersectionyxcocr0wxdk22Validator, results[0], "repairs/list_issues", token)
8334
+ ).filter(
8335
+ (issue) => (flags.domain === void 0 || issue.domain === flags.domain) && (flags.severity === void 0 || issue.severity === flags.severity)
8336
+ );
8337
+ printItems(this, issues, id, "repairs issue", (issue) => issue, token, flags);
7439
8338
  }
7440
- const response = opened.value;
7441
- const redact = createLineRedactor(token);
7442
- let stopped = false;
7443
- void closed.then(() => {
7444
- stopped = true;
7445
- response.close();
7446
- });
7447
- let partial = "";
7448
- let skip = follow && wanted === 1 ? 1 : 0;
7449
- const collected = [];
7450
- const take = (lines) => {
7451
- if (!follow) {
7452
- collected.push(...lines);
7453
- return;
7454
- }
7455
- print(context, lines.slice(skip));
7456
- skip = Math.max(0, skip - lines.length);
7457
- };
7458
- const lost = (reason) => new UnreachableError(`lost the log from ${baseUrl(target)}: ${reason}`);
8339
+ });
8340
+
8341
+ // src/commands/get/services.ts
8342
+ var command = "get_services";
8343
+ var translationCommand = "frontend/get_translations";
8344
+ async function serviceTexts(session, token) {
7459
8345
  try {
7460
- for await (const chunk of response.body) {
7461
- const lines = `${partial}${chunk}`.split("\n");
7462
- partial = lines.pop() ?? "";
7463
- if (lines.length > 0) {
7464
- take(redact(lines));
7465
- }
7466
- }
7467
- if (partial !== "") {
7468
- take(redact([partial]));
7469
- }
8346
+ const result = await session.send(translationCommand, { language: "en", category: "services" });
8347
+ return parseResult(intersection1etdk1h0e9wp9wValidator, result, translationCommand, token).resources;
7470
8348
  } catch (error) {
7471
- if (!stopped) {
7472
- throw lost(redactText(causeMessage(error), token));
8349
+ if (error instanceof HaCommandError) {
8350
+ return {};
7473
8351
  }
7474
- } finally {
7475
- response.close();
7476
- }
7477
- if (!follow) {
7478
- print(context, collected.slice(-wanted));
7479
- } else if (!stopped) {
7480
- throw lost("the stream ended");
8352
+ throw error;
7481
8353
  }
7482
8354
  }
7483
- var logsCommand = buildCommand({
8355
+ var servicesCommand = buildCommand({
7484
8356
  docs: {
7485
- brief: "Print or follow the log of Home Assistant, Supervisor or an app",
7486
- fullDescription: `Print or follow the log of Home Assistant, Supervisor or an app
7487
-
7488
- Sources:
7489
- (none) the Core log, on every install type
7490
- supervisor the Supervisor's log
7491
- <app slug> that app's (add-on's) log, e.g. core_mosquitto
7492
- supervisor and apps need an instance with Supervisor. An app that is not installed is not_found.
7493
- Every source needs the token of an admin user. SSH is not used.
7494
-
7495
- Output is plain text, not JSON, oldest line first, without color codes. A record spanning
7496
- several lines counts as that many. Which levels are logged is up to Home Assistant's logger
7497
- settings.
8357
+ brief: "List services, or show one with its fields",
8358
+ fullDescription: `List services, or show one with its fields
7498
8359
 
7499
- Existing lines: Home Assistant offers the last 100 lines of the Core log, or up to 5000 with
7500
- --integration, going back only to its last start; a larger --lines prints what there is.
7501
- Other sources print 100 lines unless --lines says otherwise.
7502
- --lines accepts only digits, up to 9007199254740991. Core must send its initial tail
7503
- within 10 seconds of accepting the subscription, even if the tail is empty.
7504
- Supervisor and app sources have a 10-second header deadline, but no body deadline.
8360
+ The id is <domain>.<service>, as \`hactl call\` and \`hactl query\` take it. A list has "id"
8361
+ plus "name" and "description" when available. hactl requests English translations for
8362
+ missing names and descriptions. Use --domain to list services in a domain.
7505
8363
 
7506
- --follow keeps printing new lines and never ends by itself: press Ctrl+C to exit successfully. When the
7507
- connection ends, also because Home Assistant restarts, it fails with unreachable after the
7508
- lines already printed; it does not reconnect.
8364
+ An id adds:
8365
+ "target" true when the service takes --entity, --area or --device
8366
+ "response" when it returns data: required (use \`hactl query\`) or optional
8367
+ (\`hactl call --response\`)
8368
+ "fields" the keys --data takes: "id", "name", "description", "required", "example"
8369
+ and "selector" (the type and limits of the value)
7509
8370
 
7510
- --integration limits the Core log to one integration and the libraries it uses. It cannot
7511
- be combined with a source. An unknown integration is not_found.
8371
+ --limit caps the sorted list; --count prints {"count": n} for all matches. Neither can be
8372
+ used with an id, and they cannot be combined.
7512
8373
 
7513
- Credentials are printed as REDACTED. Redaction cannot catch every secret in free text: one
7514
- without a recognizable name or shape is printed.
8374
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8375
+ caught.
7515
8376
 
7516
- hactl logs --lines 20
7517
- hactl logs --integration zha --follow
7518
- hactl logs supervisor`
8377
+ hactl get services --domain light
8378
+ hactl get services light.turn_on`
7519
8379
  },
7520
8380
  parameters: {
7521
8381
  flags: {
7522
- lines: {
7523
- kind: "parsed",
7524
- parse: parseLines,
7525
- optional: true,
7526
- brief: "Print at most this many existing lines",
7527
- placeholder: "n"
7528
- },
7529
- follow: {
7530
- kind: "boolean",
7531
- optional: true,
7532
- brief: "Keep printing new lines until interrupted"
7533
- },
7534
- integration: {
7535
- kind: "parsed",
7536
- parse: String,
7537
- optional: true,
7538
- brief: "Only this integration (Core log only)",
7539
- placeholder: "domain"
7540
- }
8382
+ domain: filterFlag("Only services in this domain, e.g. light", "domain"),
8383
+ ...listFlags
7541
8384
  },
7542
- positional: {
7543
- kind: "tuple",
7544
- parameters: [
7545
- { brief: "supervisor or an app slug", placeholder: "source", parse: String, optional: true }
7546
- ]
7547
- }
8385
+ positional: { kind: "tuple", parameters: [idParameter("Service id, e.g. light.turn_on")] }
7548
8386
  },
7549
- async func(flags, source) {
7550
- if (source !== void 0 && flags.integration !== void 0) {
7551
- throw new UsageError("--integration only applies to the Core log, without a source");
8387
+ async func(flags, id) {
8388
+ checkListFlags(flags, id);
8389
+ const {
8390
+ value: [result, texts],
8391
+ token
8392
+ } = await withHa(
8393
+ this,
8394
+ async (session, activeToken) => Promise.all([session.send(command), serviceTexts(session, activeToken)])
8395
+ );
8396
+ const all = toServices(parseResult(intersection128bswg1yy3khmValidator, result, command, token), texts);
8397
+ if (id !== void 0 && all.some((service) => service.id.startsWith(`${id}.`))) {
8398
+ throw new NotFoundError(
8399
+ `service "${id}" does not exist`,
8400
+ `"${id}" is a domain: use \`--domain ${id}\`.`
8401
+ );
7552
8402
  }
8403
+ const found = all.filter(
8404
+ (service) => flags.domain === void 0 || service.id.startsWith(`${flags.domain}.`)
8405
+ );
8406
+ printItems(
8407
+ this,
8408
+ found,
8409
+ id,
8410
+ "service",
8411
+ (service) => pick(service, ["id", "name", "description"]),
8412
+ token,
8413
+ flags
8414
+ );
8415
+ }
8416
+ });
8417
+
8418
+ // src/commands/get/index.ts
8419
+ var getRoutes = buildRouteMap({
8420
+ routes: {
8421
+ entities: entitiesCommand,
8422
+ devices: devicesCommand,
8423
+ ...registryRoutes,
8424
+ services: servicesCommand,
8425
+ integrations: integrationsCommand,
8426
+ repairs: repairsCommand
8427
+ },
8428
+ docs: {
8429
+ brief: "Read entities, devices, areas, floors, labels, services, integrations and repairs from Home Assistant",
8430
+ fullDescription: `Read entities, devices, areas, floors, labels, services, integrations and repairs from Home Assistant
8431
+
8432
+ Reads from the active context over the WebSocket API; SSH is not needed.
8433
+ Without an id, a command prints a JSON array of summaries sorted by "id". With an id, it
8434
+ prints one JSON object, or fails with not_found if no item matches. --limit caps a list;
8435
+ --count prints {"count": n} instead. Neither combines with an id or each other.
8436
+ Items refer to each other by id, so an "area", "device", "floor" or an entry in "labels"
8437
+ can be passed to another command. Zones are entities: \`hactl get entities --domain zone\`.`
8438
+ }
8439
+ });
8440
+
8441
+ // src/commands/overview.ts
8442
+ var commands3 = [
8443
+ "get_config",
8444
+ "get_states",
8445
+ "config/device_registry/list",
8446
+ "config/area_registry/list",
8447
+ "config/floor_registry/list",
8448
+ "config/label_registry/list",
8449
+ "get_services"
8450
+ ];
8451
+ var overviewCommand = buildCommand({
8452
+ docs: {
8453
+ brief: "Print a compact, read-only summary of the whole instance",
8454
+ fullDescription: `Print a compact, read-only summary of the whole instance
8455
+
8456
+ One JSON object: "version" and "state", "counts" of entities (with a state), devices,
8457
+ areas, floors, labels and services, "domains" (each entity domain with its "total" and,
8458
+ when nonzero, "unavailable" and "unknown" state counts, sorted by domain),
8459
+ "unhealthyIntegrations" (config entries not loaded and not manually disabled, sorted by
8460
+ id, with "id", "domain", "title", "state" and "reason") and "repairs" ("total" non-ignored
8461
+ issues plus "bySeverity" when any exist).
8462
+
8463
+ Only reads: it changes nothing and needs no SSH. If reading config entries or repairs is
8464
+ denied or unsupported, that section is omitted and "unavailable" lists "integrations"
8465
+ and/or "repairs". Use \`hactl diagnose\` for details of one entity, device or integration.
8466
+
8467
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8468
+ caught.`
8469
+ },
8470
+ parameters: {},
8471
+ async func() {
7553
8472
  const active = await resolveActiveContext(this);
7554
- let stopListening;
7555
- const closed = flags.follow === true ? Promise.race([
7556
- this.stdoutClosed(),
7557
- new Promise((resolve) => stopListening = this.onInterrupt(resolve))
7558
- ]) : this.stdoutClosed();
8473
+ const { token } = active;
8474
+ const unavailable = /* @__PURE__ */ new Set();
8475
+ const session = await openHa(this.connect, active);
7559
8476
  try {
7560
- await (source === void 0 ? coreLog(this, active, flags, closed) : sourceLog(this, active, source, flags, closed));
8477
+ const [config, statesResult, devices, areas, floors, labels, svcs, entries, issues] = await Promise.all([
8478
+ ...commands3.map((command2) => session.send(command2)),
8479
+ optionalRead(unavailable, "integrations", () => session.send("config_entries/get")),
8480
+ optionalRead(unavailable, "repairs", () => session.send("repairs/list_issues"))
8481
+ ]);
8482
+ const current = parseResult(intersection10qmong0na8e8rValidator, statesResult, commands3[1], token);
8483
+ const byDomain = /* @__PURE__ */ new Map();
8484
+ for (const { entity_id: entityId2, state } of current) {
8485
+ const key = entityId2.slice(0, entityId2.indexOf("."));
8486
+ const bucket = byDomain.get(key) ?? { total: 0, unavailable: 0, unknown: 0 };
8487
+ bucket.total += 1;
8488
+ if (state === "unavailable") {
8489
+ bucket.unavailable += 1;
8490
+ } else if (state === "unknown") {
8491
+ bucket.unknown += 1;
8492
+ }
8493
+ byDomain.set(key, bucket);
8494
+ }
8495
+ const domains2 = [...byDomain.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([domain, bucket]) => {
8496
+ const entry = {
8497
+ domain,
8498
+ total: bucket.total
8499
+ };
8500
+ if (bucket.unavailable > 0) {
8501
+ entry.unavailable = bucket.unavailable;
8502
+ }
8503
+ if (bucket.unknown > 0) {
8504
+ entry.unknown = bucket.unknown;
8505
+ }
8506
+ return entry;
8507
+ });
8508
+ const severities = /* @__PURE__ */ new Map();
8509
+ let repairs;
8510
+ if (issues !== void 0) {
8511
+ const activeIssues = parseResult(
8512
+ intersectionyxcocr0wxdk22Validator,
8513
+ issues,
8514
+ "repairs/list_issues",
8515
+ token
8516
+ ).issues.filter((issue) => issue.ignored !== true);
8517
+ for (const issue of activeIssues) {
8518
+ const severity = issue.severity ?? "warning";
8519
+ severities.set(severity, (severities.get(severity) ?? 0) + 1);
8520
+ }
8521
+ repairs = activeIssues.length === 0 ? { total: 0 } : {
8522
+ total: activeIssues.length,
8523
+ bySeverity: Object.fromEntries(
8524
+ [...severities.entries()].sort(([a], [b]) => a.localeCompare(b))
8525
+ )
8526
+ };
8527
+ }
8528
+ const overview = {
8529
+ ...pick(parseResult(intersection150ify80evssmcValidator, config, commands3[0], token), ["version", "state"]),
8530
+ counts: {
8531
+ entities: current.length,
8532
+ devices: parseResult(intersection3rk9um0b729ivValidator, devices, commands3[2], token).length,
8533
+ areas: parseResult(intersection16hnzan16c9ou0Validator, areas, commands3[3], token).length,
8534
+ floors: parseResult(intersection1tagcym1fnxkeyValidator, floors, commands3[4], token).length,
8535
+ labels: parseResult(intersection1rp35ue1fi65ccValidator, labels, commands3[5], token).length,
8536
+ services: toServices(parseResult(intersection128bswg1yy3khmValidator, svcs, commands3[6], token)).length
8537
+ },
8538
+ domains: domains2,
8539
+ ...entries === void 0 ? {} : {
8540
+ unhealthyIntegrations: toIntegrations(
8541
+ parseResult(intersection1kkjjod0jxg0s5Validator, entries, "config_entries/get", token).filter(
8542
+ isUnhealthyEntry
8543
+ )
8544
+ ).map((entry) => pick(entry, ["id", "domain", "title", "state", "reason"]))
8545
+ },
8546
+ ...repairs === void 0 ? {} : { repairs },
8547
+ ...unavailable.size === 0 ? {} : { unavailable: [...unavailable].sort() }
8548
+ };
8549
+ printJson(this, redactData(overview, token));
7561
8550
  } finally {
7562
- stopListening?.();
8551
+ session.close();
7563
8552
  }
7564
8553
  }
7565
8554
  });
@@ -7567,14 +8556,16 @@ without a recognizable name or shape is printed.
7567
8556
  // src/commands/query.ts
7568
8557
  var queryCommand = buildCommand({
7569
8558
  docs: {
7570
- brief: "Run a service that only returns data, and print it",
7571
- fullDescription: `Run a service that only returns data, and print it
8559
+ brief: "Run a response-required service and print its data",
8560
+ fullDescription: `Run a response-required service and print its data
7572
8561
 
7573
8562
  Calls <domain>.<service> on the active context and prints its response data as JSON. It only
7574
8563
  runs services that Home Assistant says require a response, such as forecasts, calendar
7575
8564
  events, to-do items and statistics: \`hactl get services <id>\` shows "response": "required".
7576
- Any other service is refused with usage_error and nothing is called: use \`hactl call\`, also
7577
- for scripts. query relies on the integration's own claim that such a service changes nothing.
8565
+ An unknown service fails with not_found. A known service whose response is optional or
8566
+ unsupported fails with usage_error: use \`hactl call\` instead. In both cases nothing is
8567
+ called. Treat a query as read-only only if you trust the integration's own claim about
8568
+ what the service does.
7578
8569
 
7579
8570
  Targets: --entity, --area, --device, --floor and --label are repeatable and replace the same
7580
8571
  key in --data, which holds the service's other fields. A target flag naming something that
@@ -7584,7 +8575,8 @@ does not exist fails with not_found and nothing is called. Ids in --data are not
7584
8575
  The response can hold private data. Credentials in it and in error messages are printed as
7585
8576
  REDACTED; a secret without a recognizable name or shape cannot be caught.
7586
8577
 
7587
- After 10 seconds without an answer the command fails with timeout.
8578
+ If Home Assistant does not answer a sent service call within 10 seconds, the command fails
8579
+ with timeout; the service may still finish.
7588
8580
 
7589
8581
  hactl query weather.get_forecasts --entity weather.home --data '{"type": "daily"}'
7590
8582
  hactl query todo.get_items --entity todo.shopping
@@ -7595,10 +8587,11 @@ After 10 seconds without an answer the command fails with timeout.
7595
8587
  positional: { kind: "tuple", parameters: [serviceParameter] }
7596
8588
  },
7597
8589
  async func(flags, service) {
7598
- const { context, token } = await resolveActiveContext(this);
8590
+ const active = await resolveActiveContext(this);
8591
+ const { token } = active;
7599
8592
  const data = buildServiceData(flags);
7600
8593
  const id = `${service.domain}.${service.service}`;
7601
- const session = await openHa(this.connect, context, token);
8594
+ const session = await openHa(this.connect, active);
7602
8595
  try {
7603
8596
  const read = readOnce(session);
7604
8597
  await inOrder([
@@ -7608,7 +8601,7 @@ After 10 seconds without an answer the command fails with timeout.
7608
8601
  }
7609
8602
  if (support !== "required") {
7610
8603
  throw new UsageError(
7611
- `"${id}" can change the instance, so query does not run it`,
8604
+ `"${id}" is not marked as requiring a response`,
7612
8605
  `Run it with \`hactl call ${id}\`.`
7613
8606
  );
7614
8607
  }
@@ -7624,39 +8617,220 @@ After 10 seconds without an answer the command fails with timeout.
7624
8617
  }
7625
8618
  });
7626
8619
 
8620
+ // src/commands/search.ts
8621
+ var defaultLimit2 = 20;
8622
+ var kinds2 = ["entity", "device", "area", "floor", "label", "service"];
8623
+ var registryCommand3 = {
8624
+ device: "config/device_registry/list",
8625
+ area: "config/area_registry/list",
8626
+ floor: "config/floor_registry/list",
8627
+ label: "config/label_registry/list",
8628
+ service: "get_services"
8629
+ };
8630
+ function score({ id, name }, query) {
8631
+ if (id.toLowerCase() === query) {
8632
+ return 4;
8633
+ }
8634
+ if (id.toLowerCase().startsWith(query)) {
8635
+ return 3;
8636
+ }
8637
+ if (name?.toLowerCase() === query) {
8638
+ return 2;
8639
+ }
8640
+ return 1;
8641
+ }
8642
+ function lower(values) {
8643
+ return values.flatMap((value) => value === void 0 ? [] : [value.toLowerCase()]);
8644
+ }
8645
+ async function collect2(session, token, wanted, all) {
8646
+ const needsAreas = wanted.has("entity") || wanted.has("device") || wanted.has("area");
8647
+ const commands4 = /* @__PURE__ */ new Set();
8648
+ if (wanted.has("entity")) {
8649
+ for (const command2 of [
8650
+ "get_states",
8651
+ "config/entity_registry/list",
8652
+ "config/device_registry/list"
8653
+ ]) {
8654
+ commands4.add(command2);
8655
+ }
8656
+ }
8657
+ for (const kind of wanted) {
8658
+ if (kind !== "entity") {
8659
+ commands4.add(registryCommand3[kind]);
8660
+ }
8661
+ }
8662
+ if (needsAreas) {
8663
+ commands4.add("config/area_registry/list");
8664
+ }
8665
+ const list = [...commands4];
8666
+ const [results, texts] = await Promise.all([
8667
+ Promise.all(list.map((command2) => session.send(command2))),
8668
+ wanted.has("service") ? serviceTexts(session, token) : Promise.resolve({})
8669
+ ]);
8670
+ const raw = new Map(list.map((command2, index) => [command2, results[index]]));
8671
+ const got = (schema, command2) => parseResult(schema, raw.get(command2), command2, token);
8672
+ const areas = needsAreas ? got(intersection16hnzan16c9ou0Validator, "config/area_registry/list").map((area) => ({
8673
+ id: area.area_id,
8674
+ name: area.name,
8675
+ aliases: area.aliases ?? []
8676
+ })) : [];
8677
+ const areaName = new Map(areas.map((area) => [area.id, area.name]));
8678
+ const areaFields = (id) => {
8679
+ if (id === void 0) {
8680
+ return [];
8681
+ }
8682
+ const name = areaName.get(id);
8683
+ return name === void 0 ? [id] : [id, name];
8684
+ };
8685
+ const items = [];
8686
+ const add = (type11, { id, name, state, area }, extra) => {
8687
+ items.push({ type: type11, id, name, state, area, fields: lower([id, name, ...extra]) });
8688
+ };
8689
+ if (wanted.has("entity")) {
8690
+ for (const entity of toEntities(
8691
+ got(intersection10qmong0na8e8rValidator, "get_states"),
8692
+ got(intersection1nv9uj515bs7itValidator, "config/entity_registry/list"),
8693
+ got(intersection3rk9um0b729ivValidator, "config/device_registry/list"),
8694
+ { all }
8695
+ )) {
8696
+ add("entity", entity, areaFields(entity.area));
8697
+ }
8698
+ }
8699
+ if (wanted.has("device")) {
8700
+ for (const device of toDevices(got(intersection3rk9um0b729ivValidator, "config/device_registry/list"))) {
8701
+ if (device.disabled === true && !all) {
8702
+ continue;
8703
+ }
8704
+ add("device", device, areaFields(device.area));
8705
+ }
8706
+ }
8707
+ if (wanted.has("area")) {
8708
+ for (const area of areas) {
8709
+ add("area", area, area.aliases);
8710
+ }
8711
+ }
8712
+ if (wanted.has("floor")) {
8713
+ for (const floor of toFloors(got(intersection1tagcym1fnxkeyValidator, "config/floor_registry/list"))) {
8714
+ add("floor", floor, floor.aliases ?? []);
8715
+ }
8716
+ }
8717
+ if (wanted.has("label")) {
8718
+ for (const label of toLabels(got(intersection1rp35ue1fi65ccValidator, "config/label_registry/list"))) {
8719
+ add("label", label, [label.description]);
8720
+ }
8721
+ }
8722
+ if (wanted.has("service")) {
8723
+ for (const service of toServices(got(intersection128bswg1yy3khmValidator, "get_services"), texts)) {
8724
+ add("service", service, [service.description]);
8725
+ }
8726
+ }
8727
+ return items;
8728
+ }
8729
+ var searchCommand = buildCommand({
8730
+ docs: {
8731
+ brief: "Search entities, devices, areas, floors, labels and services in one call",
8732
+ fullDescription: `Search entities, devices, areas, floors, labels and services in one call
8733
+
8734
+ Matches <query> ignoring case: split on whitespace, every word must appear in a result's
8735
+ id, name, area, description or aliases (aliases are searched for area and floor results).
8736
+ Results are ranked: an exact id match first, then
8737
+ an id prefix match, then an exact name match, then word matches; ties sort by id.
8738
+
8739
+ Prints a JSON array of {"type", "id", "name", "state", "area", "score"} with absent fields
8740
+ omitted. "state" appears only for entities, "area" as the area id. The entity set is the
8741
+ same as \`hactl get entities\` (entities with a state, hidden included); --all adds
8742
+ registry-only entities and disabled devices. --type narrows the kinds searched; repeat it
8743
+ for more than one. --limit caps the output (default ${defaultLimit2}).
8744
+
8745
+ Only reads: it changes nothing and needs no SSH.
8746
+
8747
+ Credentials are printed as REDACTED; a secret without a recognizable name or shape cannot be
8748
+ caught.
8749
+
8750
+ hactl search kitchen
8751
+ hactl search "kitchen ceiling" --type entity
8752
+ hactl search sensor --type entity --type service --limit 5`
8753
+ },
8754
+ parameters: {
8755
+ flags: {
8756
+ type: {
8757
+ kind: "enum",
8758
+ values: kinds2,
8759
+ optional: true,
8760
+ variadic: true,
8761
+ brief: "Only this resource kind; repeat for more"
8762
+ },
8763
+ limit: {
8764
+ ...listFlags.limit,
8765
+ brief: `Print at most this many results (positive whole number, default ${defaultLimit2})`
8766
+ },
8767
+ all: {
8768
+ kind: "boolean",
8769
+ optional: true,
8770
+ brief: "Also search registry-only entities and disabled devices"
8771
+ }
8772
+ },
8773
+ positional: {
8774
+ kind: "tuple",
8775
+ parameters: [{ brief: "The text to search for", placeholder: "query", parse: String }]
8776
+ }
8777
+ },
8778
+ async func(flags, query) {
8779
+ const trimmed = query.trim();
8780
+ if (trimmed === "") {
8781
+ throw new UsageError("the query cannot be empty");
8782
+ }
8783
+ const tokens = trimmed.toLowerCase().split(/\s+/);
8784
+ const wanted = new Set(flags.type ?? kinds2);
8785
+ const limit = flags.limit ?? defaultLimit2;
8786
+ const active = await resolveActiveContext(this);
8787
+ const { token } = active;
8788
+ const session = await openHa(this.connect, active);
8789
+ try {
8790
+ const items = await collect2(session, token, wanted, flags.all === true);
8791
+ const hits = items.filter((item) => tokens.every((word) => item.fields.some((f) => f.includes(word)))).map((item) => ({
8792
+ type: item.type,
8793
+ id: item.id,
8794
+ name: item.name,
8795
+ state: item.state,
8796
+ area: item.area,
8797
+ score: score(item, trimmed.toLowerCase())
8798
+ })).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)).slice(0, limit);
8799
+ printJson(this, redactData(hits, token));
8800
+ } finally {
8801
+ session.close();
8802
+ }
8803
+ }
8804
+ });
8805
+
7627
8806
  // src/commands/template.ts
7628
8807
  var renderSeconds = 5;
7629
8808
  var answerMs = 1e4;
7630
8809
  async function render(session, template) {
7631
8810
  const warnings = /* @__PURE__ */ new Set();
7632
- let done = () => void 0;
7633
- let failed = () => void 0;
7634
- const outcome = new Promise((resolve, reject) => {
7635
- done = resolve;
7636
- failed = reject;
7637
- });
7638
- outcome.catch(() => void 0);
8811
+ const outcome = Promise.withResolvers();
8812
+ outcome.promise.catch(() => void 0);
7639
8813
  await session.stream(
7640
8814
  "render_template",
7641
8815
  { template, timeout: renderSeconds, report_errors: true },
7642
8816
  (event) => {
7643
8817
  const success = intersection1r95ni81xgl88zValidator(event);
7644
8818
  if (!(success instanceof Issues)) {
7645
- done({ result: success.result, warnings: [...warnings] });
8819
+ outcome.resolve({ result: success.result, warnings: [...warnings] });
7646
8820
  return;
7647
8821
  }
7648
8822
  const problem = intersection8yr2o71ja81ufValidator(event);
7649
8823
  if (problem instanceof Issues) {
7650
- failed(new HaError("render_template sent an unexpected event"));
8824
+ outcome.reject(new HaError("render_template sent an unexpected event"));
7651
8825
  } else if (problem.level === "WARNING") {
7652
8826
  warnings.add(problem.error);
7653
8827
  } else {
7654
- failed(new HaError(problem.error));
8828
+ outcome.reject(new HaError(problem.error));
7655
8829
  }
7656
8830
  }
7657
8831
  );
7658
8832
  return Promise.race([
7659
- outcome,
8833
+ outcome.promise,
7660
8834
  session.wait(answerMs).then(() => {
7661
8835
  throw new TimeoutError("render_template sent no result");
7662
8836
  })
@@ -7680,16 +8854,17 @@ Renders <template> on the active context, to try it before putting it in the con
7680
8854
  With - the template is read from standard input. A template cannot call services, so nothing
7681
8855
  on the instance changes, and no admin token is needed.
7682
8856
 
7683
- Output: text is printed as it is, nothing when empty. Anything else Home Assistant makes of
7684
- the result, such as a number, boolean, list or object, is printed as JSON.
8857
+ Output: a string is printed as text with a final newline if needed; an empty string prints
8858
+ nothing. Other results, such as a number, boolean, list or object, are printed as JSON.
7685
8859
 
7686
8860
  Warnings, such as an undefined variable, go to standard error as \`warning: <message>\` and do
7687
8861
  not change the exit code. A template that cannot be rendered fails with ha_error. Variables
7688
8862
  that an automation or script would supply, such as trigger, are not defined here: stand in
7689
8863
  for them with {% set %}.
7690
8864
 
7691
- Home Assistant stops rendering after ${renderSeconds} seconds, which fails with timeout. hactl also
7692
- times out after ${answerMs / 1e3} seconds without a reply or ${answerMs / 1e3} seconds after acknowledgement without a result.
8865
+ hactl asks Home Assistant to finish rendering within ${renderSeconds} seconds. A reported render
8866
+ timeout, no reply to the render request within ${answerMs / 1e3} seconds, or no result within
8867
+ ${answerMs / 1e3} seconds of acknowledgement fails with timeout.
7693
8868
  An expensive template slows Home Assistant down while it runs.
7694
8869
 
7695
8870
  Values that hactl hides elsewhere, such as password states and camera tokens, are printed as
@@ -7715,8 +8890,9 @@ recognizable name or shape cannot be caught.
7715
8890
  if (template.trim() === "") {
7716
8891
  throw new UsageError("the template is empty");
7717
8892
  }
7718
- const { context, token } = await resolveActiveContext(this);
7719
- const session = await openHa(this.connect, context, token);
8893
+ const active = await resolveActiveContext(this);
8894
+ const { token } = active;
8895
+ const session = await openHa(this.connect, active);
7720
8896
  let secrets = /* @__PURE__ */ new Set();
7721
8897
  try {
7722
8898
  secrets = collectSecrets(
@@ -7865,19 +9041,27 @@ var upgradeCommand = buildCommand({
7865
9041
  brief: "Replace this binary with the latest release, or with a specific version",
7866
9042
  fullDescription: `Replace this binary with the latest release, or with a specific version
7867
9043
 
7868
- Without a version, installs the latest release. Older versions can be installed too.
7869
- The download is checked against the SHA-256 digest GitHub publishes for it.
7870
- Only works on a release binary. Prints {"from", "to"}.
9044
+ Without a version, installs the latest release. Give a version like 0.9.0 or v0.9.0 to
9045
+ install that release, including older versions. If it is already installed, nothing is
9046
+ replaced. A downloaded binary must match GitHub's SHA-256 digest and report the expected
9047
+ version before it replaces the current binary.
9048
+ Only works on a release binary and requires write access to its directory. Does not use a
9049
+ Home Assistant context. Prints {"from", "to"}, even when the versions are the same.
7871
9050
  Update an npm install with \`npm install -g hactl@latest\` instead.
7872
9051
 
7873
9052
  hactl upgrade
7874
- hactl upgrade 0.2.0`
9053
+ hactl upgrade 0.9.0`
7875
9054
  },
7876
9055
  parameters: {
7877
9056
  positional: {
7878
9057
  kind: "tuple",
7879
9058
  parameters: [
7880
- { brief: "Version to install", placeholder: "version", parse: parseVersion, optional: true }
9059
+ {
9060
+ brief: "Release version, with or without a leading v",
9061
+ placeholder: "version",
9062
+ parse: parseVersion,
9063
+ optional: true
9064
+ }
7881
9065
  ]
7882
9066
  }
7883
9067
  },
@@ -7918,38 +9102,51 @@ var root = buildRouteMap({
7918
9102
  get: getRoutes,
7919
9103
  query: queryCommand,
7920
9104
  call: callCommand,
9105
+ overview: overviewCommand,
9106
+ search: searchCommand,
9107
+ related: relatedCommand,
7921
9108
  template: templateCommand,
7922
9109
  logs: logsCommand,
9110
+ check: checkCommand,
9111
+ diagnose: diagnoseCommand,
7923
9112
  upgrade: upgradeCommand
7924
9113
  },
7925
9114
  docs: {
7926
9115
  brief: "Manage Home Assistant instances",
7927
9116
  fullDescription: `Manage Home Assistant instances
7928
9117
 
7929
- hactl works on one context at a time: a Home Assistant instance and how to reach it.
7930
- Set one up first (details in \`hactl ctx --help\`):
9118
+ hactl uses one active connection profile (context) at a time. Create a long-lived access
9119
+ token in your Home Assistant profile, then set up a context (see \`hactl ctx --help\`):
7931
9120
 
7932
9121
  hactl ctx set home --url https://ha.example.ts.net --install haos
7933
9122
  hactl ctx token-set home
7934
9123
  hactl ctx use home
9124
+ hactl ctx verify
7935
9125
 
7936
9126
  Then read with \`hactl get\` and \`hactl query\`, act with \`hactl call\` and see what happened with
7937
- \`hactl logs\`. Try Jinja with \`hactl template\`.
9127
+ \`hactl logs\`. Try Jinja with \`hactl template\`. \`hactl overview\` summarizes the instance,
9128
+ \`hactl search\` finds resources by text and \`hactl related\` shows what refers to one.
9129
+ \`hactl check\` validates YAML without applying it, and \`hactl diagnose\` summarizes instance
9130
+ health or collects details about one target.
7938
9131
 
7939
- \`get\`, \`logs\` and \`template\` only read. Use \`call\` for actions that change the instance.
9132
+ \`get\`, \`overview\`, \`search\`, \`related\`, \`logs\`, \`template\`, \`check\` and \`diagnose\`
9133
+ only read. Use \`call\` for actions that change the instance.
7940
9134
  \`query\` only calls services Home Assistant marks as requiring a response; it relies on the
7941
9135
  integration not to change the instance.
7942
9136
  \`ctx\` and \`upgrade\` change only this machine.
7943
9137
  Every command and group has its own \`--help\` with its behavior, output and examples.
7944
9138
 
7945
- Output is JSON on standard output, except that \`hactl logs\` prints plain text and \`hactl
7946
- template\` prints a text result as it is. Fields without a value are left out.
9139
+ Command results go to standard output as JSON, except that \`hactl logs\` prints plain text
9140
+ and \`hactl template\` prints string results as text. Help and version information are text.
7947
9141
 
7948
9142
  A failure prints nothing on standard output, except that a lost \`hactl logs --follow\` fails
7949
9143
  after the lines it already printed. Standard error starts with a stable code and
7950
9144
  a message, sometimes followed by a \`hint:\` line. The exit code is 252 for bad flags or
7951
9145
  arguments, 251 for an unknown command, and 1 otherwise.
7952
9146
 
9147
+ For headless runs, set HACTL_CONTEXT to an existing context. A non-empty HACTL_TOKEN then
9148
+ replaces the keychain token for that context only. See \`hactl ctx --help\`.
9149
+
7953
9150
  Error codes:
7954
9151
  ${Object.entries(errorMeanings).map(([code, meaning]) => ` ${code.padEnd(23)}${meaning}`).join("\n")}`
7955
9152
  }