@avantics/node-red-home-automation 3.0.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +285 -13
  2. package/dist/lib/activity-lighting-controller.d.ts +7 -1
  3. package/dist/lib/activity-lighting-controller.js +37 -3
  4. package/dist/lib/adopted-request.d.ts +26 -0
  5. package/dist/lib/adopted-request.js +44 -0
  6. package/dist/lib/avr-controller.d.ts +8 -1
  7. package/dist/lib/avr-controller.js +27 -3
  8. package/dist/lib/avr-publishing.d.ts +24 -0
  9. package/dist/lib/avr-publishing.js +80 -0
  10. package/dist/lib/backlighting-controller.d.ts +7 -1
  11. package/dist/lib/backlighting-controller.js +26 -3
  12. package/dist/lib/circadian.d.ts +1 -0
  13. package/dist/lib/circadian.js +3 -0
  14. package/dist/lib/command-echo.d.ts +2 -0
  15. package/dist/lib/command-echo.js +39 -15
  16. package/dist/lib/cover-availability.d.ts +7 -0
  17. package/dist/lib/cover-availability.js +24 -0
  18. package/dist/lib/cover-controller.d.ts +13 -1
  19. package/dist/lib/cover-controller.js +113 -30
  20. package/dist/lib/cover-group.d.ts +62 -0
  21. package/dist/lib/cover-group.js +125 -0
  22. package/dist/lib/cover-models.d.ts +37 -0
  23. package/dist/lib/cover-models.js +83 -0
  24. package/dist/lib/cover-publishing.d.ts +40 -0
  25. package/dist/lib/cover-publishing.js +102 -0
  26. package/dist/lib/cover-requests.d.ts +21 -0
  27. package/dist/lib/cover-requests.js +49 -0
  28. package/dist/lib/display-mode-controller.d.ts +4 -0
  29. package/dist/lib/display-mode-controller.js +26 -2
  30. package/dist/lib/ha-discovery.d.ts +27 -0
  31. package/dist/lib/ha-discovery.js +91 -0
  32. package/dist/lib/house-schedule-publishing.d.ts +23 -0
  33. package/dist/lib/house-schedule-publishing.js +71 -0
  34. package/dist/lib/house-schedule.d.ts +23 -0
  35. package/dist/lib/house-schedule.js +29 -0
  36. package/dist/lib/motion-policy.d.ts +9 -0
  37. package/dist/lib/motion-policy.js +45 -11
  38. package/dist/lib/motion-publishing.d.ts +28 -0
  39. package/dist/lib/motion-publishing.js +92 -0
  40. package/dist/lib/occupancy-publishing.d.ts +10 -0
  41. package/dist/lib/occupancy-publishing.js +45 -0
  42. package/dist/lib/open-close-cover.d.ts +92 -0
  43. package/dist/lib/open-close-cover.js +287 -0
  44. package/dist/lib/publishing-node.d.ts +39 -0
  45. package/dist/lib/publishing-node.js +72 -0
  46. package/dist/lib/retained-topics.d.ts +10 -0
  47. package/dist/lib/retained-topics.js +19 -0
  48. package/dist/lib/room-controller.d.ts +10 -0
  49. package/dist/lib/room-controller.js +68 -59
  50. package/dist/lib/room-lighting-discovery.d.ts +20 -1
  51. package/dist/lib/room-lighting-discovery.js +135 -13
  52. package/dist/lib/room-publishing.d.ts +42 -0
  53. package/dist/lib/room-publishing.js +182 -0
  54. package/dist/lib/room-schedule.d.ts +8 -0
  55. package/dist/lib/room-schedule.js +41 -0
  56. package/dist/lib/settings.d.ts +2 -0
  57. package/dist/lib/settings.js +20 -0
  58. package/dist/lib/source-capability-controller.d.ts +8 -1
  59. package/dist/lib/source-capability-controller.js +29 -3
  60. package/dist/lib/theatre-activity-controller.d.ts +0 -1
  61. package/dist/lib/theatre-activity-controller.js +27 -24
  62. package/dist/lib/theatre-ha-discovery.d.ts +3 -4
  63. package/dist/lib/theatre-ha-discovery.js +46 -36
  64. package/dist/lib/theatre-state-contract.d.ts +6 -0
  65. package/dist/lib/theatre-state-contract.js +83 -47
  66. package/dist/lib/theatre-state.d.ts +1 -1
  67. package/dist/lib/theatre-state.js +1 -1
  68. package/dist/lib/topic-names.d.ts +4 -0
  69. package/dist/lib/topic-names.js +31 -0
  70. package/dist/nodes/activity-lighting-controller.js +5 -3
  71. package/dist/nodes/adapter.d.ts +6 -1
  72. package/dist/nodes/adapter.js +65 -1
  73. package/dist/nodes/avr-controller.html +59 -5
  74. package/dist/nodes/avr-controller.js +74 -4
  75. package/dist/nodes/backlighting-controller.js +5 -3
  76. package/dist/nodes/cover-controller.d.ts +3 -0
  77. package/dist/nodes/cover-controller.html +177 -0
  78. package/dist/nodes/cover-controller.js +178 -0
  79. package/dist/nodes/cover-group.d.ts +3 -0
  80. package/dist/nodes/cover-group.html +89 -0
  81. package/dist/nodes/cover-group.js +84 -0
  82. package/dist/nodes/flows-started.d.ts +4 -0
  83. package/dist/nodes/flows-started.js +39 -0
  84. package/dist/nodes/house-schedule-mqtt.d.ts +3 -0
  85. package/dist/nodes/house-schedule-mqtt.html +61 -0
  86. package/dist/nodes/house-schedule-mqtt.js +80 -0
  87. package/dist/nodes/house-schedule.d.ts +3 -0
  88. package/dist/nodes/house-schedule.html +31 -0
  89. package/dist/nodes/house-schedule.js +51 -0
  90. package/dist/nodes/motion-policy.html +81 -5
  91. package/dist/nodes/motion-policy.js +69 -8
  92. package/dist/nodes/occupancy-fusion.html +69 -14
  93. package/dist/nodes/occupancy-fusion.js +46 -4
  94. package/dist/nodes/publishing-lifecycle.d.ts +25 -0
  95. package/dist/nodes/publishing-lifecycle.js +38 -0
  96. package/dist/nodes/room-controller.html +54 -5
  97. package/dist/nodes/room-controller.js +67 -8
  98. package/dist/nodes/shared-schedule.d.ts +6 -0
  99. package/dist/nodes/shared-schedule.js +15 -0
  100. package/dist/nodes/source-capability-controller.js +5 -3
  101. package/dist/nodes/theatre-activity-controller.html +1 -3
  102. package/dist/nodes/theatre-activity-controller.js +1 -2
  103. package/dist/nodes/theatre-state-contract.html +28 -5
  104. package/dist/nodes/theatre-state-contract.js +22 -4
  105. package/examples/Cover control.json +380 -0
  106. package/examples/Cover pair.json +230 -0
  107. package/examples/Home theatre activity.json +4 -4
  108. package/examples/House schedule.json +164 -0
  109. package/examples/Room lighting.json +4 -3
  110. package/package.json +6 -2
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.roomRetainedTopics = roomRetainedTopics;
4
+ exports.roomPublishesState = roomPublishesState;
5
+ exports.roomPublishesDiscovery = roomPublishesDiscovery;
6
+ exports.roomStartingOutputs = roomStartingOutputs;
7
+ exports.roomStoppingOutputs = roomStoppingOutputs;
8
+ exports.roomInbound = roomInbound;
9
+ exports.publishRoom = publishRoom;
10
+ const ha_discovery_1 = require("./ha-discovery");
11
+ const room_controller_1 = require("./room-controller");
12
+ const room_lighting_discovery_1 = require("./room-lighting-discovery");
13
+ const topic_names_1 = require("./topic-names");
14
+ function ownTimes(config) {
15
+ return config.timesFrom !== "house";
16
+ }
17
+ function targetIds(config) {
18
+ return config.targets.map((target) => target.id);
19
+ }
20
+ function discoveryConfig(config) {
21
+ return { ...config, discoveryPrefix: config.discoveryPrefix ?? ha_discovery_1.DEFAULT_DISCOVERY_PREFIX };
22
+ }
23
+ // Every retained topic the room publishes, for clearing those it no longer
24
+ // does after a change. The discovery entry counts whenever the room has an
25
+ // area, as it is published or cleared at each start.
26
+ function roomRetainedTopics(config) {
27
+ const topics = (0, topic_names_1.areaId)(config.area) ? (0, room_lighting_discovery_1.roomDiscovery)(discoveryConfig(config), targetIds(config)).map(({ topic }) => topic) : [];
28
+ if (roomPublishesState(config)) {
29
+ topics.push((0, room_lighting_discovery_1.roomAvailabilityTopic)(config.area), (0, room_lighting_discovery_1.circadianStateTopic)(config.area), (0, room_lighting_discovery_1.sleepStateTopic)(config.area));
30
+ if (ownTimes(config))
31
+ topics.push((0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "wake-time"), (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "bed-time"));
32
+ topics.push(...config.targets.map((target) => (0, room_lighting_discovery_1.roomControlTopic)(config.area, target.id)));
33
+ }
34
+ return topics;
35
+ }
36
+ // Whether the room publishes state under its area, and its circadian
37
+ // switch's discovery, which reads that state.
38
+ function roomPublishesState(config) {
39
+ return config.area !== "" && config.publishState !== false;
40
+ }
41
+ function roomPublishesDiscovery(config) {
42
+ return roomPublishesState(config) && config.discovery !== false;
43
+ }
44
+ // What the room publishes as it starts and as it stops, when it publishes at
45
+ // all, so Home Assistant shows its entities as available only while it runs.
46
+ function roomStartingOutputs(config) {
47
+ return roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, true)] : [];
48
+ }
49
+ function roomStoppingOutputs(config) {
50
+ return roomPublishesState(config) ? [(0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, false)] : [];
51
+ }
52
+ function onOff(payload) {
53
+ const requested = typeof payload === "string" ? payload.trim().toUpperCase() : "";
54
+ return requested === "ON" ? true : requested === "OFF" ? false : null;
55
+ }
56
+ // The set topics the room reads, what each payload means as a room event,
57
+ // and the trace reason when it means nothing.
58
+ function setTopics(area, ownTimesToo) {
59
+ const topics = [
60
+ { name: "circadian-set", topic: (0, room_lighting_discovery_1.circadianCommandTopic)(area), invalid: "not-on-or-off",
61
+ event: (payload) => {
62
+ const enabled = onOff(payload);
63
+ return enabled === null ? null : { kind: "circadian", enabled };
64
+ } },
65
+ { name: "sleep-set", topic: (0, room_lighting_discovery_1.sleepCommandTopic)(area), invalid: "not-on-or-off",
66
+ event: (payload) => {
67
+ const enabled = onOff(payload);
68
+ return enabled === null ? null : { kind: "sleep", enabled };
69
+ } },
70
+ { name: "wake-time-set", topic: (0, room_lighting_discovery_1.scheduleCommandTopic)(area, "wake-time"), invalid: "not-a-time",
71
+ event: (payload) => {
72
+ const wakeTime = (0, ha_discovery_1.timeEntityValue)(payload);
73
+ return wakeTime === null ? null : { kind: "schedule", wakeTime };
74
+ } },
75
+ { name: "bed-time-set", topic: (0, room_lighting_discovery_1.scheduleCommandTopic)(area, "bed-time"), invalid: "not-a-time",
76
+ event: (payload) => {
77
+ const bedTime = (0, ha_discovery_1.timeEntityValue)(payload);
78
+ return bedTime === null ? null : { kind: "schedule", bedTime };
79
+ } }
80
+ ];
81
+ // Following the house, the room's own wake and bed set topics are not read.
82
+ return ownTimesToo ? topics : topics.filter(({ name }) => name !== "wake-time-set" && name !== "bed-time-set");
83
+ }
84
+ // MQTT the room reads, as room events: the set topics of its Home Assistant
85
+ // entities (circadian lighting and sleep, ON or OFF; wake and bed times).
86
+ // Read only while the room publishes, as the entities are only discovered
87
+ // then; a bare MQTT message, or one a flow tagged as observed, is accepted.
88
+ // Anything else passes through unchanged.
89
+ function roomInbound(msg, config) {
90
+ const event = msg.lighting || {};
91
+ const set = roomPublishesState(config) && (!event.kind || event.kind === "observed" || event.kind === "command-observed")
92
+ ? setTopics(config.area, ownTimes(config)).find(({ topic }) => topic === msg.topic)
93
+ : undefined;
94
+ if (!set)
95
+ return { msg, traces: [] };
96
+ if (msg.retain === true || event.retained === true) {
97
+ return {
98
+ msg: { ...msg, lighting: { kind: "ignored" } },
99
+ traces: [{ event: set.name, outcome: "ignored", reason: "retained-message", details: {} }]
100
+ };
101
+ }
102
+ const mapped = set.event(msg.payload);
103
+ if (mapped)
104
+ return { msg: { ...msg, lighting: mapped }, traces: [] };
105
+ return {
106
+ msg: { ...msg, lighting: { kind: "ignored" } },
107
+ traces: [{
108
+ event: set.name,
109
+ outcome: "ignored",
110
+ reason: set.invalid,
111
+ details: { payload: typeof msg.payload === "string" ? msg.payload : null }
112
+ }]
113
+ };
114
+ }
115
+ // A light's retained control state: in-control, overridden or manual.
116
+ function controlMessage(config, state, targetId) {
117
+ const entry = state.control[targetId];
118
+ return {
119
+ topic: (0, room_lighting_discovery_1.roomControlTopic)(config.area, targetId),
120
+ payload: { state: entry?.state ?? "in-control", owner: entry?.state === "overridden" ? entry.owner : null },
121
+ retain: true
122
+ };
123
+ }
124
+ // The room's transition with its MQTT side: incoming MQTT becomes room
125
+ // events, and the controller's decisions are published. At startup, the
126
+ // discovery entry (or its removal), availability and circadian state come
127
+ // first and every light's control state last; a circadian change publishes
128
+ // the circadian state before the lights are restyled; any light whose control
129
+ // state changed has it published after the commands.
130
+ function publishRoom(saved, msg, config, now) {
131
+ const inbound = roomInbound(msg, config);
132
+ const result = (0, room_controller_1.transitionRoom)(saved, inbound.msg, config, now);
133
+ const kind = inbound.msg.lighting?.kind;
134
+ const publishes = roomPublishesState(config);
135
+ const before = [];
136
+ if (kind === "startup") {
137
+ if ((0, topic_names_1.areaId)(config.area) !== "") {
138
+ // Discovery switched off: empty retained entries remove the entities
139
+ // from Home Assistant.
140
+ for (const entry of (0, room_lighting_discovery_1.roomDiscovery)(discoveryConfig(config), targetIds(config))) {
141
+ before.push(roomPublishesDiscovery(config) ? entry : { topic: entry.topic, payload: "", retain: true });
142
+ }
143
+ }
144
+ if (publishes) {
145
+ before.push((0, room_lighting_discovery_1.roomAvailabilityMessage)(config.area, true));
146
+ before.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, result.state.circadianEnabled));
147
+ before.push((0, room_lighting_discovery_1.sleepStateMessage)(config.area, result.state.sleeping));
148
+ if (ownTimes(config))
149
+ before.push(...(0, room_lighting_discovery_1.scheduleStateMessages)(config.area, result.state.schedule));
150
+ }
151
+ // Following the house, the room's own time entities and their state are
152
+ // cleared, every start, whatever was published before.
153
+ if (!ownTimes(config) && (0, topic_names_1.areaId)(config.area) !== "") {
154
+ const ownTimeTopics = [
155
+ ...(0, room_lighting_discovery_1.roomTimeDiscoveryTopics)(discoveryConfig(config)),
156
+ (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "wake-time"),
157
+ (0, room_lighting_discovery_1.scheduleStateTopic)(config.area, "bed-time")
158
+ ];
159
+ before.push(...ownTimeTopics.map((topic) => ({ topic, payload: "", retain: true })));
160
+ }
161
+ }
162
+ else if (kind === "circadian" && publishes) {
163
+ before.push((0, room_lighting_discovery_1.circadianStateMessage)(config.area, result.state.circadianEnabled));
164
+ }
165
+ else if (kind === "sleep" && publishes) {
166
+ before.push((0, room_lighting_discovery_1.sleepStateMessage)(config.area, result.state.sleeping));
167
+ }
168
+ else if (kind === "schedule" && publishes && ownTimes(config)) {
169
+ before.push(...(0, room_lighting_discovery_1.scheduleStateMessages)(config.area, result.state.schedule));
170
+ }
171
+ const controls = publishes
172
+ ? config.targets
173
+ .filter((target) => kind === "startup" || result.controlChanged.includes(target.id))
174
+ .map((target) => controlMessage(config, result.state, target.id))
175
+ : [];
176
+ return {
177
+ ...result,
178
+ outputs: [...before, ...result.outputs, ...controls],
179
+ traces: [...inbound.traces, ...result.traces]
180
+ };
181
+ }
182
+ //# sourceMappingURL=room-publishing.js.map
@@ -0,0 +1,8 @@
1
+ import { type DaySchedule } from "./circadian-schedule";
2
+ import type { RoomConfig, RoomState } from "./room-controller";
3
+ export declare function savedSchedule(config: RoomConfig, saved: Partial<RoomState>): Pick<RoomState, "schedule" | "scheduleSetting">;
4
+ export declare function withActiveSchedule(config: RoomConfig, state: RoomState): RoomConfig;
5
+ export declare function requestedSchedule(current: DaySchedule, event: {
6
+ wakeTime?: unknown;
7
+ bedTime?: unknown;
8
+ }): DaySchedule | null;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.savedSchedule = savedSchedule;
4
+ exports.withActiveSchedule = withActiveSchedule;
5
+ exports.requestedSchedule = requestedSchedule;
6
+ // The room's wake and bed times while it runs: the configured times, or times
7
+ // set at runtime (from Home Assistant, say), which last until the node is
8
+ // deployed with a different setting for them. And the room's lighting on
9
+ // whichever times are in use.
10
+ const circadian_schedule_1 = require("./circadian-schedule");
11
+ const settings_1 = require("./settings");
12
+ function configuredSchedule(config) {
13
+ return config.schedule ?? { wakeTime: circadian_schedule_1.DEFAULT_WAKE_TIME, bedTime: circadian_schedule_1.DEFAULT_BED_TIME };
14
+ }
15
+ // Each saved time stands only while the setting it was based on is
16
+ // unchanged; state saved before times could change takes the settings.
17
+ function savedSchedule(config, saved) {
18
+ const setting = configuredSchedule(config);
19
+ const kept = (key) => (0, settings_1.keptOverride)(saved.schedule?.[key], saved.scheduleSetting?.[key], setting[key]);
20
+ return { schedule: { wakeTime: kept("wakeTime"), bedTime: kept("bedTime") }, scheduleSetting: { ...setting } };
21
+ }
22
+ // The room's settings with lighting that follows the times in use.
23
+ function withActiveSchedule(config, state) {
24
+ const setting = configuredSchedule(config);
25
+ const same = state.schedule.wakeTime === setting.wakeTime && state.schedule.bedTime === setting.bedTime;
26
+ if (same)
27
+ return config;
28
+ return { ...config, lighting: config.lighting.withSchedule(state.schedule) };
29
+ }
30
+ // New times from a "schedule" message, each "HH:MM", with a time left out
31
+ // staying as it is; null if they aren't valid, different times.
32
+ function requestedSchedule(current, event) {
33
+ const next = {
34
+ wakeTime: typeof event.wakeTime === "string" ? event.wakeTime.trim() : current.wakeTime,
35
+ bedTime: typeof event.bedTime === "string" ? event.bedTime.trim() : current.bedTime
36
+ };
37
+ const wake = (0, circadian_schedule_1.clockMinutes)(next.wakeTime);
38
+ const bed = (0, circadian_schedule_1.clockMinutes)(next.bedTime);
39
+ return wake === null || bed === null || wake === bed ? null : next;
40
+ }
41
+ //# sourceMappingURL=room-schedule.js.map
@@ -3,3 +3,5 @@ export declare function booleanSetting(value: unknown, label: string, fallback:
3
3
  export declare function optionalBooleanSetting(value: unknown, label: string): boolean | null;
4
4
  export declare function textSetting(value: unknown, label: string, fallback?: string): string;
5
5
  export declare function jsonSetting(value: unknown, label: string, fallback: unknown): unknown;
6
+ export declare function optionalChoiceSetting<Choice extends string>(value: unknown, label: string, choices: readonly Choice[]): Choice | null;
7
+ export declare function keptOverride<Value extends string | number>(savedValue: unknown, savedSetting: unknown, setting: Value): Value;
@@ -5,6 +5,8 @@ exports.booleanSetting = booleanSetting;
5
5
  exports.optionalBooleanSetting = optionalBooleanSetting;
6
6
  exports.textSetting = textSetting;
7
7
  exports.jsonSetting = jsonSetting;
8
+ exports.optionalChoiceSetting = optionalChoiceSetting;
9
+ exports.keptOverride = keptOverride;
8
10
  // A numeric node setting, read from the editor's value. A setting absent from
9
11
  // a flow saved before it existed takes its default. Anything else must be a
10
12
  // number: an emptied field, null or text is an error naming the setting, so
@@ -65,4 +67,22 @@ function jsonSetting(value, label, fallback) {
65
67
  }
66
68
  throw new Error(`${label} must be valid JSON`);
67
69
  }
