@ajclarkson/homerun 0.0.1-edge.84d47fa → 0.0.1-edge.90fa3ca

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 (32) hide show
  1. package/README.md +17 -1
  2. package/dist/scripts/generate-ha-services.d.ts +16 -0
  3. package/dist/scripts/generate-ha-services.js +111 -0
  4. package/dist/src/framework/action-runtime.d.ts +4 -2
  5. package/dist/src/framework/action-runtime.js +14 -5
  6. package/dist/src/framework/api-server.d.ts +9 -2
  7. package/dist/src/framework/api-server.js +27 -2
  8. package/dist/src/framework/config.d.ts +27 -0
  9. package/dist/src/framework/config.js +80 -0
  10. package/dist/src/framework/{observability.d.ts → event-publisher.d.ts} +11 -2
  11. package/dist/src/framework/{observability.js → event-publisher.js} +15 -2
  12. package/dist/src/framework/ha-client.d.ts +1 -0
  13. package/dist/src/framework/ha-client.js +4 -0
  14. package/dist/src/framework/hot-reload.d.ts +2 -0
  15. package/dist/src/framework/hot-reload.js +38 -1
  16. package/dist/src/framework/metrics-prom.d.ts +16 -0
  17. package/dist/src/framework/metrics-prom.js +82 -0
  18. package/dist/src/framework/metrics.d.ts +8 -0
  19. package/dist/src/framework/metrics.js +4 -0
  20. package/dist/src/framework/pipeline.d.ts +4 -2
  21. package/dist/src/framework/pipeline.js +14 -5
  22. package/dist/src/framework/timer-manager.d.ts +1 -0
  23. package/dist/src/framework/timer-manager.js +5 -0
  24. package/dist/src/framework/trigger-engine.d.ts +4 -1
  25. package/dist/src/framework/trigger-engine.js +93 -29
  26. package/dist/src/index.d.ts +1 -1
  27. package/dist/src/index.js +88 -43
  28. package/dist/src/testing.d.ts +2 -0
  29. package/dist/src/testing.js +2 -2
  30. package/dist/src/types/automation.d.ts +1 -0
  31. package/dist/src/types/triggers.d.ts +2 -1
  32. package/package.json +9 -3
package/README.md CHANGED
@@ -131,6 +131,7 @@ const ctx = kitchenLights.context(mockState, mockHAContext);
131
131
  | `on_start` | The system is ready and the state cache is fully populated. |
132
132
  | `timer_expired` | A named timer set by a previous `timer.start` action expires. |
133
133
  | `button` | A Zigbee button entity emits a `single_press`, `double_press`, or `hold` gesture. |
134
+ | `mqtt_in` | A message arrives on a subscribed MQTT topic. |
134
135
 
