@avantics/node-red-home-automation 0.0.0-stage → 2.3.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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/contract-examples/README.md +28 -0
  4. package/contract-examples/_shared.mjs +11 -0
  5. package/contract-examples/motion-lighting.mjs +42 -0
  6. package/contract-examples/occupancy-fusion.mjs +35 -0
  7. package/contract-examples/room-lighting.mjs +58 -0
  8. package/contract-examples/run.mjs +16 -0
  9. package/contract-examples/source-readiness.mjs +64 -0
  10. package/contract-examples/switch-gestures.mjs +34 -0
  11. package/contract-examples/theatre-activity.mjs +62 -0
  12. package/contract-examples/volume-ownership.mjs +59 -0
  13. package/dist/lib/activity-lighting-controller.d.ts +129 -0
  14. package/dist/lib/activity-lighting-controller.js +372 -0
  15. package/dist/lib/avr-controller.d.ts +169 -0
  16. package/dist/lib/avr-controller.js +948 -0
  17. package/dist/lib/backlighting-controller.d.ts +108 -0
  18. package/dist/lib/backlighting-controller.js +269 -0
  19. package/dist/lib/bounded-trace.d.ts +30 -0
  20. package/dist/lib/bounded-trace.js +36 -0
  21. package/dist/lib/circadian-refresh.d.ts +7 -0
  22. package/dist/lib/circadian-refresh.js +11 -0
  23. package/dist/lib/circadian-schedule.d.ts +11 -0
  24. package/dist/lib/circadian-schedule.js +63 -0
  25. package/dist/lib/circadian.d.ts +6 -0
  26. package/dist/lib/circadian.js +15 -0
  27. package/dist/lib/cover-controller.d.ts +130 -0
  28. package/dist/lib/cover-controller.js +336 -0
  29. package/dist/lib/display-mode-controller.d.ts +148 -0
  30. package/dist/lib/display-mode-controller.js +587 -0
  31. package/dist/lib/display-transport.d.ts +41 -0
  32. package/dist/lib/display-transport.js +177 -0
  33. package/dist/lib/light-styling.d.ts +11 -0
  34. package/dist/lib/light-styling.js +15 -0
  35. package/dist/lib/motion-policy.d.ts +72 -0
  36. package/dist/lib/motion-policy.js +251 -0
  37. package/dist/lib/observation-time.d.ts +10 -0
  38. package/dist/lib/observation-time.js +40 -0
  39. package/dist/lib/occupancy-fusion.d.ts +53 -0
  40. package/dist/lib/occupancy-fusion.js +131 -0
  41. package/dist/lib/room-controller.d.ts +113 -0
  42. package/dist/lib/room-controller.js +431 -0
  43. package/dist/lib/source-capability-controller.d.ts +144 -0
  44. package/dist/lib/source-capability-controller.js +494 -0
  45. package/dist/lib/switch-policy.d.ts +53 -0
  46. package/dist/lib/switch-policy.js +110 -0
  47. package/dist/lib/theatre-activity-controller.d.ts +165 -0
  48. package/dist/lib/theatre-activity-controller.js +846 -0
  49. package/dist/lib/theatre-slo.d.ts +49 -0
  50. package/dist/lib/theatre-slo.js +156 -0
  51. package/dist/lib/theatre-state-contract.d.ts +77 -0
  52. package/dist/lib/theatre-state-contract.js +391 -0
  53. package/dist/lib/wall-input.d.ts +62 -0
  54. package/dist/lib/wall-input.js +198 -0
  55. package/dist/nodes/activity-lighting-controller.d.ts +3 -0
  56. package/dist/nodes/activity-lighting-controller.html +38 -0
  57. package/dist/nodes/activity-lighting-controller.js +116 -0
  58. package/dist/nodes/avr-controller.d.ts +3 -0
  59. package/dist/nodes/avr-controller.html +47 -0
  60. package/dist/nodes/avr-controller.js +130 -0
  61. package/dist/nodes/backlighting-controller.d.ts +3 -0
  62. package/dist/nodes/backlighting-controller.html +31 -0
  63. package/dist/nodes/backlighting-controller.js +103 -0
  64. package/dist/nodes/display-mode-controller.d.ts +3 -0
  65. package/dist/nodes/display-mode-controller.html +66 -0
  66. package/dist/nodes/display-mode-controller.js +132 -0
  67. package/dist/nodes/motion-policy.d.ts +3 -0
  68. package/dist/nodes/motion-policy.html +35 -0
  69. package/dist/nodes/motion-policy.js +194 -0
  70. package/dist/nodes/occupancy-fusion.d.ts +3 -0
  71. package/dist/nodes/occupancy-fusion.html +32 -0
  72. package/dist/nodes/occupancy-fusion.js +53 -0
  73. package/dist/nodes/room-controller.d.ts +3 -0
  74. package/dist/nodes/room-controller.html +82 -0
  75. package/dist/nodes/room-controller.js +123 -0
  76. package/dist/nodes/source-capability-controller.d.ts +3 -0
  77. package/dist/nodes/source-capability-controller.html +46 -0
  78. package/dist/nodes/source-capability-controller.js +114 -0
  79. package/dist/nodes/switch-policy.d.ts +3 -0
  80. package/dist/nodes/switch-policy.html +29 -0
  81. package/dist/nodes/switch-policy.js +129 -0
  82. package/dist/nodes/theatre-activity-controller.d.ts +3 -0
  83. package/dist/nodes/theatre-activity-controller.html +32 -0
  84. package/dist/nodes/theatre-activity-controller.js +105 -0
  85. package/dist/nodes/theatre-state-contract.d.ts +3 -0
  86. package/dist/nodes/theatre-state-contract.html +41 -0
  87. package/dist/nodes/theatre-state-contract.js +83 -0
  88. package/examples/Home theatre activity.json +477 -0
  89. package/examples/Home theatre equipment.json +329 -0
  90. package/examples/Room lighting.json +212 -0
  91. package/package.json +62 -4