70
+ // One of a fixed set of words, such as a scheme name. Absent or null is "not
71
+ // set" (null), for the caller to give its documented meaning; anything else
72
+ // that isn't one of the choices is an error naming them.
73
+ function optionalChoiceSetting(value, label, choices) {
74
+ if (value === undefined || value === null)
75
+ return null;
76
+ if (typeof value === "string" && choices.includes(value))
77
+ return value;
78
+ throw new Error(`${label} must be ${choices.slice(0, -1).join(", ")}${choices.length > 1 ? " or " : ""}${choices.at(-1)}`);
79
+ }
80
+ // The rule for a value set at runtime (from Home Assistant, say) over a
81
+ // setting: it lasts until the node is deployed with a different setting,
82
+ // which then applies. `savedSetting` is the setting the saved value was
83
+ // based on; state saved before such values were recorded has none, so the
84
+ // setting applies.
85
+ function keptOverride(savedValue, savedSetting, setting) {
86
+ return savedSetting === setting && typeof savedValue === typeof setting ? savedValue : setting;
87
+ }
68
88
  //# sourceMappingURL=settings.js.map
@@ -54,6 +54,7 @@ export interface SourceState {
54
54
  lastAttempt: number;
55
55
  fallbackUsed: boolean;
56
56
  refreshAsked: boolean;
57
+ adoptedGeneration: number | null;
57
58
  }
