@camstack/addon-export-alexa 1.2.180 → 1.2.182

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.
@@ -5987,7 +5987,7 @@ var ZodIssueCode = {
5987
5987
  var ZodFirstPartyTypeKind;
5988
5988
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5989
5989
  //#endregion
5990
- //#region ../types/dist/sleep-BKClVk0K.mjs
5990
+ //#region ../types/dist/sleep-BkzQdpzF.mjs
5991
5991
  /**
5992
5992
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5993
5993
  * window to float samples (D455).
@@ -8124,6 +8124,10 @@ var BaseAddon = class {
8124
8124
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
8125
8125
  const patch = {};
8126
8126
  for (const key of keys) {
8127
+ if (tree.get(key)?.kind === "array") {
8128
+ patch[key] = [];
8129
+ continue;
8130
+ }
8127
8131
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
8128
8132
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
8129
8133
  }
@@ -9185,7 +9189,7 @@ function defineRecordKinds(specs) {
9185
9189
  retention: spec.retention,
9186
9190
  deviceRemoval: spec.deviceRemoval,
9187
9191
  maxDataBytes: spec.maxDataBytes,
9188
- secretPaths: [...secretPaths],
9192
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9189
9193
  secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9190
9194
  transactFamily: spec.transactFamily,
9191
9195
  entry: spec.entry === void 0 ? void 0 : {
@@ -9216,6 +9220,7 @@ function defineEntryKind(name, spec) {
9216
9220
  ...spec.database === void 0 ? {} : { database: spec.database },
9217
9221
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9218
9222
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9223
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9219
9224
  entry: {
9220
9225
  title: spec.title,
9221
9226
  ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
@@ -11899,7 +11904,7 @@ object({
11899
11904
  params: record(string(), union([string(), number()])).optional()
11900
11905
  });
11901
11906
  //#endregion
11902
- //#region ../types/dist/composition-BodkvOV0.mjs
11907
+ //#region ../types/dist/composition-CRNwcFYY.mjs
11903
11908
  /**
11904
11909
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11905
11910
  *
@@ -12662,38 +12667,6 @@ function validateExpressionSource(src) {
12662
12667
  return null;
12663
12668
  }
12664
12669
  /**
12665
- * One power reading becomes a washer, dryer or dishwasher (D944 helper).
12666
- *
12667
- * Standby of the control board is under 5 W; a motor or a heater is far
12668
- * above that, so 5 W is the line. A door lock or a short pump spike is not
12669
- * a cycle, so running starts only after 30 s above the line.
12670
- *
12671
- * A wash, dry or dishwasher pause (soak, heat-wait, heater off between
12672
- * bursts) lasts several minutes. Ending the cycle on the first dip would
12673
- * report "finished" in the middle of the program, so the stop dwell is
12674
- * 10 minutes on every type. The number is stored per type so one machine
12675
- * can move later without moving the others.
12676
- */
12677
- var APPLIANCE_TEMPLATE_ID = "appliance";
12678
- var APPLIANCE_KINDS = [
12679
- "washer",
12680
- "dryer",
12681
- "dishwasher"
12682
- ];
12683
- DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher;
12684
- /**
12685
- * A dumb plug-in stove or heater, built from a smart plug (a `Heater`).
12686
- *
12687
- * The plug is the actuator: `switch.setState` is a FORWARD to the plug's own
12688
- * (D967), so the heater switches exactly as the plug does. Running is the
12689
- * plug being on; when a power reading is also named, running is the draw
12690
- * staying above the line instead (a plug left on with the stove's own
12691
- * thermostat open is not heating). 50 W is far above any standby and below
12692
- * the smallest radiator.
12693
- */
12694
- var HEATER_TEMPLATE_ID = "heater";
12695
- DeviceType.Heater;
12696
- /**
12697
12670
  * Statistics and integrals over a history read (D944).
12698
12671
  *
12699
12672
  * Pure: the same points always give the same answer, so a restart recomputes
@@ -12837,34 +12810,6 @@ var HelperSpecSchema = discriminatedUnion("kind", [
12837
12810
  /** Actuator groups only. Readings leave this unset. */
12838
12811
  active: ActiveCriterionSchema.optional()
12839
12812
  }),
12840
- object({
12841
- kind: literal("appliance"),
12842
- templateId: literal(APPLIANCE_TEMPLATE_ID),
12843
- appliance: _enum(APPLIANCE_KINDS),
12844
- thresholdWatts: number().positive(),
12845
- startDwellMs: number().int().nonnegative(),
12846
- stopDwellMs: number().int().nonnegative(),
12847
- member: HelperMemberSchema,
12848
- /**
12849
- * The plug that powers the appliance (`switch.on`). Optional: when set, the
12850
- * composition carries a `power-source` feature, so the hub can cut and restore
12851
- * that plug (power-source link of a NEW-target composition).
12852
- */
12853
- powerSwitch: HelperMemberSchema.optional(),
12854
- /** How long a forced restart keeps the plug off; the cap's default when unset. */
12855
- offSeconds: number().optional()
12856
- }),
12857
- object({
12858
- kind: literal("heater"),
12859
- templateId: literal(HEATER_TEMPLATE_ID),
12860
- /** The plug, read and commanded at `switch.on`. */
12861
- plug: HelperMemberSchema,
12862
- /** The plug's power reading, when it has one: running is then the draw, not the switch. */
12863
- meter: HelperMemberSchema.optional(),
12864
- thresholdWatts: number().positive(),
12865
- startDwellMs: number().int().nonnegative(),
12866
- stopDwellMs: number().int().nonnegative()
12867
- }),
12868
12813
  object({
12869
12814
  kind: literal("statistic"),
12870
12815
  stat: _enum(STATISTIC_STATS),
@@ -13088,7 +13033,7 @@ var CompositionSchema = object({
13088
13033
  kind: literal("existing"),
13089
13034
  device: CompositionSourceRefSchema
13090
13035
  })]),