135
136
  ```typescript
136
137
  triggers: [
@@ -192,7 +193,7 @@ Every pipeline run publishes a decision snapshot to MQTT — whether it complete
192
193
  "automation_id": "kitchen:lighting",
193
194
  "location": "kitchen",
194
195
  "subsystem": "lighting",
195
- "type": "decision",
196
+ "event_type": "decision",
196
197
  "decision": "lights_on",
197
198
  "inputs": { "motion": true, "lux": 20, "luxThreshold": 40 },
198
199
  "actions": [{ "type": "ha.call_service", "domain": "light", "service": "turn_on" }],
@@ -230,6 +231,21 @@ Set `DRY_RUN=true` to run the full pipeline — context, reduce, observability
230
231
 
231
232
  ---
232
233
 
234
+ ## API
235
+
236
+ The server exposes an HTTP API on port `7070` by default.
237
+
238
+ | Method | Path | Description |
239
+ |--------|------|-------------|
240
+ | `GET` | `/health/live` | Always returns `200 { status: "live" }` — used for liveness probes. |
241
+ | `GET` | `/health/ready` | Returns `200` when the HA state cache is populated and automations are loaded, `503` while starting. Response includes `entities`, `automations` counts, and `dry_run: true` if running in dry-run mode. |
242
+ | `GET` | `/automations` | Lists all registered automations with their `id`, `location`, `subsystem`, and trigger types. |
243
+ | `POST` | `/automations/:id/trigger` | Manually fires an `on_start` event for the given automation. |
244
+ | `POST` | `/reload` | Rescans the automations directory and hot-reloads changed files. |
245
+ | `GET` | `/events` | Server-sent event stream of all pipeline decisions and action events in real time. |
246
+
247
+ ---
248
+
233
249
  ## Architecture
234
250
 
235
251
  ```
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ export interface HAServicePayload {
3
+ domain: string;
4
+ services: Record<string, HAServiceDef>;
5
+ }
6
+ export interface HAServiceDef {
7
+ fields: Record<string, HAServiceField>;
8
+ target?: unknown;
9
+ }
10
+ export interface HAServiceField {
11
+ required?: boolean;
12
+ selector?: Record<string, unknown>;
13
+ advanced?: boolean;
14
+ }
15
+ export declare function inferFieldType(field: HAServiceField): string;
16
+ export declare function generateFileContent(services: HAServicePayload[], domains?: string[]): string;
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile, mkdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ // ---------- Type inference ----------
5
+ export function inferFieldType(field) {
6
+ const selector = field.selector;
7
+ if (!selector)
8
+ return 'unknown';
9
+ const key = Object.keys(selector)[0];
10
+ if (!key)
11
+ return 'unknown';
12
+ switch (key) {
13
+ case 'number':
14
+ case 'color_temp':
15
+ return 'number';
16
+ case 'boolean':
17
+ return 'boolean';
18
+ case 'color_rgb':
19
+ return '[number, number, number]';
20
+ case 'duration':
21
+ return '{ hours?: number; minutes?: number; seconds?: number }';
22
+ case 'object':
23
+ return 'Record<string, unknown>';
24
+ default:
25
+ return 'string';
26
+ }
27
+ }
28
+ // ---------- Service builder generation ----------
29
+ function generateServiceBuilder(domain, service, def) {
30
+ const hasTarget = !!def.target;
31
+ const fieldEntries = Object.entries(def.fields ?? {});
32
+ const hasFields = fieldEntries.length > 0;
33
+ const params = [];
34
+ if (hasTarget)
35
+ params.push('target: { entity_id: string }');
36
+ let anyRequired = false;
37
+ if (hasFields) {
38
+ anyRequired = fieldEntries.some(([, f]) => f.required);
39
+ const fieldDefs = fieldEntries
40
+ .map(([name, field]) => `${name}${field.required ? '' : '?'}: ${inferFieldType(field)}`)
41
+ .join('; ');
42
+ params.push(`data${anyRequired ? '' : '?'}: { ${fieldDefs} }`);
43
+ }
44
+ const bodyParts = [
45
+ `type: 'ha.call_service'`,
46
+ `domain: '${domain}'`,
47
+ `service: '${service}'`,
48
+ ];
49
+ if (hasTarget)
50
+ bodyParts.push('target');
51
+ if (hasFields) {
52
+ bodyParts.push(`data: data as Record<string, unknown>${anyRequired ? '' : ' | undefined'}`);
53
+ }
54
+ return ` ${service}: (${params.join(', ')}): Action => ({ ${bodyParts.join(', ')} })`;
55
+ }
56
+ // ---------- File generation ----------
57
+ export function generateFileContent(services, domains) {
58
+ const filtered = domains
59
+ ? services.filter(({ domain }) => domains.includes(domain))
60
+ : services;
61
+ const domainBlocks = filtered.map(({ domain, services: svcMap }) => {
62
+ const builders = Object.entries(svcMap)
63
+ .map(([service, def]) => generateServiceBuilder(domain, service, def))
64
+ .join(',\n');
65
+ return ` ${domain}: {\n${builders},\n }`;
66
+ });
67
+ const domainsNote = domains ? `\n// domains: ${domains.join(', ')}` : '';
68
+ const blockStr = domainBlocks.length > 0 ? `\n${domainBlocks.join(',\n')},\n` : '';
69
+ return `// generated — do not edit — run: npm run generate:ha-services${domainsNote}
70
+ import type { Action } from '@ajclarkson/homerun';
71
+
72
+ export const Services = {${blockStr}};
73
+ `;
74
+ }
75
+ // ---------- CLI ----------
76
+ async function main() {
77
+ const url = process.env.HA_URL;
78
+ const token = process.env.HA_TOKEN;
79
+ if (!url || !token) {
80
+ console.error('Error: HA_URL and HA_TOKEN must be set');
81
+ process.exit(1);
82
+ }
83
+ const domainsArg = process.argv.find((a) => a.startsWith('--domains='));
84
+ const domains = domainsArg ? domainsArg.slice('--domains='.length).split(',') : undefined;
85
+ const res = await fetch(`${url}/api/services`, {
86
+ headers: { Authorization: `Bearer ${token}` },
87
+ });
88
+ if (!res.ok) {
89
+ console.error(`Error: HA API returned ${res.status} ${res.statusText}`);
90
+ process.exit(1);
91
+ }
92
+ const allServices = (await res.json());
93
+ const content = generateFileContent(allServices, domains);
94
+ const outPath = path.join(process.cwd(), 'types', 'ha-services.ts');
95
+ await mkdir(path.dirname(outPath), { recursive: true });
96
+ await writeFile(outPath, content, 'utf8');
97
+ const filtered = domains
98
+ ? allServices.filter(({ domain }) => domains.includes(domain))
99
+ : allServices;
100
+ const serviceCount = filtered.reduce((n, { services: s }) => n + Object.keys(s).length, 0);
101
+ const domainLabel = domains ? `${domains.length} selected` : `all ${allServices.length}`;
102
+ console.log(`Written ${serviceCount} services across ${domainLabel} domains to ${outPath}`);
103
+ }
104
+ if (process.argv[1]?.endsWith('generate-ha-services.ts') ||
105
+ process.argv[1]?.endsWith('generate-ha-services.js') ||
106
+ process.argv[1]?.endsWith('homerun-generate-ha-services')) {
107
+ main().catch((err) => {
108
+ console.error('Fatal:', err);
109
+ process.exit(1);
110
+ });
111
+ }
@@ -2,7 +2,8 @@ import type { MqttClient } from 'mqtt';
2
2
  import type { Action } from '../types/actions.js';