58
59
  export type SourceEvent = {
59
60
  kind: "intent";
@@ -79,7 +80,13 @@ export type SourceEvent = {
79
80
  kind: "tick";
80
81
  generation: number;
81
82
  } | {
82
- kind: "startup" | "refresh";
83
+ kind: "startup";
84
+ } | {
85
+ kind: "refresh";
86
+ requestId?: string | null;
87
+ generation?: number;
88
+ sourceId?: string | null;
89
+ action?: string;
83
90
  };
84
91
  export interface SourceMessage {
85
92
  sourceCapability?: SourceEvent;
@@ -4,6 +4,7 @@ exports.normaliseCapabilities = normaliseCapabilities;
4
4
  exports.normaliseConfig = normaliseConfig;
5
5
  exports.readinessEvidence = readinessEvidence;
6
6
  exports.transitionSource = transitionSource;
7
+ const adopted_request_1 = require("./adopted-request");
7
8
  const settings_1 = require("./settings");
8
9
  const observation_time_1 = require("./observation-time");
9
10
  const target_state_1 = require("./target-state");
@@ -110,7 +111,8 @@ function initialState(saved = {}, sources = {}) {
110
111
  ? saved.lastAttempt
111
112
  : 0,
112
113
  fallbackUsed: saved.fallbackUsed === true,
113
- refreshAsked: saved.refreshAsked === true
114
+ refreshAsked: saved.refreshAsked === true,
115
+ adoptedGeneration: (0, adopted_request_1.savedAdoptedGeneration)(saved)
114
116
  };
115
117
  }
116
118
  function commandFor(state, operation, attempt = 1) {
@@ -272,10 +274,13 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
272
274
  required: readiness.required
273
275
  });