13091
- features: array(CompositionFeatureSchema).min(1).max(16),
13036
+ features: array(CompositionFeatureSchema).min(0).max(16),
13092
13037
  /**
13093
13038
  * Present when the block is a helper template. Absent on a free
13094
13039
  * composition (the room example, device 4603). The editor reads this,
@@ -13487,15 +13432,23 @@ var RecordIntegrationInstances = class {
13487
13432
  viewOf(record) {
13488
13433
  const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13489
13434
  const rawName = record.data[this.nameField];
13435
+ const kind = this.hooks.kindOf?.(record.data);
13436
+ const health = this.hooks.health?.(record.data, record.id);
13490
13437
  return {
13491
13438
  id: record.id,
13492
13439
  name: typeof rawName === "string" ? rawName : record.id,
13493
13440
  configured: this.hooks.configured(record.data),
13494
13441
  enabled: record.data.enabled !== false,
13495
- formValues: shown
13442
+ formValues: shown,
13443
+ ...kind !== void 0 ? { kind } : {},
13444
+ ...health?.status !== void 0 ? { status: health.status } : {},
13445
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13496
13446
  };
13497
13447
  }
13498
- describe = async () => this.hooks.description;
13448
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13449
+ ...this.hooks.description,
13450
+ mintsId: true
13451
+ };
13499
13452
  instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13500
13453
  listInstances = async () => {
13501
13454
  return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
@@ -13505,13 +13458,18 @@ var RecordIntegrationInstances = class {
13505
13458
  return record === null ? null : this.viewOf(record);
13506
13459
  };
13507
13460
  /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13508
- createInstance = async ({ id, name }) => {
13461
+ createInstance = async ({ id, name, kind }) => {
13462
+ const minted = id ?? this.hooks.mintId?.({
13463
+ name,
13464
+ ...kind !== void 0 ? { kind } : {}
13465
+ });
13466
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13509
13467
  await this.handle.put({
13510
- id,
13511
- data: this.hooks.initialBody(name)
13468
+ id: minted,
13469
+ data: this.hooks.initialBody(name, kind)
13512
13470
  }, { ifRev: 0 });
13513
- await this.hooks.onChanged?.(id);
13514
- return { id };
13471
+ await this.hooks.onChanged?.(minted);
13472
+ return { id: minted };
13515
13473
  };
13516
13474
  updateInstance = async ({ id, name, values }) => {
13517
13475
  const patch = {};
@@ -49232,49 +49190,6 @@ function actuator(input) {
49232
49190
  };
49233
49191
  }
49234
49192
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
49235
- var PowerSourceRefusalReasonSchema = _enum([
49236
- "no-power-source",
49237
- "switch-missing",
49238
- "switch-offline",
49239
- "switch-unknown",
49240
- "restart-in-progress",
49241
- "switch-call-failed"
49242
- ]);
49243
- var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
49244
- accepted: literal(false),
49245
- reason: PowerSourceRefusalReasonSchema,
49246
- /** One line for the operator, naming the switch. */
49247
- message: string()
49248
- })]);
49249
- var PowerSourceInfoSchema = object({
49250
- /** False when the device has no power source linked; the rest is then empty. */
49251
- linked: boolean(),
49252
- switchDeviceId: number().nullable(),
49253
- switchName: string().nullable(),
49254
- /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
49255
- switchOn: boolean().nullable(),
49256
- switchOnline: boolean().nullable(),
49257
- restartInProgress: boolean(),
49258
- offSeconds: number().int()
49259
- });
49260
- object({
49261
- /** Null while the switch has not reported: unknown is never `false` (D393). */
49262
- switchOn: boolean().nullable(),
49263
- offSeconds: number().int(),
49264
- lastFetchedAt: number()
49265
- });
49266
- DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
49267
- var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
49268
- systemMethod(deviceInput$2, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49269
- kind: "mutation",
49270
- auth: "admin"
49271
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49272
- kind: "mutation",
49273
- auth: "admin"
49274
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49275
- kind: "mutation",
49276
- auth: "admin"
49277
- });
49278
49193
  DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
49279
49194
  DeviceType.Camera;
49280
49195
  `${COMPOSED_DEVICE_STABLE_ID_PREFIX}`;
@@ -49302,6 +49217,165 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
49302
49217
  }).optional()
49303
49218
  })) });