3
3
  import type { HAClient } from './ha-client.js';
4
4
  import type { TimerManager } from './timer-manager.js';
5
- import type { Observability } from './observability.js';
5
+ import type { EventPublisher } from './event-publisher.js';
6
+ import type { MetricsBackend } from './metrics.js';
6
7
  export interface ExecutionContext {
7
8
  correlationId: string;
8
9
  automationId: string;
@@ -13,8 +14,9 @@ interface Deps {
13
14
  haClient: HAClient;
14
15
  mqttClient: MqttClient;
15
16
  timerManager: TimerManager;
16
- observability: Observability;
17
+ eventPublisher: EventPublisher;
17
18
  dryRun: boolean;
19
+ metrics?: MetricsBackend;
18
20
  }
19
21
  export declare class ActionRuntime {
20
22
  private readonly deps;
@@ -9,16 +9,25 @@ export class ActionRuntime {
9
9
  }
10
10
  }
11
11
  async runAction(action, ctx) {
12
- this.deps.observability.publishActionEvent(this.makeEvent(ctx, 'action_started', action));
12
+ const labels = { location: ctx.location, action_type: action.type };
13
+ this.deps.eventPublisher.publishActionEvent(this.makeEvent(ctx, 'action_started', action));
14
+ this.deps.metrics?.incrementCounter('homerun_actions_dispatched_total', labels);
15
+ const start = performance.now();
13
16
  try {
14
17
  if (!this.deps.dryRun) {
15
18
  await this.dispatch(action);
16
19
  }
17
- this.deps.observability.publishActionEvent(this.makeEvent(ctx, 'action_result', action, { reason: 'ok' }));
20
+ const duration = (performance.now() - start) / 1000;
21
+ this.deps.metrics?.observeHistogram('homerun_action_duration_seconds', duration, labels);
22
+ this.deps.metrics?.incrementCounter('homerun_actions_succeeded_total', labels);
23
+ this.deps.eventPublisher.publishActionEvent(this.makeEvent(ctx, 'action_result', action, { reason: 'ok' }));
18
24
  }
19
25
  catch (err) {
26
+ const duration = (performance.now() - start) / 1000;
27
+ this.deps.metrics?.observeHistogram('homerun_action_duration_seconds', duration, labels);
28
+ this.deps.metrics?.incrementCounter('homerun_actions_failed_total', labels);
20
29
  const reason = err instanceof Error ? err.message : String(err);
21
- this.deps.observability.publishActionEvent(this.makeEvent(ctx, 'action_result', action, { reason }));
30
+ this.deps.eventPublisher.publishActionEvent(this.makeEvent(ctx, 'action_result', action, { reason }));
22
31
  }
23
32
  }
24
33
  async dispatch(action) {
@@ -41,14 +50,14 @@ export class ActionRuntime {
41
50
  }
42
51
  }
43
52
  }