274
276
  }
275
- else if (state.phase === "ready" && !state.pending) {
277
+ else if ((state.phase === "ready" && !state.pending) || (0, adopted_request_1.isAdopted)(state)) {
278
+ // A change seen after ready, or an adopted request the source doesn't
279
+ // match: someone else's, and never corrected.
280
+ state.pending = null;
276
281
  state.classification = "manual_override";
277
282
  state.phase = "manual_override";
278
- trace("observation", "manual_override", null, {
283
+ trace("observation", "manual_override", (0, adopted_request_1.isAdopted)(state) ? adopted_request_1.ADOPTED_MISMATCH : null, {
279
284
  sourceId: state.desired.sourceId,
280
285
  status: state.observed.status
281
286
  });
@@ -435,6 +440,18 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
435
440
  trace("command", "emitted", null, { sourceId: state.desired.sourceId, operation: "observe" });
436
441
  }
437
442
  }
443
+ // A refresh with the activity's wanted values, reaching a node with
444
+ // nothing desired (it started with nothing saved): adopt them, and observe
445
+ // below as at startup (see adopted-request.ts).
446
+ const adoptable = event.kind === "refresh" ? (0, adopted_request_1.adoptableRefresh)(event, state) : null;
447
+ if (adoptable && event.kind === "refresh" && typeof event.action === "string" && Object.hasOwn(ACTIONS, event.action) &&
448
+ ((typeof event.sourceId === "string" && Object.hasOwn(config.sources, event.sourceId)) ||
449
+ (!event.sourceId && event.action === "deactivate"))) {
450
+ state.desired = { ...adoptable, sourceId: event.sourceId || null, action: event.action };
451
+ state.generation = adoptable.generation;
452
+ state.adoptedGeneration = adoptable.generation;
453
+ trace("refresh", "adopted", "nothing-desired", { sourceId: event.sourceId || null, action: event.action, generation: adoptable.generation });
454
+ }
438
455
  if (event.kind === "intent") {
439
456
  acceptIntent(event);
440
457
  }
@@ -485,6 +502,15 @@ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()
485
502
  throw new Error("unknown source capability event kind");
486
503
  }
487
504
  // A refresh of a settled source reports nothing until its reading arrives.
505
+ // An adopted request only reads the source (see adopted-request.ts).
506
+ const held = (0, adopted_request_1.readsOnly)(state, commands, (command) => command.operation === "observe");
507
+ if (held.mismatch) {
508
+ commands.splice(0, commands.length, ...held.commands);
509
+ state.pending = null;
510
+ state.classification = "manual_override";
511
+ state.phase = "manual_override";
512
+ trace("command", "withheld", adopted_request_1.ADOPTED_MISMATCH);
513
+ }
488
514
  const outputEvent = event.kind === "refresh" && state.refreshAsked ? null : targetEvent(state, now, config.sources);
489
515
  if (outputEvent)
490
516
  events.push(outputEvent);
@@ -7,7 +7,6 @@ export interface TheatreConfig {
7
7
  area: string;
8
8
  freshnessMs: number;
9
9
  activityProfiles: ActivityProfiles;
10
- recoveryOffActivity?: string;
11
10
  }
12
11
  export type TheatreInputEvent = {
13
12
  kind: "intent";
@@ -18,13 +18,11 @@ var theatre_state_2 = require("./theatre-state");
18
18
  Object.defineProperty(exports, "createTheatreState", { enumerable: true, get: function () { return theatre_state_2.createTheatreState; } });
19
19
  function normaliseConfig(config = {}) {
20
20
  const activityProfiles = (0, theatre_profiles_1.normaliseActivityProfiles)(config.activityProfiles);
21
- const recoveryOffActivity = (0, settings_1.textSetting)(config.recoveryOffActivity, "recovery off activity", "off");
22
21
  return {
23
22
  // Optional: an empty area means none.
24
23
  area: typeof config.area === "string" ? config.area.trim() : "",
25
24
  freshnessMs: Math.max(1000, (0, settings_1.numberSetting)(config.freshnessMs, "freshness", 30000)),
26
- activityProfiles,
27
- recoveryOffActivity
25
+ activityProfiles
28
26
  };
29
27
  }
30
28
  function targetCommand(target, kind, desired, values = {}) {
@@ -51,8 +49,15 @@ function targetIntentCommands(desired, config, previousDesired) {
51
49
  return targetCommand(target, "intent", desired, values);
52
50
  });
53
51
  }
54
- function targetRefreshCommands(desired) {
55
- return theatre_profiles_1.TARGETS.map((target) => targetCommand(target, "refresh", desired));
52
+ // A refresh carries the activity's wanted values for the target, as its
53
+ // intent did, so a target node that has nothing desired (it started with
54
+ // nothing saved) can adopt them and observe, instead of staying idle.
55
+ function targetRefreshCommand(target, desired, config) {
56
+ const values = desired ? config.activityProfiles[desired.activity]?.[target] ?? {} : {};
57
+ return targetCommand(target, "refresh", desired, values);
58
+ }
59
+ function targetRefreshCommands(desired, config) {
60
+ return theatre_profiles_1.TARGETS.map((target) => targetRefreshCommand(target, desired, config));
56
61
  }
57
62
  function targetProbeCommands() {
58
63
  return theatre_profiles_1.TARGETS.map((target) => targetCommand(target, "refresh", null));
@@ -287,7 +292,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
287
292
  noResponse(action.target);
288
293
  continue;
289
294
  }
290
- commands.push(targetCommand(action.target, "refresh", state.desired));
295
+ commands.push(targetRefreshCommand(action.target, state.desired, config));
291
296
  if (action.kind === "retry")
292
297
  trace("refresh", "retried", null, { target: action.target, attempt: action.attempt });
293
298
  if (action.kind === "re-ask")
@@ -309,7 +314,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
309
314
  };
310
315
  }