49304
49219
  /**
49220
+ * A saved Customize assignment (D936). The schema is the type: callers use
49221
+ * `z.infer`, they do not restate the shape.
49222
+ */
49223
+ var OverrideSourceSchema = object({
49224
+ addonId: string().min(1),
49225
+ stableId: string().min(1),
49226
+ cap: string().min(1),
49227
+ fieldPath: string().min(1)
49228
+ });
49229
+ var IdentityTransformDraftSchema = object({ kind: literal("identity") });
49230
+ var InvertTransformDraftSchema = object({ kind: literal("invert") });
49231
+ var ThresholdTransformDraftSchema = object({
49232
+ kind: literal("threshold"),
49233
+ comparison: _enum(["gte", "lte"]),
49234
+ threshold: number(),
49235
+ startDwellMs: number().nonnegative(),
49236
+ stopDwellMs: number().nonnegative()
49237
+ });
49238
+ var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49239
+ IdentityTransformDraftSchema,
49240
+ InvertTransformDraftSchema,
49241
+ ThresholdTransformDraftSchema,
49242
+ object({
49243
+ kind: literal("linear"),
49244
+ scale: number(),
49245
+ offset: number(),
49246
+ clampMin: number().optional(),
49247
+ clampMax: number().optional()
49248
+ }),
49249
+ object({
49250
+ kind: literal("enum-map"),
49251
+ mapping: record(string(), string().nullable())
49252
+ }),
49253
+ object({ kind: literal("number") })
49254
+ ]);
49255
+ var ScalarOverrideDraftSchema = object({
49256
+ kind: literal("scalar"),
49257
+ cap: string().min(1),
49258
+ targetId: string().min(1),
49259
+ source: OverrideSourceSchema,
49260
+ transform: CustomizeTransformDraftSchema
49261
+ });
49262
+ var KeyedArrayOverrideDraftSchema = object({
49263
+ kind: literal("keyedArray"),
49264
+ cap: string().min(1),
49265
+ targetId: string().min(1),
49266
+ key: string().min(1),
49267
+ label: string().min(1),
49268
+ fieldPath: string().min(1),
49269
+ source: OverrideSourceSchema,
49270
+ transform: CustomizeTransformDraftSchema
49271
+ });
49272
+ var PulseOverrideDraftSchema = object({
49273
+ kind: literal("pulse"),
49274
+ cap: string().min(1),
49275
+ targetId: string().min(1),
49276
+ enabled: boolean(),
49277
+ debounceMs: number().nonnegative(),
49278
+ edges: array(_enum([
49279
+ "rising",
49280
+ "button",
49281
+ "native-event"
49282
+ ])).min(1).optional(),
49283
+ sources: array(OverrideSourceSchema).min(1)
49284
+ });
49285
+ var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
49286
+ "in-addition",
49287
+ "confirm",
49288
+ "replace"
49289
+ ]).optional() });
49290
+ discriminatedUnion("kind", [
49291
+ ScalarOverrideDraftSchema,
49292
+ KeyedArrayOverrideDraftSchema,
49293
+ PulseOverrideDraftSchema,
49294
+ object({
49295
+ kind: literal("span"),
49296
+ cap: string().min(1),
49297
+ targetId: string().min(1),
49298
+ timeoutMs: number().nonnegative(),
49299
+ cooldownMs: number().nonnegative().optional(),
49300
+ sources: array(SpanSourceDraftSchema)
49301
+ })
49302
+ ]);
49303
+ object({
49304
+ targetId: string().min(1),
49305
+ configured: boolean(),
49306
+ source: _enum(["native", "assigned"]),
49307
+ state: _enum([
49308
+ "active",
49309
+ "stale",
49310
+ "released",
49311
+ "unavailable"
49312
+ ]),
49313
+ reason: string().nullable()
49314
+ });
49315
+ /**
49316
+ * What a running-threshold proposal says (planning#405). The schema is the
49317
+ * type: the algorithm, the capability method and the UI all read `z.infer`.
49318
+ *
49319
+ * A proposal is read-only advice: it carries the numbers it was derived from
49320
+ * (`evidence`) so the operator can judge it, and an `insufficient` answer names
49321
+ * WHY with a typed reason and the catalog defaults, never an invented number.
49322
+ */
49323
+ var RunningProposalTierSchema = _enum(["raw", "5m"]);
49324
+ var RunningProposalConfidenceSchema = _enum([
49325
+ "high",
49326
+ "medium",
49327
+ "low"
49328
+ ]);
49329
+ var RunningProposalInsufficientReasonSchema = _enum([
49330
+ "no-history",
49331
+ "span-too-short",
49332
+ "truncated",
49333
+ "no-idle-floor",
49334
+ "no-runs",
49335
+ "no-separation"
49336
+ ]);
49337
+ var RunningProposalReplaySchema = object({
49338
+ /** Intervals the real dwell expression held true over the window. */
49339
+ intervals: number().int().nonnegative(),
49340
+ /** Intervals outside every run, or a second interval inside one. */
49341
+ extra: number().int().nonnegative(),
49342
+ /** Runs without an interval of their own (none, or merged into a neighbour). */
49343
+ missed: number().int().nonnegative()
49344
+ });
49345
+ var RunningProposalEvidenceSchema = object({
49346
+ tier: RunningProposalTierSchema,
49347
+ spanMs: number().nonnegative(),
49348
+ from: number(),
49349
+ to: number(),
49350
+ points: number().int().nonnegative(),
49351
+ runsFound: number().int().nonnegative(),
49352
+ pausesFound: number().int().nonnegative(),
49353
+ longestPauseMs: number().nonnegative(),
49354
+ idleFloorW: number(),
49355
+ noiseCeilingW: number(),
49356
+ plateauW: number(),
49357
+ replay: RunningProposalReplaySchema
49358
+ });
49359
+ var RunningProposalInsufficientEvidenceSchema = object({
49360
+ spanMs: number().nonnegative(),
49361
+ points: number().int().nonnegative(),
49362
+ runsFound: number().int().nonnegative()
49363
+ });
49364
+ var RunningThresholdProposalSchema = discriminatedUnion("state", [object({
49365
+ state: literal("proposal"),
49366
+ transform: ThresholdTransformDraftSchema,
49367
+ evidence: RunningProposalEvidenceSchema,
49368
+ confidence: RunningProposalConfidenceSchema,
49369
+ /** Why the confidence is not higher; empty when nothing held it back. */
49370
+ notes: array(string())
49371
+ }), object({
49372
+ state: literal("insufficient"),
49373
+ reason: RunningProposalInsufficientReasonSchema,
49374
+ evidence: RunningProposalInsufficientEvidenceSchema,
49375
+ /** The catalog defaults, offered as what stands when nothing better is known. */
49376
+ fallback: ThresholdTransformDraftSchema
49377
+ })]);
49378
+ /**
49305
49379
  * The report of a one-shot "move this owner's plaintext secrets into the
49306
49380
  * keychain" run (D878). COUNTS only - never a value, never a ref.
49307
49381
  *
@@ -49591,6 +49665,14 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
49591
49665
  kind: "mutation",
49592
49666
  auth: "admin",
49593
49667
  access: "view"
49668
+ }), method(object({
49669
+ deviceId: number().int(),
49670
+ cap: string().min(1),
49671
+ fieldPath: string().min(1),
49672
+ deviceType: _enum(DeviceType).optional()
49673
+ }), RunningThresholdProposalSchema, {
49674
+ auth: "admin",
49675
+ access: "view"
49594
49676
  }), method(object({
49595
49677
  blockId: string().min(1),
49596
49678
  trace: AutomationRunTraceSchema.optional(),
@@ -50399,7 +50481,53 @@ method(object({
50399
50481
  * exposes only the COMMON surface: link state, supported device
50400
50482
  * kinds (so the UI can filter the device picker), and per-device
50401
50483
  * expose/unexpose.
50484
+ *
50485
+ * INSTANCES. One export addon can serve several independent targets (a
50486
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
50487
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
50488
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
50489
+ * default instance's); present = that instance; an id the provider does not
50490
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
50491
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
50492
+ * change always names the target it changes. A single-instance provider
50493
+ * accepts an absent id on a read or its own id, and refuses any other.
50494
+ */
50495
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
50496
+ var InstanceIdSchema$1 = string().min(1);
50497
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
50498
+ /** One independent export target of an addon. */
50499
+ var ExportInstanceSchema = object({
50500
+ instanceId: InstanceIdSchema$1,
50501
+ name: string(),
50502
+ enabled: boolean(),
50503
+ kind: string().optional()
50504
+ });
50505
+ var EXPORT_INSTANCE_UNKNOWN = "export-instance-unknown";
50506
+ /** The named failure of an `instanceId` the provider does not serve. The message starts with the code. */
50507
+ var ExportInstanceUnknownError = class extends Error {
50508
+ code = EXPORT_INSTANCE_UNKNOWN;
50509
+ instanceId;
50510
+ constructor(addon, instanceId) {
50511
+ super(`${EXPORT_INSTANCE_UNKNOWN}: ${addon} serves no instance "${instanceId}"`);
50512
+ this.name = "ExportInstanceUnknownError";
50513
+ this.instanceId = instanceId;
50514
+ }
50515
+ };
50516
+ /**
50517
+ * The instance a `getStatus` call names. The cap's `status` block injects a per-device
50518
+ * `getStatus({ deviceId })` beside the method's own `{ instanceId? }`, so the provider sees
50519
+ * both shapes; only the second names an instance (a per-device status read is addon-wide).
50520
+ */
50521
+ function statusInstanceOf(input) {
50522
+ return "instanceId" in input ? input.instanceId : void 0;
50523
+ }
50524
+ /**
50525
+ * A single-instance provider's check: an absent id or its own passes, any other throws
50526
+ * `ExportInstanceUnknownError`.
50402
50527
  */