44
- makeEvent(ctx, type, action, extra = {}) {
53
+ makeEvent(ctx, event_type, action, extra = {}) {
45
54
  return {
46
55
  schema: 'home.events.v1',
47
56
  correlation_id: ctx.correlationId,
48
57
  automation_id: ctx.automationId,
49
58
  location: ctx.location,
50
59
  subsystem: ctx.subsystem,
51
- type,
60
+ event_type,
52
61
  actions: [action],
53
62
  timestamp: new Date().toISOString(),
54
63
  ...(this.deps.dryRun ? { dry_run: true } : {}),
@@ -1,14 +1,20 @@
1
1
  import type { AutomationRegistry } from './registry.js';
2
- import type { Observability } from './observability.js';
2
+ import type { EventPublisher } from './event-publisher.js';
3
3
  import type { Automation } from '../types/automation.js';
4
4
  import type { TriggerEvent } from '../types/triggers.js';
5
+ export interface MetricsProvider {
6
+ getMetrics(): Promise<string>;
7
+ contentType: string;
8
+ }
5
9
  export interface ApiServerDeps {
6
10
  registry: AutomationRegistry;
7
11
  onTrigger: (automation: Automation<unknown>, event: TriggerEvent) => void;
8
12
  onReload: () => Promise<void>;
9
13
  isReady: () => boolean;
10
14
  entityCount: () => number;
11
- observability: Observability;
15
+ eventPublisher: EventPublisher;
16
+ dryRun?: boolean;
17
+ metrics?: MetricsProvider;
12
18
  }
13
19
  export declare class ApiServer {
14
20
  private readonly deps;
@@ -24,5 +30,6 @@ export declare class ApiServer {
24
30
  private postReload;
25
31
  private getHealthLive;
26
32
  private getHealthReady;
33
+ private getMetrics;
27
34
  private getEvents;
28
35
  }
@@ -41,6 +41,8 @@ export class ApiServer {
41
41
  return this.getHealthReady(res);
42
42
  if (method === 'GET' && url === '/events')
43
43
  return this.getEvents(req, res);
44
+ if (method === 'GET' && url === '/metrics')
45
+ return this.getMetrics(res);
44
46
  const triggerMatch = method === 'POST' && url.match(/^\/automations\/(.+)\/trigger$/);
45
47
  if (triggerMatch)
46
48
  return this.postTrigger(triggerMatch[1], res);
@@ -51,7 +53,8 @@ export class ApiServer {
51
53
  id: a.id,
52
54
  location: a.location,
53
55
  subsystem: a.subsystem,
54
- triggerTypes: a.triggers.map((t) => t.type),
56
+ enabled: a.enabled ?? true,
57
+ triggers: a.triggers.map(serializeTrigger),
55
58
  }));
56
59
  json(res, 200, automations);
57
60
  }
@@ -84,6 +87,22 @@ export class ApiServer {
84
87
  status: 'ready',
85
88
  entities: this.deps.entityCount(),
86
89
  automations: this.deps.registry.getAll().length,
90
+ ...(this.deps.dryRun && { dry_run: true }),
91
+ });
92
+ }
93
+ getMetrics(res) {
94
+ if (!this.deps.metrics) {
95
+ json(res, 404, { error: 'metrics not enabled' });
96
+ return;
97
+ }
98
+ this.deps.metrics.getMetrics()
99
+ .then((output) => {
100
+ res.writeHead(200, { 'Content-Type': this.deps.metrics.contentType });
101
+ res.end(output);
102
+ })
103
+ .catch((err) => {
104
+ console.error('[ApiServer] metrics scrape failed:', err);
105
+ json(res, 500, { error: 'metrics scrape failed' });
87
106
  });
88
107
  }