@@ -0,0 +1,144 @@
1
+ export type SourceAction = "activate" | "deactivate";
2
+ export type SourceControlMode = "command" | "external" | "unavailable";
3
+ export type SourceConfirmation = "active" | "available" | "application" | "playing" | "unavailable";
4
+ export type SourceObservationStatus = "active" | "inactive" | "available" | "unavailable" | "unknown";
5
+ export type SourcePlaybackState = "playing" | "paused" | "idle" | "buffering" | "stopped" | "unknown";
6
+ export interface SourceDescriptor {
7
+ activation: SourceControlMode;
8
+ deactivation: SourceControlMode;
9
+ confirmation: SourceConfirmation;
10
+ fallback?: boolean;
11
+ }
12
+ export type SourceCapabilities = Record<string, SourceDescriptor>;
13
+ export interface SourceConfig {
14
+ sources: SourceCapabilities;
15
+ pollMs: number;
16
+ confirmationTimeoutMs: number;
17
+ maxAttempts: number;
18
+ }
19
+ export interface SourceDesired {
20
+ requestId: string;
21
+ generation: number;
22
+ sourceId: string | null;
23
+ action: SourceAction;
24
+ }
25
+ export interface SourceObservation {
26
+ sourceId: string;
27
+ status: SourceObservationStatus;
28
+ observedAt: string;
29
+ confirmedAt?: string;
30
+ application: string | null;
31
+ playback: SourcePlaybackState;
32
+ }
33
+ export interface SourcePending {
34
+ operation: SourceAction | "observe";
35
+ attempt: number;
36
+ deadlineAt: number;
37
+ nextAt: number;
38
+ }
39
+ export interface SourceFailure {
40
+ operation: string;
41
+ reason: string;
42
+ occurredAt: string;
43
+ }
44
+ export interface SourceState {
45
+ desired: SourceDesired | null;
46
+ generation: number;
47
+ phase: string;
48
+ observed: SourceObservation | null;
49
+ pending: SourcePending | null;
50
+ failure: SourceFailure | null;
51
+ blockedGeneration: number | null;
52
+ classification: "manual_override" | null;
53
+ lastAttempt: number;
54
+ fallbackUsed: boolean;
55
+ refreshAsked: boolean;
56
+ }
57
+ export type SourceEvent = {
58
+ kind: "intent";
59
+ requestId: string;
60
+ generation: number;
61
+ sourceId: string | null;
62
+ action: SourceAction;
63
+ } | {
64
+ kind: "observed";
65
+ generation: number;
66
+ sourceId: string;
67
+ status: SourceObservationStatus;
68
+ observedAt: string;
69
+ application?: string | null;
70
+ playback?: SourcePlaybackState;
71
+ } | {
72
+ kind: "command_result";
73
+ generation: number;
74
+ sourceId: string;
75
+ ok: boolean;
76
+ reason?: string;
77
+ } | {
78
+ kind: "tick";
79
+ generation: number;
80
+ } | {
81
+ kind: "startup" | "refresh";
82
+ };
83
+ export interface SourceMessage {
84
+ sourceCapability?: SourceEvent;
85
+ }
86
+ export declare function normaliseCapabilities(value: unknown): SourceCapabilities;
87
+ export declare function normaliseConfig(config?: Partial<SourceConfig> & {
88
+ sources?: unknown;
89
+ }): SourceConfig;
90
+ export interface SourceCommand {
91
+ sourceId: string | null;
92
+ operation: SourceAction | "observe";
93
+ requestId: string;
94
+ generation: number;
95
+ attempt: number;
96
+ }
97
+ export interface SourceOutputEvent {
98
+ theatre: {
99
+ kind: "target_state";
100
+ target: "source";
101
+ requestId: string;
102
+ generation: number;
103
+ status: string;
104
+ observedAt: string;
105
+ sourceId: string | null;
106
+ action: SourceAction;
107
+ classification?: "manual_override";
108
+ details: {
109
+ observedStatus: SourceObservationStatus | null;
110
+ readiness: {
111
+ required: SourceConfirmation;
112
+ available: boolean;
113
+ active: boolean;
114
+ application: string | null;
115
+ playback: SourcePlaybackState;
116
+ satisfied: boolean;
117
+ };
118
+ recovery: Record<string, unknown>;
119
+ metrics: {
120
+ attempts: number;
121
+ retries: number;
122
+ fallbackUsed: boolean;
123
+ };
124
+ };
125
+ failure?: SourceFailure;
126
+ };
127
+ }
128
+ export declare function transitionSource(saved: Partial<SourceState> | undefined, msg: SourceMessage, suppliedConfig?: Partial<SourceConfig> & {
129
+ sources?: unknown;
130
+ }, nowValue?: Date | string | number): {
131
+ state: SourceState;
132
+ commands: SourceCommand[];
133
+ events: SourceOutputEvent[];
134
+ traces: {
135
+ event: string;
136
+ outcome: string;
137
+ reason: string | null;
138
+ details: Record<string, unknown>;
139
+ }[];
140
+ status: {
141
+ phase: string;
142
+ text: string;
143
+ };
144
+ };
@@ -0,0 +1,494 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normaliseCapabilities = normaliseCapabilities;
4
+ exports.normaliseConfig = normaliseConfig;
5
+ exports.transitionSource = transitionSource;
6
+ const observation_time_1 = require("./observation-time");
7
+ const ACTIONS = { activate: true, deactivate: true };
8
+ const CONTROL_MODES = {
9
+ command: true,
10
+ external: true,
11
+ unavailable: true
12
+ };
13
+ const CONFIRMATIONS = {
14
+ active: true,
15
+ available: true,
16
+ application: true,
17
+ playing: true,
18
+ unavailable: true
19
+ };
20
+ const OBSERVATION_STATUSES = {
21
+ active: true,
22
+ inactive: true,
23
+ available: true,
24
+ unavailable: true,
25
+ unknown: true
26
+ };
27
+ const PLAYBACK_STATES = {
28
+ playing: true,
29
+ paused: true,
30
+ idle: true,
31
+ buffering: true,
32
+ stopped: true,
33
+ unknown: true
34
+ };
35
+ function iso(now) {
36
+ return now.toISOString();
37
+ }
38
+ function normaliseCapabilities(value) {
39
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
40
+ throw new Error("sources must be an object");
41
+ }
42
+ const sources = {};
43
+ for (const [sourceId, descriptorValue] of Object.entries(value)) {
44
+ if (!/^[a-z][a-z0-9_-]*$/.test(sourceId))
45
+ throw new Error(`invalid sourceId: ${sourceId}`);
46
+ if (!descriptorValue || typeof descriptorValue !== "object" || Array.isArray(descriptorValue)) {
47
+ throw new Error(`source ${sourceId} must be an object`);
48
+ }
49
+ const descriptor = descriptorValue;
50
+ const activation = descriptor.activation;
51
+ const deactivation = descriptor.deactivation;
52
+ const confirmation = descriptor.confirmation;
53
+ if (!Object.hasOwn(CONTROL_MODES, activation)) {
54
+ throw new Error(`source ${sourceId} has invalid activation capability`);
55
+ }
56
+ if (!Object.hasOwn(CONTROL_MODES, deactivation)) {
57
+ throw new Error(`source ${sourceId} has invalid deactivation capability`);
58
+ }
59
+ if (!Object.hasOwn(CONFIRMATIONS, confirmation)) {
60
+ throw new Error(`source ${sourceId} has invalid confirmation capability`);
61
+ }
62
+ sources[sourceId] = {
63
+ activation: activation,
64
+ deactivation: deactivation,
65
+ confirmation: confirmation,
66
+ ...(descriptor.fallback === true ? { fallback: true } : {})
67
+ };
68
+ }
69
+ if (Object.keys(sources).length === 0)
70
+ throw new Error("sources must not be empty");
71
+ return sources;
72
+ }
73
+ function normaliseConfig(config = {}) {
74
+ return {
75
+ sources: normaliseCapabilities(config.sources),
76
+ pollMs: Math.max(250, Number(config.pollMs) || 2000),
77
+ confirmationTimeoutMs: Math.max(1000, Number(config.confirmationTimeoutMs) || 15000),
78
+ maxAttempts: Math.max(1, Math.floor(Number(config.maxAttempts) || 2))
79
+ };
80
+ }
81
+ function initialState(saved = {}, sources = {}) {
82
+ const desired = saved.desired &&
83
+ (saved.desired.sourceId === null || Object.hasOwn(sources, saved.desired.sourceId))
84
+ ? { ...saved.desired }
85
+ : null;
86
+ return {
87
+ desired,
88
+ generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0 ? saved.generation : 0,
89
+ phase: typeof saved.phase === "string" ? saved.phase : "idle",
90
+ observed: saved.observed && typeof saved.observed === "object"
91
+ ? {
92
+ ...saved.observed,
93
+ application: typeof saved.observed.application === "string" && saved.observed.application
94
+ ? saved.observed.application
95
+ : null,
96
+ playback: Object.hasOwn(PLAYBACK_STATES, saved.observed.playback)
97
+ ? saved.observed.playback
98
+ : "unknown"
99
+ }
100
+ : null,
101
+ pending: saved.pending && typeof saved.pending === "object" ? { ...saved.pending } : null,
102
+ failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
103
+ blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
104
+ classification: saved.classification === "manual_override" ? "manual_override" : null,
105
+ lastAttempt: Number.isInteger(saved.lastAttempt) && (saved.lastAttempt ?? -1) >= 0
106
+ ? saved.lastAttempt
107
+ : 0,
108
+ fallbackUsed: saved.fallbackUsed === true,
109
+ refreshAsked: saved.refreshAsked === true
110
+ };
111
+ }
112
+ function commandFor(state, operation, attempt = 1) {
113
+ if (!state.desired)
114
+ throw new Error("source command requires desired state");
115
+ return {
116
+ sourceId: state.desired.sourceId,
117
+ operation,
118
+ requestId: state.desired.requestId,
119
+ generation: state.generation,
120
+ attempt
121
+ };
122
+ }
123
+ function targetStatus(phase) {
124
+ if (phase === "ready")
125
+ return "ready";
126
+ if (phase === "failed")
127
+ return "failed";
128
+ if (phase === "unavailable")
129
+ return "unavailable";
130
+ if (phase === "waiting_for_source")
131
+ return "waiting_for_source";
132
+ if (phase === "transitioning")
133
+ return "transitioning";
134
+ return "confirming";
135
+ }
136
+ function descriptorFor(state, sources) {
137
+ if (!state.desired || state.desired.sourceId === null)
138
+ return null;
139
+ return sources[state.desired.sourceId] ?? null;
140
+ }
141
+ function readinessEvidence(observation, required) {
142
+ const available = observation?.status === "active" || observation?.status === "available";
143
+ const active = observation?.status === "active";
144
+ const application = observation?.application ?? null;
145
+ const playback = observation?.playback ?? "unknown";
146
+ const satisfied = required === "available"
147
+ ? available
148
+ : required === "active"
149
+ ? active
150
+ : required === "application"
151
+ ? active && application !== null
152
+ : required === "playing"
153
+ ? active && playback === "playing"
154
+ : false;
155
+ return { required, available, active, application, playback, satisfied };
156
+ }
157
+ function targetEvent(state, now, sources) {
158
+ if (!state.desired)
159
+ return null;
160
+ const readiness = readinessEvidence(state.observed, descriptorFor(state, sources)?.confirmation ?? "unavailable");
161
+ const theatre = {
162
+ kind: "target_state",
163
+ target: "source",
164
+ requestId: state.desired.requestId,
165
+ generation: state.generation,
166
+ status: targetStatus(state.phase),
167
+ observedAt: state.observed?.confirmedAt ?? state.observed?.observedAt ?? iso(now),
168
+ sourceId: state.desired.sourceId,
169
+ action: state.desired.action,
170
+ details: {
171
+ observedStatus: state.observed?.status ?? null,
172
+ readiness,
173
+ recovery: state.observed?.status === "active" || state.observed?.status === "available"
174
+ ? { action: "activate", sourceId: state.observed.sourceId }
175
+ : state.observed?.status === "inactive"
176
+ ? { action: "deactivate" }
177
+ : {},
178
+ metrics: {
179
+ attempts: state.lastAttempt,
180
+ retries: Math.max(0, state.lastAttempt - 1),
181
+ fallbackUsed: state.fallbackUsed
182
+ }
183
+ }
184
+ };
185
+ if (state.failure)
186
+ theatre.failure = { ...state.failure };
187
+ if (state.classification)
188
+ theatre.classification = state.classification;
189
+ return { theatre };
190
+ }
191
+ function statusFor(state) {
192
+ const sourceId = state.desired?.sourceId || "none";
193
+ return { phase: state.phase, text: `${sourceId}: ${state.phase}` };
194
+ }
195
+ function transitionSource(saved, msg, suppliedConfig = {}, nowValue = new Date()) {
196
+ const config = normaliseConfig(suppliedConfig);
197
+ const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
198
+ const nowMs = now.getTime();
199
+ if (!Number.isFinite(nowMs))
200
+ throw new Error("now must be a valid date");
201
+ const state = initialState(saved, config.sources);
202
+ const event = msg?.sourceCapability;
203
+ const commands = [];
204
+ const events = [];
205
+ const traces = [];
206
+ if (!event || typeof event.kind !== "string") {
207
+ throw new Error("msg.sourceCapability.kind is required");
208
+ }
209
+ function trace(name, outcome, reason = null, details = {}) {
210
+ traces.push({ event: name, outcome, reason, details });
211
+ }
212
+ function descriptor() {
213
+ return descriptorFor(state, config.sources);
214
+ }
215
+ function markUnavailable(reason) {
216
+ state.pending = null;
217
+ state.phase = "unavailable";
218
+ state.failure = {
219
+ operation: state.desired?.action ?? "observe",
220
+ reason,
221
+ occurredAt: iso(now)
222
+ };
223
+ trace("source", "unavailable", reason, { sourceId: state.desired?.sourceId ?? null });
224
+ }
225
+ function fail(operation, reason) {
226
+ state.pending = null;
227
+ state.phase = "failed";
228
+ state.blockedGeneration = state.generation;
229
+ state.failure = { operation, reason, occurredAt: iso(now) };
230
+ trace("source", "failed", reason, { sourceId: state.desired?.sourceId ?? null, operation });
231
+ }
232
+ function issue(operation, attempt = 1) {
233
+ const command = commandFor(state, operation, attempt);
234
+ state.pending = {
235
+ operation,
236
+ attempt,
237
+ deadlineAt: nowMs + config.confirmationTimeoutMs,
238
+ nextAt: nowMs + config.pollMs
239
+ };
240
+ state.phase = "transitioning";
241
+ commands.push(command);
242
+ trace("command", "emitted", null, { sourceId: state.desired?.sourceId ?? null, operation, attempt });
243
+ state.lastAttempt = Math.max(state.lastAttempt, attempt);
244
+ if (operation !== "observe" && descriptor()?.fallback === true)
245
+ state.fallbackUsed = true;
246
+ }
247
+ function observationSatisfies(observation) {
248
+ if (!state.desired || !observation)
249
+ return false;
250
+ if (state.desired.action === "deactivate")
251
+ return observation.status === "inactive";
252
+ return readinessEvidence(observation, descriptor()?.confirmation ?? "unavailable").satisfied;
253
+ }
254
+ function reconcileObservation() {
255
+ if (!state.desired || !state.observed)
256
+ return;
257
+ if (state.observed.status === "unavailable") {
258
+ markUnavailable("adapter-unavailable");
259
+ return;
260
+ }
261
+ if (observationSatisfies(state.observed)) {
262
+ state.pending = null;
263
+ state.failure = null;
264
+ state.blockedGeneration = null;
265
+ state.classification = null;
266
+ state.phase = "ready";
267
+ const readiness = readinessEvidence(state.observed, descriptor()?.confirmation ?? "unavailable");
268
+ trace("observation", "ready", null, {
269
+ sourceId: state.desired.sourceId,
270
+ status: state.observed.status,
271
+ application: readiness.application,
272
+ playback: readiness.playback,
273
+ required: readiness.required
274
+ });
275
+ }
276
+ else if (state.phase === "ready" && !state.pending) {
277
+ state.classification = "manual_override";
278
+ state.phase = "manual_override";
279
+ trace("observation", "manual_override", null, {
280
+ sourceId: state.desired.sourceId,
281
+ status: state.observed.status
282
+ });
283
+ }
284
+ else if (state.classification === "manual_override") {
285
+ state.phase = "manual_override";
286
+ }
287
+ else if (state.phase !== "transitioning") {
288
+ state.phase = "waiting_for_source";
289
+ }
290
+ }
291
+ function acceptIntent(event) {
292
+ if (typeof event.requestId !== "string" || !event.requestId) {
293
+ throw new Error("source requestId is required");
294
+ }
295
+ if (!Number.isInteger(event.generation) || event.generation < 1) {
296
+ throw new Error("source generation must be a positive integer");
297
+ }
298
+ if (!Object.hasOwn(ACTIONS, event.action))
299
+ throw new Error("unknown source action");
300
+ const unknownSource = event.sourceId === null && event.action === "deactivate";
301
+ if (!unknownSource &&
302
+ (typeof event.sourceId !== "string" || !Object.hasOwn(config.sources, event.sourceId))) {
303
+ throw new Error("unknown sourceId");
304
+ }
305
+ if (event.generation < state.generation) {
306
+ trace("intent", "ignored", "stale-generation", { generation: event.generation });
307
+ return;
308
+ }
309
+ if (event.generation === state.generation && state.desired) {
310
+ const duplicate = state.desired.requestId === event.requestId &&
311
+ state.desired.sourceId === event.sourceId && state.desired.action === event.action;
312
+ trace("intent", duplicate ? "duplicate" : "rejected", duplicate ? null : "generation-conflict");
313
+ return;
314
+ }
315
+ state.desired = {
316
+ requestId: event.requestId,
317
+ generation: event.generation,
318
+ sourceId: event.sourceId,
319
+ action: event.action
320
+ };
321
+ state.generation = event.generation;
322
+ state.observed = null;
323
+ state.refreshAsked = false;
324
+ state.pending = null;
325
+ state.failure = null;
326
+ state.blockedGeneration = null;
327
+ state.classification = null;
328
+ state.lastAttempt = 0;
329
+ state.fallbackUsed = false;
330
+ if (unknownSource) {
331
+ markUnavailable("unknown-active-source");
332
+ return;
333
+ }
334
+ const source = descriptor();
335
+ if (!source)
336
+ throw new Error("source descriptor is missing");
337
+ const control = event.action === "activate" ? source.activation : source.deactivation;
338
+ if (source.confirmation === "unavailable" || control === "unavailable") {
339
+ markUnavailable(event.action === "activate" ? "unobservable-source" : "unsupported-deactivation");
340
+ return;
341
+ }
342
+ if (control === "command") {
343
+ issue(event.action);
344
+ }
345
+ else {
346
+ state.phase = "waiting_for_source";
347
+ commands.push(commandFor(state, "observe"));
348
+ trace("intent", "waiting", "external-control", { sourceId: event.sourceId });
349
+ }
350
+ }
351
+ function acceptObservation(event) {
352
+ if (!Number.isInteger(event.generation) || event.generation < 1) {
353
+ throw new Error("source observation generation must be a positive integer");
354
+ }
355
+ if (!Object.hasOwn(config.sources, event.sourceId))
356
+ throw new Error("unknown sourceId");
357
+ if (!Object.hasOwn(OBSERVATION_STATUSES, event.status))
358
+ throw new Error("unknown source observation status");
359
+ const parsedAt = (0, observation_time_1.parseObservedAt)(event.observedAt);
360
+ if (parsedAt === null || typeof event.observedAt !== "string")
361
+ throw new Error("source observedAt must be an ISO timestamp");
362
+ if (!state.desired || event.generation !== state.generation || event.sourceId !== state.desired.sourceId) {
363
+ trace("observation", "ignored", "stale-generation", { generation: event.generation });
364
+ return;
365
+ }
366
+ const bounded = (0, observation_time_1.boundObservedAt)(event.observedAt, parsedAt, nowMs);
367
+ if (bounded.skewed)
368
+ trace("observation", "adjusted", "clock-skew", { reported: event.observedAt, usedAt: bounded.observedAt });
369
+ if ((0, observation_time_1.isOutOfOrder)(bounded.ms, state.observed?.observedAt, nowMs)) {
370
+ trace("observation", "ignored", "out-of-order");
371
+ return;
372
+ }
373
+ const application = event.application == null
374
+ ? null
375
+ : typeof event.application === "string" && event.application.trim()
376
+ ? event.application.trim()
377
+ : null;
378
+ const playback = event.playback ?? "unknown";
379
+ if (!Object.hasOwn(PLAYBACK_STATES, playback))
380
+ throw new Error("unknown source playback state");
381
+ state.observed = {
382
+ sourceId: event.sourceId,
383
+ status: event.status,
384
+ observedAt: bounded.observedAt,
385
+ application,
386
+ playback
387
+ };
388
+ if (state.refreshAsked) {
389
+ state.observed.confirmedAt = new Date(Math.max(bounded.ms, nowMs)).toISOString();
390
+ state.refreshAsked = false;
391
+ }
392
+ reconcileObservation();
393
+ }
394
+ function acceptCommandResult(event) {
395
+ if (!state.desired || event.generation !== state.generation ||
396
+ event.sourceId !== state.desired.sourceId || !state.pending) {
397
+ trace("command-result", "ignored", "stale-generation");
398
+ return;
399
+ }
400
+ if (event.ok === true) {
401
+ state.phase = "confirming";
402
+ state.pending.nextAt = nowMs;
403
+ trace("command-result", "accepted");
404
+ return;
405
+ }
406
+ const reason = typeof event.reason === "string" && event.reason ? event.reason : "command-failed";
407
+ if (state.pending.attempt < config.maxAttempts) {
408
+ issue(state.pending.operation, state.pending.attempt + 1);
409
+ }
410
+ else {
411
+ fail(state.pending.operation, reason);
412
+ }
413
+ }
414
+ function tick(event) {
415
+ if (!state.desired || event.generation !== state.generation) {
416
+ trace("tick", "ignored", "stale-generation");
417
+ return;
418
+ }
419
+ if (!state.pending) {
420
+ trace("tick", "ignored", "nothing-pending");
421
+ return;
422
+ }
423
+ if (nowMs >= state.pending.deadlineAt) {
424
+ if (state.pending.attempt < config.maxAttempts) {
425
+ issue(state.pending.operation, state.pending.attempt + 1);
426
+ }
427
+ else {
428
+ fail(state.pending.operation, "confirmation-timeout");
429
+ }
430
+ return;
431
+ }
432
+ if (nowMs >= state.pending.nextAt) {
433
+ commands.push(commandFor(state, "observe", state.pending.attempt));
434
+ state.pending.nextAt = nowMs + config.pollMs;
435
+ state.phase = "confirming";
436
+ trace("command", "emitted", null, { sourceId: state.desired.sourceId, operation: "observe" });
437
+ }
438
+ }
439
+ if (event.kind === "intent") {
440
+ acceptIntent(event);
441
+ }
442
+ else if (event.kind === "observed") {
443
+ acceptObservation(event);
444
+ }
445
+ else if (event.kind === "command_result") {
446
+ acceptCommandResult(event);
447
+ }
448
+ else if (event.kind === "tick") {
449
+ tick(event);
450
+ }
451
+ else if (event.kind === "refresh" && state.desired && state.phase === "ready" && !state.pending &&
452
+ descriptor()?.confirmation !== "unavailable") {
453
+ // Re-read a settled source without putting it back into confirmation: it
454
+ // stays ready, and its target state follows the reading. A refresh that
455
+ // is never answered leaves it to the activity controller to report.
456
+ commands.push(commandFor(state, "observe"));
457
+ state.refreshAsked = true;
458
+ trace("refresh", "querying", null, { sourceId: state.desired.sourceId });
459
+ }
460
+ else if (event.kind === "startup" || event.kind === "refresh") {
461
+ state.refreshAsked = false;
462
+ if (state.desired) {
463
+ if (state.desired.sourceId === null || descriptor()?.confirmation === "unavailable") {
464
+ markUnavailable(state.desired.sourceId === null ? "unknown-active-source" : "unobservable-source");
465
+ }
466
+ else if (state.classification === "manual_override") {
467
+ commands.push(commandFor(state, "observe"));
468
+ state.pending = null;
469
+ state.phase = "manual_override";
470
+ trace(event.kind, "querying", null, { sourceId: state.desired.sourceId });
471
+ }
472
+ else {
473
+ // Re-observe with a deadline, so an activation interrupted by the
474
+ // restart ends ready or failed instead of waiting for good. The
475
+ // activation itself is not replayed.
476
+ issue("observe");
477
+ state.phase = "confirming";
478
+ trace(event.kind, "querying", null, { sourceId: state.desired.sourceId });
479
+ }
480
+ }
481
+ else {
482
+ trace(event.kind, "idle");
483
+ }
484
+ }
485
+ else {
486
+ throw new Error("unknown source capability event kind");
487
+ }
488
+ // A refresh of a settled source reports nothing until its reading arrives.
489
+ const outputEvent = event.kind === "refresh" && state.refreshAsked ? null : targetEvent(state, now, config.sources);
490
+ if (outputEvent)
491
+ events.push(outputEvent);
492
+ return { state, commands, events, traces, status: statusFor(state) };
493
+ }
494
+ //# sourceMappingURL=source-capability-controller.js.map
@@ -0,0 +1,53 @@
1
+ import { type WallInputConfig, type WallInputState } from "./wall-input";
2
+ export interface SwitchPolicyConfig extends WallInputConfig {
3
+ targets: string[];
4
+ }
5
+ export interface SwitchPolicyState {
6
+ wallInput: WallInputState;
7
+ }
8
+ export interface SwitchPolicyInput {
9
+ source: string;
10
+ payload?: unknown;
11
+ retain?: boolean;
12
+ baseline?: boolean;
13
+ generation?: number;
14
+ switchAt?: number;
15
+ observedAt?: unknown;
16
+ }
17
+ export interface SwitchLightingIntent {
18
+ lighting: {
19
+ kind: "intent";
20
+ targets: string[];
21
+ state: "ON" | "TOGGLE";
22
+ source: "wall";
23
+ person: true;
24
+ manual?: boolean;
25
+ values?: {
26
+ brightness: number;
27
+ };
28
+ };
29
+ }
30
+ export type SwitchPolicyEffect = {
31
+ kind: "cancel-switch-timer";
32
+ } | {
33
+ kind: "schedule-switch-timer";
34
+ delayMs: number;
35
+ generation: number;
36
+ switchAt: number;
37
+ } | {
38
+ kind: "send";
39
+ message: SwitchLightingIntent;
40
+ };
41
+ export interface SwitchPolicyTrace {
42
+ event: string;
43
+ outcome: string;
44
+ reason: string | null;
45
+ details: Record<string, unknown>;
46
+ }
47
+ export declare function createSwitchPolicyState(saved?: Partial<SwitchPolicyState>): SwitchPolicyState;
48
+ export declare function transitionSwitchPolicy(saved: Partial<SwitchPolicyState> | undefined, input: SwitchPolicyInput, config: SwitchPolicyConfig, now?: number): {
49
+ state: SwitchPolicyState;
50
+ effects: SwitchPolicyEffect[];
51
+ traces: SwitchPolicyTrace[];
52
+ status: import("./wall-input").WallInputStatus;
53
+ };