50528
+ function assertOwnExportInstance(addon, own, instanceId) {
50529
+ if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
50530
+ }
50403
50531
  var LinkStateSchema = _enum([
50404
50532
  "unlinked",
50405
50533
  "linked",
@@ -50450,10 +50578,14 @@ var ExposedDeviceSchema = object({
50450
50578
  capabilities: array(string()).optional()
50451
50579
  });
50452
50580
  var ExposeInputSchema = object({
50581
+ instanceId: InstanceIdSchema$1,
50453
50582
  deviceId: string(),
50454
50583
  capabilities: array(string()).optional()
50455
50584
  });
50456
- var UnexposeInputSchema = object({ deviceId: string() });
50585
+ var UnexposeInputSchema = object({
50586
+ instanceId: InstanceIdSchema$1,
50587
+ deviceId: string()
50588
+ });
50457
50589
  /**
50458
50590
  * What an exporter may expose besides devices (D968). An action and a
50459
50591
  * notification target are LIST ENTRIES, never devices (D954): they enter an
@@ -50482,8 +50614,14 @@ var ExposedEntitySchema = object({
50482
50614
  entity: ExportEntityRefSchema,
50483
50615
  exposedAs: string().optional()
50484
50616
  });
50485
- var ExposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50486
- var UnexposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50617
+ var ExposeEntityInputSchema = object({
50618
+ instanceId: InstanceIdSchema$1,
50619
+ entity: ExportEntityRefSchema
50620
+ });
50621
+ var UnexposeEntityInputSchema = object({
50622
+ instanceId: InstanceIdSchema$1,
50623
+ entity: ExportEntityRefSchema
50624
+ });
50487
50625
  var deviceExportCapability = {
50488
50626
  name: "device-export",
50489
50627
  scope: "system",
@@ -50503,9 +50641,10 @@ var deviceExportCapability = {
50503
50641
  */
50504
50642
  exposesDeviceSettings: true,
50505
50643
  methods: {
50506
- getStatus: method(_void(), DeviceExportStatusSchema),
50507
- listSupportedDeviceKinds: method(_void(), array(DeviceKindSchema)),
50508
- listExposedDevices: method(_void(), array(ExposedDeviceSchema)),
50644
+ getStatus: method(InstancePinSchema, DeviceExportStatusSchema),
50645
+ listInstances: method(_void(), array(ExportInstanceSchema)),
50646
+ listSupportedDeviceKinds: method(InstancePinSchema, array(DeviceKindSchema)),
50647
+ listExposedDevices: method(InstancePinSchema, array(ExposedDeviceSchema)),
50509
50648
  exposeDevice: method(ExposeInputSchema, _void(), {
50510
50649
  kind: "mutation",
50511
50650
  auth: "admin"
@@ -50515,7 +50654,7 @@ var deviceExportCapability = {
50515
50654
  auth: "admin"
50516
50655
  }),
50517
50656
  listSupportedEntityKinds: optionalMethod(_void(), array(ExportEntityKindSchema)),
50518
- listExposedEntities: optionalMethod(_void(), array(ExposedEntitySchema)),
50657
+ listExposedEntities: optionalMethod(InstancePinSchema, array(ExposedEntitySchema)),
50519
50658
  exposeEntity: optionalMethod(ExposeEntityInputSchema, _void(), {
50520
50659
  kind: "mutation",
50521
50660
  auth: "admin"
@@ -53720,15 +53859,15 @@ var FanPresetCaptureResultSchema = object({
53720
53859
  items: array(FanCaptureItemSchema),
53721
53860
  omitted: array(FanCaptureOmissionSchema)
53722
53861
  });
53723
- var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
53862
+ var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
53724
53863
  DeviceType.Fan;
53725
- method(deviceInput$1, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$1.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
53864
+ method(deviceInput$2, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$2.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
53726
53865
  kind: "mutation",
53727
53866
  auth: "admin"
53728
- }), method(deviceInput$1.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
53867
+ }), method(deviceInput$2.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
53729
53868
  kind: "mutation",
53730
53869
  auth: "protected"
53731
- }), method(deviceInput$1.extend({
53870
+ }), method(deviceInput$2.extend({
53732
53871
  fields: array(FanCaptureFieldSchema).optional(),
53733
53872
  steps: array(ActionStepSchema).max(20).default([])
53734
53873
  }), FanPresetCaptureResultSchema, { auth: "protected" });
@@ -54260,13 +54399,50 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54260
54399
  */
54261
54400
  var ConfigSchemaPassthrough$3 = custom();
54262
54401
  var IntegrationInstanceIdSchema = string().min(1);
54402
+ var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54403
+ /**
54404
+ * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54405
+ * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54406
+ * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
54407
+ * interactive account link (popup) and may carry `{{brokerId}}`, which the UI replaces with the
54408
+ * instance id.
54409
+ */
54410
+ var IntegrationInstanceKindSchema = object({
54411
+ /** Stable id of the kind, sent back as `createInstance.kind`. */
54412
+ id: string().min(1),
54413
+ label: string().min(1),
54414
+ /** The kind signs in through a server-held interactive session. */
54415
+ signIn: object({
54416
+ basePath: string().min(1),
54417
+ methods: array(_enum(["device-code", "proxy"])).optional()
54418
+ }).optional(),
54419
+ /** Relative hub path to start an interactive account link of an instance of this kind. */
54420
+ connectPath: string().min(1).optional(),
54421
+ /** Relative hub path to disconnect that account. */
54422
+ disconnectPath: string().min(1).optional()
54423
+ });
54263
54424
  var IntegrationInstanceDescriptionSchema = object({
54264
54425
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54265
- instanceMode: _enum(["single", "multiple"]),
54426
+ instanceMode: IntegrationInstanceModeSchema,
54266
54427
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
54267
54428
  kind: string(),
54268
54429
  /** True when `testInstance` really probes the remote. */
54269
- canTest: boolean()
54430
+ canTest: boolean(),
54431
+ /**
54432
+ * The kinds an instance can be of. Absent or one entry: nothing to choose; more than one: the
54433
+ * Add flow asks which first and sends it as `createInstance.kind`.
54434
+ */
54435
+ kinds: array(IntegrationInstanceKindSchema).optional(),
54436
+ /**
54437
+ * The provider accepts `createInstance.id` for an id that once existed (an adopted id, because
54438
+ * devices carry it). The UI then offers "restore under its old id" on Add. Absent means no.
54439
+ */
54440
+ allowRestoreId: boolean().optional(),
54441
+ /**
54442
+ * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54443
+ * send an id (the UI then mints an opaque one).
54444
+ */
54445
+ mintsId: boolean().optional()
54270
54446
  });
54271
54447
  var IntegrationInstanceStatusSchema = object({
54272
54448
  state: _enum([
@@ -54275,7 +54451,9 @@ var IntegrationInstanceStatusSchema = object({
54275
54451
  "error",
54276
54452
  "unknown"
54277
54453
  ]),
54278
- detail: string().optional()
54454
+ detail: string().optional(),
54455
+ /** A short human word for the state ("Signed in", "Token expired"); shown instead of `state`. */
54456
+ label: string().optional()
54279
54457
  });
54280
54458
  var IntegrationInstanceSchema = object({
54281
54459
  id: IntegrationInstanceIdSchema,
@@ -54287,9 +54465,13 @@ var IntegrationInstanceSchema = object({
54287
54465
  * (`enabled !== false`, so a row written before the field existed is on).
54288
54466
  */
54289
54467
  enabled: boolean(),
54468
+ /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
54469
+ kind: string().optional(),
54290
54470
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
54291
54471
  formValues: record(string(), unknown()),
54292
- status: IntegrationInstanceStatusSchema.optional()
54472
+ status: IntegrationInstanceStatusSchema.optional(),
54473
+ /** Epoch ms of the last probe of the remote that produced `status`; absent when never checked. */
54474
+ lastCheckedAt: number().optional()
54293
54475
  });
54294
54476
  var IntegrationInstancePatchSchema = object({
54295
54477
  id: IntegrationInstanceIdSchema,
@@ -54307,10 +54489,14 @@ var integrationInstancesCapability = {
54307
54489
  instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54308
54490
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54309
54491
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54310
- /** Insert the typed record under the given id (a duplicate id is refused). */
54492
+ /**
54493
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
54494
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
54495
+ */
54311
54496
  createInstance: method(object({
54312
- id: IntegrationInstanceIdSchema,
54313
- name: string().min(1)
54497
+ id: IntegrationInstanceIdSchema.optional(),
54498
+ name: string().min(1),
54499
+ kind: string().min(1).optional()
54314
54500
  }), object({ id: string() }), {
54315
54501
  kind: "mutation",
54316
54502
  auth: "admin"
@@ -56142,6 +56328,11 @@ var LogEntrySchema = object({
56142
56328
  * flight, and not asking for the next slice ends the scan.
56143
56329
  */
56144
56330
  var LogReadQuerySchema = object({
56331
+ /**
56332
+ * Which destination INSTANCE answers (a destination addon may hold several records). Absent ⇒
56333
+ * the provider's first readable one, so a caller written before instances existed is unchanged.
56334
+ */
56335
+ instanceId: string().min(1).max(200).optional(),
56145
56336
  /** Correlates `cancelRead`. Caller-chosen, unique per in-flight read. */
56146
56337
  requestId: string().min(1).max(64).optional(),
56147
56338
  /** The device the line is about (`tags.deviceId`, numeric). */
@@ -56204,6 +56395,8 @@ var LogReadResultSchema = object({
56204
56395
  /** True when `cancelRead` ended this slice early. */
56205
56396
  cancelled: boolean().optional()
56206
56397
  });
56398
+ /** Names one destination instance; absent ⇒ the provider's first readable one. */
56399
+ var LogInstanceSelectorSchema = object({ instanceId: string().min(1).max(200).optional() });
56207
56400
  var LogReadCapabilitiesSchema = object({
56208
56401
  /** False ⇒ this destination only ships lines (console, forwarder, an unconfigured Loki). */
56209
56402
  readable: boolean(),
@@ -56222,7 +56415,7 @@ var LogReadCapabilitiesSchema = object({
56222
56415
  /** How far back the store reaches, when the provider knows (days). */
56223
56416
  retentionDays: number().nullable()
56224
56417
  });
56225
- method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(_void(), LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
56418
+ method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(LogInstanceSelectorSchema, LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
56226
56419
  kind: "mutation",
56227
56420
  auth: "admin"
56228
56421
  });
@@ -67810,6 +68003,49 @@ object({
67810
68003
  DeviceType.PetFeeder,
67811
68004
  DeviceType.Heater
67812
68005
  ].filter((type) => type !== DeviceType.Sensor);
68006
+ var PowerSourceRefusalReasonSchema = _enum([
68007
+ "no-power-source",
68008
+ "switch-missing",
68009
+ "switch-offline",
68010
+ "switch-unknown",
68011
+ "restart-in-progress",
68012
+ "switch-call-failed"
68013
+ ]);
68014
+ var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
68015
+ accepted: literal(false),
68016
+ reason: PowerSourceRefusalReasonSchema,
68017
+ /** One line for the operator, naming the switch. */
68018
+ message: string()
68019
+ })]);
68020
+ var PowerSourceInfoSchema = object({
68021
+ /** False when the device has no power source linked; the rest is then empty. */
68022
+ linked: boolean(),
68023
+ switchDeviceId: number().nullable(),
68024
+ switchName: string().nullable(),
68025
+ /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
68026
+ switchOn: boolean().nullable(),
68027
+ switchOnline: boolean().nullable(),
68028
+ restartInProgress: boolean(),
68029
+ offSeconds: number().int()
68030
+ });
68031
+ object({
68032
+ /** Null while the switch has not reported: unknown is never `false` (D393). */
68033
+ switchOn: boolean().nullable(),
68034
+ offSeconds: number().int(),
68035
+ lastFetchedAt: number()
68036
+ });
68037
+ DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
68038
+ var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
68039
+ systemMethod(deviceInput$1, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68040
+ kind: "mutation",
68041
+ auth: "admin"
68042
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68043
+ kind: "mutation",
68044
+ auth: "admin"
68045
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68046
+ kind: "mutation",
68047
+ auth: "admin"
68048
+ });
67813
68049
  /**
67814
68050
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
67815
68051
  * on `DeviceType.Presence`. Read-only — no setters: presence is
@@ -75882,6 +76118,25 @@ function buildDescriptor(capName, kind) {
75882
76118
  * contributes one entry per bound cap present in this map.
75883
76119
  */
75884
76120
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
76121
+ /**
76122
+ * What a remote key is CALLED and what it LOOKS like, for every role (D963),
76123
+ * shared by the admin UI and the viewer. A role is data on the wire; each
76124
+ * client resolves its name from `label` (English and Italian side by side) and
76125
+ * its glyph from `icon`, a lucide id from the shared icon catalogue — the
76126
+ * server sends an id, a client maps it to its own icon set.
76127
+ *
76128
+ * `legend` is text printed on the key INSTEAD of a glyph (a digit has no
76129
+ * pictogram): a client that can draw text shows it, one that cannot falls back
76130
+ * to `icon`.
76131
+ */
76132
+ function digit(n) {
76133
+ return {
76134
+ label: t(n, n),
76135
+ icon: "hash",
76136
+ legend: n
76137
+ };
76138
+ }
76139
+ digit("0"), digit("1"), digit("2"), digit("3"), digit("4"), digit("5"), digit("6"), digit("7"), digit("8"), digit("9");
75885
76140
  DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
75886
76141
  var btn = (idSuffix, row, col, init) => ({
75887
76142
  idSuffix,
@@ -76009,6 +76264,34 @@ discriminatedUnion("kind", [object({
76009
76264
  kind: literal("pronto"),
76010
76265
  code: string()
76011
76266
  })]);
76267
+ /**
76268
+ * Propose a running threshold from a device's own power history (planning#405).
76269
+ *
76270
+ * Pure and deterministic: the same series gives the same answer. The series is
76271
+ * a HELD-VALUE step series — a point's value stands until the next point — which
76272
+ * is how device-history stores a gauge, so "time at a level" is exact, not a
76273
+ * count of samples.
76274
+ *
76275
+ * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
76276
+ * near F. A device that is not near one level most of the time has no floor.
76277
+ * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
76278
+ * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
76279
+ * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
76280
+ * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
76281
+ * grid a person would type; stop dwell covers the longest pause; start dwell
76282
+ * covers the longest standby blip above T.
76283
+ * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
76284
+ * run must hold exactly one true interval and nothing may flap outside.
76285
+ */
76286
+ var SECOND_MS = 1e3;
76287
+ var MINUTE_MS$1 = 60 * SECOND_MS;
76288
+ 24 * (60 * MINUTE_MS$1);
76289
+ 10 * MINUTE_MS$1;
76290
+ 30 * SECOND_MS;
76291
+ 60 * SECOND_MS;
76292
+ 20 * MINUTE_MS$1;
76293
+ 10 * SECOND_MS;
76294
+ 10 * SECOND_MS;
76012
76295
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
76013
76296
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
76014
76297
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
@@ -77550,6 +77833,13 @@ Object.freeze({
77550
77833
  access: "create",
77551
77834
  role: "admin"
77552
77835
  },
77836
+ "coreBlocks.proposeRunningThreshold": {
77837
+ capName: "core-blocks",
77838
+ capScope: "system",
77839
+ addonId: null,
77840
+ access: "view",
77841
+ role: "admin"
77842
+ },
77553
77843
  "coreBlocks.reportAutomationRun": {
77554
77844
  capName: "core-blocks",
77555
77845
  capScope: "system",
@@ -78061,6 +78351,13 @@ Object.freeze({
78061
78351
  access: "view",
78062
78352
  role: "admin"
78063
78353
  },
78354
+ "deviceExport.listInstances": {
78355
+ capName: "device-export",
78356
+ capScope: "system",
78357
+ addonId: null,
78358
+ access: "view",
78359
+ role: "admin"
78360
+ },
78064
78361
  "deviceExport.listSupportedDeviceKinds": {
78065
78362
  capName: "device-export",
78066
78363
  capScope: "system",
@@ -87033,6 +87330,11 @@ Object.freeze({
87033
87330
  form: "single",
87034
87331
  optional: false
87035
87332
  }],
87333
+ "coreBlocks.proposeRunningThreshold": [{
87334
+ name: "deviceId",
87335
+ form: "single",
87336
+ optional: false
87337
+ }],
87036
87338
  "cover.close": [{
87037
87339
  name: "deviceId",
87038
87340
  form: "single",
@@ -89696,99 +89998,6 @@ Object.freeze({
89696
89998
  "network-access": "ingress",
89697
89999
  "smtp-provider": "email"
89698
90000
  });
89699
- /**
89700
- * A saved Customize assignment (D936). The schema is the type: callers use
89701
- * `z.infer`, they do not restate the shape.
89702
- */
89703
- var OverrideSourceSchema = object({
89704
- addonId: string().min(1),
89705
- stableId: string().min(1),
89706
- cap: string().min(1),
89707
- fieldPath: string().min(1)
89708
- });
89709
- var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
89710
- object({ kind: literal("identity") }),
89711
- object({ kind: literal("invert") }),
89712
- object({
89713
- kind: literal("threshold"),
89714
- comparison: _enum(["gte", "lte"]),
89715
- threshold: number(),
89716
- startDwellMs: number().nonnegative(),
89717
- stopDwellMs: number().nonnegative()
89718
- }),
89719
- object({
89720
- kind: literal("linear"),
89721
- scale: number(),
89722
- offset: number(),
89723
- clampMin: number().optional(),
89724
- clampMax: number().optional()
89725
- }),
89726
- object({
89727
- kind: literal("enum-map"),
89728
- mapping: record(string(), string().nullable())
89729
- }),
89730
- object({ kind: literal("number") })
89731
- ]);
89732
- var ScalarOverrideDraftSchema = object({
89733
- kind: literal("scalar"),
89734
- cap: string().min(1),
89735
- targetId: string().min(1),
89736
- source: OverrideSourceSchema,
89737
- transform: CustomizeTransformDraftSchema
89738
- });
89739
- var KeyedArrayOverrideDraftSchema = object({
89740
- kind: literal("keyedArray"),
89741
- cap: string().min(1),
89742
- targetId: string().min(1),
89743
- key: string().min(1),
89744
- label: string().min(1),
89745
- fieldPath: string().min(1),
89746
- source: OverrideSourceSchema,
89747
- transform: CustomizeTransformDraftSchema
89748
- });
89749
- var PulseOverrideDraftSchema = object({
89750
- kind: literal("pulse"),
89751
- cap: string().min(1),
89752
- targetId: string().min(1),
89753
- enabled: boolean(),
89754
- debounceMs: number().nonnegative(),
89755
- edges: array(_enum([
89756
- "rising",
89757
- "button",
89758
- "native-event"
89759
- ])).min(1).optional(),
89760
- sources: array(OverrideSourceSchema).min(1)
89761
- });
89762
- var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
89763
- "in-addition",
89764
- "confirm",
89765
- "replace"
89766
- ]).optional() });
89767
- discriminatedUnion("kind", [
89768
- ScalarOverrideDraftSchema,
89769
- KeyedArrayOverrideDraftSchema,
89770
- PulseOverrideDraftSchema,
89771
- object({
89772
- kind: literal("span"),
89773
- cap: string().min(1),
89774
- targetId: string().min(1),
89775
- timeoutMs: number().nonnegative(),
89776
- cooldownMs: number().nonnegative().optional(),
89777
- sources: array(SpanSourceDraftSchema)
89778
- })
89779
- ]);
89780
- object({
89781
- targetId: string().min(1),
89782
- configured: boolean(),
89783
- source: _enum(["native", "assigned"]),
89784
- state: _enum([
89785
- "active",
89786
- "stale",
89787
- "released",
89788
- "unavailable"
89789
- ]),
89790
- reason: string().nullable()
89791
- });
89792
90001
  var G711_SCALE_CORRECTION_DB = {
89793
90002
  PCMU: 20 * Math.log10(4),
89794
90003
  PCMA: 20 * Math.log10(8)
@@ -101936,8 +102145,17 @@ async function moveLedgersToLinks(ports) {
101936
102145
  linkedAccounts,
101937
102146
  tokens
101938
102147
  });
101939
- const held = await ports.readLinks();
101940
- if (!(held !== null && canonical(held.linkedAccounts) === canonical(linkedAccounts) && canonical(held.tokens) === canonical(tokens))) {
102148
+ let held = await ports.readLinks();
102149
+ const matches = (record) => record !== null && canonical(record.linkedAccounts) === canonical(linkedAccounts) && canonical(record.tokens) === canonical(tokens);
102150
+ if (put === "exists" && !matches(held) && isCoveredBy(held, linkedAccounts, tokens)) {
102151
+ await ports.replaceLinks({
102152
+ name: LINKS_NAME,
102153
+ linkedAccounts,
102154
+ tokens
102155
+ });
102156
+ held = await ports.readLinks();
102157
+ }
102158
+ if (!matches(held)) {
101941
102159
  ports.warn("Alexa migration: the skill-links record does not hold what the settings carried; the legacy ledgers are kept");
101942
102160
  if (put === "created") throw new Error("the Alexa link record does not match the legacy settings; nothing was cleared");
101943
102161
  return {
@@ -101953,10 +102171,32 @@ async function moveLedgersToLinks(ports) {
101953
102171
  accounts: linkedAccounts.length
101954
102172
  }
101955
102173
  } : {
101956
- outcome: "already-done",
101957
- summary: { moved: false }
102174
+ outcome: "done",
102175
+ summary: {
102176
+ moved: true,
102177
+ repaired: true,
102178
+ accounts: linkedAccounts.length
102179
+ }
101958
102180
  };
101959
102181
  }
102182
+ /**
102183
+ * The record carries this migration's own name and every account and grant it holds is also in
102184
+ * the settings: rewriting it loses nothing and touches nothing an operator named.
102185
+ */
102186
+ function isCoveredBy(held, linkedAccounts, tokens) {
102187
+ if (held === null || held.name !== LINKS_NAME) return false;
102188
+ const accounts = new Set(linkedAccounts.map((a) => a.userId));
102189
+ const grants = new Set(tokens.map((t) => t.userId));
102190
+ return held.linkedAccounts.every((a) => accounts.has(a.userId)) && held.tokens.every((t) => grants.has(t.userId));
102191
+ }
102192
+ /**
102193
+ * A ledger key the drop may judge: absent, a list, or the leftover of a credential clear
102194
+ * (`{ $secretClear: true }`, stored where a list belongs by an older build). Anything else is
102195
+ * not understood, so nothing is deleted on its account.
102196
+ */
102197
+ function isLedgerShape(value) {
102198
+ return value === void 0 || Array.isArray(value) || isSecretClear(value);
102199
+ }
101960
102200
  /** Whether a stored token entry still carries a credential: text, or a keychain marker. */
101961
102201
  function carriesCredential(entry) {
101962
102202
  if (typeof entry !== "object" || entry === null) return false;
@@ -101984,11 +102224,17 @@ async function planDropMovedSettings(ports) {
101984
102224
  if (ledgerKeys.length > 0) {
101985
102225
  const links = await ports.readLinks();
101986
102226
  if (links === null) return refuse("no Alexa link record exists");
101987
- const held = new Set(links.linkedAccounts.map((a) => a.userId));
101988
- const heldTokens = new Set(links.tokens.map((t) => t.userId));
102227
+ if (!isLedgerShape(stored["linkedAccounts"])) return refuse("the old linkedAccounts setting is not a list the migration understands");
102228
+ if (!isLedgerShape(stored["tokens"])) return refuse("the old tokens setting is not a list the migration understands");
101989
102229
  const legacyTokens = stored["tokens"];
101990
102230
  if (Array.isArray(legacyTokens) && legacyTokens.some(carriesCredential)) return refuse("the old settings still carry Amazon push credentials");
101991
- for (const account of accountsOf(stored["linkedAccounts"])) if (!held.has(account.userId)) return refuse(`the record lacks the account ${account.userId}`);
102231
+ const heldAccounts = new Map(links.linkedAccounts.map((a) => [a.userId, a]));
102232
+ const heldTokens = new Set(links.tokens.map((t) => t.userId));
102233
+ for (const account of accountsOf(stored["linkedAccounts"])) {
102234
+ const held = heldAccounts.get(account.userId);
102235
+ if (held === void 0) return refuse(`the record lacks the account ${account.userId}`);
102236
+ if (canonical(held) !== canonical(account)) return refuse(`the record holds the account ${account.userId} differently`);
102237
+ }
101992
102238
  for (const token of tokensOf(stored["tokens"])) if (!heldTokens.has(token.userId)) return refuse(`the record lacks the grant ${token.userId}`);
101993
102239
  }
101994
102240
  const present = [...skillKeys, ...ledgerKeys];
@@ -103427,6 +103673,8 @@ function hasUnresolvedCredential(entry) {
103427
103673
  if (typeof entry !== "object" || entry === null) return false;
103428
103674
  return "accessToken" in entry && isSecretMarker(entry.accessToken) || "refreshToken" in entry && isSecretMarker(entry.refreshToken) || "brokerCredential" in entry && isSecretMarker(entry.brokerCredential);
103429
103675
  }
103676
+ /** The one export instance this addon serves. */
103677
+ var EXPORT_ALEXA_ADDON_ID = "export-alexa";
103430
103678
  var ExportAlexaAddon = class extends BaseAddon {
103431
103679
  /** Hidden state that is a credential — kept in the keychain, never the blob (D787). */
103432
103680
  secretStatePaths = [
@@ -103470,15 +103718,31 @@ var ExportAlexaAddon = class extends BaseAddon {
103470
103718
  /** The keychain refused the link credentials: the ledger is read-only until it answers (D49). */
103471
103719
  linksLocked = false;
103472
103720
  /**
103721
+ * The legacy ledger keys as lists. A store written by an older build may hold something that
103722
+ * is not a list there (a clear instruction stored as the value); the page and the gateway read
103723
+ * a list or nothing.
103724
+ */
103725
+ legacyLedgers() {
103726
+ return {
103727
+ linkedAccounts: Array.isArray(this.config.linkedAccounts) ? this.config.linkedAccounts : [],
103728
+ tokens: Array.isArray(this.config.tokens) ? this.config.tokens : []
103729
+ };
103730
+ }
103731
+ /**
103473
103732
  * The settings as the addon reads them: the records where they exist, the legacy keys until
103474
103733
  * the migrations have moved them.
103475
103734
  */
103476
103735
  get view() {
103477
103736
  const skill = this.skillRow;
103478
103737
  const links = this.linksRow;
103479
- if (skill === null && links === null) return this.config;
103738
+ const legacy = this.legacyLedgers();
103739
+ if (skill === null && links === null) return {
103740
+ ...this.config,
103741
+ ...legacy
103742
+ };
103480
103743
  return {
103481
103744
  ...this.config,
103745
+ ...legacy,
103482
103746
  ...skill === null ? {} : {
103483
103747
  skillMode: skill.skillMode,
103484
103748
  region: skill.region,
@@ -103577,30 +103841,55 @@ var ExportAlexaAddon = class extends BaseAddon {
103577
103841
  actionScenes.reconcile().catch((err) => {
103578
103842
  this.ctx.logger.warn("export-alexa: action scene reconcile at boot failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
103579
103843
  });
103844
+ const ownInstance = (instanceId) => assertOwnExportInstance("export-alexa", EXPORT_ALEXA_ADDON_ID, instanceId);
103580
103845
  const deviceExportProvider = {
103581
- getStatus: async () => ({
103582
- linkState: this.view.linkedAccounts.length > 0 ? "linked" : "unlinked",
103583
- exposedDeviceCount: this.config.exposed.length,
103584
- setup: await this.buildSetupBlock()
103585
- }),
103586
- listSupportedDeviceKinds: async () => [...SUPPORTED_KINDS],
103587
- listExposedDevices: async () => this.config.exposed.map((e) => ({ deviceId: String(e.deviceId) })),
103588
- exposeDevice: async ({ deviceId }) => this.exposeDevice(deviceId),
103589
- unexposeDevice: async ({ deviceId }) => this.unexposeDevice(deviceId),
103846
+ getStatus: async (input) => {
103847
+ ownInstance(statusInstanceOf(input));
103848
+ return {
103849
+ linkState: this.view.linkedAccounts.length > 0 ? "linked" : "unlinked",
103850
+ exposedDeviceCount: this.config.exposed.length,
103851
+ setup: await this.buildSetupBlock()
103852
+ };
103853
+ },
103854
+ listInstances: async () => [{
103855
+ instanceId: EXPORT_ALEXA_ADDON_ID,
103856
+ name: "Alexa",
103857
+ enabled: true,
103858
+ kind: "alexa-skill"
103859
+ }],
103860
+ listSupportedDeviceKinds: async ({ instanceId }) => {
103861
+ ownInstance(instanceId);
103862
+ return [...SUPPORTED_KINDS];
103863
+ },
103864
+ listExposedDevices: async ({ instanceId }) => {
103865
+ ownInstance(instanceId);
103866
+ return this.config.exposed.map((e) => ({ deviceId: String(e.deviceId) }));
103867
+ },
103868
+ exposeDevice: async ({ instanceId, deviceId }) => {
103869
+ ownInstance(instanceId);
103870
+ return this.exposeDevice(deviceId);
103871
+ },
103872
+ unexposeDevice: async ({ instanceId, deviceId }) => {
103873
+ ownInstance(instanceId);
103874
+ return this.unexposeDevice(deviceId);
103875
+ },
103590
103876
  listSupportedEntityKinds: async () => ["device", "action"],
103591
- listExposedEntities: async () => {
103877
+ listExposedEntities: async ({ instanceId }) => {
103878
+ ownInstance(instanceId);
103592
103879
  await actionScenes.reconcile();
103593
103880
  return [...this.config.exposed.map((e) => ({ entity: {
103594
103881
  kind: "device",
103595
103882
  deviceId: String(e.deviceId)
103596
103883
  } })), ...actionScenes.list()];
103597
103884
  },
103598
- exposeEntity: async ({ entity }) => {
103885
+ exposeEntity: async ({ instanceId, entity }) => {
103886
+ ownInstance(instanceId);
103599
103887
  if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
103600
103888
  if (entity.kind === "action") return actionScenes.expose(entity.actionId);
103601
103889
  throw new Error("export-alexa: a notification target cannot be exported to Alexa");
103602
103890
  },
103603
- unexposeEntity: async ({ entity }) => {
103891
+ unexposeEntity: async ({ instanceId, entity }) => {
103892
+ ownInstance(instanceId);
103604
103893
  if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
103605
103894
  if (entity.kind === "action") return actionScenes.unexpose(entity.actionId);
103606
103895
  throw new Error("export-alexa: a notification target cannot be exported to Alexa");
@@ -104442,6 +104731,12 @@ var ExportAlexaAddon = class extends BaseAddon {
104442
104731
  },
104443
104732
  putSkill: (body) => putOnce(skills, body),
104444
104733
  putLinks: (body) => putOnce(links, body),
104734
+ replaceLinks: async (body) => {
104735
+ await links.put({
104736
+ id: ALEXA_INSTANCE_ID,
104737
+ data: body
104738
+ });
104739
+ },
104445
104740
  readLinks: async () => (await links.getResolved("export-alexa"))?.data ?? null,
104446
104741
  hasSkill: async () => await skills.get(ALEXA_INSTANCE_ID) !== null,
104447
104742
  clearOldTokenSecrets: async () => {