89
108
  getEvents(req, res) {
@@ -93,12 +112,18 @@ export class ApiServer {
93
112
  Connection: 'keep-alive',
94
113
  });
95
114
  res.flushHeaders();
96
- const unsubscribe = this.deps.observability.subscribe((event) => {
115
+ const unsubscribe = this.deps.eventPublisher.subscribe((event) => {
97
116
  res.write(`data: ${JSON.stringify(event)}\n\n`);
98
117
  });
99
118
  req.on('close', unsubscribe);
100
119
  }
101
120
  }
121
+ function serializeTrigger(trigger) {
122
+ if (trigger.type === 'state_changed' && trigger.entity instanceof RegExp) {
123
+ return { ...trigger, entity: trigger.entity.toString() };
124
+ }
125
+ return trigger;
126
+ }
102
127
  function json(res, status, body) {
103
128
  const payload = JSON.stringify(body);
104
129
  res.writeHead(status, { 'Content-Type': 'application/json' });
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ declare const ConfigSchema: z.ZodObject<{
3
+ homeassistant: z.ZodObject<{
4
+ url: z.ZodString;
5
+ token: z.ZodString;
6
+ }, z.core.$strip>;
7
+ mqtt: z.ZodObject<{
8
+ url: z.ZodString;
9
+ }, z.core.$strip>;
10
+ automations: z.ZodObject<{
11
+ dir: z.ZodString;
12
+ }, z.core.$strip>;
13
+ server: z.ZodDefault<z.ZodObject<{
14
+ port: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
15
+ shutdown_timeout_ms: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
16
+ }, z.core.$strip>>;
17
+ options: z.ZodDefault<z.ZodObject<{
18
+ dry_run: z.ZodDefault<z.ZodBoolean>;
19
+ }, z.core.$strip>>;
20
+ metrics: z.ZodDefault<z.ZodObject<{
21
+ enabled: z.ZodDefault<z.ZodBoolean>;
22
+ }, z.core.$strip>>;
23
+ }, z.core.$strip>;
24
+ export type HomerunConfig = z.infer<typeof ConfigSchema>;
25
+ export declare function parseConfig(configContent: string, secretsContent?: string): HomerunConfig;
26
+ export declare function loadConfig(configPath?: string): Promise<HomerunConfig>;
27
+ export {};
@@ -0,0 +1,80 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { existsSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { load, CORE_SCHEMA, defineScalarTag } from 'js-yaml';
5
+ import { z } from 'zod';
6
+ function isSecretRef(v) {
7
+ return typeof v === 'object' && v !== null && '__secret' in v;
8
+ }
9
+ const secretTag = defineScalarTag('!secret', {
10
+ implicit: false,
11
+ resolve: (source) => ({ __secret: source }),
12
+ });
13
+ const SCHEMA_WITH_SECRET = CORE_SCHEMA.withTags(secretTag);
14
+ const ConfigSchema = z.object({
15
+ homeassistant: z.object({
16
+ url: z.string().min(1, 'homeassistant.url is required'),
17
+ token: z.string().min(1, 'homeassistant.token is required'),
18
+ }),
19
+ mqtt: z.object({
20
+ url: z.string().min(1, 'mqtt.url is required'),
21
+ }),
22
+ automations: z.object({
23
+ dir: z.string().min(1, 'automations.dir is required'),
24
+ }),
25
+ server: z.object({
26
+ port: z.coerce.number().int().min(1).max(65535).default(7070),
27
+ shutdown_timeout_ms: z.coerce.number().int().min(0).default(10_000),
28
+ }).default({ port: 7070, shutdown_timeout_ms: 10_000 }),
29
+ options: z.object({
30
+ dry_run: z.boolean().default(false),
31
+ }).default({ dry_run: false }),
32
+ metrics: z.object({
33
+ enabled: z.boolean().default(false),
34
+ }).default({ enabled: false }),
35
+ });
36
+ function resolveSecrets(value, secrets) {
37
+ if (isSecretRef(value)) {
38
+ const key = value.__secret;
39
+ if (!(key in secrets)) {
40
+ throw new Error(`!secret '${key}' not found in secrets.yaml`);
41
+ }
42
+ return secrets[key];
43
+ }
44
+ if (Array.isArray(value)) {
45
+ return value.map((item) => resolveSecrets(item, secrets));
46
+ }
47
+ if (typeof value === 'object' && value !== null) {
48
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, resolveSecrets(v, secrets)]));
49
+ }
50
+ return value;
51
+ }
52
+ export function parseConfig(configContent, secretsContent) {
53
+ const raw = (load(configContent, { schema: SCHEMA_WITH_SECRET }) ?? {});
54
+ const secrets = secretsContent
55
+ ? (load(secretsContent) ?? {})
56
+ : {};
57
+ const resolved = resolveSecrets(raw, secrets);
58
+ const result = ConfigSchema.safeParse(resolved);
59
+ if (!result.success) {
60
+ const errors = result.error.issues
61
+ .map((i) => ` ${i.path.join('.') || '(root)'}: ${i.message}`)
62
+ .join('\n');
63
+ throw new Error(`[homerun] Invalid configuration:\n${errors}`);
64
+ }
65
+ return result.data;
66
+ }
67
+ export async function loadConfig(configPath) {
68
+ const absPath = path.resolve(configPath ?? process.env.HOMERUN_CONFIG ?? './configuration.yaml');
69
+ if (!existsSync(absPath)) {
70
+ throw new Error(`[homerun] Config file not found: ${absPath}\n` +
71
+ 'Create configuration.yaml or set HOMERUN_CONFIG to point to your config file.\n' +
72
+ 'See configuration.yaml.example for reference.');
73
+ }
74
+ const configContent = await readFile(absPath, 'utf8');
75
+ const secretsPath = path.join(path.dirname(absPath), 'secrets.yaml');
76
+ const secretsContent = existsSync(secretsPath)
77
+ ? await readFile(secretsPath, 'utf8')
78
+ : undefined;
79
+ return parseConfig(configContent, secretsContent);
80
+ }
@@ -6,7 +6,7 @@ export interface ObsEvent {
6
6
  automation_id: string;
7
7
  location: string;
8
8
  subsystem: string;
9
- type: 'decision' | 'abort' | 'action_started' | 'action_result';
9
+ event_type: 'decision' | 'abort' | 'action_started' | 'action_result';
10
10
  decision?: string;
11
11
  reason?: string;
12
12
  inputs?: Record<string, unknown>;
@@ -14,12 +14,21 @@ export interface ObsEvent {
14
14
  dry_run?: boolean;
15
15
  timestamp: string;
16
16
  }
17
- export declare class Observability {
17
+ export type LifecycleEventType = 'server_started' | 'server_stopping' | 'rescan_complete' | 'ha_reconnected';
18
+ export interface LifecycleEvent {
19
+ schema: 'home.lifecycle.v1';
20
+ type: LifecycleEventType;
21
+ automation_count: number;
22
+ timestamp: string;
23
+ dry_run?: boolean;
24
+ }
25
+ export declare class EventPublisher {
18
26
  private readonly mqtt;
19
27
  private readonly listeners;
20
28
  constructor(mqtt: MqttClient);
21
29
  subscribe(listener: (event: ObsEvent) => void): () => void;
22
30
  publishDecision(event: ObsEvent): void;
23
31
  publishActionEvent(event: ObsEvent): void;
32
+ publishLifecycle(type: LifecycleEventType, automationCount: number, dryRun?: boolean): void;
24
33
  private publish;
25
34
  }
@@ -1,4 +1,4 @@
1
- export class Observability {
1
+ export class EventPublisher {
2
2
  mqtt;
3
3
  listeners = [];
4
4
  constructor(mqtt) {
@@ -26,9 +26,22 @@ export class Observability {
26
26
  for (const l of this.listeners)
27
27
  l(event);
28
28
  }
29
+ publishLifecycle(type, automationCount, dryRun = false) {
30
+ const event = {
31
+ schema: 'home.lifecycle.v1',
32
+ type,
33
+ automation_count: automationCount,
34
+ timestamp: new Date().toISOString(),
35
+ ...(dryRun && { dry_run: true }),
36
+ };
37
+ const ns = dryRun ? 'homerun/dev' : 'homerun';
38
+ const payload = JSON.stringify(event);
39
+ this.publish(`${ns}/lifecycle`, payload, false);
40
+ this.publish(`${ns}/status`, JSON.stringify({ status: 'online', automation_count: automationCount, timestamp: event.timestamp }), true);
41
+ }
29
42
  publish(topic, payload, retain) {
30
43
  this.mqtt.publishAsync(topic, payload, { retain }).catch((err) => {
31
- console.error(`[Observability] MQTT publish failed on ${topic}:`, err);
44
+ console.error(`[EventPublisher] MQTT publish failed on ${topic}:`, err);
32
45
  });
33
46
  }
34
47
  }
@@ -40,6 +40,7 @@ export declare class HAClient extends EventEmitter {
40
40
  readonly context: HAContext;
41
41
  get entityCount(): number;
42
42
  callService(domain: string, service: string, target?: HassServiceTarget, data?: Record<string, unknown>): Promise<void>;
43
+ disconnect(): void;
43
44
  connect(url: string, token: string): Promise<void>;
44
45
  private repopulateCache;
45
46
  private diffAndUpdate;
@@ -28,6 +28,10 @@ export class HAClient extends EventEmitter {
28
28
  throw new Error('HAClient not connected');
29
29
  await callService(this.connection, domain, service, data, target);
30
30
  }
31
+ disconnect() {
32
+ this.connection?.close();
33
+ this.connection = null;
34
+ }
31
35
  async connect(url, token) {
32
36
  const auth = createLongLivedTokenAuth(url, token);
33
37
  this.connection = await createConnection({ auth });
@@ -3,5 +3,7 @@ type Importer = (dataUri: string) => Promise<{
3
3
  default: unknown;
4
4
  }>;
5
5
  export declare function _reloadFile(filePath: string, registry: AutomationRegistry, importer?: Importer, fileToIds?: Map<string, string[]>): Promise<void>;
6
+ export declare function _deleteFile(filePath: string, registry: AutomationRegistry, fileToIds?: Map<string, string[]>): void;
7
+ export declare function rescanAutomations(automationsDir: string, registry: AutomationRegistry, fileToIds?: Map<string, string[]>, importer?: Importer): Promise<void>;
6
8
  export declare function startHotReload(automationsDir: string, registry: AutomationRegistry): void;
7
9
  export {};
@@ -39,13 +39,50 @@ export async function _reloadFile(filePath, registry, importer = defaultImporter
39
39
  console.error(`[hot-reload] failed to reload ${filePath}:`, err);
40
40
  }
41
41
  }
42
+ export function _deleteFile(filePath, registry, fileToIds = moduleFileToIds) {
43
+ for (const id of fileToIds.get(filePath) ?? []) {
44
+ registry.unregister(id);
45
+ }
46
+ fileToIds.delete(filePath);
47
+ }
48
+ const EXCLUDED_DIRS = new Set(['types', 'lib']);
49
+ const isAutomationFile = (f) => f.endsWith('.ts') &&
50
+ !f.endsWith('.test.ts') &&
51
+ !f.includes('node_modules') &&
52
+ !f.includes('.d.ts') &&
53
+ !f.split(path.sep).some(seg => EXCLUDED_DIRS.has(seg));
54
+ export async function rescanAutomations(automationsDir, registry, fileToIds = moduleFileToIds, importer = defaultImporter) {
55
+ let files = [];
56
+ try {
57
+ const { readdir } = await import('node:fs/promises');
58
+ files = (await readdir(automationsDir, { recursive: true }));
59
+ }
60
+ catch {
61
+ console.warn(`[homerun] AUTOMATIONS_DIR not found: ${automationsDir} — starting with no automations`);
62
+ }
63
+ const currentPaths = new Set(files.filter(isAutomationFile).map((f) => path.join(automationsDir, f)));
64
+ for (const trackedPath of [...fileToIds.keys()]) {
65
+ if (!currentPaths.has(trackedPath)) {
66
+ _deleteFile(trackedPath, registry, fileToIds);
67
+ }
68
+ }
69
+ for (const filePath of currentPaths) {
70
+ await _reloadFile(filePath, registry, importer, fileToIds);
71
+ }
72
+ }
42
73
  export function startHotReload(automationsDir, registry) {
43
74
  const target = process.env.AUTOMATION
44
75
  ? path.join(automationsDir, `${process.env.AUTOMATION}.ts`)
45
76
  : `${automationsDir}/**/*.ts`;
46
- watch(target, { ignoreInitial: true, ignored: [/node_modules/, /\.test\.ts$/] }).on('change', (filePath) => {
77
+ const watcher = watch(target, { ignoreInitial: true, ignored: [/node_modules/, /\.test\.ts$/] });
78
+ const reload = (filePath) => {
47
79
  _reloadFile(filePath, registry).catch((err) => {
48
80
  console.error('[hot-reload] unexpected error:', err);
49
81
  });
82
+ };
83
+ watcher.on('add', reload);
84
+ watcher.on('change', reload);
85
+ watcher.on('unlink', (filePath) => {
86
+ _deleteFile(filePath, registry);
50
87
  });
51
88
  }
@@ -0,0 +1,16 @@
1
+ import { Registry } from 'prom-client';
2
+ import type { MetricsBackend } from './metrics.js';
3
+ export declare class PromMetricsBackend implements MetricsBackend {
4
+ readonly registry: Registry<"text/plain; version=0.0.4; charset=utf-8">;
5
+ private readonly haEventsTotal;
6
+ private readonly pipelineRunsTotal;
7
+ private readonly actionsDispatchedTotal;
8
+ private readonly actionsSucceededTotal;
9
+ private readonly actionsFailedTotal;
10
+ private readonly actionDurationSeconds;
11
+ constructor(collectDefaults?: boolean);
12
+ incrementCounter(name: string, labels?: Record<string, string>): void;
13
+ observeHistogram(name: string, value: number, labels?: Record<string, string>): void;
14
+ getMetrics(): Promise<string>;
15
+ get contentType(): string;
16
+ }