311
316
  }
312
- function acceptIntent(event, internal = false) {
317
+ function acceptIntent(event) {
313
318
  if (typeof event.requestId !== "string" || !event.requestId) {
314
319
  throw new Error("theatre requestId is required");
315
320
  }
@@ -326,7 +331,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
326
331
  // already taken (for example by a recovery) gets the next free one.
327
332
  let generation = event.generation;
328
333
  const taken = generation < state.generation || (generation === state.generation && state.desired !== null);
329
- if (taken && !internal && state.desired?.requestId !== event.requestId &&
334
+ if (taken && state.desired?.requestId !== event.requestId &&
330
335
  event.generation > state.lastProposedGeneration) {
331
336
  generation = state.generation + 1;
332
337
  trace("intent", "reassigned", "generation-taken", { requestId: event.requestId, proposed: event.generation, assigned: generation });
@@ -368,8 +373,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
368
373
  requestedAt
369
374
  };
370
375
  state.generation = generation;
371
- if (!internal)
372
- state.lastProposedGeneration = Math.max(state.lastProposedGeneration, event.generation);
376
+ state.lastProposedGeneration = Math.max(state.lastProposedGeneration, event.generation);
373
377
  state.phase = "preparing";
374
378
  state.currentActivity = "unknown";
375
379
  state.targets = (0, theatre_state_1.emptyTargets)();
@@ -501,22 +505,21 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
501
505
  return;
502
506
  }
503
507
  if (event.reason === "startup") {
504
- if (!Object.hasOwn(config.activityProfiles, config.recoveryOffActivity)) {
505
- throw new Error(`recovery off activity does not exist: ${config.recoveryOffActivity}`);
506
- }
507
- state.metrics.recoveriesSafeOff += 1;
508
- acceptIntent({
509
- kind: "intent",
510
- requestId: `recovery-safe-off-${nowMs}`,
511
- generation: state.generation + 1,
512
- activity: config.recoveryOffActivity,
513
- requestedAt: now.toISOString()
514
- }, true);
515
- emit("recovery_safe_off", {
508
+ // No evidence, or more than one match: the activity is unknown, and
509
+ // nothing is commanded until the next request. Starting with nothing
510
+ // saved happens on a redeploy without a context store, so it must never
511
+ // switch a running activity off.
512
+ state.refreshPending = (0, theatre_state_1.emptyRefreshPending)();
513
+ state.phase = "idle";
514
+ state.currentActivity = "unknown";
515
+ state.availability = "unknown";
516
+ state.metrics.recoveriesUnknown += 1;
517
+ state.metrics.lastOutcome = "recovery_unknown";
518
+ emit("recovery_unknown", {
516
519
  matchCount: matches.length,
517
520
  matchedActivities: matches
518
521
  });
519
- trace("recovery", "safe_off", matches.length ? "ambiguous" : "no-clean-match", {
522
+ trace("recovery", "unknown", matches.length ? "ambiguous" : "no-clean-match", {
520
523
  matchedActivities: matches
521
524
  });
522
525
  return;
@@ -546,7 +549,7 @@ function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date(
546
549
  state.targets = (0, theatre_state_1.emptyTargets)();
547
550
  state.refreshPending = (0, theatre_state_1.emptyRefreshPending)();
548
551
  if (state.desired) {
549
- commands.push(...targetRefreshCommands(state.desired));
552
+ commands.push(...targetRefreshCommands(state.desired, config));
550
553
  for (const target of theatre_profiles_1.TARGETS)
551
554
  state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
552
555
  state.phase = state.blockedGeneration === state.generation ? "failed" : "confirming";
@@ -1,11 +1,10 @@
1
+ import { type DiscoveryOwner } from "./ha-discovery";
1
2
  import { type TheatreTarget } from "./theatre-profiles";
2
- export type TheatreTopicName = "request" | "desired" | "current" | "phase" | "availability" | "failure" | "metrics" | "slo" | "slo/breach" | `health/${TheatreTarget}`;
3
+ export type TheatreTopicName = "request" | "desired" | "current" | "phase" | "transition" | "availability" | "readiness" | "failure" | "metrics" | "slo" | "slo/breach" | `health/${TheatreTarget}`;
3
4
  export declare function theatreTopic(baseTopic: string, name: TheatreTopicName): string;
4
- export interface TheatreDiscoveryConfig {
5
- area: string;
5
+ export interface TheatreDiscoveryConfig extends DiscoveryOwner {
6
6
  displayName: string;
7
7
  baseTopic: string;
8
- discoveryPrefix: string;
9
8
  activities: string[];
10
9
  }
11
10
  export declare function theatreDiscovery(config: TheatreDiscoveryConfig): Array<{