@camstack/addon-import-alexa 0.2.192 → 0.2.193

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 (4) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/addon.js +1748 -1414
  3. package/dist/addon.mjs +1749 -1415
  4. package/package.json +2 -2
package/dist/addon.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { createHash, randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
3
  import https from "node:https";
4
4
  import * as fs$1 from "node:fs/promises";
5
5
  import * as path from "node:path";
@@ -6042,7 +6042,7 @@ function number(params) {
6042
6042
  return /* @__PURE__ */ _coercedNumber(ZodNumber, params);
6043
6043
  }
6044
6044
  //#endregion
6045
- //#region ../types/dist/sleep-CmjWurK5.mjs
6045
+ //#region ../types/dist/sleep-CdKka2ri.mjs
6046
6046
  /**
6047
6047
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6048
6048
  * window to float samples (D455).
@@ -6798,6 +6798,13 @@ var DeclarationRefusedError = class extends RecordsError {
6798
6798
  function linkField(target) {
6799
6799
  return string().meta({ link: target });
6800
6800
  }
6801
+ /**
6802
+ * A link that may stay empty (absent): for a link the addon fills itself, or one an instance does not
6803
+ * always need. The meta rides on the optional wrapper, where {@link linksOfKind} reads it.
6804
+ */
6805
+ function optionalLinkField(target) {
6806
+ return string().optional().meta({ link: target });
6807
+ }
6801
6808
  function linkTargetOf(meta) {
6802
6809
  if (typeof meta !== "object" || meta === null) return void 0;
6803
6810
  const link = Reflect.get(meta, "link");
@@ -9589,286 +9596,6 @@ function normalizeAddonInitResult(result) {
9589
9596
  if (Array.isArray(result)) return { providers: result };
9590
9597
  return result;
9591
9598
  }
9592
- /**
9593
- * The share-view scope kinds a share-link token can carry. The hub mints
9594
- * and validates them (`ShareViewGrantSchema` builds its
9595
- * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9596
- */
9597
- var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9598
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9599
- var PeerBytesTicketSchema = object({
9600
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9601
- url: string().min(1),
9602
- /**
9603
- * The HOST node this URL means something on — the hub or a named agent,
9604
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9605
- * refuses `cross-node` by name when they differ, without dialling.
9606
- */
9607
- hostNodeId: string().min(1),
9608
- expiresAtMs: number$1().int().nonnegative(),
9609
- /**
9610
- * What the producer DECLARED the body to be, when it knows — `null` when it
9611
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9612
- * must be able to tell "the producer did not say" from "the body is empty".
9613
- */
9614
- declaredBytes: number$1().int().nonnegative().nullable()
9615
- });
9616
- function defOf(schema) {
9617
- const zodBag = Reflect.get(schema, "_zod");
9618
- if (typeof zodBag !== "object" || zodBag === null) return {};
9619
- const def = Reflect.get(zodBag, "def");
9620
- if (typeof def !== "object" || def === null) return {};
9621
- return def;
9622
- }
9623
- function declaredHere(schema) {
9624
- return globalRegistry.get(schema)?.secret === true;
9625
- }
9626
- /** Wrapper kinds whose `innerType` is the field itself. */
9627
- var WRAPPERS = new Set([
9628
- "optional",
9629
- "nullable",
9630
- "default",
9631
- "prefault",
9632
- "catch",
9633
- "readonly",
9634
- "nonoptional"
9635
- ]);
9636
- /**
9637
- * The schema layers that make up ONE field: the schema itself and every
9638
- * wrapper below it (optional / default / nullable / readonly / catch), plus
9639
- * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9640
- * `.transform` on `in`).
9641
- */
9642
- function layersOf(schema) {
9643
- const out = [];
9644
- const queue = [schema];
9645
- while (queue.length > 0) {
9646
- const s = queue.shift();
9647
- if (!s || out.includes(s)) continue;
9648
- out.push(s);
9649
- const def = defOf(s);
9650
- if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9651
- if (def.type === "pipe") {
9652
- if (def.in) queue.push(def.in);
9653
- if (def.out) queue.push(def.out);
9654
- }
9655
- }
9656
- return out;
9657
- }
9658
- /** True when any layer of this field declares `.meta({ secret: true })`. */
9659
- function isZodSecret(schema) {
9660
- return layersOf(schema).some(declaredHere);
9661
- }
9662
- /**
9663
- * Every declared secret path in a config schema: dotted keys, `[]` for "each
9664
- * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9665
- * map" (`applianceSecrets{}`). A declared
9666
- * object or array is reported as one path and not descended into — everything
9667
- * under it is secret.
9668
- */
9669
- function collectZodSecretPaths(schema, prefix = "") {
9670
- if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9671
- const paths = [];
9672
- for (const layer of layersOf(schema)) {
9673
- const def = defOf(layer);
9674
- if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9675
- else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9676
- else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9677
- else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9678
- else if (def.type === "intersection") {
9679
- if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9680
- if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9681
- }
9682
- }
9683
- return [...new Set(paths)];
9684
- }
9685
- /**
9686
- * Record kinds (D881): the declaration an addon makes of one kind of fact, the
9687
- * Zod row schema that describes it, and the helper that turns the two into the
9688
- * JSON the engine stores.
9689
- *
9690
- * A kind is declared ONCE, next to the code that owns it, and the engine's
9691
- * reconciler creates its indexes - nothing creates DDL at runtime from a write.
9692
- * Everything the generic machinery needs (secret fields, the entry descriptor)
9693
- * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
9694
- * never a field name (D879).
9695
- */
9696
- /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
9697
- var RecordFieldPathSchema = string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
9698
- var RecordIndexSchema = object({
9699
- name: string().regex(/^[a-z][a-z0-9_]{0,31}$/),
9700
- fields: array(RecordFieldPathSchema).min(1).max(4),
9701
- unique: boolean().optional()
9702
- }).strict();
9703
- var RecordRetentionSchema = union([
9704
- object({
9705
- ttlMs: number$1().int().positive(),
9706
- from: _enum(["at", "write"])
9707
- }).strict(),
9708
- object({
9709
- maxRows: number$1().int().positive().optional(),
9710
- maxRowsPerDevice: number$1().int().positive().optional()
9711
- }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
9712
- object({
9713
- owner: string().min(1),
9714
- reason: string().min(1)
9715
- }).strict(),
9716
- object({ none: string().min(1) }).strict()
9717
- ]);
9718
- /** The descriptor a generic entries UI reads (D881 "generic entries"). */
9719
- var EntryDescriptorSchema = object({
9720
- title: string().min(1),
9721
- /** The record body field shown as the entry's name. */
9722
- nameField: string().min(1),
9723
- /** JSON Schema of the entry body; `secret: true` marks a password field. */
9724
- fields: record(string(), unknown())
9725
- }).strict();
9726
- /** What crosses the wire from an addon: JSON only, no Zod. An unknown key is refused. */
9727
- var RecordKindDeclarationSchema = object({
9728
- database: _enum(RECORD_DATABASES).default("settings"),
9729
- class: _enum(RECORD_CLASSES),
9730
- writeTrigger: string().min(1),
9731
- device: _enum([
9732
- "required",
9733
- "optional",
9734
- "none"
9735
- ]).default("none"),
9736
- at: _enum(["required", "none"]).default("none"),
9737
- indexes: array(RecordIndexSchema).max(8).default([]),
9738
- retention: RecordRetentionSchema,
9739
- deviceRemoval: _enum(["delete", "none"]).default("none"),
9740
- maxDataBytes: number$1().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
9741
- /** Derived from the Zod schema; never written by hand. */
9742
- secretPaths: array(string().min(1)).default([]),
9743
- /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
9744
- secretArrayKeys: record(string(), string()).default({}),
9745
- /** Kinds that must agree through `transact` sit in one file under one family name. */
9746
- transactFamily: string().min(1).optional(),
9747
- entry: EntryDescriptorSchema.optional()
9748
- }).strict();
9749
- /** The kind names: lower-case, dash separated, short enough for an index name. */
9750
- var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9751
- /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9752
- function assertValidDeclaration(name, decl) {
9753
- const refuse = (why) => {
9754
- throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9755
- };
9756
- if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9757
- const seen = /* @__PURE__ */ new Set();
9758
- for (const index of decl.indexes) {
9759
- if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9760
- seen.add(index.name);
9761
- }
9762
- const { retention } = decl;
9763
- const hasSecrets = decl.secretPaths.length > 0;
9764
- if ("ttlMs" in retention) {
9765
- if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9766
- if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9767
- }
9768
- if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9769
- if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9770
- if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9771
- if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9772
- const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9773
- if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9774
- }
9775
- if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9776
- for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9777
- }
9778
- function bodyFieldsOf(schema) {
9779
- return { ...toJSONSchema(schema, {
9780
- unrepresentable: "any",
9781
- io: "input"
9782
- }) };
9783
- }
9784
- function isRecordLike(value) {
9785
- return typeof value === "object" && value !== null && !Array.isArray(value);
9786
- }
9787
- /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9788
- function hasNameField(json, field) {
9789
- const branches = json["oneOf"] ?? json["anyOf"];
9790
- if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9791
- const properties = json["properties"];
9792
- return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9793
- }
9794
- /**
9795
- * Declare the kinds of a package. The keys are the kind names. The result is
9796
- * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9797
- * types its handle from.
9798
- */
9799
- function defineRecordKinds(specs) {
9800
- const out = {};
9801
- for (const [name, spec] of Object.entries(specs)) {
9802
- const secretPaths = collectZodSecretPaths(spec.schema);
9803
- const nameField = spec.entry?.nameField ?? "name";
9804
- const fields = bodyFieldsOf(spec.schema);
9805
- if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9806
- const parsed = RecordKindDeclarationSchema.parse({
9807
- database: spec.database,
9808
- class: spec.class,
9809
- writeTrigger: spec.writeTrigger,
9810
- device: spec.device,
9811
- at: spec.at,
9812
- indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9813
- retention: spec.retention,
9814
- deviceRemoval: spec.deviceRemoval,
9815
- maxDataBytes: spec.maxDataBytes,
9816
- secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9817
- secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9818
- transactFamily: spec.transactFamily,
9819
- entry: spec.entry === void 0 ? void 0 : {
9820
- title: spec.entry.title,
9821
- nameField,
9822
- fields
9823
- }
9824
- });
9825
- assertValidDeclaration(name, parsed);
9826
- out[name] = {
9827
- name,
9828
- schema: spec.schema,
9829
- declaration: parsed
9830
- };
9831
- }
9832
- return out;
9833
- }
9834
- /**
9835
- * Entry kinds (D881): every list of user-created entries (notification
9836
- * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
9837
- * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
9838
- * through the `record-entries` capability with password fields derived from
9839
- * the schema (`.meta({ secret: true })`).
9840
- */
9841
- /** The body of a plain entry: a name and the fields the kind adds. */
9842
- function entryBody(shape) {
9843
- return object({
9844
- name: string().min(1),
9845
- enabled: boolean().optional(),
9846
- ...shape
9847
- });
9848
- }
9849
- /**
9850
- * Declare one entry kind. An entry is configuration: never trimmed by the
9851
- * engine, never aged, belonging to no device.
9852
- */
9853
- function defineEntryKind(name, spec) {
9854
- const defined = defineRecordKinds({ [name]: {
9855
- schema: spec.schema,
9856
- class: "config",
9857
- writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9858
- retention: { none: "an entry goes only when the operator deletes it" },
9859
- ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9860
- ...spec.database === void 0 ? {} : { database: spec.database },
9861
- ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9862
- ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9863
- ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9864
- entry: {
9865
- title: spec.title,
9866
- ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9867
- }
9868
- } })[name];
9869
- if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9870
- return defined;
9871
- }
9872
9599
  object({
9873
9600
  field: string().min(1),
9874
9601
  on: literal("advance")
@@ -9961,6 +9688,286 @@ function optionalMethod(input, output, options) {
9961
9688
  function event(data) {
9962
9689
  return { data };
9963
9690
  }
9691
+ function defOf(schema) {
9692
+ const zodBag = Reflect.get(schema, "_zod");
9693
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9694
+ const def = Reflect.get(zodBag, "def");
9695
+ if (typeof def !== "object" || def === null) return {};
9696
+ return def;
9697
+ }
9698
+ function declaredHere(schema) {
9699
+ return globalRegistry.get(schema)?.secret === true;
9700
+ }
9701
+ /** Wrapper kinds whose `innerType` is the field itself. */
9702
+ var WRAPPERS = new Set([
9703
+ "optional",
9704
+ "nullable",
9705
+ "default",
9706
+ "prefault",
9707
+ "catch",
9708
+ "readonly",
9709
+ "nonoptional"
9710
+ ]);
9711
+ /**
9712
+ * The schema layers that make up ONE field: the schema itself and every
9713
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9714
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9715
+ * `.transform` on `in`).
9716
+ */
9717
+ function layersOf(schema) {
9718
+ const out = [];
9719
+ const queue = [schema];
9720
+ while (queue.length > 0) {
9721
+ const s = queue.shift();
9722
+ if (!s || out.includes(s)) continue;
9723
+ out.push(s);
9724
+ const def = defOf(s);
9725
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9726
+ if (def.type === "pipe") {
9727
+ if (def.in) queue.push(def.in);
9728
+ if (def.out) queue.push(def.out);
9729
+ }
9730
+ }
9731
+ return out;
9732
+ }
9733
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9734
+ function isZodSecret(schema) {
9735
+ return layersOf(schema).some(declaredHere);
9736
+ }
9737
+ /**
9738
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9739
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9740
+ * map" (`applianceSecrets{}`). A declared
9741
+ * object or array is reported as one path and not descended into — everything
9742
+ * under it is secret.
9743
+ */
9744
+ function collectZodSecretPaths(schema, prefix = "") {
9745
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9746
+ const paths = [];
9747
+ for (const layer of layersOf(schema)) {
9748
+ const def = defOf(layer);
9749
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9750
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9751
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9752
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9753
+ else if (def.type === "intersection") {
9754
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9755
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9756
+ }
9757
+ }
9758
+ return [...new Set(paths)];
9759
+ }
9760
+ /**
9761
+ * Record kinds (D881): the declaration an addon makes of one kind of fact, the
9762
+ * Zod row schema that describes it, and the helper that turns the two into the
9763
+ * JSON the engine stores.
9764
+ *
9765
+ * A kind is declared ONCE, next to the code that owns it, and the engine's
9766
+ * reconciler creates its indexes - nothing creates DDL at runtime from a write.
9767
+ * Everything the generic machinery needs (secret fields, the entry descriptor)
9768
+ * is DERIVED from the Zod schema: `.meta({ secret: true })` marks a credential,
9769
+ * never a field name (D879).
9770
+ */
9771
+ /** A JSON field path: `trackId`, `auth.accessToken`. Charset-restricted: it is rendered into DDL. */
9772
+ var RecordFieldPathSchema = string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}(\.[A-Za-z_][A-Za-z0-9_]{0,63}){0,3}$/);
9773
+ var RecordIndexSchema = object({
9774
+ name: string().regex(/^[a-z][a-z0-9_]{0,31}$/),
9775
+ fields: array(RecordFieldPathSchema).min(1).max(4),
9776
+ unique: boolean().optional()
9777
+ }).strict();
9778
+ var RecordRetentionSchema = union([
9779
+ object({
9780
+ ttlMs: number$1().int().positive(),
9781
+ from: _enum(["at", "write"])
9782
+ }).strict(),
9783
+ object({
9784
+ maxRows: number$1().int().positive().optional(),
9785
+ maxRowsPerDevice: number$1().int().positive().optional()
9786
+ }).strict().refine((r) => r.maxRows !== void 0 || r.maxRowsPerDevice !== void 0, { message: "name maxRows, maxRowsPerDevice or both" }),
9787
+ object({
9788
+ owner: string().min(1),
9789
+ reason: string().min(1)
9790
+ }).strict(),
9791
+ object({ none: string().min(1) }).strict()
9792
+ ]);
9793
+ /** The descriptor a generic entries UI reads (D881 "generic entries"). */
9794
+ var EntryDescriptorSchema = object({
9795
+ title: string().min(1),
9796
+ /** The record body field shown as the entry's name. */
9797
+ nameField: string().min(1),
9798
+ /** JSON Schema of the entry body; `secret: true` marks a password field. */
9799
+ fields: record(string(), unknown())
9800
+ }).strict();
9801
+ /** What crosses the wire from an addon: JSON only, no Zod. An unknown key is refused. */
9802
+ var RecordKindDeclarationSchema = object({
9803
+ database: _enum(RECORD_DATABASES).default("settings"),
9804
+ class: _enum(RECORD_CLASSES),
9805
+ writeTrigger: string().min(1),
9806
+ device: _enum([
9807
+ "required",
9808
+ "optional",
9809
+ "none"
9810
+ ]).default("none"),
9811
+ at: _enum(["required", "none"]).default("none"),
9812
+ indexes: array(RecordIndexSchema).max(8).default([]),
9813
+ retention: RecordRetentionSchema,
9814
+ deviceRemoval: _enum(["delete", "none"]).default("none"),
9815
+ maxDataBytes: number$1().int().positive().max(RECORD_MAX_DATA_BYTES).default(RECORD_DEFAULT_MAX_DATA_BYTES),
9816
+ /** Derived from the Zod schema; never written by hand. */
9817
+ secretPaths: array(string().min(1)).default([]),
9818
+ /** The id key of each array that carries a secret (`{ headers: 'name' }`). */
9819
+ secretArrayKeys: record(string(), string()).default({}),
9820
+ /** Kinds that must agree through `transact` sit in one file under one family name. */
9821
+ transactFamily: string().min(1).optional(),
9822
+ entry: EntryDescriptorSchema.optional()
9823
+ }).strict();
9824
+ /** The kind names: lower-case, dash separated, short enough for an index name. */
9825
+ var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9826
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9827
+ function assertValidDeclaration(name, decl) {
9828
+ const refuse = (why) => {
9829
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9830
+ };
9831
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9832
+ const seen = /* @__PURE__ */ new Set();
9833
+ for (const index of decl.indexes) {
9834
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9835
+ seen.add(index.name);
9836
+ }
9837
+ const { retention } = decl;
9838
+ const hasSecrets = decl.secretPaths.length > 0;
9839
+ if ("ttlMs" in retention) {
9840
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9841
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9842
+ }
9843
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9844
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9845
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9846
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9847
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9848
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9849
+ }
9850
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9851
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9852
+ }
9853
+ function bodyFieldsOf(schema) {
9854
+ return { ...toJSONSchema(schema, {
9855
+ unrepresentable: "any",
9856
+ io: "input"
9857
+ }) };
9858
+ }
9859
+ function isRecordLike(value) {
9860
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9861
+ }
9862
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9863
+ function hasNameField(json, field) {
9864
+ const branches = json["oneOf"] ?? json["anyOf"];
9865
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9866
+ const properties = json["properties"];
9867
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9868
+ }
9869
+ /**
9870
+ * Declare the kinds of a package. The keys are the kind names. The result is
9871
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9872
+ * types its handle from.
9873
+ */
9874
+ function defineRecordKinds(specs) {
9875
+ const out = {};
9876
+ for (const [name, spec] of Object.entries(specs)) {
9877
+ const secretPaths = collectZodSecretPaths(spec.schema);
9878
+ const nameField = spec.entry?.nameField ?? "name";
9879
+ const fields = bodyFieldsOf(spec.schema);
9880
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9881
+ const parsed = RecordKindDeclarationSchema.parse({
9882
+ database: spec.database,
9883
+ class: spec.class,
9884
+ writeTrigger: spec.writeTrigger,
9885
+ device: spec.device,
9886
+ at: spec.at,
9887
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9888
+ retention: spec.retention,
9889
+ deviceRemoval: spec.deviceRemoval,
9890
+ maxDataBytes: spec.maxDataBytes,
9891
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9892
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9893
+ transactFamily: spec.transactFamily,
9894
+ entry: spec.entry === void 0 ? void 0 : {
9895
+ title: spec.entry.title,
9896
+ nameField,
9897
+ fields
9898
+ }
9899
+ });
9900
+ assertValidDeclaration(name, parsed);
9901
+ out[name] = {
9902
+ name,
9903
+ schema: spec.schema,
9904
+ declaration: parsed
9905
+ };
9906
+ }
9907
+ return out;
9908
+ }
9909
+ /**
9910
+ * Entry kinds (D881): every list of user-created entries (notification
9911
+ * targets, brokers, LLM profiles) is ONE record kind with an id, a name and a
9912
+ * kind-specific body, and the admin UI lists/adds/edits/deletes all of them
9913
+ * through the `record-entries` capability with password fields derived from
9914
+ * the schema (`.meta({ secret: true })`).
9915
+ */
9916
+ /** The body of a plain entry: a name and the fields the kind adds. */
9917
+ function entryBody(shape) {
9918
+ return object({
9919
+ name: string().min(1),
9920
+ enabled: boolean().optional(),
9921
+ ...shape
9922
+ });
9923
+ }
9924
+ /**
9925
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9926
+ * engine, never aged, belonging to no device.
9927
+ */
9928
+ function defineEntryKind(name, spec) {
9929
+ const defined = defineRecordKinds({ [name]: {
9930
+ schema: spec.schema,
9931
+ class: "config",
9932
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9933
+ retention: { none: "an entry goes only when the operator deletes it" },
9934
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9935
+ ...spec.database === void 0 ? {} : { database: spec.database },
9936
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9937
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9938
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9939
+ entry: {
9940
+ title: spec.title,
9941
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9942
+ }
9943
+ } })[name];
9944
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9945
+ return defined;
9946
+ }
9947
+ /**
9948
+ * The share-view scope kinds a share-link token can carry. The hub mints
9949
+ * and validates them (`ShareViewGrantSchema` builds its
9950
+ * enum from this list); a data plane names the kinds it ACCEPTS in `share`.
9951
+ */
9952
+ var SHARE_VIEW_KINDS = ["grid-view", "events-view"];
9953
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
9954
+ var PeerBytesTicketSchema = object({
9955
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
9956
+ url: string().min(1),
9957
+ /**
9958
+ * The HOST node this URL means something on — the hub or a named agent,
9959
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
9960
+ * refuses `cross-node` by name when they differ, without dialling.
9961
+ */
9962
+ hostNodeId: string().min(1),
9963
+ expiresAtMs: number$1().int().nonnegative(),
9964
+ /**
9965
+ * What the producer DECLARED the body to be, when it knows — `null` when it
9966
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
9967
+ * must be able to tell "the producer did not say" from "the body is empty".
9968
+ */
9969
+ declaredBytes: number$1().int().nonnegative().nullable()
9970
+ });
9964
9971
  var READING_QUANTITIES = [
9965
9972
  "temperature",
9966
9973
  "pressure",
@@ -10539,7 +10546,6 @@ var CAP_NAMES = Object.freeze([
10539
10546
  "climate-control",
10540
10547
  "color",
10541
10548
  "composer",
10542
- "connection-test",
10543
10549
  "connectivity",
10544
10550
  "consumables",
10545
10551
  "contact",
@@ -12559,8 +12565,7 @@ Object.freeze({
12559
12565
  "offerArtifact": 3e5,
12560
12566
  "readResult": 3e5,
12561
12567
  "submitJob": 18e5,
12562
- "uploadDataset": 72e5,
12563
- "validateCredentials": 3e4
12568
+ "uploadDataset": 72e5
12564
12569
  }
12565
12570
  });
12566
12571
  object({
@@ -14061,6 +14066,17 @@ function composeInstanceKinds(parts, base) {
14061
14066
  if (part === void 0) throw new UnknownInstanceKindError(kindId);
14062
14067
  return part;
14063
14068
  };
14069
+ /**
14070
+ * The part a DRAFT test runs on. A named kind is that kind; an unnamed one is the provider's only
14071
+ * testable kind. Several testable kinds and none named is a typed refusal that lists them, never a throw.
14072
+ */
14073
+ const draftPart = (kindId) => {
14074
+ if (kindId !== void 0) return parts.find((candidate) => candidate.kind.id === kindId) ?? { error: `Unknown instance kind '${kindId}'` };
14075
+ const testable = parts.filter((part) => part.kind.canTest !== false);
14076
+ const only = testable.length === 1 ? testable[0] : parts.length === 1 ? parts[0] : void 0;
14077
+ if (only !== void 0) return only;
14078
+ return { error: `This provider has several kinds: name one of ${(testable.length > 0 ? testable : parts).map((part) => part.kind.id).join(", ")}` };
14079
+ };
14064
14080
  const holderOf = async (id) => {
14065
14081
  for (const part of parts) if (await part.provider.getInstance({ id }) !== null) return part;
14066
14082
  throw new UnknownInstanceError(id);
@@ -14096,7 +14112,13 @@ function composeInstanceKinds(parts, base) {
14096
14112
  setInstanceEnabled: async (input) => (await holderOf(input.id)).provider.setInstanceEnabled(input),
14097
14113
  deleteInstance: async (input) => (await holderOf(input.id)).provider.deleteInstance(input),
14098
14114
  testInstance: async (input) => {
14099
- const test = (input.id === null ? byKind(input.kind) : await holderOf(input.id)).provider.testInstance;
14115
+ const resolved = input.id === null ? draftPart(input.kind) : await holderOf(input.id);
14116
+ if ("error" in resolved) return {
14117
+ success: false,
14118
+ status: "inconclusive",
14119
+ error: resolved.error
14120
+ };
14121
+ const test = resolved.provider.testInstance;
14100
14122
  if (test === void 0) return {
14101
14123
  success: false,
14102
14124
  status: "inconclusive",
@@ -14106,6 +14128,745 @@ function composeInstanceKinds(parts, base) {
14106
14128
  }
14107
14129
  };
14108
14130
  }
14131
+ /**
14132
+ * notification-output — canonical, capability-gated notification delivery.
14133
+ *
14134
+ * Apprise-derived model (see
14135
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
14136
+ * callers emit ONE canonical `Notification`; each provider declares a
14137
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
14138
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
14139
+ * message to what the kind supports — callers never special-case a service.
14140
+ *
14141
+ * DESIGN DECISIONS (locked):
14142
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
14143
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
14144
+ * cap. Rationale: the admin UI needs one uniform surface across the
14145
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
14146
+ * alternative would fork the UI per addon and cannot host the
14147
+ * discovery→adopt flow.
14148
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
14149
+ * the generated cap-mount auto-`concatCollection`-fans them across every
14150
+ * registered provider (notifiers addon + HA addon) so one catalog is
14151
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
14152
+ * `addonId` the generated collection router extracts from the call input.
14153
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
14154
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
14155
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
14156
+ * base64 fallback needed.
14157
+ *
14158
+ * TODO (deferred, closed-set change — separate decision): add
14159
+ * `providerKind: 'notify'` so notification providers surface on the unified
14160
+ * admin "Integrations" page.
14161
+ */
14162
+ /**
14163
+ * Zentik-derived typed-media enum — the superset across every kind. Each
14164
+ * adapter picks what it supports and the degrade engine filters the rest.
14165
+ */
14166
+ var AttachmentMediaTypeSchema = _enum([
14167
+ "image",
14168
+ "video",
14169
+ "gif",
14170
+ "audio",
14171
+ "icon"
14172
+ ]);
14173
+ /**
14174
+ * A single attachment. Exactly one of `url` (remote source, most adapters
14175
+ * prefer this) or `bytes` (inline source; required for Pushover-style
14176
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
14177
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
14178
+ */
14179
+ var AttachmentSchema = object({
14180
+ mediaType: AttachmentMediaTypeSchema,
14181
+ url: string().optional(),
14182
+ bytes: _instanceof(Uint8Array).optional(),
14183
+ mime: string().optional(),
14184
+ name: string().optional()
14185
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
14186
+ var NotificationFormatSchema = _enum([
14187
+ "text",
14188
+ "markdown",
14189
+ "html"
14190
+ ]);
14191
+ /**
14192
+ * The CLOSED icon vocabulary an action button may use.
14193
+ *
14194
+ * A closed set, not a free string, and that is the whole point: an arbitrary
14195
+ * icon name is one that ntfy renders, zentik silently drops, and nobody
14196
+ * notices — the same class of gap as a zone vocabulary nothing produced
14197
+ * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
14198
+ * declares `actionIcons: false` and the degrade engine strips the field.
14199
+ *
14200
+ * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
14201
+ * renderer's icon set; "acknowledge" survives an adapter that draws it
14202
+ * differently.
14203
+ *
14204
+ * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
14205
+ *
14206
+ * These names are for US. **No adapter may forward one verbatim.** Each maps
14207
+ * the whole set onto its own renderer's vocabulary through a
14208
+ * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
14209
+ * fallback, so adding a member here fails every adapter's build until someone
14210
+ * decides its glyph, which is the only place that decision can be made
14211
+ * honestly.
14212
+ *
14213
+ * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
14214
+ * `disarm` straight through; iOS feeds that string to
14215
+ * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
14216
+ * and every snooze and alarm button arrived BLANK. A pass-through is not a
14217
+ * mapping, and "the field is documented" is not "the value renders".
14218
+ *
14219
+ * Adding a member is TRAIN-BOUND. The enum lives in the published
14220
+ * `@camstack/server` closure and the cap seam validates against the HUB's copy,
14221
+ * so an addon that emits a token the running hub does not know does not lose an
14222
+ * icon — its whole `send` fails Zod validation and the notification never
14223
+ * arrives. Never emit a new token from an addon before the train carrying it.
14224
+ */
14225
+ var NotificationActionIconSchema = _enum([
14226
+ "acknowledge",
14227
+ "dismiss",
14228
+ "silence",
14229
+ "snooze",
14230
+ "view",
14231
+ "play",
14232
+ "open",
14233
+ "close",
14234
+ "lock",
14235
+ "unlock",
14236
+ "arm",
14237
+ "arm-home",
14238
+ "arm-away",
14239
+ "arm-night",
14240
+ "disarm",
14241
+ "light",
14242
+ "alert",
14243
+ "camera"
14244
+ ]);
14245
+ /** A single tap-through action button. */
14246
+ var NotificationActionSchema = object({
14247
+ id: string(),
14248
+ label: string(),
14249
+ url: string().optional(),
14250
+ /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
14251
+ icon: NotificationActionIconSchema.optional(),
14252
+ /**
14253
+ * Renders in a warning style where the notifier supports it.
14254
+ *
14255
+ * A HINT, never a gate. The callback's authority is its token and nothing
14256
+ * else — see `notification-center/action-token.ts` for what that does and
14257
+ * does not buy.
14258
+ */
14259
+ destructive: boolean().optional(),
14260
+ /**
14261
+ * How the tap should REACH the url.
14262
+ *
14263
+ * `navigate` (absent, and every button authored before this field) opens it:
14264
+ * the phone leaves the notification and shows whatever the callback returns.
14265
+ * That is right for a button whose answer the operator wants to read.
14266
+ *
14267
+ * `background` fires it as a POST and stays put. It exists for the buttons
14268
+ * whose whole point is not to interrupt — "silence this for 30 minutes" is
14269
+ * an answer to the notification, and being thrown into a browser tab to
14270
+ * confirm it costs more attention than the notification did. A backend that
14271
+ * cannot do a background call renders it as an ordinary link (the adapters
14272
+ * fall back rather than dropping the button), so this is a preference, never
14273
+ * a requirement.
14274
+ */
14275
+ mode: _enum(["navigate", "background"]).optional()
14276
+ });
14277
+ /** A delivery parameter value: what a notifier declared it takes. */
14278
+ var DeliveryParamValueSchema = union([
14279
+ string(),
14280
+ number$1(),
14281
+ boolean()
14282
+ ]);
14283
+ /**
14284
+ * One extra delivery parameter a notifier KIND declares (D938). A rule that
14285
+ * addresses a target of that kind may set it; a kind that declares nothing is
14286
+ * never handed one. The admin UI derives its control from this descriptor —
14287
+ * no editor knows a service by name.
14288
+ *
14289
+ * Optional fields are `.optional()`, never `.default()` (a Zod default does not
14290
+ * run on the addon cap path).
14291
+ */
14292
+ var DeliveryParamSchema = object({
14293
+ key: string().min(1),
14294
+ label: string(),
14295
+ /** i18n key of the label, resolved by the declaring addon's namespace. */
14296
+ labelKey: string().optional(),
14297
+ type: _enum([
14298
+ "enum",
14299
+ "number",
14300
+ "boolean",
14301
+ "string"
14302
+ ]),
14303
+ /** `enum` only: the closed set of accepted values. */
14304
+ options: array(object({
14305
+ value: string(),
14306
+ label: string()
14307
+ })).optional(),
14308
+ /** `number` only. */
14309
+ min: number$1().optional(),
14310
+ max: number$1().optional(),
14311
+ /** What the notifier does when the rule sets nothing; shown as the placeholder. */
14312
+ default: DeliveryParamValueSchema.optional()
14313
+ });
14314
+ /**
14315
+ * The canonical notification. `body` is the only hard field (Apprise model).
14316
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
14317
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
14318
+ * the adapter maps this ordinal onto its native level. `level?` is an
14319
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
14320
+ * `priority` for that one target.
14321
+ */
14322
+ var NotificationSchema = object({
14323
+ body: string(),
14324
+ title: string().optional(),
14325
+ format: NotificationFormatSchema.default("text"),
14326
+ priority: number$1().int().min(1).max(5).default(3),
14327
+ level: string().optional(),
14328
+ attachments: array(AttachmentSchema).optional(),
14329
+ clickUrl: string().optional(),
14330
+ actions: array(NotificationActionSchema).optional(),
14331
+ sound: string().optional(),
14332
+ ttl: number$1().optional(),
14333
+ tag: string().optional(),
14334
+ deviceId: number$1().optional(),
14335
+ eventId: string().optional(),
14336
+ metadata: record(string(), unknown()).optional(),
14337
+ /**
14338
+ * Values for the parameters the target's kind DECLARES in
14339
+ * {@link TargetKindSchema} `deliveryParams`. Already validated against the
14340
+ * declaration by the sender; a notifier reads only the keys it declared.
14341
+ */
14342
+ delivery: record(string(), DeliveryParamValueSchema).optional()
14343
+ });
14344
+ /** One declared native severity/priority level for a kind. */
14345
+ var TargetKindLevelSchema = object({
14346
+ id: string(),
14347
+ label: string(),
14348
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
14349
+ ordinal: number$1().int().min(1).max(5).nullable(),
14350
+ flags: object({
14351
+ critical: boolean().optional(),
14352
+ silent: boolean().optional(),
14353
+ noPush: boolean().optional()
14354
+ }).optional(),
14355
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
14356
+ requires: array(string()).optional(),
14357
+ description: string().optional()
14358
+ });
14359
+ /** The full capability block consulted before dispatch. */
14360
+ var TargetKindCapsSchema = object({
14361
+ attachments: object({
14362
+ mediaTypes: array(AttachmentMediaTypeSchema),
14363
+ mode: _enum([
14364
+ "url",
14365
+ "bytes",
14366
+ "both"
14367
+ ]),
14368
+ max: number$1().int().nonnegative(),
14369
+ maxBytes: number$1().int().positive().optional()
14370
+ }),
14371
+ /** Max action buttons (0 = none). */
14372
+ actions: number$1().int().nonnegative(),
14373
+ /**
14374
+ * Whether this kind renders a per-action ICON.
14375
+ *
14376
+ * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
14377
+ * run on the addon cap path — three production failures in one day taught
14378
+ * this repo that once. Absent is read as false by the degrade engine, which
14379
+ * is the safe direction: an icon that is not rendered costs nothing, an icon
14380
+ * assumed and dropped costs the operator's trust in the field.
14381
+ */
14382
+ actionIcons: boolean().optional(),
14383
+ levels: array(TargetKindLevelSchema),
14384
+ format: array(NotificationFormatSchema),
14385
+ clickUrl: boolean(),
14386
+ sound: boolean(),
14387
+ ttl: boolean(),
14388
+ bodyMaxLen: number$1().int().positive()
14389
+ });
14390
+ /**
14391
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
14392
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
14393
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
14394
+ * the union is large and not meant for runtime validation here; the exported
14395
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
14396
+ */
14397
+ var ConfigSchemaPassthrough$4 = unknown();
14398
+ var TargetKindSchema = object({
14399
+ kind: string(),
14400
+ label: string(),
14401
+ icon: string(),
14402
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
14403
+ addonId: string(),
14404
+ /**
14405
+ * URL of the kind's bundled BRAND icon, served by the providing addon over
14406
+ * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
14407
+ * when the addon bundles no icon for that kind — the client then falls back
14408
+ * to a neutral glyph rather than rendering the raw `icon` NAME as text.
14409
+ *
14410
+ * Root-relative on purpose: it resolves against whatever origin serves a web
14411
+ * client, and a native client joins it onto its own hub base.
14412
+ *
14413
+ * DECLARED here deliberately. It used to travel as an undeclared passthrough
14414
+ * field that survived only because the runtime cap-router forwards provider
14415
+ * output verbatim — so every consumer had to re-declare it by hand to stop
14416
+ * its own Zod parse from stripping it, and the whole arrangement would have
14417
+ * broken silently the moment output validation was tightened anywhere.
14418
+ */
14419
+ iconUrl: string().optional(),
14420
+ /**
14421
+ * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
14422
+ *
14423
+ * The server knows this and therefore says it, because the client cannot
14424
+ * safely guess: a React-Native client renders SVG and raster through two
14425
+ * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
14426
+ * not decode SVG on iOS/Android), so without this it silently fell back to a
14427
+ * placeholder glyph for every vector icon while the web build looked fine.
14428
+ *
14429
+ * Absent when {@link iconUrl} is absent, or for a legacy provider that has
14430
+ * not been updated — a client that cannot determine the type should prefer
14431
+ * its raster path, which is the safe default for an unknown image.
14432
+ */
14433
+ iconMediaType: string().optional(),
14434
+ configSchema: ConfigSchemaPassthrough$4,
14435
+ /**
14436
+ * The config keys that decide WHERE this kind's secrets are sent (server,
14437
+ * base URL, instance, chat, recipient). A save that changes any of them
14438
+ * while leaving a secret redacted is refused by the provider (D634), so an
14439
+ * editor uses this to ask for the secret on exactly those edits instead of
14440
+ * on every edit.
14441
+ *
14442
+ * Optional: absent from a provider that holds no secret (the Home Assistant
14443
+ * kinds) and from a provider older than this field — an editor that finds
14444
+ * it absent must assume ANY edit may need the secret.
14445
+ */
14446
+ destinationKeys: array(string()).optional(),
14447
+ supportsDiscovery: boolean(),
14448
+ /**
14449
+ * Extra delivery parameters a rule may set for a target of this kind (D938).
14450
+ * Absent = none; the rule editor then offers nothing.
14451
+ */
14452
+ deliveryParams: array(DeliveryParamSchema).optional(),
14453
+ caps: TargetKindCapsSchema
14454
+ });
14455
+ /**
14456
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
14457
+ * (return a presence marker only) when serving `listTargets` — never
14458
+ * round-trip a stored secret to the UI.
14459
+ */
14460
+ var TargetSchema = object({
14461
+ id: string(),
14462
+ name: string(),
14463
+ kind: string(),
14464
+ addonId: string(),
14465
+ enabled: boolean(),
14466
+ config: record(string(), unknown())
14467
+ });
14468
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
14469
+ var DiscoveredTargetSchema = object({
14470
+ kind: string(),
14471
+ suggestedName: string(),
14472
+ config: record(string(), unknown())
14473
+ });
14474
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
14475
+ var RenderedAsSchema = object({
14476
+ level: string(),
14477
+ format: NotificationFormatSchema,
14478
+ attachmentsSent: number$1().int().nonnegative(),
14479
+ actionsSent: number$1().int().nonnegative(),
14480
+ truncated: boolean(),
14481
+ dropped: array(string())
14482
+ });
14483
+ var SendResultSchema = object({
14484
+ success: boolean(),
14485
+ error: string().optional(),
14486
+ renderedAs: RenderedAsSchema.optional()
14487
+ });
14488
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
14489
+ var TestResultSchema = SendResultSchema;
14490
+ /**
14491
+ * Pre-save credential probe against a partial (unsaved) target config.
14492
+ * `resolvedUrl` never includes secrets (token stripped from path).
14493
+ */
14494
+ var ProbeTargetConfigResultSchema = object({
14495
+ ok: boolean(),
14496
+ resolvedUrl: string(),
14497
+ httpStatus: number$1().int().optional(),
14498
+ stateInstance: string().optional(),
14499
+ error: string().optional()
14500
+ });
14501
+ var notificationOutputCapability = {
14502
+ name: "notification-output",
14503
+ scope: "system",
14504
+ mode: "collection",
14505
+ methods: {
14506
+ listTargetKinds: method(object({}), array(TargetKindSchema)),
14507
+ listTargets: method(object({}), array(TargetSchema), { auth: "admin" }),
14508
+ /**
14509
+ * One target WITH secrets — admin edit / duplicate hydration only.
14510
+ * `listTargets` stays redacted; the editor loads this so password fields
14511
+ * are filled (masked in the input) and a save can round-trip the token
14512
+ * when a destination changes (Duplicate with a new chatId, etc.).
14513
+ */
14514
+ getTarget: method(object({ targetId: string() }), TargetSchema, { auth: "admin" }),
14515
+ discoverTargets: method(object({
14516
+ kind: string(),
14517
+ config: record(string(), unknown()).optional(),
14518
+ /**
14519
+ * When editing / duplicating, the blank password field never round-trips
14520
+ * the stored token. Pass the source target id so the provider can restore
14521
+ * secrets server-side before dialling (same merge as upsert).
14522
+ */
14523
+ targetId: string().optional()
14524
+ }), array(DiscoveredTargetSchema), { auth: "admin" }),
14525
+ probeTargetConfig: method(object({
14526
+ kind: string(),
14527
+ config: record(string(), unknown()),
14528
+ /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
14529
+ targetId: string().optional()
14530
+ }), ProbeTargetConfigResultSchema, {
14531
+ kind: "mutation",
14532
+ auth: "admin"
14533
+ }),
14534
+ send: method(object({
14535
+ targetId: string(),
14536
+ notification: NotificationSchema
14537
+ }), SendResultSchema, {
14538
+ kind: "mutation",
14539
+ auth: "admin"
14540
+ }),
14541
+ testTarget: method(object({
14542
+ targetId: string(),
14543
+ sample: NotificationSchema.optional()
14544
+ }), TestResultSchema, {
14545
+ kind: "mutation",
14546
+ auth: "admin"
14547
+ }),
14548
+ upsertTarget: method(object({
14549
+ target: TargetSchema,
14550
+ /**
14551
+ * Duplicate flow: create a NEW target id while copying secrets from an
14552
+ * existing row. The UI never holds the stored token; blank / redacted
14553
+ * password fields are restored from this source (D634 still applies if
14554
+ * destinations diverge without a re-typed secret).
14555
+ */
14556
+ cloneSecretsFrom: string().optional()
14557
+ }), TargetSchema, {
14558
+ kind: "mutation",
14559
+ auth: "admin"
14560
+ }),
14561
+ deleteTarget: method(object({ targetId: string() }), _void(), {
14562
+ kind: "mutation",
14563
+ auth: "admin"
14564
+ }),
14565
+ setTargetEnabled: method(object({
14566
+ targetId: string(),
14567
+ enabled: boolean()
14568
+ }), _void(), {
14569
+ kind: "mutation",
14570
+ auth: "admin"
14571
+ })
14572
+ }
14573
+ };
14574
+ /**
14575
+ * Notification targets as instances of the function cap `notification-output` (epic #440, step 6).
14576
+ *
14577
+ * A notification target used to be one row of one record kind (`{ name, kind, addonId, enabled,
14578
+ * config }`) with a free-form `config` blob whose secrets nobody could name. Now every target KIND
14579
+ * the provider offers (ntfy, telegram, webhook, ...) is a record kind of its own whose flat body IS
14580
+ * that kind's form: the adapter's `configSchema` lifted into a Zod object, a `password` field marked
14581
+ * `.meta({ secret: true })` so the records door keeps it in the keychain, an `instance-select` field
14582
+ * declared as a link so the hub refuses to delete what a target points at.
14583
+ *
14584
+ * Three providers (notifiers, Home Assistant, Alexa) serve the same shape, so the pieces are shared:
14585
+ * - {@link defineNotificationTargetKind}: the record kind of one `TargetKind` descriptor;
14586
+ * - {@link NotificationTargetStore}: the `Target`-shaped facade the existing provider code keeps
14587
+ * using, over one handle per kind (the old `notification-output` CRUD keeps working on it);
14588
+ * - {@link buildNotificationTargetInstances}: the `integration-instances` provider, one kind each;
14589
+ * - {@link moveTargetRows}: the D987 procedure that flattens the old `config` blobs into the bodies.
14590
+ */
14591
+ /** The function cap every notification target is an instance of. */
14592
+ var NOTIFICATION_OUTPUT_CAP = "notification-output";
14593
+ /** The most targets one provider lists (a settings page, not a table). */
14594
+ var TARGETS_LIST_MAX = 1e3;
14595
+ /** The record kind name of one target kind: `telegram` is stored under `notify-telegram`. */
14596
+ function notificationTargetKindName(kind) {
14597
+ return `notify-${kind}`;
14598
+ }
14599
+ /** The body schema of a target kind: the entry's name and switch plus the adapter's fields. */
14600
+ var TargetBodyBaseSchema = looseObject({
14601
+ name: string().min(1),
14602
+ enabled: boolean().optional()
14603
+ });
14604
+ /** The shape of one `editable-array` row: the item fields, a `password` one a secret. */
14605
+ function rowSchemaOf(itemFields) {
14606
+ const shape = {};
14607
+ let idKey = null;
14608
+ let hasSecret = false;
14609
+ for (const item of itemFields) {
14610
+ if (item.type === "password") {
14611
+ shape[item.key] = string().optional().meta({ secret: true });
14612
+ hasSecret = true;
14613
+ continue;
14614
+ }
14615
+ shape[item.key] = unknown().optional();
14616
+ idKey ??= item.key;
14617
+ }
14618
+ return {
14619
+ row: looseObject(shape),
14620
+ idKey,
14621
+ hasSecret
14622
+ };
14623
+ }
14624
+ /**
14625
+ * The Zod fields of a descriptor's form. A `password` field is a secret; an `instance-select` field is
14626
+ * a link to an instance of its function cap; an `editable-array` keeps its rows (a password inside a
14627
+ * row is a secret matched by the row's first plain field); every other field keeps whatever the
14628
+ * adapter's own parse accepts, because the form already validated its shape. The body is loose, so a key
14629
+ * the schema does not know (the owner of a personal target) survives a write.
14630
+ */
14631
+ function fieldsOf(descriptor) {
14632
+ const shape = {};
14633
+ const secretArrayKeys = {};
14634
+ for (const section of descriptor.configSchema.sections) for (const field of section.fields) switch (field.type) {
14635
+ case "info": break;
14636
+ case "password":
14637
+ shape[field.key] = string().optional().meta({ secret: true });
14638
+ break;
14639
+ case "instance-select":
14640
+ shape[field.key] = optionalLinkField({
14641
+ cap: field.functionCap,
14642
+ ...field.kind !== void 0 ? { kind: field.kind } : {}
14643
+ });
14644
+ break;
14645
+ case "editable-array": {
14646
+ const { row, idKey, hasSecret } = rowSchemaOf(field.itemFields);
14647
+ shape[field.key] = array(row).optional();
14648
+ if (hasSecret && idKey !== null) secretArrayKeys[field.key] = idKey;
14649
+ break;
14650
+ }
14651
+ default: shape[field.key] = unknown().optional();
14652
+ }
14653
+ return {
14654
+ shape,
14655
+ secretArrayKeys
14656
+ };
14657
+ }
14658
+ /** The record kind of one target kind, derived from its descriptor. */
14659
+ function defineNotificationTargetKind(descriptor) {
14660
+ const { shape, secretArrayKeys } = fieldsOf(descriptor);
14661
+ return defineEntryKind(notificationTargetKindName(descriptor.kind), {
14662
+ title: `${descriptor.label} notification targets`,
14663
+ schema: TargetBodyBaseSchema.extend(shape),
14664
+ writeTrigger: `an operator adds, edits, switches or removes a ${descriptor.label} notification target`,
14665
+ ...Object.keys(secretArrayKeys).length > 0 ? { secretArrayKeys } : {}
14666
+ });
14667
+ }
14668
+ /** The record kinds of a provider's descriptors, keyed by the record kind name (for `records.declare`). */
14669
+ function notificationTargetKinds(descriptors) {
14670
+ return Object.fromEntries(descriptors.map((descriptor) => {
14671
+ const defined = defineNotificationTargetKind(descriptor);
14672
+ return [defined.name, defined];
14673
+ }));
14674
+ }
14675
+ /** The body a stored target becomes: the switch and the name, and the config fields flat beside them. */
14676
+ function targetBody(target) {
14677
+ return {
14678
+ ...target.config,
14679
+ name: target.name.length > 0 ? target.name : target.id,
14680
+ enabled: target.enabled
14681
+ };
14682
+ }
14683
+ /** The `Target` a record of a kind is; null when the row is not a target. */
14684
+ function targetOfRecord(addonId, kind, id, data) {
14685
+ const { name, enabled: _enabled, ...config } = data;
14686
+ const parsed = TargetSchema.safeParse({
14687
+ id,
14688
+ name,
14689
+ kind,
14690
+ addonId,
14691
+ enabled: isInstanceEnabled(data),
14692
+ config
14693
+ });
14694
+ return parsed.success ? parsed.data : null;
14695
+ }
14696
+ function targetOfOld(addonId, row) {
14697
+ return {
14698
+ id: row.id,
14699
+ name: row.name,
14700
+ kind: row.kind,
14701
+ addonId,
14702
+ enabled: row.enabled,
14703
+ config: { ...row.config }
14704
+ };
14705
+ }
14706
+ /**
14707
+ * The `Target`-shaped facade over one record kind per target kind. `list` returns the stored form (a
14708
+ * secret is a keychain marker: every reader redacts it anyway); `getById` returns the target with its
14709
+ * secrets resolved, which is what a send, a probe and an edit's secret merge need. A keychain that
14710
+ * cannot answer throws: a write never goes ahead with a secret it could not read (D49).
14711
+ */
14712
+ var NotificationTargetStore = class NotificationTargetStore {
14713
+ addonId;
14714
+ handles;
14715
+ options;
14716
+ constructor(addonId, handles, options) {
14717
+ this.addonId = addonId;
14718
+ this.handles = handles;
14719
+ this.options = options;
14720
+ }
14721
+ static of(records, addonId, kinds, descriptors, options = {}) {
14722
+ const handles = [];
14723
+ for (const descriptor of descriptors) {
14724
+ const defined = kinds[notificationTargetKindName(descriptor.kind)];
14725
+ if (defined === void 0) continue;
14726
+ handles.push({
14727
+ kind: descriptor.kind,
14728
+ handle: records.kind(defined)
14729
+ });
14730
+ }
14731
+ return new NotificationTargetStore(addonId, handles, options);
14732
+ }
14733
+ /** The record handle of each kind, for the migration ports. */
14734
+ handlesByKind() {
14735
+ return new Map(this.handles.map((entry) => [entry.kind, entry.handle]));
14736
+ }
14737
+ async list() {
14738
+ const out = [];
14739
+ for (const { kind, handle } of this.handles) {
14740
+ const page = await handle.query({ limit: TARGETS_LIST_MAX });
14741
+ for (const record of page.records) {
14742
+ const target = targetOfRecord(this.addonId, kind, record.id, record.data);
14743
+ if (target !== null) {
14744
+ out.push(target);
14745
+ continue;
14746
+ }
14747
+ this.options.logger?.warn("notification target record is not a valid target; left out of the list", { meta: {
14748
+ targetId: record.id,
14749
+ kind
14750
+ } });
14751
+ }
14752
+ }
14753
+ const held = new Set(out.map((target) => target.id));
14754
+ for (const row of await this.legacyRows()) if (!held.has(row.id)) out.push(targetOfOld(this.addonId, row));
14755
+ return out;
14756
+ }
14757
+ /** The legacy rows of a kind this provider serves (the others are not ours to show). */
14758
+ async legacyRows() {
14759
+ const legacy = this.options.legacy;
14760
+ if (legacy === void 0) return [];
14761
+ const served = new Set(this.handles.map((entry) => entry.kind));
14762
+ return (await legacy.list()).filter((row) => served.has(row.kind));
14763
+ }
14764
+ async getById(id) {
14765
+ for (const { kind, handle } of this.handles) {
14766
+ const row = await handle.getResolved(id);
14767
+ if (row !== null) return targetOfRecord(this.addonId, kind, row.id, row.data);
14768
+ }
14769
+ const old = (await this.legacyRows()).find((row) => row.id === id);
14770
+ return old === void 0 ? null : targetOfOld(this.addonId, old);
14771
+ }
14772
+ /** Insert or replace by id; a target whose kind changed leaves the record of its old kind. */
14773
+ async upsert(target) {
14774
+ const own = this.handles.find((entry) => entry.kind === target.kind);
14775
+ if (own === void 0) throw new Error(`invalid target '${target.id}': unknown kind '${target.kind}'`);
14776
+ await own.handle.put({
14777
+ id: target.id,
14778
+ data: targetBody(target)
14779
+ });
14780
+ for (const other of this.handles) if (other !== own) await other.handle.delete(target.id);
14781
+ await this.options.legacy?.delete(target.id);
14782
+ }
14783
+ async delete(id) {
14784
+ for (const { handle } of this.handles) await handle.delete(id);
14785
+ await this.options.legacy?.delete(id);
14786
+ }
14787
+ /** Flip the switch on an existing target; null when it does not exist. */
14788
+ async setEnabled(id, enabled) {
14789
+ for (const { kind, handle } of this.handles) {
14790
+ if (await handle.get(id) === null) continue;
14791
+ await handle.patch(id, { enabled });
14792
+ const row = await handle.get(id);
14793
+ return row === null ? null : targetOfRecord(this.addonId, kind, row.id, row.data);
14794
+ }
14795
+ const old = (await this.legacyRows()).find((row) => row.id === id);
14796
+ if (old === void 0) return null;
14797
+ const moved = {
14798
+ ...targetOfOld(this.addonId, old),
14799
+ enabled
14800
+ };
14801
+ await this.upsert(moved);
14802
+ return moved;
14803
+ }
14804
+ };
14805
+ /**
14806
+ * A probe's answer as the tri-state of `testInstance`: `ok` validated; a refusal that carries an HTTP
14807
+ * status is the remote saying no (`rejected`); a failure with no answer at all (the network, a missing
14808
+ * field) proves nothing about the credentials (`inconclusive`).
14809
+ */
14810
+ function probeToTestResult(probed) {
14811
+ if (probed.ok) return {
14812
+ success: true,
14813
+ status: "validated",
14814
+ ...probed.stateInstance !== void 0 ? { detail: probed.stateInstance } : {}
14815
+ };
14816
+ const error = probed.error ?? "the probe failed";
14817
+ return {
14818
+ success: false,
14819
+ status: probed.httpStatus !== void 0 ? "rejected" : "inconclusive",
14820
+ error
14821
+ };
14822
+ }
14823
+ /** The form of a kind: the adapter's own sections. */
14824
+ function formOf(descriptor) {
14825
+ return descriptor.configSchema;
14826
+ }
14827
+ /** The instance kinds of a notification provider, one per target kind: a part a composition can take. */
14828
+ function notificationTargetParts(records, spec) {
14829
+ return spec.descriptors.flatMap((descriptor) => {
14830
+ const defined = spec.kinds[notificationTargetKindName(descriptor.kind)];
14831
+ if (defined === void 0) return [];
14832
+ const canTest = spec.probe !== void 0 && spec.canProbe(descriptor.kind);
14833
+ const instances = new RecordIntegrationInstances(records, defined, {
14834
+ description: {
14835
+ role: "services",
14836
+ instanceMode: "multiple",
14837
+ kind: "target",
14838
+ canTest
14839
+ },
14840
+ formSchema: () => formOf(descriptor),
14841
+ initialBody: (name) => ({ name }),
14842
+ mintId: () => spec.mintId(),
14843
+ configured: () => true,
14844
+ test: async ({ id, values }) => {
14845
+ if (spec.probe === void 0 || !canTest) return {
14846
+ success: false,
14847
+ status: "unsupported",
14848
+ error: "This kind cannot be tested"
14849
+ };
14850
+ return probeToTestResult(await spec.probe({
14851
+ kind: descriptor.kind,
14852
+ config: values,
14853
+ targetId: id ?? void 0
14854
+ }));
14855
+ }
14856
+ });
14857
+ return [{
14858
+ kind: {
14859
+ id: descriptor.kind,
14860
+ label: descriptor.label,
14861
+ functionCap: NOTIFICATION_OUTPUT_CAP,
14862
+ role: "services",
14863
+ canTest
14864
+ },
14865
+ provider: instances.toProvider()
14866
+ }];
14867
+ });
14868
+ }
14869
+ TargetSchema.omit({ id: true });
14109
14870
  var EncodeProfileSchema = object({
14110
14871
  video: object({
14111
14872
  codec: _enum([
@@ -22431,7 +23192,6 @@ var SYSTEM_CAP_VOCABULARY = {
22431
23192
  "calendar-source": system(INTERNAL),
22432
23193
  calendars: system("calendars feed schedules and conditions, not device actions"),
22433
23194
  composer: system("device composition — an authoring tool, not an action"),
22434
- "connection-test": system(INTERNAL),
22435
23195
  "core-blocks": system(INTERNAL),
22436
23196
  "custom-model-registry": system(ML),
22437
23197
  "data-store-provider": system(INTERNAL),
@@ -44408,449 +45168,6 @@ var UnitWarningSchema = object({
44408
45168
  assumedUnit: string(),
44409
45169
  message: string()
44410
45170
  });
44411
- /**
44412
- * notification-output — canonical, capability-gated notification delivery.
44413
- *
44414
- * Apprise-derived model (see
44415
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
44416
- * callers emit ONE canonical `Notification`; each provider declares a
44417
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
44418
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
44419
- * message to what the kind supports — callers never special-case a service.
44420
- *
44421
- * DESIGN DECISIONS (locked):
44422
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
44423
- * `setTargetEnabled`), each provider persisting via the `settings-store`
44424
- * cap. Rationale: the admin UI needs one uniform surface across the
44425
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
44426
- * alternative would fork the UI per addon and cannot host the
44427
- * discovery→adopt flow.
44428
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
44429
- * the generated cap-mount auto-`concatCollection`-fans them across every
44430
- * registered provider (notifiers addon + HA addon) so one catalog is
44431
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
44432
- * `addonId` the generated collection router extracts from the call input.
44433
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
44434
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
44435
- * `storage` / `storage-provider` / `recording` caps over the same path. No
44436
- * base64 fallback needed.
44437
- *
44438
- * TODO (deferred, closed-set change — separate decision): add
44439
- * `providerKind: 'notify'` so notification providers surface on the unified
44440
- * admin "Integrations" page.
44441
- */
44442
- /**
44443
- * Zentik-derived typed-media enum — the superset across every kind. Each
44444
- * adapter picks what it supports and the degrade engine filters the rest.
44445
- */
44446
- var AttachmentMediaTypeSchema = _enum([
44447
- "image",
44448
- "video",
44449
- "gif",
44450
- "audio",
44451
- "icon"
44452
- ]);
44453
- /**
44454
- * A single attachment. Exactly one of `url` (remote source, most adapters
44455
- * prefer this) or `bytes` (inline source; required for Pushover-style
44456
- * bytes-only kinds) MUST be present — the degrade engine expresses a
44457
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
44458
- */
44459
- var AttachmentSchema = object({
44460
- mediaType: AttachmentMediaTypeSchema,
44461
- url: string().optional(),
44462
- bytes: _instanceof(Uint8Array).optional(),
44463
- mime: string().optional(),
44464
- name: string().optional()
44465
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
44466
- var NotificationFormatSchema = _enum([
44467
- "text",
44468
- "markdown",
44469
- "html"
44470
- ]);
44471
- /**
44472
- * The CLOSED icon vocabulary an action button may use.
44473
- *
44474
- * A closed set, not a free string, and that is the whole point: an arbitrary
44475
- * icon name is one that ntfy renders, zentik silently drops, and nobody
44476
- * notices — the same class of gap as a zone vocabulary nothing produced
44477
- * ([D35](../../../docs/decisions/adr-0035.md)). Every adapter maps this set or
44478
- * declares `actionIcons: false` and the degrade engine strips the field.
44479
- *
44480
- * Named by INTENT, never by glyph. "check" would tie the vocabulary to one
44481
- * renderer's icon set; "acknowledge" survives an adapter that draws it
44482
- * differently.
44483
- *
44484
- * ── A TOKEN IS NOT A WIRE VALUE ─────────────────────────────────────
44485
- *
44486
- * These names are for US. **No adapter may forward one verbatim.** Each maps
44487
- * the whole set onto its own renderer's vocabulary through a
44488
- * `Record<NotificationActionIcon, string>` — a Record, never a lookup with a
44489
- * fallback, so adding a member here fails every adapter's build until someone
44490
- * decides its glyph, which is the only place that decision can be made
44491
- * honestly.
44492
- *
44493
- * This paragraph is the bug. Zentik declared `actionIcons: true` and passed
44494
- * `disarm` straight through; iOS feeds that string to
44495
- * `UNNotificationActionIcon(systemImageName:)`, `disarm` is not an SF Symbol,
44496
- * and every snooze and alarm button arrived BLANK. A pass-through is not a
44497
- * mapping, and "the field is documented" is not "the value renders".
44498
- *
44499
- * Adding a member is TRAIN-BOUND. The enum lives in the published
44500
- * `@camstack/server` closure and the cap seam validates against the HUB's copy,
44501
- * so an addon that emits a token the running hub does not know does not lose an
44502
- * icon — its whole `send` fails Zod validation and the notification never
44503
- * arrives. Never emit a new token from an addon before the train carrying it.
44504
- */
44505
- var NotificationActionIconSchema = _enum([
44506
- "acknowledge",
44507
- "dismiss",
44508
- "silence",
44509
- "snooze",
44510
- "view",
44511
- "play",
44512
- "open",
44513
- "close",
44514
- "lock",
44515
- "unlock",
44516
- "arm",
44517
- "arm-home",
44518
- "arm-away",
44519
- "arm-night",
44520
- "disarm",
44521
- "light",
44522
- "alert",
44523
- "camera"
44524
- ]);
44525
- /** A single tap-through action button. */
44526
- var NotificationActionSchema = object({
44527
- id: string(),
44528
- label: string(),
44529
- url: string().optional(),
44530
- /** Dropped by the degrade engine for a kind with `caps.actionIcons: false`. */
44531
- icon: NotificationActionIconSchema.optional(),
44532
- /**
44533
- * Renders in a warning style where the notifier supports it.
44534
- *
44535
- * A HINT, never a gate. The callback's authority is its token and nothing
44536
- * else — see `notification-center/action-token.ts` for what that does and
44537
- * does not buy.
44538
- */
44539
- destructive: boolean().optional(),
44540
- /**
44541
- * How the tap should REACH the url.
44542
- *
44543
- * `navigate` (absent, and every button authored before this field) opens it:
44544
- * the phone leaves the notification and shows whatever the callback returns.
44545
- * That is right for a button whose answer the operator wants to read.
44546
- *
44547
- * `background` fires it as a POST and stays put. It exists for the buttons
44548
- * whose whole point is not to interrupt — "silence this for 30 minutes" is
44549
- * an answer to the notification, and being thrown into a browser tab to
44550
- * confirm it costs more attention than the notification did. A backend that
44551
- * cannot do a background call renders it as an ordinary link (the adapters
44552
- * fall back rather than dropping the button), so this is a preference, never
44553
- * a requirement.
44554
- */
44555
- mode: _enum(["navigate", "background"]).optional()
44556
- });
44557
- /** A delivery parameter value: what a notifier declared it takes. */
44558
- var DeliveryParamValueSchema = union([
44559
- string(),
44560
- number$1(),
44561
- boolean()
44562
- ]);
44563
- /**
44564
- * One extra delivery parameter a notifier KIND declares (D938). A rule that
44565
- * addresses a target of that kind may set it; a kind that declares nothing is
44566
- * never handed one. The admin UI derives its control from this descriptor —
44567
- * no editor knows a service by name.
44568
- *
44569
- * Optional fields are `.optional()`, never `.default()` (a Zod default does not
44570
- * run on the addon cap path).
44571
- */
44572
- var DeliveryParamSchema = object({
44573
- key: string().min(1),
44574
- label: string(),
44575
- /** i18n key of the label, resolved by the declaring addon's namespace. */
44576
- labelKey: string().optional(),
44577
- type: _enum([
44578
- "enum",
44579
- "number",
44580
- "boolean",
44581
- "string"
44582
- ]),
44583
- /** `enum` only: the closed set of accepted values. */
44584
- options: array(object({
44585
- value: string(),
44586
- label: string()
44587
- })).optional(),
44588
- /** `number` only. */
44589
- min: number$1().optional(),
44590
- max: number$1().optional(),
44591
- /** What the notifier does when the rule sets nothing; shown as the placeholder. */
44592
- default: DeliveryParamValueSchema.optional()
44593
- });
44594
- /**
44595
- * The canonical notification. `body` is the only hard field (Apprise model).
44596
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
44597
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
44598
- * the adapter maps this ordinal onto its native level. `level?` is an
44599
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
44600
- * `priority` for that one target.
44601
- */
44602
- var NotificationSchema = object({
44603
- body: string(),
44604
- title: string().optional(),
44605
- format: NotificationFormatSchema.default("text"),
44606
- priority: number$1().int().min(1).max(5).default(3),
44607
- level: string().optional(),
44608
- attachments: array(AttachmentSchema).optional(),
44609
- clickUrl: string().optional(),
44610
- actions: array(NotificationActionSchema).optional(),
44611
- sound: string().optional(),
44612
- ttl: number$1().optional(),
44613
- tag: string().optional(),
44614
- deviceId: number$1().optional(),
44615
- eventId: string().optional(),
44616
- metadata: record(string(), unknown()).optional(),
44617
- /**
44618
- * Values for the parameters the target's kind DECLARES in
44619
- * {@link TargetKindSchema} `deliveryParams`. Already validated against the
44620
- * declaration by the sender; a notifier reads only the keys it declared.
44621
- */
44622
- delivery: record(string(), DeliveryParamValueSchema).optional()
44623
- });
44624
- /** One declared native severity/priority level for a kind. */
44625
- var TargetKindLevelSchema = object({
44626
- id: string(),
44627
- label: string(),
44628
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
44629
- ordinal: number$1().int().min(1).max(5).nullable(),
44630
- flags: object({
44631
- critical: boolean().optional(),
44632
- silent: boolean().optional(),
44633
- noPush: boolean().optional()
44634
- }).optional(),
44635
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
44636
- requires: array(string()).optional(),
44637
- description: string().optional()
44638
- });
44639
- /** The full capability block consulted before dispatch. */
44640
- var TargetKindCapsSchema = object({
44641
- attachments: object({
44642
- mediaTypes: array(AttachmentMediaTypeSchema),
44643
- mode: _enum([
44644
- "url",
44645
- "bytes",
44646
- "both"
44647
- ]),
44648
- max: number$1().int().nonnegative(),
44649
- maxBytes: number$1().int().positive().optional()
44650
- }),
44651
- /** Max action buttons (0 = none). */
44652
- actions: number$1().int().nonnegative(),
44653
- /**
44654
- * Whether this kind renders a per-action ICON.
44655
- *
44656
- * `.optional()`, deliberately NOT `.default(false)`: a Zod default does not
44657
- * run on the addon cap path — three production failures in one day taught
44658
- * this repo that once. Absent is read as false by the degrade engine, which
44659
- * is the safe direction: an icon that is not rendered costs nothing, an icon
44660
- * assumed and dropped costs the operator's trust in the field.
44661
- */
44662
- actionIcons: boolean().optional(),
44663
- levels: array(TargetKindLevelSchema),
44664
- format: array(NotificationFormatSchema),
44665
- clickUrl: boolean(),
44666
- sound: boolean(),
44667
- ttl: boolean(),
44668
- bodyMaxLen: number$1().int().positive()
44669
- });
44670
- /**
44671
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
44672
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
44673
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
44674
- * the union is large and not meant for runtime validation here; the exported
44675
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
44676
- */
44677
- var ConfigSchemaPassthrough$4 = unknown();
44678
- var TargetKindSchema = object({
44679
- kind: string(),
44680
- label: string(),
44681
- icon: string(),
44682
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
44683
- addonId: string(),
44684
- /**
44685
- * URL of the kind's bundled BRAND icon, served by the providing addon over
44686
- * its own `addon-routes` surface (`/addon/<addonId>/icons/<kind>`). Absent
44687
- * when the addon bundles no icon for that kind — the client then falls back
44688
- * to a neutral glyph rather than rendering the raw `icon` NAME as text.
44689
- *
44690
- * Root-relative on purpose: it resolves against whatever origin serves a web
44691
- * client, and a native client joins it onto its own hub base.
44692
- *
44693
- * DECLARED here deliberately. It used to travel as an undeclared passthrough
44694
- * field that survived only because the runtime cap-router forwards provider
44695
- * output verbatim — so every consumer had to re-declare it by hand to stop
44696
- * its own Zod parse from stripping it, and the whole arrangement would have
44697
- * broken silently the moment output validation was tightened anywhere.
44698
- */
44699
- iconUrl: string().optional(),
44700
- /**
44701
- * Media type of {@link iconUrl} (`image/svg+xml`, `image/png`, …).
44702
- *
44703
- * The server knows this and therefore says it, because the client cannot
44704
- * safely guess: a React-Native client renders SVG and raster through two
44705
- * DIFFERENT components (`react-native-svg` vs `expo-image` — expo-image does
44706
- * not decode SVG on iOS/Android), so without this it silently fell back to a
44707
- * placeholder glyph for every vector icon while the web build looked fine.
44708
- *
44709
- * Absent when {@link iconUrl} is absent, or for a legacy provider that has
44710
- * not been updated — a client that cannot determine the type should prefer
44711
- * its raster path, which is the safe default for an unknown image.
44712
- */
44713
- iconMediaType: string().optional(),
44714
- configSchema: ConfigSchemaPassthrough$4,
44715
- /**
44716
- * The config keys that decide WHERE this kind's secrets are sent (server,
44717
- * base URL, instance, chat, recipient). A save that changes any of them
44718
- * while leaving a secret redacted is refused by the provider (D634), so an
44719
- * editor uses this to ask for the secret on exactly those edits instead of
44720
- * on every edit.
44721
- *
44722
- * Optional: absent from a provider that holds no secret (the Home Assistant
44723
- * kinds) and from a provider older than this field — an editor that finds
44724
- * it absent must assume ANY edit may need the secret.
44725
- */
44726
- destinationKeys: array(string()).optional(),
44727
- supportsDiscovery: boolean(),
44728
- /**
44729
- * Extra delivery parameters a rule may set for a target of this kind (D938).
44730
- * Absent = none; the rule editor then offers nothing.
44731
- */
44732
- deliveryParams: array(DeliveryParamSchema).optional(),
44733
- caps: TargetKindCapsSchema
44734
- });
44735
- /**
44736
- * A persisted target. `config` holds secrets; providers REDACT secret fields
44737
- * (return a presence marker only) when serving `listTargets` — never
44738
- * round-trip a stored secret to the UI.
44739
- */
44740
- var TargetSchema = object({
44741
- id: string(),
44742
- name: string(),
44743
- kind: string(),
44744
- addonId: string(),
44745
- enabled: boolean(),
44746
- config: record(string(), unknown())
44747
- });
44748
- /** A discovery-surfaced candidate (config is partial + non-secret). */
44749
- var DiscoveredTargetSchema = object({
44750
- kind: string(),
44751
- suggestedName: string(),
44752
- config: record(string(), unknown())
44753
- });
44754
- /** The degrade engine's report — what was resolved / dropped / degraded. */
44755
- var RenderedAsSchema = object({
44756
- level: string(),
44757
- format: NotificationFormatSchema,
44758
- attachmentsSent: number$1().int().nonnegative(),
44759
- actionsSent: number$1().int().nonnegative(),
44760
- truncated: boolean(),
44761
- dropped: array(string())
44762
- });
44763
- var SendResultSchema = object({
44764
- success: boolean(),
44765
- error: string().optional(),
44766
- renderedAs: RenderedAsSchema.optional()
44767
- });
44768
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
44769
- var TestResultSchema = SendResultSchema;
44770
- /**
44771
- * Pre-save credential probe against a partial (unsaved) target config.
44772
- * `resolvedUrl` never includes secrets (token stripped from path).
44773
- */
44774
- var ProbeTargetConfigResultSchema = object({
44775
- ok: boolean(),
44776
- resolvedUrl: string(),
44777
- httpStatus: number$1().int().optional(),
44778
- stateInstance: string().optional(),
44779
- error: string().optional()
44780
- });
44781
- var notificationOutputCapability = {
44782
- name: "notification-output",
44783
- scope: "system",
44784
- mode: "collection",
44785
- methods: {
44786
- listTargetKinds: method(object({}), array(TargetKindSchema)),
44787
- listTargets: method(object({}), array(TargetSchema), { auth: "admin" }),
44788
- /**
44789
- * One target WITH secrets — admin edit / duplicate hydration only.
44790
- * `listTargets` stays redacted; the editor loads this so password fields
44791
- * are filled (masked in the input) and a save can round-trip the token
44792
- * when a destination changes (Duplicate with a new chatId, etc.).
44793
- */
44794
- getTarget: method(object({ targetId: string() }), TargetSchema, { auth: "admin" }),
44795
- discoverTargets: method(object({
44796
- kind: string(),
44797
- config: record(string(), unknown()).optional(),
44798
- /**
44799
- * When editing / duplicating, the blank password field never round-trips
44800
- * the stored token. Pass the source target id so the provider can restore
44801
- * secrets server-side before dialling (same merge as upsert).
44802
- */
44803
- targetId: string().optional()
44804
- }), array(DiscoveredTargetSchema), { auth: "admin" }),
44805
- probeTargetConfig: method(object({
44806
- kind: string(),
44807
- config: record(string(), unknown()),
44808
- /** See `discoverTargets.targetId` — restore stored secrets for a blank password. */
44809
- targetId: string().optional()
44810
- }), ProbeTargetConfigResultSchema, {
44811
- kind: "mutation",
44812
- auth: "admin"
44813
- }),
44814
- send: method(object({
44815
- targetId: string(),
44816
- notification: NotificationSchema
44817
- }), SendResultSchema, {
44818
- kind: "mutation",
44819
- auth: "admin"
44820
- }),
44821
- testTarget: method(object({
44822
- targetId: string(),
44823
- sample: NotificationSchema.optional()
44824
- }), TestResultSchema, {
44825
- kind: "mutation",
44826
- auth: "admin"
44827
- }),
44828
- upsertTarget: method(object({
44829
- target: TargetSchema,
44830
- /**
44831
- * Duplicate flow: create a NEW target id while copying secrets from an
44832
- * existing row. The UI never holds the stored token; blank / redacted
44833
- * password fields are restored from this source (D634 still applies if
44834
- * destinations diverge without a re-typed secret).
44835
- */
44836
- cloneSecretsFrom: string().optional()
44837
- }), TargetSchema, {
44838
- kind: "mutation",
44839
- auth: "admin"
44840
- }),
44841
- deleteTarget: method(object({ targetId: string() }), _void(), {
44842
- kind: "mutation",
44843
- auth: "admin"
44844
- }),
44845
- setTargetEnabled: method(object({
44846
- targetId: string(),
44847
- enabled: boolean()
44848
- }), _void(), {
44849
- kind: "mutation",
44850
- auth: "admin"
44851
- })
44852
- }
44853
- };
44854
45171
  _enum([
44855
45172
  "automation",
44856
45173
  "action",
@@ -49454,37 +49771,6 @@ method(object({
49454
49771
  kind: "mutation",
49455
49772
  auth: "admin"
49456
49773
  }), method(object({ blockIds: array(string()) }), object({ states: array(CompositionBlockStateSchema) }), { auth: "admin" });
49457
- var ConnectionTestOutcomeSchema = discriminatedUnion("outcome", [
49458
- object({
49459
- outcome: literal("validated"),
49460
- /** Round-trip of the sign-in, when the provider measured it. */
49461
- latencyMs: number$1().nonnegative().optional(),
49462
- /** Optional human detail worth showing next to the tick
49463
- * ("3 devices visible on this account"). */
49464
- detail: string().optional()
49465
- }).strict(),
49466
- object({
49467
- outcome: literal("rejected"),
49468
- error: string()
49469
- }).strict(),
49470
- object({
49471
- outcome: literal("inconclusive"),
49472
- error: string()
49473
- }).strict()
49474
- ]);
49475
- var ConnectionTestInputSchema = object({
49476
- /** Candidate integration settings, exactly as the create form collected them. */
49477
- settings: record(string(), unknown()) });
49478
- /**
49479
- * What the provider's test actually DOES, so the UI can say it in words before
49480
- * the operator presses the button ("Signs in to the Dreo cloud"). Purely
49481
- * descriptive — it never changes routing.
49482
- */
49483
- var ConnectionTestDescriptorSchema = object({ label: string() });
49484
- method(ConnectionTestInputSchema, ConnectionTestOutcomeSchema, {
49485
- kind: "mutation",
49486
- auth: "admin"
49487
- }), method(_void(), ConnectionTestDescriptorSchema, { auth: "admin" });
49488
49774
  /**
49489
49775
  * Upstream-system connectivity sensor — distinct from `device-status`,
49490
49776
  * which is the kernel-managed online/offline flag for the device's
@@ -56638,10 +56924,9 @@ var AvailableIntegrationTypeSchema = object({
56638
56924
  * locations" checkbox. Provider-declared in the addon manifest. */
56639
56925
  supportsLocationImport: boolean(),
56640
56926
  /**
56641
- * True when this integration DECLARES a pre-creation test (the
56642
- * `connection-test` cap, or a broker whose settings it stores). Drives the
56643
- * Test button: an integration that cannot be tested must say so up front
56644
- * rather than offering a button that always answers the same nonsense.
56927
+ * True when this integration's instances declare a Test (`integration-instances.describe().canTest`,
56928
+ * D1016). An integration that cannot be tested must say so up front rather than offering a
56929
+ * button that always answers the same nonsense.
56645
56930
  */
56646
56931
  canTest: boolean(),
56647
56932
  existingInstances: array(object({
@@ -56695,7 +56980,9 @@ var CreateIntegrationInputSchema = object({
56695
56980
  info: record(string(), unknown()).optional(),
56696
56981
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56697
56982
  originStableId: string().optional(),
56698
- settings: record(string(), unknown()).optional()
56983
+ settings: record(string(), unknown()).optional(),
56984
+ /** The instance kind being created, for a provider with several; omitted = its only testable kind. */
56985
+ kind: string().min(1).optional()
56699
56986
  });
56700
56987
  var UpdateIntegrationInputSchema = object({
56701
56988
  id: string(),
@@ -56721,13 +57008,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
56721
57008
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
56722
57009
  kind: "mutation",
56723
57010
  auth: "admin"
56724
- }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
56725
- addonId: string(),
56726
- settings: record(string(), unknown())
56727
- }), TestConnectionResultSchema, {
56728
- kind: "mutation",
56729
- auth: "admin"
56730
- });
57011
+ }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" });
56731
57012
  /**
56732
57013
  * `integration-instances` - the connection of an addon that holds ONE or SEVERAL
56733
57014
  * (an account, a relay, a destination) as typed records (D985, D986). The addon's
@@ -65470,13 +65751,6 @@ var AddBrokerInputSchema = object({
65470
65751
  });
65471
65752
  var AddBrokerResultSchema = object({ id: string() });
65472
65753
  var IdInputSchema = object({ id: string() });
65473
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
65474
- ok: literal(true),
65475
- latencyMs: number$1()
65476
- }), object({
65477
- ok: literal(false),
65478
- error: string()
65479
- })]);
65480
65754
  var StartEmbeddedInputSchema = object({
65481
65755
  port: number$1().int().min(1).max(65535).default(1883),
65482
65756
  /** Allow anonymous connect (no username/password). Default: false. */
@@ -65499,9 +65773,6 @@ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnection
65499
65773
  }), method(IdInputSchema, _void(), {
65500
65774
  kind: "mutation",
65501
65775
  auth: "admin"
65502
- }), method(IdInputSchema, TestResultSchema$1, {
65503
- kind: "mutation",
65504
- auth: "admin"
65505
65776
  }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, {
65506
65777
  kind: "mutation",
65507
65778
  auth: "admin"
@@ -78608,7 +78879,7 @@ var TrainingProviderTypeSchema = object({
78608
78879
  label: string(),
78609
78880
  /** Path under the addon package (e.g. `assets/training-modal/icon.svg`). */
78610
78881
  iconAsset: string(),
78611
- /** Owning `training-provider` addon — collection selector for createEntry. */
78882
+ /** Owning `training-provider` addon. */
78612
78883
  addonId: string(),
78613
78884
  /**
78614
78885
  * Fields for one entry of this type (credentials + defaults). Absent on a
@@ -78653,36 +78924,6 @@ var TrainingProviderDescriptorSchema = object({
78653
78924
  */
78654
78925
  formValues: record(string(), unknown()).optional()
78655
78926
  });
78656
- /**
78657
- * Patch one entry's name, credentials and defaults. Pin with owning `{ addonId }`.
78658
- * An omitted or empty `tokenSecret` means KEEP the stored secret (D787).
78659
- * `{ $secretClear: true }` clears it.
78660
- */
78661
- var TrainingProviderUpdateEntryInputSchema = object({
78662
- entryId: string().min(1),
78663
- name: string().min(1),
78664
- tokenId: string().optional(),
78665
- tokenSecret: union([string(), object({ $secretClear: literal(true) })]).optional(),
78666
- environment: string().optional(),
78667
- gpuType: string().optional(),
78668
- region: string().optional(),
78669
- costCapUsd: number$1().nonnegative().optional(),
78670
- maxRuntimeSec: number$1().int().positive().optional(),
78671
- failedDatasetGraceHours: number$1().nonnegative().optional()
78672
- });
78673
- var TrainingCredentialCheckSchema = object({
78674
- ok: boolean(),
78675
- /** Workspace / account name, when the provider says. */
78676
- account: string().optional(),
78677
- reason: _enum([
78678
- "missing",
78679
- "invalid",
78680
- "forbidden",
78681
- "network",
78682
- "quota"
78683
- ]).optional(),
78684
- detail: string().optional()
78685
- });
78686
78927
  var ProviderJobStateSchema = _enum([
78687
78928
  "pending",
78688
78929
  "starting",
@@ -78730,22 +78971,6 @@ var TrainingLogLineSchema = object({
78730
78971
  text: string()
78731
78972
  });
78732
78973
  method(object({}), array(TrainingProviderDescriptorSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderTypeSchema).readonly(), { auth: "admin" }), method(object({}), array(TrainingProviderEntrySchema).readonly(), { auth: "admin" }), method(object({
78733
- typeId: string().min(1),
78734
- name: string().min(1)
78735
- }), object({ entryId: string() }), {
78736
- kind: "mutation",
78737
- auth: "admin"
78738
- }), method(object({ entryId: string().min(1) }), object({ ok: literal(true) }), {
78739
- kind: "mutation",
78740
- auth: "admin"
78741
- }), method(TrainingProviderUpdateEntryInputSchema, object({ ok: literal(true) }), {
78742
- kind: "mutation",
78743
- auth: "admin"
78744
- }), method(object({ entryId: string().min(1) }), TrainingCredentialCheckSchema, {
78745
- kind: "mutation",
78746
- auth: "admin",
78747
- timeoutMs: 3e4
78748
- }), method(object({
78749
78974
  entryId: string().min(1),
78750
78975
  gpuType: string(),
78751
78976
  region: string(),
@@ -84106,20 +84331,6 @@ Object.freeze({
84106
84331
  access: "view",
84107
84332
  role: "admin"
84108
84333
  },
84109
- "connectionTest.describeTest": {
84110
- capName: "connection-test",
84111
- capScope: "system",
84112
- addonId: null,
84113
- access: "view",
84114
- role: "admin"
84115
- },
84116
- "connectionTest.testSettings": {
84117
- capName: "connection-test",
84118
- capScope: "system",
84119
- addonId: null,
84120
- access: "create",
84121
- role: "admin"
84122
- },
84123
84334
  "connectivity.getStatus": {
84124
84335
  capName: "connectivity",
84125
84336
  capScope: "device",
@@ -86486,13 +86697,6 @@ Object.freeze({
86486
86697
  access: "view",
86487
86698
  role: "admin"
86488
86699
  },
86489
- "integrations.testConnection": {
86490
- capName: "integrations",
86491
- capScope: "system",
86492
- addonId: null,
86493
- access: "create",
86494
- role: "admin"
86495
- },
86496
86700
  "integrations.update": {
86497
86701
  capName: "integrations",
86498
86702
  capScope: "system",
@@ -87725,13 +87929,6 @@ Object.freeze({
87725
87929
  access: "create",
87726
87930
  role: "admin"
87727
87931
  },
87728
- "mqttBroker.testConnection": {
87729
- capName: "mqtt-broker",
87730
- capScope: "system",
87731
- addonId: null,
87732
- access: "create",
87733
- role: "admin"
87734
- },
87735
87932
  "nativeObjectDetection.getOptions": {
87736
87933
  capName: "native-object-detection",
87737
87934
  capScope: "device",
@@ -92562,20 +92759,6 @@ Object.freeze({
92562
92759
  access: "create",
92563
92760
  role: "admin"
92564
92761
  },
92565
- "trainingProvider.createEntry": {
92566
- capName: "training-provider",
92567
- capScope: "system",
92568
- addonId: null,
92569
- access: "create",
92570
- role: "admin"
92571
- },
92572
- "trainingProvider.deleteEntry": {
92573
- capName: "training-provider",
92574
- capScope: "system",
92575
- addonId: null,
92576
- access: "delete",
92577
- role: "admin"
92578
- },
92579
92762
  "trainingProvider.describe": {
92580
92763
  capName: "training-provider",
92581
92764
  capScope: "system",
@@ -92646,13 +92829,6 @@ Object.freeze({
92646
92829
  access: "create",
92647
92830
  role: "admin"
92648
92831
  },
92649
- "trainingProvider.updateEntry": {
92650
- capName: "training-provider",
92651
- capScope: "system",
92652
- addonId: null,
92653
- access: "create",
92654
- role: "admin"
92655
- },
92656
92832
  "trainingProvider.uploadDataset": {
92657
92833
  capName: "training-provider",
92658
92834
  capScope: "system",
@@ -92660,13 +92836,6 @@ Object.freeze({
92660
92836
  access: "create",
92661
92837
  role: "admin"
92662
92838
  },
92663
- "trainingProvider.validateCredentials": {
92664
- capName: "training-provider",
92665
- capScope: "system",
92666
- addonId: null,
92667
- access: "create",
92668
- role: "admin"
92669
- },
92670
92839
  "turnProvider.getTurnServers": {
92671
92840
  capName: "turn-provider",
92672
92841
  capScope: "system",
@@ -145216,452 +145385,6 @@ function regionOfDomain(domain) {
145216
145385
  if (tail === "amazon.co.jp" || tail === "amazon.com.au" || tail === "amazon.in") return "FE";
145217
145386
  return "EU";
145218
145387
  }
145219
- process.platform, process.env["SystemRoot"];
145220
- /**
145221
- * Files only their owner may read: the one place a secret-bearing file is
145222
- * restricted, on every OS.
145223
- *
145224
- * `mode: 0o600` is a POSIX idea. On Windows Node maps it to the read-only
145225
- * attribute and nothing else, and `chmod` is a no-op for permissions, so a
145226
- * "0600" `agent.json` (the mesh private key) would have
145227
- * been readable by every local user. Windows has its own tool for this:
145228
- * `icacls`. This module removes the inherited ACL entries and grants access to
145229
- * the current user and SYSTEM only — the Windows reading of "0600".
145230
- *
145231
- * ZERO imports beyond Node built-ins, on purpose: the Electron shell bundles
145232
- * this single file (see `packages/desktop/tsup.config.ts`) instead of the
145233
- * whole `@camstack/types` barrel.
145234
- *
145235
- * Failure is NOT swallowed. A secret file that could not be restricted is a
145236
- * secret file the caller must know about, so `OwnerOnlyError` propagates; the
145237
- * write order below makes sure nothing sensitive is in the file yet when that
145238
- * happens (the temp file is empty until it has been restricted).
145239
- *
145240
- * Out of scope on purpose: files that are only tidy, not secret (the job
145241
- * journal, the addon manifest) keep a plain `mode`, since one `icacls` per
145242
- * write would be a process spawn on a hot path.
145243
- */
145244
- /** `*S-1-5-18` is SYSTEM in every locale — a name like "SYSTEM" is not. */
145245
- var WINDOWS_SYSTEM_SID = "*S-1-5-18";
145246
- var FILE_MODE = 384;
145247
- var DIR_MODE = 448;
145248
- var OwnerOnlyError = class extends Error {
145249
- target;
145250
- constructor(target, detail) {
145251
- super(`could not restrict ${target} to its owner: ${detail}`);
145252
- this.target = target;
145253
- this.name = "OwnerOnlyError";
145254
- }
145255
- };
145256
- function currentPrincipal() {
145257
- const user = process.env["USERNAME"] ?? userInfo().username;
145258
- const domain = process.env["USERDOMAIN"];
145259
- return domain !== void 0 && domain.length > 0 ? `${domain}\\${user}` : user;
145260
- }
145261
- /** Resolved per call, not at import: a platform stubbed by a test must be seen. */
145262
- function resolveDeps(overrides) {
145263
- return {
145264
- platform: process.platform,
145265
- exec: (file, args) => {
145266
- execFileSync(file, [...args], {
145267
- stdio: "pipe",
145268
- windowsHide: true
145269
- });
145270
- },
145271
- principal: currentPrincipal,
145272
- systemRoot: process.env["SystemRoot"],
145273
- ...overrides
145274
- };
145275
- }
145276
- /** The icacls argv for one path: no inheritance, owner + SYSTEM only. */
145277
- function icaclsArgs(target, principal, isDirectory) {
145278
- const inherit = isDirectory ? "(OI)(CI)" : "";
145279
- return [
145280
- target,
145281
- "/inheritance:r",
145282
- "/grant:r",
145283
- `${principal}:${inherit}F`,
145284
- "/grant:r",
145285
- `${WINDOWS_SYSTEM_SID}:${inherit}F`
145286
- ];
145287
- }
145288
- function restrictWindows(target, isDirectory, deps) {
145289
- const icacls = path.win32.join(deps.systemRoot ?? "C:\\Windows", "System32", "icacls.exe");
145290
- try {
145291
- deps.exec(icacls, icaclsArgs(target, deps.principal(), isDirectory));
145292
- } catch (err) {
145293
- throw new OwnerOnlyError(target, err instanceof Error ? err.message : String(err));
145294
- }
145295
- }
145296
- /** Restrict an existing file to its owner (chmod 0600 / owner+SYSTEM ACL). */
145297
- function restrictFileToOwnerSync(target, overrides = {}) {
145298
- const deps = resolveDeps(overrides);
145299
- if (deps.platform === "win32") {
145300
- restrictWindows(target, false, deps);
145301
- return;
145302
- }
145303
- fs.chmodSync(target, FILE_MODE);
145304
- }
145305
- /** Restrict an existing directory to its owner (chmod 0700 / owner+SYSTEM, inherited). */
145306
- function restrictDirToOwnerSync(target, overrides = {}) {
145307
- const deps = resolveDeps(overrides);
145308
- if (deps.platform === "win32") {
145309
- restrictWindows(target, true, deps);
145310
- return;
145311
- }
145312
- fs.chmodSync(target, DIR_MODE);
145313
- }
145314
- /**
145315
- * Atomically write a secret-bearing file that only its owner can read.
145316
- *
145317
- * Order matters: the temp file is created EMPTY, restricted, and only then
145318
- * given its content, so there is no moment at which the secret exists under a
145319
- * permissive ACL. The rename carries the (already restricted) ACL with it.
145320
- */
145321
- function writeOwnerOnlyFileSync(target, data, overrides = {}) {
145322
- fs.mkdirSync(path.dirname(target), { recursive: true });
145323
- const tmp = `${target}.tmp.${process.pid}`;
145324
- fs.writeFileSync(tmp, "", { mode: FILE_MODE });
145325
- try {
145326
- restrictFileToOwnerSync(tmp, overrides);
145327
- fs.writeFileSync(tmp, data);
145328
- fs.renameSync(tmp, target);
145329
- } catch (err) {
145330
- fs.rmSync(tmp, { force: true });
145331
- throw err;
145332
- }
145333
- }
145334
- //#endregion
145335
- //#region src/speak/secret-file.ts
145336
- /**
145337
- * Hand a refresh token or a saved Amazon session to the Python worker as an
145338
- * owner-only file. The path travels on stdin. The bytes never travel on
145339
- * argv or in the environment, and they are removed when the call settles.
145340
- */
145341
- var REDACTED = "‹redacted›";
145342
- function decodeSession(sessionB64) {
145343
- if (sessionB64.length === 0) return Buffer.alloc(0);
145344
- return Buffer.from(sessionB64, "base64");
145345
- }
145346
- async function readSessionB64(sessionPath) {
145347
- const bytes = await fs$1.readFile(sessionPath);
145348
- if (bytes.length === 0) return "";
145349
- return bytes.toString("base64");
145350
- }
145351
- /**
145352
- * Create a 0700 directory, write the refresh token and the session 0600, run
145353
- * `body`, then delete the directory whether `body` succeeded or threw.
145354
- * Returns the session file as base64 so the caller can store it in the keychain.
145355
- */
145356
- async function withSpeakSecretFiles(input, body) {
145357
- const dir = await fs$1.mkdtemp(path.join(os.tmpdir(), "camstack-alexa-"));
145358
- const paths = {
145359
- dir,
145360
- refreshTokenPath: path.join(dir, "refresh-token"),
145361
- sessionPath: path.join(dir, "session")
145362
- };
145363
- try {
145364
- restrictDirToOwnerSync(dir);
145365
- writeOwnerOnlyFileSync(paths.refreshTokenPath, input.refreshToken);
145366
- writeOwnerOnlyFileSync(paths.sessionPath, decodeSession(input.sessionB64));
145367
- await body(paths);
145368
- return { sessionB64: await readSessionB64(paths.sessionPath) };
145369
- } finally {
145370
- await fs$1.rm(dir, {
145371
- recursive: true,
145372
- force: true
145373
- });
145374
- }
145375
- }
145376
- /** Replace every occurrence of each non-empty secret. Used before a log line is emitted. */
145377
- function scrubSecrets(text, secrets) {
145378
- let out = text;
145379
- for (const secret of secrets) {
145380
- if (secret.length === 0) continue;
145381
- out = out.split(secret).join(REDACTED);
145382
- }
145383
- return out;
145384
- }
145385
- //#endregion
145386
- //#region src/speak/broker-echo.ts
145387
- function withDevice(deviceId) {
145388
- return deviceId === void 0 ? {} : { deviceId };
145389
- }
145390
- var BrokerEcho = class {
145391
- deps;
145392
- currentState = "starting";
145393
- currentError = null;
145394
- currentDevices = [];
145395
- backoffMs = 0;
145396
- limitedUntil = 0;
145397
- channelState = "down";
145398
- channelWasUp = false;
145399
- secrets = [];
145400
- unknownPushLogged = /* @__PURE__ */ new Set();
145401
- constructor(deps) {
145402
- this.deps = deps;
145403
- deps.worker.onPush((push) => this.onPush(push));
145404
- }
145405
- /** Whether Amazon's push channel is open for this account right now. */
145406
- get pushChannel() {
145407
- return this.channelState;
145408
- }
145409
- /** A reason is text from the library: capped, then scrubbed of the secrets in play. */
145410
- safeReason(reason) {
145411
- return scrubSecrets(reason.slice(0, 200), this.secrets);
145412
- }
145413
- onPush(push) {
145414
- const tags = { tags: { brokerId: this.deps.brokerId } };
145415
- if (push.push === "channel") {
145416
- if (push.state === this.channelState) {
145417
- if (push.state === "down") this.deps.logger.debug("alexa echo: push channel still down", {
145418
- ...tags,
145419
- meta: {
145420
- reason: this.safeReason(push.reason),
145421
- retryInMs: push.retryInMs
145422
- }
145423
- });
145424
- return;
145425
- }
145426
- this.channelState = push.state;
145427
- if (push.state === "up") {
145428
- this.deps.logger.info(this.channelWasUp ? "alexa echo: push channel reconnected, polling slows down" : "alexa echo: push channel connected, polling slows down", tags);
145429
- this.channelWasUp = true;
145430
- } else this.deps.logger.warn("alexa echo: push channel down, polling at the normal pace", {
145431
- ...tags,
145432
- meta: {
145433
- reason: this.safeReason(push.reason),
145434
- retryInMs: push.retryInMs
145435
- }
145436
- });
145437
- this.deps.push?.channel(this.deps.brokerId, push.state);
145438
- return;
145439
- }
145440
- if (PUSH_READ_COMMANDS.has(push.command)) {
145441
- if (push.serial === null) {
145442
- this.deps.logger.debug("alexa echo: push event without an Echo, ignored", {
145443
- ...tags,
145444
- meta: { command: push.command }
145445
- });
145446
- return;
145447
- }
145448
- this.deps.push?.event(this.deps.brokerId, push.serial);
145449
- return;
145450
- }
145451
- if (PUSH_IGNORED_COMMANDS.has(push.command)) return;
145452
- if (this.unknownPushLogged.has(push.command)) return;
145453
- this.unknownPushLogged.add(push.command);
145454
- this.deps.logger.info("alexa echo: unknown push event, ignored (logged once)", {
145455
- ...tags,
145456
- meta: { command: push.command }
145457
- });
145458
- }
145459
- get id() {
145460
- return this.deps.brokerId;
145461
- }
145462
- get name() {
145463
- return this.deps.brokerName;
145464
- }
145465
- get state() {
145466
- return this.currentState;
145467
- }
145468
- get error() {
145469
- return this.currentError;
145470
- }
145471
- get devices() {
145472
- return this.currentDevices;
145473
- }
145474
- /** Ms epoch until which Amazon asked us to wait (429), or null when the account is free. */
145475
- get rateLimitedUntil() {
145476
- return this.limitedUntil > this.nowMs() ? this.limitedUntil : null;
145477
- }
145478
- nowMs() {
145479
- return (this.deps.now ?? Date.now)();
145480
- }
145481
- stop() {
145482
- this.deps.worker.stop();
145483
- if (this.channelState === "up") {
145484
- this.channelState = "down";
145485
- this.deps.push?.channel(this.deps.brokerId, "down");
145486
- }
145487
- }
145488
- /** Sign the worker in as the broker's account. Never throws; the outcome is `state`. */
145489
- async signIn() {
145490
- const { brokerId, worker, sessions, logger } = this.deps;
145491
- const tags = { tags: { brokerId } };
145492
- let secrets = [];
145493
- try {
145494
- const seed = await this.deps.readSeed();
145495
- const stored = await sessions.get(brokerId);
145496
- logger.info("alexa speak: broker sign-in material", {
145497
- ...tags,
145498
- meta: {
145499
- seedFound: seed !== null,
145500
- hasRefreshToken: seed !== null && seed.refreshToken.length > 0,
145501
- hasDeviceAppName: seed !== null && seed.deviceAppName.length > 0,
145502
- hasStoredSession: stored.length > 0
145503
- }
145504
- });
145505
- if (seed === null && stored.length === 0) {
145506
- this.currentState = "broker-not-signed-in";
145507
- this.currentError = null;
145508
- logger.warn("alexa speak: the broker has no sign-in to share yet", tags);
145509
- return;
145510
- }
145511
- secrets = seed === null ? [] : [seed.refreshToken];
145512
- worker.noteSecrets(secrets);
145513
- this.secrets = secrets;
145514
- let outcome = parseLoginResult({
145515
- status: "failed",
145516
- error: "worker gave no answer"
145517
- });
145518
- const held = await withSpeakSecretFiles({
145519
- refreshToken: seed?.refreshToken ?? "",
145520
- sessionB64: stored
145521
- }, async (paths) => {
145522
- outcome = parseLoginResult(await worker.request({
145523
- op: "login_broker",
145524
- label: brokerId,
145525
- refreshTokenPath: seed === null ? "" : paths.refreshTokenPath,
145526
- deviceAppName: seed?.deviceAppName ?? "",
145527
- domain: this.deps.domain,
145528
- sessionPath: paths.sessionPath,
145529
- region: regionOfDomain(this.deps.domain)
145530
- }));
145531
- });
145532
- if (held.sessionB64.length > 0 && held.sessionB64 !== stored) await sessions.put(brokerId, held.sessionB64);
145533
- this.currentError = outcome.status === "ok" ? null : outcome.error ?? "sign-in failed";
145534
- this.currentState = outcome.status === "ok" ? "ready" : "failed";
145535
- if (outcome.status !== "ok") {
145536
- logger.warn("alexa speak: sign-in as the broker failed", {
145537
- ...tags,
145538
- meta: { error: this.currentError }
145539
- });
145540
- return;
145541
- }
145542
- await this.refreshDevices();
145543
- } catch (err) {
145544
- this.currentState = "failed";
145545
- this.currentError = scrubSecrets(err instanceof Error ? err.message : String(err), secrets);
145546
- logger.warn("alexa speak: sign-in as the broker failed", {
145547
- ...tags,
145548
- meta: { error: this.currentError }
145549
- });
145550
- }
145551
- }
145552
- /** A session that is not ready tries to sign in again before it gives up. */
145553
- async ensureReady() {
145554
- if (this.currentState !== "ready") await this.signIn();
145555
- return this.currentState === "ready";
145556
- }
145557
- async refreshDevices() {
145558
- if (this.currentState !== "ready") return;
145559
- try {
145560
- this.currentDevices = [...parseDevices(await this.deps.worker.request({ op: "devices" }))];
145561
- } catch (err) {
145562
- this.deps.logger.warn("alexa speak: step 3 of 3, device list failed after a good sign-in", {
145563
- tags: { brokerId: this.deps.brokerId },
145564
- meta: { error: err instanceof Error ? err.message : String(err) }
145565
- });
145566
- }
145567
- }
145568
- async utter(op, targets, text) {
145569
- if (!await this.ensureReady()) throw new Error(this.notReadyReason());
145570
- return parseDeliveries(await this.deps.worker.request({
145571
- op,
145572
- targets,
145573
- text
145574
- }));
145575
- }
145576
- /**
145577
- * Run one worker call. A 429 starts (or doubles) the account's back-off and is
145578
- * rethrown as is; any answer ends it. Rate limiting is a status, not a failure.
145579
- */
145580
- async limited(call) {
145581
- try {
145582
- const result = await call();
145583
- this.backoffMs = 0;
145584
- this.limitedUntil = 0;
145585
- return result;
145586
- } catch (err) {
145587
- if (err instanceof RateLimitedError) {
145588
- this.backoffMs = this.backoffMs === 0 ? ECHO_RATE_BACKOFF_BASE_MS : Math.min(this.backoffMs * 2, ECHO_RATE_BACKOFF_MAX_MS);
145589
- this.limitedUntil = this.nowMs() + this.backoffMs;
145590
- this.deps.logger.info("alexa echo: amazon asked for a pause (429)", {
145591
- tags: { brokerId: this.deps.brokerId },
145592
- meta: { backoffMs: this.backoffMs }
145593
- });
145594
- }
145595
- throw err;
145596
- }
145597
- }
145598
- /** The raw player state of one Echo. Throws on any failure, a 429 included: never an empty answer. */
145599
- async playerState(serial, deviceType, deviceId) {
145600
- await this.requireReady();
145601
- return this.limited(async () => parsePlayerState(await this.deps.worker.request({
145602
- op: "player_state",
145603
- serial,
145604
- deviceType
145605
- }, withDevice(deviceId))));
145606
- }
145607
- async npCommand(serial, command, deviceId) {
145608
- await this.requireReady();
145609
- await this.limited(() => this.deps.worker.request({
145610
- op: "np_command",
145611
- serial,
145612
- command
145613
- }, withDevice(deviceId)));
145614
- }
145615
- async setVolume(serial, level, deviceId) {
145616
- await this.requireReady();
145617
- await this.limited(() => this.deps.worker.request({
145618
- op: "set_volume",
145619
- serial,
145620
- level
145621
- }, withDevice(deviceId)));
145622
- }
145623
- /** Do Not Disturb of every device of the account, by serial, in one call. */
145624
- async dndState() {
145625
- await this.requireReady();
145626
- return this.limited(async () => parseDndState(await this.deps.worker.request({ op: "dnd_state" })));
145627
- }
145628
- /** Speaker volume and mute of every device of the account, by serial, in one call. */
145629
- async deviceVolumes() {
145630
- await this.requireReady();
145631
- return this.limited(async () => parseDeviceVolumes(await this.deps.worker.request({ op: "device_volumes" })));
145632
- }
145633
- async setDnd(serial, enabled, deviceId) {
145634
- await this.requireReady();
145635
- await this.limited(() => this.deps.worker.request({
145636
- op: "set_dnd",
145637
- serial,
145638
- enabled
145639
- }, withDevice(deviceId)));
145640
- }
145641
- async requireReady() {
145642
- if (!await this.ensureReady()) throw new Error(this.notReadyReason());
145643
- }
145644
- async session() {
145645
- if (this.deps.worker.failed) return {
145646
- loggedIn: false,
145647
- ageSec: 0,
145648
- lastSuccessAt: null
145649
- };
145650
- try {
145651
- return parseSessionStatus(await this.deps.worker.request({ op: "session_status" }));
145652
- } catch {
145653
- return {
145654
- loggedIn: this.currentState === "ready",
145655
- ageSec: 0,
145656
- lastSuccessAt: null
145657
- };
145658
- }
145659
- }
145660
- notReadyReason() {
145661
- if (this.currentState === "broker-not-signed-in") return `account '${this.deps.brokerName}' is not signed in on its broker`;
145662
- return this.currentError ?? "alexa session is not ready";
145663
- }
145664
- };
145665
145388
  //#endregion
145666
145389
  //#region src/speak/rate-limit.ts
145667
145390
  /**
@@ -145885,7 +145608,6 @@ function discoveredFrom(broker, device) {
145885
145608
  }
145886
145609
  function createAlexaNotificationProvider(ports) {
145887
145610
  const logger = ports.logger ?? quietLogger$1();
145888
- let targets = ports.loadTargets();
145889
145611
  let ledger = emptySpeechLedger();
145890
145612
  let deliveries = [];
145891
145613
  function record(row) {
@@ -145904,10 +145626,6 @@ function createAlexaNotificationProvider(ports) {
145904
145626
  const owners = all.filter((broker) => broker.devices.some((device) => device.id === echoId));
145905
145627
  return owners.length === 1 ? owners[0] : void 0;
145906
145628
  }
145907
- function persist(next) {
145908
- targets = next;
145909
- ports.saveTargets(next);
145910
- }
145911
145629
  async function deliver(target, notification) {
145912
145630
  const speech = speechFromNotification(notification);
145913
145631
  const echoId = readString(target.config, "echoId");
@@ -146109,10 +145827,10 @@ function createAlexaNotificationProvider(ports) {
146109
145827
  return [alexaTargetKind()];
146110
145828
  },
146111
145829
  async listTargets() {
146112
- return [...targets];
145830
+ return [...await ports.loadTargets()];
146113
145831
  },
146114
145832
  async getTarget(input) {
146115
- const found = targets.find((target) => target.id === input.targetId);
145833
+ const found = (await ports.loadTargets()).find((target) => target.id === input.targetId);
146116
145834
  if (found === void 0) throw new Error(`target not found: ${input.targetId}`);
146117
145835
  return found;
146118
145836
  },
@@ -146131,7 +145849,7 @@ function createAlexaNotificationProvider(ports) {
146131
145849
  suggestedName: echoOptionLabel(device)
146132
145850
  }));
146133
145851
  }
146134
- const taken = new Set(targets.flatMap((row) => {
145852
+ const taken = new Set((await ports.loadTargets()).flatMap((row) => {
146135
145853
  const owner = brokerFor(row.config);
146136
145854
  return owner === void 0 ? [] : [`${owner.id}/${readString(row.config, "echoId")}`];
146137
145855
  }));
@@ -146149,7 +145867,7 @@ function createAlexaNotificationProvider(ports) {
146149
145867
  };
146150
145868
  },
146151
145869
  async send(input) {
146152
- const target = targets.find((row) => row.id === input.targetId);
145870
+ const target = (await ports.loadTargets()).find((row) => row.id === input.targetId);
146153
145871
  if (target === void 0) return {
146154
145872
  success: false,
146155
145873
  error: `target not found: ${input.targetId}`
@@ -146161,7 +145879,7 @@ function createAlexaNotificationProvider(ports) {
146161
145879
  return deliver(target, input.notification);
146162
145880
  },
146163
145881
  async testTarget(input) {
146164
- const found = targets.find((row) => row.id === input.targetId);
145882
+ const found = (await ports.loadTargets()).find((row) => row.id === input.targetId);
146165
145883
  if (found === void 0) return {
146166
145884
  success: false,
146167
145885
  error: `target not found: ${input.targetId}`
@@ -146191,20 +145909,554 @@ function createAlexaNotificationProvider(ports) {
146191
145909
  addonId: ALEXA_SPEAK_ADDON_ID,
146192
145910
  kind: ALEXA_SPEAK_KIND
146193
145911
  };
146194
- persist([...targets.filter((row) => row.id !== target.id), target]);
145912
+ await ports.putTarget(target);
146195
145913
  return target;
146196
145914
  },
146197
145915
  async deleteTarget(input) {
146198
- persist(targets.filter((row) => row.id !== input.targetId));
145916
+ await ports.removeTarget(input.targetId);
146199
145917
  },
146200
145918
  async setTargetEnabled(input) {
146201
- persist(targets.map((row) => row.id === input.targetId ? {
146202
- ...row,
145919
+ const found = (await ports.loadTargets()).find((row) => row.id === input.targetId);
145920
+ if (found !== void 0) await ports.putTarget({
145921
+ ...found,
146203
145922
  enabled: input.enabled
146204
- } : row));
145923
+ });
145924
+ }
145925
+ };
145926
+ }
145927
+ //#endregion
145928
+ //#region src/speak/echo-store.ts
145929
+ /**
145930
+ * The Echo targets as records: one `notify-alexa-echo` record per target (an instance of the function
145931
+ * cap `notification-output`), the id the one a notification rule names. The records are the one source:
145932
+ * the controller reads them on every use and writes only the row it changes.
145933
+ */
145934
+ var alexaNotifyRecordKinds = notificationTargetKinds([alexaTargetKind()]);
145935
+ function echoTargetStoreOver(records, options = {}) {
145936
+ return NotificationTargetStore.of(records, ALEXA_SPEAK_ADDON_ID, alexaNotifyRecordKinds, [alexaTargetKind()], options);
145937
+ }
145938
+ /** The `echoTargets` setting as the legacy source: a row the migration left there is still served. */
145939
+ function legacyEchoTargetsOver(setting) {
145940
+ return {
145941
+ list: async () => readEchoTargets({ echoTargets: setting.readRows() }).map((row) => ({
145942
+ id: row.id,
145943
+ name: row.name,
145944
+ kind: alexaTargetKind().kind,
145945
+ enabled: row.enabled,
145946
+ config: {
145947
+ ...row.brokerId.length > 0 ? { brokerId: row.brokerId } : {},
145948
+ echoId: row.echoId,
145949
+ respectDnd: row.respectDnd
145950
+ }
145951
+ })),
145952
+ delete: async (id) => {
145953
+ const rest = setting.readRows().filter((row) => {
145954
+ const parsed = alexaEchoTargetSchema.safeParse(row);
145955
+ return !(parsed.success && parsed.data.id === id);
145956
+ });
145957
+ if (rest.length !== setting.readRows().length) await setting.writeRows(rest);
145958
+ }
145959
+ };
145960
+ }
145961
+ /** The row a stored target is for the settings page: the account link is '' until one is chosen. */
145962
+ function echoRowOf(target) {
145963
+ return {
145964
+ id: target.id,
145965
+ name: target.name,
145966
+ enabled: target.enabled,
145967
+ brokerId: typeof target.config["brokerId"] === "string" ? target.config["brokerId"] : "",
145968
+ echoId: typeof target.config["echoId"] === "string" ? target.config["echoId"] : "",
145969
+ respectDnd: target.config["respectDnd"] !== false
145970
+ };
145971
+ }
145972
+ /** The migration's ports over the `notify-alexa-echo` record kind. */
145973
+ function echoRecordPortsOver(records, logger) {
145974
+ const handle = echoTargetStoreOver(records).handlesByKind().get(alexaTargetKind().kind);
145975
+ if (handle === void 0) throw new Error("import-alexa: the Echo target record kind is not declared");
145976
+ return {
145977
+ readEchoRecord: async (id) => (await handle.getResolved(id))?.data ?? null,
145978
+ writeEchoRecord: async (id, body) => {
145979
+ await handle.put({
145980
+ id,
145981
+ data: body
145982
+ });
145983
+ },
145984
+ dropEchoRecord: async (id) => {
145985
+ await handle.delete(id);
145986
+ },
145987
+ echoSkipped: (row) => {
145988
+ logger.warn("Echo target left in the echoTargets setting; it keeps being served", { meta: {
145989
+ targetId: row.id,
145990
+ reason: row.reason
145991
+ } });
146205
145992
  }
146206
145993
  };
146207
145994
  }
145995
+ /**
145996
+ * The Echo instance's test: the old probe (is the Amazon account of the target signed in on its
145997
+ * broker?) as the tri-state of `testInstance`. Speech not running yet answers `inconclusive` through
145998
+ * the same mapping (a failure with no HTTP status), never `unsupported`.
145999
+ */
146000
+ function echoTargetProbe(speak) {
146001
+ return async (input) => {
146002
+ const source = speak();
146003
+ if (source === null) return {
146004
+ ok: false,
146005
+ resolvedUrl: "alexa://session",
146006
+ error: "Echo speech is not running"
146007
+ };
146008
+ return source.provider.probeTargetConfig({
146009
+ kind: input.kind,
146010
+ config: input.config
146011
+ });
146012
+ };
146013
+ }
146014
+ process.platform, process.env["SystemRoot"];
146015
+ /**
146016
+ * Files only their owner may read: the one place a secret-bearing file is
146017
+ * restricted, on every OS.
146018
+ *
146019
+ * `mode: 0o600` is a POSIX idea. On Windows Node maps it to the read-only
146020
+ * attribute and nothing else, and `chmod` is a no-op for permissions, so a
146021
+ * "0600" `agent.json` (the mesh private key) would have
146022
+ * been readable by every local user. Windows has its own tool for this:
146023
+ * `icacls`. This module removes the inherited ACL entries and grants access to
146024
+ * the current user and SYSTEM only — the Windows reading of "0600".
146025
+ *
146026
+ * ZERO imports beyond Node built-ins, on purpose: the Electron shell bundles
146027
+ * this single file (see `packages/desktop/tsup.config.ts`) instead of the
146028
+ * whole `@camstack/types` barrel.
146029
+ *
146030
+ * Failure is NOT swallowed. A secret file that could not be restricted is a
146031
+ * secret file the caller must know about, so `OwnerOnlyError` propagates; the
146032
+ * write order below makes sure nothing sensitive is in the file yet when that
146033
+ * happens (the temp file is empty until it has been restricted).
146034
+ *
146035
+ * Out of scope on purpose: files that are only tidy, not secret (the job
146036
+ * journal, the addon manifest) keep a plain `mode`, since one `icacls` per
146037
+ * write would be a process spawn on a hot path.
146038
+ */
146039
+ /** `*S-1-5-18` is SYSTEM in every locale — a name like "SYSTEM" is not. */
146040
+ var WINDOWS_SYSTEM_SID = "*S-1-5-18";
146041
+ var FILE_MODE = 384;
146042
+ var DIR_MODE = 448;
146043
+ var OwnerOnlyError = class extends Error {
146044
+ target;
146045
+ constructor(target, detail) {
146046
+ super(`could not restrict ${target} to its owner: ${detail}`);
146047
+ this.target = target;
146048
+ this.name = "OwnerOnlyError";
146049
+ }
146050
+ };
146051
+ function currentPrincipal() {
146052
+ const user = process.env["USERNAME"] ?? userInfo().username;
146053
+ const domain = process.env["USERDOMAIN"];
146054
+ return domain !== void 0 && domain.length > 0 ? `${domain}\\${user}` : user;
146055
+ }
146056
+ /** Resolved per call, not at import: a platform stubbed by a test must be seen. */
146057
+ function resolveDeps(overrides) {
146058
+ return {
146059
+ platform: process.platform,
146060
+ exec: (file, args) => {
146061
+ execFileSync(file, [...args], {
146062
+ stdio: "pipe",
146063
+ windowsHide: true
146064
+ });
146065
+ },
146066
+ principal: currentPrincipal,
146067
+ systemRoot: process.env["SystemRoot"],
146068
+ ...overrides
146069
+ };
146070
+ }
146071
+ /** The icacls argv for one path: no inheritance, owner + SYSTEM only. */
146072
+ function icaclsArgs(target, principal, isDirectory) {
146073
+ const inherit = isDirectory ? "(OI)(CI)" : "";
146074
+ return [
146075
+ target,
146076
+ "/inheritance:r",
146077
+ "/grant:r",
146078
+ `${principal}:${inherit}F`,
146079
+ "/grant:r",
146080
+ `${WINDOWS_SYSTEM_SID}:${inherit}F`
146081
+ ];
146082
+ }
146083
+ function restrictWindows(target, isDirectory, deps) {
146084
+ const icacls = path.win32.join(deps.systemRoot ?? "C:\\Windows", "System32", "icacls.exe");
146085
+ try {
146086
+ deps.exec(icacls, icaclsArgs(target, deps.principal(), isDirectory));
146087
+ } catch (err) {
146088
+ throw new OwnerOnlyError(target, err instanceof Error ? err.message : String(err));
146089
+ }
146090
+ }
146091
+ /** Restrict an existing file to its owner (chmod 0600 / owner+SYSTEM ACL). */
146092
+ function restrictFileToOwnerSync(target, overrides = {}) {
146093
+ const deps = resolveDeps(overrides);
146094
+ if (deps.platform === "win32") {
146095
+ restrictWindows(target, false, deps);
146096
+ return;
146097
+ }
146098
+ fs.chmodSync(target, FILE_MODE);
146099
+ }
146100
+ /** Restrict an existing directory to its owner (chmod 0700 / owner+SYSTEM, inherited). */
146101
+ function restrictDirToOwnerSync(target, overrides = {}) {
146102
+ const deps = resolveDeps(overrides);
146103
+ if (deps.platform === "win32") {
146104
+ restrictWindows(target, true, deps);
146105
+ return;
146106
+ }
146107
+ fs.chmodSync(target, DIR_MODE);
146108
+ }
146109
+ /**
146110
+ * Atomically write a secret-bearing file that only its owner can read.
146111
+ *
146112
+ * Order matters: the temp file is created EMPTY, restricted, and only then
146113
+ * given its content, so there is no moment at which the secret exists under a
146114
+ * permissive ACL. The rename carries the (already restricted) ACL with it.
146115
+ */
146116
+ function writeOwnerOnlyFileSync(target, data, overrides = {}) {
146117
+ fs.mkdirSync(path.dirname(target), { recursive: true });
146118
+ const tmp = `${target}.tmp.${process.pid}`;
146119
+ fs.writeFileSync(tmp, "", { mode: FILE_MODE });
146120
+ try {
146121
+ restrictFileToOwnerSync(tmp, overrides);
146122
+ fs.writeFileSync(tmp, data);
146123
+ fs.renameSync(tmp, target);
146124
+ } catch (err) {
146125
+ fs.rmSync(tmp, { force: true });
146126
+ throw err;
146127
+ }
146128
+ }
146129
+ //#endregion
146130
+ //#region src/speak/secret-file.ts
146131
+ /**
146132
+ * Hand a refresh token or a saved Amazon session to the Python worker as an
146133
+ * owner-only file. The path travels on stdin. The bytes never travel on
146134
+ * argv or in the environment, and they are removed when the call settles.
146135
+ */
146136
+ var REDACTED = "‹redacted›";
146137
+ function decodeSession(sessionB64) {
146138
+ if (sessionB64.length === 0) return Buffer.alloc(0);
146139
+ return Buffer.from(sessionB64, "base64");
146140
+ }
146141
+ async function readSessionB64(sessionPath) {
146142
+ const bytes = await fs$1.readFile(sessionPath);
146143
+ if (bytes.length === 0) return "";
146144
+ return bytes.toString("base64");
146145
+ }
146146
+ /**
146147
+ * Create a 0700 directory, write the refresh token and the session 0600, run
146148
+ * `body`, then delete the directory whether `body` succeeded or threw.
146149
+ * Returns the session file as base64 so the caller can store it in the keychain.
146150
+ */
146151
+ async function withSpeakSecretFiles(input, body) {
146152
+ const dir = await fs$1.mkdtemp(path.join(os.tmpdir(), "camstack-alexa-"));
146153
+ const paths = {
146154
+ dir,
146155
+ refreshTokenPath: path.join(dir, "refresh-token"),
146156
+ sessionPath: path.join(dir, "session")
146157
+ };
146158
+ try {
146159
+ restrictDirToOwnerSync(dir);
146160
+ writeOwnerOnlyFileSync(paths.refreshTokenPath, input.refreshToken);
146161
+ writeOwnerOnlyFileSync(paths.sessionPath, decodeSession(input.sessionB64));
146162
+ await body(paths);
146163
+ return { sessionB64: await readSessionB64(paths.sessionPath) };
146164
+ } finally {
146165
+ await fs$1.rm(dir, {
146166
+ recursive: true,
146167
+ force: true
146168
+ });
146169
+ }
146170
+ }
146171
+ /** Replace every occurrence of each non-empty secret. Used before a log line is emitted. */
146172
+ function scrubSecrets(text, secrets) {
146173
+ let out = text;
146174
+ for (const secret of secrets) {
146175
+ if (secret.length === 0) continue;
146176
+ out = out.split(secret).join(REDACTED);
146177
+ }
146178
+ return out;
146179
+ }
146180
+ //#endregion
146181
+ //#region src/speak/broker-echo.ts
146182
+ function withDevice(deviceId) {
146183
+ return deviceId === void 0 ? {} : { deviceId };
146184
+ }
146185
+ var BrokerEcho = class {
146186
+ deps;
146187
+ currentState = "starting";
146188
+ currentError = null;
146189
+ currentDevices = [];
146190
+ backoffMs = 0;
146191
+ limitedUntil = 0;
146192
+ channelState = "down";
146193
+ channelWasUp = false;
146194
+ secrets = [];
146195
+ unknownPushLogged = /* @__PURE__ */ new Set();
146196
+ constructor(deps) {
146197
+ this.deps = deps;
146198
+ deps.worker.onPush((push) => this.onPush(push));
146199
+ }
146200
+ /** Whether Amazon's push channel is open for this account right now. */
146201
+ get pushChannel() {
146202
+ return this.channelState;
146203
+ }
146204
+ /** A reason is text from the library: capped, then scrubbed of the secrets in play. */
146205
+ safeReason(reason) {
146206
+ return scrubSecrets(reason.slice(0, 200), this.secrets);
146207
+ }
146208
+ onPush(push) {
146209
+ const tags = { tags: { brokerId: this.deps.brokerId } };
146210
+ if (push.push === "channel") {
146211
+ if (push.state === this.channelState) {
146212
+ if (push.state === "down") this.deps.logger.debug("alexa echo: push channel still down", {
146213
+ ...tags,
146214
+ meta: {
146215
+ reason: this.safeReason(push.reason),
146216
+ retryInMs: push.retryInMs
146217
+ }
146218
+ });
146219
+ return;
146220
+ }
146221
+ this.channelState = push.state;
146222
+ if (push.state === "up") {
146223
+ this.deps.logger.info(this.channelWasUp ? "alexa echo: push channel reconnected, polling slows down" : "alexa echo: push channel connected, polling slows down", tags);
146224
+ this.channelWasUp = true;
146225
+ } else this.deps.logger.warn("alexa echo: push channel down, polling at the normal pace", {
146226
+ ...tags,
146227
+ meta: {
146228
+ reason: this.safeReason(push.reason),
146229
+ retryInMs: push.retryInMs
146230
+ }
146231
+ });
146232
+ this.deps.push?.channel(this.deps.brokerId, push.state);
146233
+ return;
146234
+ }
146235
+ if (PUSH_READ_COMMANDS.has(push.command)) {
146236
+ if (push.serial === null) {
146237
+ this.deps.logger.debug("alexa echo: push event without an Echo, ignored", {
146238
+ ...tags,
146239
+ meta: { command: push.command }
146240
+ });
146241
+ return;
146242
+ }
146243
+ this.deps.push?.event(this.deps.brokerId, push.serial);
146244
+ return;
146245
+ }
146246
+ if (PUSH_IGNORED_COMMANDS.has(push.command)) return;
146247
+ if (this.unknownPushLogged.has(push.command)) return;
146248
+ this.unknownPushLogged.add(push.command);
146249
+ this.deps.logger.info("alexa echo: unknown push event, ignored (logged once)", {
146250
+ ...tags,
146251
+ meta: { command: push.command }
146252
+ });
146253
+ }
146254
+ get id() {
146255
+ return this.deps.brokerId;
146256
+ }
146257
+ get name() {
146258
+ return this.deps.brokerName;
146259
+ }
146260
+ get state() {
146261
+ return this.currentState;
146262
+ }
146263
+ get error() {
146264
+ return this.currentError;
146265
+ }
146266
+ get devices() {
146267
+ return this.currentDevices;
146268
+ }
146269
+ /** Ms epoch until which Amazon asked us to wait (429), or null when the account is free. */
146270
+ get rateLimitedUntil() {
146271
+ return this.limitedUntil > this.nowMs() ? this.limitedUntil : null;
146272
+ }
146273
+ nowMs() {
146274
+ return (this.deps.now ?? Date.now)();
146275
+ }
146276
+ stop() {
146277
+ this.deps.worker.stop();
146278
+ if (this.channelState === "up") {
146279
+ this.channelState = "down";
146280
+ this.deps.push?.channel(this.deps.brokerId, "down");
146281
+ }
146282
+ }
146283
+ /** Sign the worker in as the broker's account. Never throws; the outcome is `state`. */
146284
+ async signIn() {
146285
+ const { brokerId, worker, sessions, logger } = this.deps;
146286
+ const tags = { tags: { brokerId } };
146287
+ let secrets = [];
146288
+ try {
146289
+ const seed = await this.deps.readSeed();
146290
+ const stored = await sessions.get(brokerId);
146291
+ logger.info("alexa speak: broker sign-in material", {
146292
+ ...tags,
146293
+ meta: {
146294
+ seedFound: seed !== null,
146295
+ hasRefreshToken: seed !== null && seed.refreshToken.length > 0,
146296
+ hasDeviceAppName: seed !== null && seed.deviceAppName.length > 0,
146297
+ hasStoredSession: stored.length > 0
146298
+ }
146299
+ });
146300
+ if (seed === null && stored.length === 0) {
146301
+ this.currentState = "broker-not-signed-in";
146302
+ this.currentError = null;
146303
+ logger.warn("alexa speak: the broker has no sign-in to share yet", tags);
146304
+ return;
146305
+ }
146306
+ secrets = seed === null ? [] : [seed.refreshToken];
146307
+ worker.noteSecrets(secrets);
146308
+ this.secrets = secrets;
146309
+ let outcome = parseLoginResult({
146310
+ status: "failed",
146311
+ error: "worker gave no answer"
146312
+ });
146313
+ const held = await withSpeakSecretFiles({
146314
+ refreshToken: seed?.refreshToken ?? "",
146315
+ sessionB64: stored
146316
+ }, async (paths) => {
146317
+ outcome = parseLoginResult(await worker.request({
146318
+ op: "login_broker",
146319
+ label: brokerId,
146320
+ refreshTokenPath: seed === null ? "" : paths.refreshTokenPath,
146321
+ deviceAppName: seed?.deviceAppName ?? "",
146322
+ domain: this.deps.domain,
146323
+ sessionPath: paths.sessionPath,
146324
+ region: regionOfDomain(this.deps.domain)
146325
+ }));
146326
+ });
146327
+ if (held.sessionB64.length > 0 && held.sessionB64 !== stored) await sessions.put(brokerId, held.sessionB64);
146328
+ this.currentError = outcome.status === "ok" ? null : outcome.error ?? "sign-in failed";
146329
+ this.currentState = outcome.status === "ok" ? "ready" : "failed";
146330
+ if (outcome.status !== "ok") {
146331
+ logger.warn("alexa speak: sign-in as the broker failed", {
146332
+ ...tags,
146333
+ meta: { error: this.currentError }
146334
+ });
146335
+ return;
146336
+ }
146337
+ await this.refreshDevices();
146338
+ } catch (err) {
146339
+ this.currentState = "failed";
146340
+ this.currentError = scrubSecrets(err instanceof Error ? err.message : String(err), secrets);
146341
+ logger.warn("alexa speak: sign-in as the broker failed", {
146342
+ ...tags,
146343
+ meta: { error: this.currentError }
146344
+ });
146345
+ }
146346
+ }
146347
+ /** A session that is not ready tries to sign in again before it gives up. */
146348
+ async ensureReady() {
146349
+ if (this.currentState !== "ready") await this.signIn();
146350
+ return this.currentState === "ready";
146351
+ }
146352
+ async refreshDevices() {
146353
+ if (this.currentState !== "ready") return;
146354
+ try {
146355
+ this.currentDevices = [...parseDevices(await this.deps.worker.request({ op: "devices" }))];
146356
+ } catch (err) {
146357
+ this.deps.logger.warn("alexa speak: step 3 of 3, device list failed after a good sign-in", {
146358
+ tags: { brokerId: this.deps.brokerId },
146359
+ meta: { error: err instanceof Error ? err.message : String(err) }
146360
+ });
146361
+ }
146362
+ }
146363
+ async utter(op, targets, text) {
146364
+ if (!await this.ensureReady()) throw new Error(this.notReadyReason());
146365
+ return parseDeliveries(await this.deps.worker.request({
146366
+ op,
146367
+ targets,
146368
+ text
146369
+ }));
146370
+ }
146371
+ /**
146372
+ * Run one worker call. A 429 starts (or doubles) the account's back-off and is
146373
+ * rethrown as is; any answer ends it. Rate limiting is a status, not a failure.
146374
+ */
146375
+ async limited(call) {
146376
+ try {
146377
+ const result = await call();
146378
+ this.backoffMs = 0;
146379
+ this.limitedUntil = 0;
146380
+ return result;
146381
+ } catch (err) {
146382
+ if (err instanceof RateLimitedError) {
146383
+ this.backoffMs = this.backoffMs === 0 ? ECHO_RATE_BACKOFF_BASE_MS : Math.min(this.backoffMs * 2, ECHO_RATE_BACKOFF_MAX_MS);
146384
+ this.limitedUntil = this.nowMs() + this.backoffMs;
146385
+ this.deps.logger.info("alexa echo: amazon asked for a pause (429)", {
146386
+ tags: { brokerId: this.deps.brokerId },
146387
+ meta: { backoffMs: this.backoffMs }
146388
+ });
146389
+ }
146390
+ throw err;
146391
+ }
146392
+ }
146393
+ /** The raw player state of one Echo. Throws on any failure, a 429 included: never an empty answer. */
146394
+ async playerState(serial, deviceType, deviceId) {
146395
+ await this.requireReady();
146396
+ return this.limited(async () => parsePlayerState(await this.deps.worker.request({
146397
+ op: "player_state",
146398
+ serial,
146399
+ deviceType
146400
+ }, withDevice(deviceId))));
146401
+ }
146402
+ async npCommand(serial, command, deviceId) {
146403
+ await this.requireReady();
146404
+ await this.limited(() => this.deps.worker.request({
146405
+ op: "np_command",
146406
+ serial,
146407
+ command
146408
+ }, withDevice(deviceId)));
146409
+ }
146410
+ async setVolume(serial, level, deviceId) {
146411
+ await this.requireReady();
146412
+ await this.limited(() => this.deps.worker.request({
146413
+ op: "set_volume",
146414
+ serial,
146415
+ level
146416
+ }, withDevice(deviceId)));
146417
+ }
146418
+ /** Do Not Disturb of every device of the account, by serial, in one call. */
146419
+ async dndState() {
146420
+ await this.requireReady();
146421
+ return this.limited(async () => parseDndState(await this.deps.worker.request({ op: "dnd_state" })));
146422
+ }
146423
+ /** Speaker volume and mute of every device of the account, by serial, in one call. */
146424
+ async deviceVolumes() {
146425
+ await this.requireReady();
146426
+ return this.limited(async () => parseDeviceVolumes(await this.deps.worker.request({ op: "device_volumes" })));
146427
+ }
146428
+ async setDnd(serial, enabled, deviceId) {
146429
+ await this.requireReady();
146430
+ await this.limited(() => this.deps.worker.request({
146431
+ op: "set_dnd",
146432
+ serial,
146433
+ enabled
146434
+ }, withDevice(deviceId)));
146435
+ }
146436
+ async requireReady() {
146437
+ if (!await this.ensureReady()) throw new Error(this.notReadyReason());
146438
+ }
146439
+ async session() {
146440
+ if (this.deps.worker.failed) return {
146441
+ loggedIn: false,
146442
+ ageSec: 0,
146443
+ lastSuccessAt: null
146444
+ };
146445
+ try {
146446
+ return parseSessionStatus(await this.deps.worker.request({ op: "session_status" }));
146447
+ } catch {
146448
+ return {
146449
+ loggedIn: this.currentState === "ready",
146450
+ ageSec: 0,
146451
+ lastSuccessAt: null
146452
+ };
146453
+ }
146454
+ }
146455
+ notReadyReason() {
146456
+ if (this.currentState === "broker-not-signed-in") return `account '${this.deps.brokerName}' is not signed in on its broker`;
146457
+ return this.currentError ?? "alexa session is not ready";
146458
+ }
146459
+ };
146208
146460
  //#endregion
146209
146461
  //#region src/speak/python-paths.ts
146210
146462
  /** Locate bundled `python/alexa_worker.py` from dist/ or from src/ under test. */
@@ -146583,34 +146835,9 @@ function startAlexaWorker(deps) {
146583
146835
  }
146584
146836
  //#endregion
146585
146837
  //#region src/speak/controller.ts
146586
- function targetsFrom(rows) {
146587
- return rows.map((row) => ({
146588
- id: row.id,
146589
- name: row.name,
146590
- kind: ALEXA_SPEAK_KIND,
146591
- addonId: ALEXA_SPEAK_ADDON_ID,
146592
- enabled: row.enabled,
146593
- config: {
146594
- ...row.brokerId.length > 0 ? { brokerId: row.brokerId } : {},
146595
- echoId: row.echoId,
146596
- respectDnd: row.respectDnd
146597
- }
146598
- }));
146599
- }
146600
- function rowsFrom(targets) {
146601
- return targets.map((target) => ({
146602
- id: target.id,
146603
- name: target.name,
146604
- enabled: target.enabled,
146605
- brokerId: typeof target.config["brokerId"] === "string" ? target.config["brokerId"] : "",
146606
- echoId: typeof target.config["echoId"] === "string" ? target.config["echoId"] : "",
146607
- respectDnd: target.config["respectDnd"] !== false
146608
- }));
146609
- }
146610
146838
  var AlexaSpeakController = class {
146611
146839
  host;
146612
146840
  provider;
146613
- rows;
146614
146841
  pythonPath = null;
146615
146842
  echoes = /* @__PURE__ */ new Map();
146616
146843
  timer = null;
@@ -146619,16 +146846,13 @@ var AlexaSpeakController = class {
146619
146846
  constructor(host) {
146620
146847
  this.host = host;
146621
146848
  this.now = host.now ?? (() => Date.now());
146622
- this.rows = readEchoTargets(host.readConfig());
146623
146849
  this.provider = createAlexaNotificationProvider({
146624
146850
  brokers: () => this.brokerViews(),
146625
146851
  now: this.now,
146626
146852
  logger: host.logger,
146627
- loadTargets: () => targetsFrom(this.rows),
146628
- saveTargets: (targets) => {
146629
- this.rows = rowsFrom(targets);
146630
- this.persist();
146631
- },
146853
+ loadTargets: () => host.readTargets(),
146854
+ putTarget: (target) => host.putTarget(target),
146855
+ removeTarget: (targetId) => host.removeTarget(targetId),
146632
146856
  speak: (command) => this.utter(command.brokerId, command.mode, command.targets, command.text)
146633
146857
  });
146634
146858
  }
@@ -146670,13 +146894,6 @@ var AlexaSpeakController = class {
146670
146894
  };
146671
146895
  });
146672
146896
  }
146673
- async persist() {
146674
- try {
146675
- await this.host.writeTargets(this.rows);
146676
- } catch (err) {
146677
- this.host.logger.warn("alexa speak: could not store targets", { meta: { error: err instanceof Error ? err.message : String(err) } });
146678
- }
146679
- }
146680
146897
  makeWorker(brokerId, pythonPath) {
146681
146898
  if (this.host.startWorker !== void 0) return this.host.startWorker(brokerId, pythonPath);
146682
146899
  return startAlexaWorker({
@@ -146878,6 +147095,80 @@ async function stripEchoTargetVolumeAndMode(ports) {
146878
147095
  };
146879
147096
  }
146880
147097
  //#endregion
147098
+ //#region src/migrations/echo-targets-to-records.ts
147099
+ /**
147100
+ * The Echo notification targets move from the `echoTargets` setting (one array in the addon's global
147101
+ * settings) to one `notify-alexa-echo` record each, under the SAME id so a notification rule naming it
147102
+ * still resolves (epic #440, step 6). The switch (`enabled`) is carried across, never reset.
147103
+ *
147104
+ * Each record is read back before its row leaves the setting. One bad row never aborts the others: a row
147105
+ * whose write or read-back fails is undone, reported with its id and reason, and stays in the setting,
147106
+ * where the Echo store keeps serving it. A record that already exists is never overwritten (an operator
147107
+ * may have edited it since). A row that does not parse is left where it is and keeps the setting in
147108
+ * place: nothing is destroyed on a guess (D49).
147109
+ */
147110
+ var ECHO_TARGETS_TO_RECORDS_ID = "import-alexa/2026-11-06-echo-targets-to-records";
147111
+ async function moveEchoTargetsToRecords(ports) {
147112
+ const rows = ports.readRows();
147113
+ if (rows.length === 0) return {
147114
+ outcome: "already-done",
147115
+ summary: { converted: 0 }
147116
+ };
147117
+ let converted = 0;
147118
+ let kept = 0;
147119
+ let unparsed = 0;
147120
+ const left = [];
147121
+ for (const row of rows) {
147122
+ const parsed = alexaEchoTargetSchema.safeParse(row);
147123
+ if (!parsed.success) {
147124
+ unparsed += 1;
147125
+ continue;
147126
+ }
147127
+ const target = parsed.data;
147128
+ try {
147129
+ if (await ports.readEchoRecord(target.id) !== null) {
147130
+ kept += 1;
147131
+ continue;
147132
+ }
147133
+ const body = targetBody({
147134
+ id: target.id,
147135
+ name: target.name,
147136
+ enabled: target.enabled,
147137
+ config: {
147138
+ ...target.brokerId.length > 0 ? { brokerId: target.brokerId } : {},
147139
+ echoId: target.echoId,
147140
+ respectDnd: target.respectDnd
147141
+ }
147142
+ });
147143
+ await ports.writeEchoRecord(target.id, body);
147144
+ const back = await ports.readEchoRecord(target.id);
147145
+ if (!(back !== null && back["name"] === body["name"] && back["enabled"] === body["enabled"] && back["echoId"] === body["echoId"] && back["respectDnd"] === body["respectDnd"] && back["brokerId"] === body["brokerId"])) {
147146
+ await ports.dropEchoRecord(target.id);
147147
+ throw new Error("the new record did not read back");
147148
+ }
147149
+ converted += 1;
147150
+ } catch (err) {
147151
+ await ports.dropEchoRecord(target.id).catch(() => void 0);
147152
+ ports.echoSkipped({
147153
+ id: target.id,
147154
+ reason: err instanceof Error ? err.message : String(err)
147155
+ });
147156
+ left.push(row);
147157
+ }
147158
+ }
147159
+ if (unparsed === 0) await ports.writeRows(left);
147160
+ return {
147161
+ outcome: converted > 0 || kept > 0 ? "done" : "already-done",
147162
+ summary: {
147163
+ converted,
147164
+ kept,
147165
+ unparsed,
147166
+ skipped: left.length,
147167
+ kind: ALEXA_SPEAK_KIND
147168
+ }
147169
+ };
147170
+ }
147171
+ //#endregion
146881
147172
  //#region src/migrations/index.ts
146882
147173
  /** The `import-alexa` catalogue (D987): offered to the engine when the addon initialises. */
146883
147174
  var ADDON_MIGRATIONS = [
@@ -146944,6 +147235,22 @@ var ADDON_MIGRATIONS = [
146944
147235
  fixtureMark: "the name and the extra field of the account that keeps its record"
146945
147236
  },
146946
147237
  procedure: moveBrokerLinksToConnections
147238
+ },
147239
+ {
147240
+ meta: {
147241
+ id: ECHO_TARGETS_TO_RECORDS_ID,
147242
+ owner: "import-alexa",
147243
+ level: "addon-state",
147244
+ seq: 5,
147245
+ dependsOn: ["import-alexa/2026-11-01-strip-echo-target-volume-and-mode"],
147246
+ store: "settings",
147247
+ scope: "cluster",
147248
+ onFailure: "tolerate",
147249
+ bodyKind: "procedure",
147250
+ description: "Move each Echo target from the echoTargets setting to a notify-alexa-echo record under the same id, the switch carried, read back before its row leaves the setting; a row that fails stays in the setting and is still served; a record that exists is never overwritten",
147251
+ fixtureMark: "the switch (off) and the id of an Echo target"
147252
+ },
147253
+ procedure: moveEchoTargetsToRecords
146947
147254
  }
146948
147255
  ];
146949
147256
  /** The migrations that rewrite the broker records: they run BEFORE anything reads or persists one. */
@@ -147053,6 +147360,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147053
147360
  accountInstances = null;
147054
147361
  activeBrokers = [];
147055
147362
  speak = null;
147363
+ echoStore = null;
147056
147364
  constructor() {
147057
147365
  super({ ...DEFAULTS });
147058
147366
  }
@@ -147060,7 +147368,10 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147060
147368
  const regs = this.providerRegistrationsFromSuper(await super.onInitialize());
147061
147369
  const records = this.ctx.records;
147062
147370
  if (records === void 0) throw new Error("import-alexa: ctx.records is required (hub-only addon)");
147063
- await records.declare(alexaRecordKinds);
147371
+ await records.declare({
147372
+ ...alexaRecordKinds,
147373
+ ...alexaNotifyRecordKinds
147374
+ });
147064
147375
  this.brokerStore = AlexaBrokerStore.of(records);
147065
147376
  this.instances = buildAlexaInstances(records);
147066
147377
  this.accountInstances = buildAlexaAccountInstances(records, {
@@ -147110,12 +147421,16 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147110
147421
  commitCookie: (input) => this.commitCapturedCookie(input)
147111
147422
  }), ...speakIconRoutes()];
147112
147423
  await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.migrationPorts(records)), { only: ADDON_MIGRATIONS.map((m) => m.meta.id).filter((id) => !BROKER_RECORD_MIGRATION_IDS.includes(id)) });
147424
+ const echoStore = echoTargetStoreOver(records, {
147425
+ logger: this.ctx.logger,
147426
+ legacy: legacyEchoTargetsOver(this.echoSettingPorts())
147427
+ });
147428
+ this.echoStore = echoStore;
147113
147429
  const speak = new AlexaSpeakController({
147114
147430
  logger: this.ctx.logger.child("speak"),
147115
- readConfig: () => this.config,
147116
- writeTargets: async (next) => {
147117
- await this.updateGlobalSettings({ echoTargets: [...next] });
147118
- },
147431
+ readTargets: () => echoStore.list(),
147432
+ putTarget: (target) => echoStore.upsert(target),
147433
+ removeTarget: (targetId) => echoStore.delete(targetId),
147119
147434
  listBrokers: () => this.activeBrokers.map((entry) => ({
147120
147435
  id: entry.id,
147121
147436
  name: entry.name,
@@ -147158,16 +147473,23 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147158
147473
  }
147159
147474
  ] };
147160
147475
  }
147161
- migrationPorts(records) {
147162
- const secrets = this.ctx.secrets;
147163
- if (secrets === void 0) throw new Error("import-alexa: ctx.secrets is required");
147476
+ /** The `echoTargets` setting, read and written as the migration and the legacy store see it. */
147477
+ echoSettingPorts() {
147164
147478
  return {
147165
147479
  readRows: () => Array.isArray(this.config.echoTargets) ? this.config.echoTargets : [],
147166
147480
  writeRows: async (rows) => {
147167
147481
  await this.updateGlobalSettings({ echoTargets: [...readEchoTargets({ echoTargets: rows })] });
147168
- },
147482
+ }
147483
+ };
147484
+ }
147485
+ migrationPorts(records) {
147486
+ const secrets = this.ctx.secrets;
147487
+ if (secrets === void 0) throw new Error("import-alexa: ctx.secrets is required");
147488
+ return {
147489
+ ...this.echoSettingPorts(),
147169
147490
  ...flattenPortsOver(records.kind(alexaBrokersEntryKind)),
147170
147491
  ...alexaBrokerLinkPorts(records, (message) => this.ctx.logger.warn(message)),
147492
+ ...echoRecordPortsOver(records, this.ctx.logger),
147171
147493
  ...alexaIntegrationRowsPorts({
147172
147494
  api: defaultIntegrationApiOver(this.ctx.api),
147173
147495
  records,
@@ -147179,28 +147501,40 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147179
147501
  /** One provider over the two record kinds: the account (broker) and the integrations using it. */
147180
147502
  buildInstancesProvider() {
147181
147503
  if (this.accountInstances === null) throw new Error("import-alexa: account instances not ready");
147182
- return composeInstanceKinds([{
147183
- kind: {
147184
- id: "account",
147185
- label: "Alexa account",
147186
- functionCap: "broker",
147187
- brokerKind: ALEXA_BROKER_KIND,
147188
- role: "services",
147189
- signIn: {
147190
- basePath: ALEXA_SIGN_IN_PATH,
147191
- methods: ["device-code", "proxy"]
147192
- }
147504
+ const records = this.ctx.records;
147505
+ if (records === void 0) throw new Error("import-alexa: ctx.records is required");
147506
+ return composeInstanceKinds([
147507
+ {
147508
+ kind: {
147509
+ id: "account",
147510
+ label: "Alexa account",
147511
+ functionCap: "broker",
147512
+ brokerKind: ALEXA_BROKER_KIND,
147513
+ role: "services",
147514
+ signIn: {
147515
+ basePath: ALEXA_SIGN_IN_PATH,
147516
+ methods: ["device-code", "proxy"]
147517
+ }
147518
+ },
147519
+ provider: guardInstanceDelete(this.accountInstances.toProvider(), () => this.brokerUsers())
147193
147520
  },
147194
- provider: guardInstanceDelete(this.accountInstances.toProvider(), () => this.brokerUsers())
147195
- }, {
147196
- kind: {
147197
- id: "integration",
147198
- label: "Alexa",
147199
- functionCap: "device-provider",
147200
- role: "devices"
147521
+ {
147522
+ kind: {
147523
+ id: "integration",
147524
+ label: "Alexa",
147525
+ functionCap: "device-provider",
147526
+ role: "devices"
147527
+ },
147528
+ provider: this.requireInstances().toProvider()
147201
147529
  },
147202
- provider: this.requireInstances().toProvider()
147203
- }], {
147530
+ ...notificationTargetParts(records, {
147531
+ descriptors: [alexaTargetKind()],
147532
+ kinds: alexaNotifyRecordKinds,
147533
+ mintId: () => randomUUID(),
147534
+ probe: echoTargetProbe(() => this.speak),
147535
+ canProbe: () => true
147536
+ })
147537
+ ], {
147204
147538
  role: "devices",
147205
147539
  instanceMode: "multiple",
147206
147540
  kind: "account",
@@ -147491,7 +147825,7 @@ var AlexaImportAddon = class extends BaseDeviceProvider {
147491
147825
  }
147492
147826
  /** Who still points at an Alexa account: its integrations and the Echo targets that speak through it. */
147493
147827
  brokerUsers() {
147494
- return [linkUserFinder(this.requireInstances(), "brokerId"), { find: async (brokerId) => readEchoTargets(this.config).filter((target) => target.brokerId === brokerId).map((target) => ({
147828
+ return [linkUserFinder(this.requireInstances(), "brokerId"), { find: async (brokerId) => (this.echoStore === null ? [] : (await this.echoStore.list()).map(echoRowOf)).filter((target) => target.brokerId === brokerId).map((target) => ({
147495
147829
  kind: "notification-target",
147496
147830
  id: target.id,
147497
147831
  name: target.name