node-red-contrib-knx-ultimate 6.1.1 → 6.2.1

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.
@@ -1,18 +1,82 @@
1
1
  <script type="text/markdown" data-help-name="knxUltimateAI">
2
2
  Dieser Node überwacht **alle KNX-Telegramme** des ausgewählten KNX-Ultimate-Gateways, erstellt Verkehrsstatistiken, erkennt Anomalien und kann optional ein LLM befragen.
3
3
 
4
+ Der Editor verwendet drei Hauptbereiche als Akkordeon: **KI-Assistent** enthält Einrichtung, Wissen/Kontext und Anbietergrenzen; **Gespräche & Zuhause** enthält Chat-Kanäle, proaktives Zuhause und begrenztes Gedächtnis; **KNX-Verkehrsanalyse** enthält Bus-Telegramme, Verlauf/Zusammenfassungen und Anomalien/Muster. Beim Öffnen eines Hauptbereichs werden alle zugehörigen Optionen gemeinsam angezeigt. Gespeicherte Feld-IDs und Werte bleiben unverändert.
5
+
4
6
  ## Ausgänge
5
7
  1. **Zusammenfassung/Statistik** (`msg.payload` JSON)
6
8
  2. **Anomalien** (`msg.payload` JSON)
7
9
  3. **KI-Assistent** (`msg.payload` Text, mit `msg.summary`)
10
+ 4. **KNX-Operationen** (eine Universal-Mode-Nachricht je validierter Lese- oder Schreiboperation)
11
+
12
+ Jede an den Ausgängen 3 und 4 ausgegebene Nachricht enthält außerdem eine Kopie der ursprünglichen Eingangsnachricht in `msg.inputMessage`. Dadurch bleiben der ursprüngliche Payload, das Topic, die Chat-Metadaten und alle weiteren Eingangseigenschaften für nachfolgende Nodes verfügbar. Fehler beim Klonen oder Ausgeben werden abgefangen und gemeldet, statt in die Node-RED-Laufzeit zu gelangen.
8
13
 
9
14
  ## Befehle (Eingang)
10
15
  Sende `msg.topic`:
11
16
  - `summary` (oder leer): Summary sofort senden
12
- - `reset`: internen Verlauf/Zähler zurücksetzen
17
+ - `reset`: internen Verlauf, Zähler und gelerntes Hausgedächtnis löschen; die KI-Erziehung bleibt unverändert
13
18
  - `ask`: Frage an das konfigurierte LLM senden
19
+ - `confirm` / `cancel`: ausstehende KNX-Befehle ohne erneuten LLM-Aufruf bestätigen oder abbrechen
20
+ - `clear_chat`: Gesprächsspeicher der aktuellen Sitzung löschen
21
+
22
+ Für `ask` die Frage in `msg.prompt` (empfohlen), `msg.payload` (String) oder den üblichen Telegram-Feldern `msg.payload.content` / `msg.payload.text` übergeben.
23
+
24
+ Bei aktiviertem KNX-Steuern werden die letzten Gesprächsschritte im RAM nach `msg.knxAi.sessionId`, `msg.sessionId` oder erkannter Telegram-Chat-ID getrennt. Ausgang 3 mit dem Chat-Sender und Ausgang 4 mit einem KNX-Ultimate-Node im **Universalmodus** verbinden. Bei aktiver Bestätigung zeigt die erste Antwort GA, DPT und Payload, ohne Schreiboperationen auszugeben; dieselbe Sitzung muss innerhalb von 5 Minuten `BESTÄTIGEN` oder `ABBRECHEN` antworten. Eine neue Anfrage ersetzt einen älteren Plan. Jeder bestätigte Befehl enthält `msg.destination`, `msg.dpt`, `msg.payload` und `msg.event = "GroupValue_Write"`.
25
+ Bei DPT-1.xxx-Schreibvorgängen werden die sicheren KI-Entsprechungen `true`/`false`, `1`/`0` und `on`/`off` vor der lokalen Validierung und Ausgabe in echte Boolesche Werte normalisiert.
26
+
27
+ ### Aktuelle KNX-Lesewerte
28
+ Wenn der Benutzer ausdrücklich einen aktuellen oder aktualisierten Zustand anfordert, kann die KI exakte Objekte aus dem importierten ETS-Katalog abfragen, einschließlich Status- und anderer schreibgeschützter Objekte. Ausgang 4 gibt `msg.destination`, `msg.dpt`, `msg.event = "GroupValue_Read"` und `msg.readstatus = true` aus. Der Node wartet bis zu 6 Sekunden auf jede `GroupValue_Response` oder ein aktuelles Write-Telegramm, gibt anschließend die dekodierten Werte an Ausgang 3 zurück und stellt Details in `msg.knxAi.readResults` bereit. Leseoperationen erfordern keine Bestätigung und werden niemals in Schreiboperationen umgewandelt.
29
+
30
+ ### Bestätigungsanfrage für Chat-Schaltflächen
31
+ Solange ein Plan aussteht, enthält Ausgang 3 `msg.knxAi.confirmationRequest`. Das Objekt enthält `required`, `status`, `sessionId`, `expiresAt`, `commandCount` und zwei Einträge in `actions`. Verwenden Sie `action.label` als Text der Telegram-Schaltfläche, `action.callbackData` als Callback und senden Sie `action.message` an KNX AI zurück, um ohne Texteingabe zu bestätigen oder abzubrechen.
32
+
33
+ ### Chat-Adapter-Vorlagen
34
+ Der Tab **Chat-Adapter** lädt seine auswählbaren Zuordnungen aus `resources/KNXAIChatAdapterMappings.js`. Die Auswahl einer Vorlage fügt zwei bearbeitbare synchrone JavaScript-Zuordnungen in Textfeldern über die volle Breite ein: eine vor der Verarbeitung des Eingangs durch KNX AI und eine vor der Ausgabe an Ausgang 3. Geben Sie `msg` zurück, um fortzufahren, oder keinen Wert, um die Nachricht zu verwerfen. Syntax- und Laufzeitfehler werden abgefangen und gemeldet, ohne Node-RED anzuhalten.
35
+
36
+ Die enthaltene Vorlage **windkh/node-red-contrib-telegrambot** folgt dem Receiver-/Sender-Vertrag des Pakets. Verbinden Sie einen `telegram receiver` direkt mit KNX AI und Ausgang 3 direkt mit einem `telegram sender`. Für Inline-Bestätigungsschaltflächen verbinden Sie zusätzlich einen als `callback_query` konfigurierten `telegram event` mit demselben KNX-AI-Eingang. Die Eingangszuordnung liest `msg.payload.content`, `msg.payload.chatId` und die Telegram-Sprache. Die Ausgangszuordnung erstellt `msg.payload.chatId`, `type` und `content` und ergänzt bei ausstehender Schreibbestätigung `options.reply_markup` aus `msg.knxAi.confirmationRequest`. Das Telegram-Paket bleibt eine separate optionale Abhängigkeit.
37
+
38
+ ## Proaktive Hausintelligenz und begrenztes Gedächtnis
39
+ Der Unterbereich **Proaktives Zuhause & Gedächtnis** in **Gespräche & Zuhause** aktiviert proaktive Benachrichtigungen auf Wunsch des Benutzers. Aus ETS-Hierarchie, Namen, Rollen und DPTs erstellt der Node ein deterministisches semantisches Modell für Rollläden, Fenster, Türen, Licht, Temperatur, Klima, Anwesenheit und Alarme mit italienischen, englischen, deutschen, französischen, spanischen und chinesischen Begriffen. Der erste proaktive Detektor überwacht nur zuverlässig erkannte Nicht-Befehlszustände von Rollläden/Fenstern/Türen. Nach der konfigurierten Offenzeit und außerhalb der Ruhezeiten gibt Ausgang 3 eine lokalisierte Nachricht mit `msg.knxAi.type = "proactive_notification"` aus. Ausgang 4 wird niemals proaktiv verwendet und KNX wird nicht selbstständig verändert; eine spätere Benutzeranfrage durchläuft weiterhin die normale Validierung und Bestätigung.
40
+
41
+ Die letzte Chat-Sitzung wird als Eigentümer gespeichert; alternativ kann **Hauptempfänger / Chat-ID** sie ausdrücklich festlegen. Ein synthetisches `msg.inputMessage` bewahrt den Empfänger, damit der Telegram-Adapter eine spontane Nachricht senden kann. Cooldown und höchstens drei proaktive Nachrichten pro Stunde verhindern eine Nachrichtenflut.
42
+
43
+ Die gelernte Referenz wird beim Start aus `<userDir>/knxai/memory/knxai-home-memory-<node-id>.md` geladen, alle 15 Minuten atomar neu geschrieben und strikt auf konfigurierbare 64–1.024 KB begrenzt (standardmäßig 256 KB). Sie enthält höchstens 120 wichtige Beobachtungen, 80 aggregierte Gewohnheiten, 80 Benachrichtigungen und 300 semantische ETS-Objekte, niemals einen unbegrenzten Rohtelegrammstrom. Alte Einträge mit niedriger Priorität werden zuerst entfernt. **KI-Erziehung** ist auf 16.000 Zeichen begrenzt und stammt immer aus der Node-Konfiguration: Die KI darf sie als verbindliche Vorgabe lesen, aber weder ändern noch überschreiben. Ist eine Erziehung vorhanden, kann das LLM sie aber nicht auswerten, wird die mögliche Benachrichtigung unterdrückt, statt ihr möglicherweise zu widersprechen.
44
+
45
+ ## Praktisches Konfigurationsbeispiel
46
+ Dieses Beispiel erstellt einen knappen Assistenten, der wichtige Öffnungen meldet, aber akzeptiert, dass der Rollladen im Büro offen bleiben darf:
47
+
48
+ | Editor-Feld | Beispielwert | Wirkung |
49
+ |---|---|---|
50
+ | **Proaktive Hausbenachrichtigungen aktivieren** (`proactiveEnabled`) | aktiv | Zuverlässig erkannte offene Rollladen-/Fenster-/Türzustände werden bewertet. |
51
+ | **Hauptempfänger / Chat-ID** (`proactiveRecipient`) | `123456789` | Spontane Nachrichten gehen an diesen Chat; leer bedeutet: letzte Ask-Sitzung merken. |
52
+ | **Nach offener Dauer benachrichtigen** (`proactiveOpenMinutes`) | `120` | Nach zwei Stunden wird eine mögliche Meldung bewertet. |
53
+ | **Ruhezeit Beginn / Ende** | `23:00` / `07:00` | Nachts werden keine proaktiven Nachrichten ausgegeben. |
54
+ | **Wiederholungs-Cooldown** (`proactiveCooldownMinutes`) | `360` | Dasselbe Objekt meldet sich sechs Stunden lang nicht erneut. |
55
+ | **Maximale Hausgedächtnis-Datei** (`homeMemoryMaxKb`) | `256` | Die Markdown-Referenz dieses Nodes bleibt unter 256 KB. |
56
+
57
+ Beispiel für **KI-Erziehung** (`aiEducation`):
58
+
59
+ ```text
60
+ Nenne mich Alex und antworte in derselben Sprache wie ich.
61
+ Antworte kurz, außer ich bitte um technische Einzelheiten.
62
+ Der Büro-Rollladen darf tagsüber offen bleiben: benachrichtige mich nicht.
63
+ Melde andere Rollläden, Fenster oder Türen, die ungewöhnlich lange offen bleiben.
64
+ Wenn „Wohnzimmerlicht“ mehrdeutig ist, frage nach der gemeinten Leuchte.
65
+ Behaupte nie eine Aktoränderung, bevor ein KNX-Statusobjekt sie bestätigt.
66
+ ```
67
+
68
+ Damit kann Ausgang 3 nach 120 Minuten eine lokalisierte `proactive_notification` für den Wohnzimmer-Rollladen ausgeben, während eine Meldung für den Büro-Rollladen durch die Erziehung unterdrückt wird. Bittet Alex danach um das Schließen, erstellt KNX AI den exakten ETS-Befehl, behält aber Validierung und Bestätigung vor Ausgang 4 bei.
69
+
70
+ Verwenden Sie aussagekräftige ETS-Hierarchien und Objektnamen sowie korrekte Status-/Befehlsrollen. Die Erziehung personalisiert Entscheidungen und Formulierungen, kann aber keine Gruppenadresse erfinden, keinen DPT ändern und die KNX-Validierung nicht umgehen.
14
71
 
15
- Für `ask` die Frage in `msg.prompt` (empfohlen) oder `msg.payload` (String) übergeben.
72
+ ## Kurzer Ablauf: KNX-Steuerung
73
+ 1. Importieren Sie die ETS-CSV in das Gateway und konfigurieren Sie LLM-Anbieter, Modell und Zugangsdaten.
74
+ 2. Aktivieren Sie **LLM-Assistent** und **KNX-Zustände lesen und Aktoren steuern**; lassen Sie die Bestätigung aktiviert.
75
+ 3. Verbinden Sie den Chat-Eingang mit KNX AI und behalten Sie eine stabile Sitzungs-/Chat-ID bei.
76
+ 4. Verbinden Sie Ausgang 3 mit der Chat-Antwort und Ausgang 4 mit KNX Ultimate im **Universalmodus**.
77
+ 5. Der Benutzer sendet eine Anfrage; aktuelle Zustandsabfragen werden sofort gelesen, während Schreiboperationen zuerst GA, DPT und Wert ohne Bus-Schreibzugriff anzeigen.
78
+ 6. Innerhalb von 5 Minuten antwortet derselbe Chat exakt mit `BESTÄTIGEN` oder `ABBRECHEN`.
79
+ 7. Nur `BESTÄTIGEN` validiert erneut und gibt Befehle an Ausgang 4 aus; prüfen Sie die Ausführung über eine KNX-Status-GA.
16
80
 
17
81
  ## Konfigurationsfelder
18
82
  Hier sind alle Felder aufgeführt, wie sie im KNX-AI-Editor sichtbar sind.
@@ -53,7 +117,20 @@ Hier sind alle Felder aufgeführt, wie sie im KNX-AI-Editor sichtbar sind.
53
117
  - **Endpoint URL**: URL des Chat/Completions-Endpunkts.
54
118
  - **API key**: API-Schlüssel (für lokales Ollama nicht erforderlich).
55
119
  - **Model**: Modell-ID/Name.
120
+ - **Chatmodell-Kompatibilität**: Das ausgewählte Modell muss den konfigurierten Chat-Completions-Endpunkt unterstützen. Ältere reine Completions-Modelle wie `gpt-3.5-turbo-instruct` werden beim Aktualisieren der Modellliste ausgeschlossen. Lehnt der Anbieter einen benutzerdefinierten Temperaturwert oder den Token-Limit-Parameter ab, wiederholt KNX AI die Anfrage und entfernt oder ersetzt nur das inkompatible Feld.
56
121
  - **System prompt**: Globale Instruktion für KNX-Analyse (Advanced).
122
+ - **KI darf KNX-Zustände lesen und Aktoren steuern**: Aktiviert Ausgang 4 und ist standardmäßig aus. Exakte ETS-Katalogobjekte dürfen gelesen werden; Schreiboperationen werden ausschließlich für Objekte mit Rolle `command` akzeptiert. Unbekannte, DPT-falsche, ungültige oder überzählige Operationen sowie Schreiboperationen auf Status-/Neutralobjekte werden lokal abgewiesen.
123
+ - **Vor dem Senden von KNX-Befehlen bestätigen lassen**: Standardmäßig aktiv. Zeigt zuerst die validierten Änderungen und sendet nichts, bis dieselbe Chat-Sitzung bestätigt. Wenn Befehle auf Bestätigung warten, fügt die Antwort immer die genauen Anweisungen zum Bestätigen oder Abbrechen in der Sprache der aktuellen Anfrage hinzu. Vor der Ausgabe werden die Befehle erneut validiert.
124
+ - **Adapter-Vorlage**: Lädt ein Paar aus Ein- und Ausgangszuordnung aus der mitgelieferten Chat-Adapter-Datei. Die Auswahl ersetzt bewusst beide Textfelder; der Code bleibt danach bearbeitbar.
125
+ - **Eingangszuordnung (Chat → KNX AI)**: Synchrones JavaScript vor der Verarbeitung des Eingangsbefehls.
126
+ - **Ausgangszuordnung (KNX AI → Chat)**: Synchrones JavaScript ausschließlich für Nachrichten an Ausgang 3.
127
+ - **Proaktive Hausbenachrichtigungen aktivieren**: Optionaler Detektor für zuverlässig erkannte offene Rollladen-/Fenster-/Türzustände; er schreibt nie selbstständig auf KNX.
128
+ - **Hauptempfänger / Chat-ID**: Optionales Ziel für unaufgeforderte Chatnachrichten; andernfalls wird die letzte Ask-Sitzung gespeichert.
129
+ - **Nach offener Dauer benachrichtigen (Minuten)**: Schwelle, bevor eine proaktive Nachricht erwogen wird.
130
+ - **Ruhezeit Beginn / Ende**: Täglicher Zeitraum, in dem proaktive Nachrichten unterdrückt werden.
131
+ - **KI-Erziehung**: Verbindliche, ausschließlich vom Benutzer verwaltete Hinweise, die die KI lesen, aber nie ändern darf.
132
+ - **Wiederholungs-Cooldown (Minuten)**: Mindestintervall vor einer weiteren Meldung desselben Objekts.
133
+ - **Maximale Hausgedächtnis-Datei (KB)**: Harte Grenze von 64 bis 1.024 KB; standardmäßig 256 KB.
57
134
  - Wenn das Festplattenarchiv aktiv ist, nutzt **Ask** standardmäßig dieses Archiv: explizite Datumsangaben/Zeitbereiche werden beachtet, sonst durchsucht der Assistent die letzten 24 Stunden plus aktuelle RAM-Events.
58
135
  - **Include raw payload hex**: Rohe Hex-Payload im Prompt einfügen.
59
136
  - **Node-RED-Projektinventar einbeziehen**: Nimmt das gesamte Node-RED-Projektinventar in den Prompt auf, einschließlich KNX-Nodes und anderer hilfreicher Nodes wie function/change/inject/template, wenn sie KNX-Logik oder Gruppenadressen enthalten.
@@ -84,5 +161,5 @@ Hier sind alle Felder aufgeführt, wie sie im KNX-AI-Editor sichtbar sind.
84
161
  - Wenn Node-RED in Docker läuft, im Endpoint `host.docker.internal` statt `localhost` verwenden.
85
162
 
86
163
  ## Sicherheitshinweis
87
- Bei aktiviertem LLM kann KNX-Traffic-Kontext an den konfigurierten Endpoint gesendet werden. Für striktes On-Premise lokale Provider verwenden.
164
+ Bei aktiviertem LLM kann KNX-Traffic-Kontext an den konfigurierten Endpoint gesendet werden. Für striktes On-Premise lokale Provider verwenden. Ein Befehl an Ausgang 4 hat die lokale Validierung bestanden und wurde an den Flow weitergegeben; dies bestätigt nicht die Ausführung durch den Aktor. Dafür eine KNX-Status-GA verwenden.
88
165
  </script>
@@ -2,12 +2,19 @@
2
2
  "knxUltimateAI": {
3
3
  "title": "KNX AI (Traffic Analyzer)",
4
4
  "sections": {
5
- "capture": "Capture",
6
- "storage": "Speicher & Zusammenfassung",
7
- "detection": "Erkennung & Warnungen",
5
+ "groupAssistant": "KI-Assistent",
6
+ "groupChatHome": "Gespräche & Zuhause",
7
+ "groupKnxAnalysis": "KNX-Verkehrsanalyse",
8
+ "quickSetup": "Assistent einrichten",
9
+ "capture": "Bus-Telegrammeingang",
10
+ "storage": "KNX-Verlauf & Zusammenfassungen",
11
+ "detection": "Anomalien & Muster",
8
12
  "llmConnection": "KI-Assistent-Verbindung",
9
- "llmContext": "KI-Assistent-Kontext",
10
- "advanced": "Erweiterte Einstellungen"
13
+ "llmContext": "KI-Wissen & Kontext",
14
+ "chatAdapter": "Chat-Kanäle",
15
+ "homeIntelligence": "Proaktives Zuhause & Gedächtnis",
16
+ "homeIntelligenceAdvanced": "Erweiterte proaktive Einstellungen",
17
+ "advanced": "Anbieter & Grenzen"
11
18
  },
12
19
  "properties": {
13
20
  "server": "Gateway",
@@ -39,26 +46,45 @@
39
46
  "llmSystemPrompt": "System prompt",
40
47
  "llmIncludeRaw": "Include raw payload hex",
41
48
  "llmIncludeFlowContext": "Node-RED-Projektinventar einbeziehen",
49
+ "llmAllowKnxCommands": "KI darf KNX-Zustände lesen und Aktoren steuern",
50
+ "llmRequireCommandConfirmation": "Vor dem Senden von KNX-Befehlen bestätigen lassen",
51
+ "chatAdapterPreset": "Adapter-Vorlage",
52
+ "chatInputCode": "Eingangszuordnung (Chat → KNX AI)",
53
+ "chatOutputCode": "Ausgangszuordnung (KNX AI → Chat)",
54
+ "proactiveEnabled": "Proaktive Hausbenachrichtigungen aktivieren",
55
+ "proactiveRecipient": "Hauptempfänger / Chat-ID",
56
+ "proactiveOpenMinutes": "Nach Offenstand benachrichtigen (Minuten)",
57
+ "proactiveCooldownMinutes": "Wiederholsperre (Minuten)",
58
+ "proactiveQuietStart": "Beginn der Ruhezeit",
59
+ "proactiveQuietEnd": "Ende der Ruhezeit",
60
+ "homeMemoryMaxKb": "Maximale Hausgedächtnisdatei (KB)",
61
+ "aiEducation": "KI-Erziehung (vom Benutzer verwaltet)",
42
62
  "llmIncludeDocsSnippets": "Include documentation snippets (help/README/examples)",
43
63
  "llmDocsLanguage": "Docs language"
44
64
  },
45
65
  "outputs": {
46
66
  "summary": "Zusammenfassung/Statistik",
47
67
  "anomalies": "Anomalien",
48
- "assistant": "KI-Assistent"
68
+ "assistant": "KI-Assistent",
69
+ "knxCommands": "KNX-Operationen"
49
70
  },
50
71
  "selectlists": {
51
72
  "llmProvider": {
52
73
  "openai_compat": "OpenAI-compatible (chat/completions)",
53
74
  "anthropic": "Anthropic (Claude)",
54
75
  "ollama": "Ollama (local, beta)"
76
+ },
77
+ "chatAdapter": {
78
+ "none": "Kein Adapter"
55
79
  }
56
80
  },
57
81
  "placeholder": {
58
82
  "llmBaseUrl": "https://api.openai.com/v1/chat/completions (or your compatible endpoint)",
59
83
  "llmApiKey": "Paste API key (starts with sk-)",
60
84
  "llmModel": "e.g. gpt-4o-mini",
61
- "llmSystemPrompt": "Optional. Leave empty for default."
85
+ "llmSystemPrompt": "Optional. Leave empty for default.",
86
+ "proactiveRecipient": "Optional: Telegram-Chat-ID; andernfalls wird die letzte Chat-Sitzung gespeichert",
87
+ "aiEducation": "Beispiel: Zwischen 23:00 und 07:00 nicht benachrichtigen. Der Rollladen im Büro darf nachts offen bleiben."
62
88
  },
63
89
  "messages": {
64
90
  "ollamaNotSupported": "Ollama local mode: API key not required. Default endpoint is http://localhost:11434/api/chat.",
@@ -67,7 +93,12 @@
67
93
  "installedOllamaModel": "Ollama model installed",
68
94
  "installOllamaModelFailed": "Failed to install Ollama model",
69
95
  "ollamaInstallSteps": "1) Open the model library and copy the model name (for example llama3.1). 2) Put the name in the Model field and click Install it.",
70
- "ollamaStartedAuto": "Ollama server started automatically."
96
+ "ollamaStartedAuto": "Ollama server started automatically.",
97
+ "chatAdapterIntro": "Wählen Sie eine Vorlage, um den Code für Ein- und Ausgang einzufügen. Die Liste wird aus der mitgelieferten Chat-Adapter-Datei geladen; der erzeugte Code bleibt bearbeitbar.",
98
+ "chatAdapterCodeHelp": "Zuordnungen laufen synchron. Geben Sie msg zurück, um fortzufahren, oder keinen Wert, um die Nachricht zu verwerfen. Fehler werden abgefangen und gemeldet, ohne Node-RED anzuhalten.",
99
+ "homeIntelligenceIntro": "Der Node erstellt ein mehrsprachiges semantisches ETS-Modell und kann den Chat benachrichtigen, wenn ein zuverlässig erkannter Rollladen, ein Fenster oder eine Tür offen bleibt. Er sendet niemals selbstständig einen KNX-Befehl.",
100
+ "aiEducationHelp": "Nur der Benutzer kann diesen Abschnitt bearbeiten. Die KI liest ihn als verbindliche Vorgabe; gelernte Erinnerungen können ihn niemals überschreiben. Maximal 16.000 Zeichen.",
101
+ "homeMemoryLimitHelp": "Das Markdown-Gedächtnis wird alle 15 Minuten atomar neu geschrieben und bleibt stets auf 64 bis 1.024 KB begrenzt. Alte Beobachtungen werden vor Gewohnheiten und semantischen Objekten entfernt."
71
102
  },
72
103
  "sidebar": {
73
104
  "ui": {
@@ -1,18 +1,86 @@
1
1
  <script type="text/markdown" data-help-name="knxUltimateAI">
2
2
  This node listens to **all KNX telegrams** from the selected KNX Ultimate gateway, builds traffic statistics, detects anomalies, and can optionally query an LLM.
3
3
 
4
+ The editor uses three main accordion sections: **AI assistant** contains setup, knowledge/context and provider limits; **Conversations & home** contains chat channels, proactive home and bounded memory; **KNX traffic analysis** contains bus telegram input, history/summaries and anomalies/patterns. Opening a main section shows all of its related options together. Saved field IDs and values remain unchanged.
5
+
4
6
  ## Outputs
5
7
  1. **Summary/Stats** (`msg.payload` JSON)
6
8
  2. **Anomalies** (`msg.payload` JSON)
7
9
  3. **AI Assistant** (`msg.payload` text, with `msg.summary`)
10
+ 4. **KNX operations** (one Universal Mode message per validated read or write)
11
+
12
+ Every message emitted by outputs 3 and 4 also contains a clone of the original input message in `msg.inputMessage`. This preserves the original payload, topic, chat metadata, and any other input properties for downstream nodes. Cloning and output errors are contained and reported instead of escaping into the Node-RED runtime.
8
13
 
9
14
  ## Commands (input)
10
15
  Send `msg.topic`:
11
16
  - `summary` (or empty): emit summary immediately
12
- - `reset`: clear internal history/counters
17
+ - `reset`: clear internal history, counters and learned home memory; AI Education remains unchanged
13
18
  - `ask`: send a question to the configured LLM
19
+ - `confirm` / `cancel`: confirm or cancel pending KNX commands without calling the LLM
20
+ - `clear_chat`: clear the conversation memory for the current session
21
+
22
+ For `ask`, provide the question in `msg.prompt` (preferred), `msg.payload` (string), or the common Telegram fields `msg.payload.content` / `msg.payload.text`.
23
+
24
+ When KNX control is enabled, recent turns are remembered in RAM per `msg.knxAi.sessionId`, `msg.sessionId`, or a detected Telegram chat ID. Wire output 3 back to the chat sender and output 4 to a KNX Ultimate node configured in **Universal mode**. With confirmation enabled, the first reply previews every write GA, DPT, and payload without emitting writes; the same session must then reply `CONFIRM`/`CANCEL` (localized equivalents are accepted) within 5 minutes. A new request replaces any older pending plan. Each confirmed command has `msg.destination`, `msg.dpt`, `msg.payload`, and `msg.event = "GroupValue_Write"`.
25
+ For DPT 1.xxx writes, safe AI equivalents `true`/`false`, `1`/`0`, and `on`/`off` are normalized to a real boolean before local validation and output.
26
+
27
+ ### Fresh KNX reads
28
+ When the user explicitly asks for a fresh/current state, the AI may query exact objects from the imported ETS catalog, including status and other read-only objects. Output 4 emits `msg.destination`, `msg.dpt`, `msg.event = "GroupValue_Read"`, and `msg.readstatus = true`. The node waits up to 6 seconds for each `GroupValue_Response` or fresh write, then returns the decoded values on output 3 and exposes details in `msg.knxAi.readResults`. Reads never require confirmation and never become writes.
29
+
30
+ ### Confirmation request for chat buttons
31
+ While a plan is pending, output 3 contains `msg.knxAi.confirmationRequest`. The object includes `required`, `status`, `sessionId`, `expiresAt`, `commandCount`, and two entries in `actions`. Use `action.label` as the Telegram button text, `action.callbackData` as its callback, and send `action.message` back to KNX AI to confirm or cancel without typed text.
32
+
33
+ ### Chat adapter presets
34
+ The **Chat adapters** tab loads its selectable mappings from `resources/KNXAIChatAdapterMappings.js`. Selecting a preset inserts two editable synchronous JavaScript mappings in full-width text boxes: one before KNX AI processes an input and one before output 3 is emitted. Return `msg` to continue or no value to discard the message. Syntax and execution failures are caught and reported without stopping Node-RED.
35
+
36
+ The included **windkh/node-red-contrib-telegrambot** preset follows the package's receiver/sender contract. Connect a `telegram receiver` directly to KNX AI, output 3 directly to a `telegram sender`, and—when inline confirmation buttons are required—connect a `telegram event` configured for `callback_query` to the same KNX AI input. The input mapping extracts `msg.payload.content`, `msg.payload.chatId`, and the Telegram language. The output mapping creates the required `msg.payload.chatId`, `type`, and `content`, adding `options.reply_markup` from `msg.knxAi.confirmationRequest` when writes await confirmation. The Telegram package remains a separate optional dependency.
37
+
38
+ ## Proactive home intelligence and bounded memory
39
+ The **Proactive home & memory** subsection inside **Conversations & home** enables opt-in proactive notifications. From ETS hierarchy, names, roles and DPTs, the node builds a deterministic semantic model for covers, windows, doors, lights, temperature, climate, occupancy and alarms using Italian, English, German, French, Spanish and Chinese terms. The first proactive detector watches only reliably recognized non-command cover/window/door states. After the configured open duration and outside quiet hours, output 3 emits a localized message with `msg.knxAi.type = "proactive_notification"`. It never emits output 4 or changes KNX autonomously; a subsequent user request still uses the normal validation and confirmation workflow.
40
+
41
+ The most recent chat session is remembered as the owner, or **Primary recipient / chat ID** can set it explicitly. A synthetic `msg.inputMessage` preserves this recipient so the Telegram adapter can send an unsolicited notification. Cooldown and a maximum of three proactive messages per hour prevent flooding.
42
+
43
+ The learned reference is loaded at startup from `<userDir>/knxai/memory/knxai-home-memory-<node-id>.md`, rewritten atomically every 15 minutes and hard-capped to the configured 64–1,024 KB (256 KB by default). It stores at most 120 significant observations, 80 aggregate habits, 80 notifications and 300 semantic ETS objects—never a raw unlimited telegram stream. Older low-priority entries are removed first. **AI Education** is limited to 16,000 characters and always comes from the node configuration: the AI can read it as authoritative guidance but cannot modify or overwrite it. When Education is present but the LLM cannot evaluate it, the candidate notification is suppressed rather than risking a contradiction.
44
+
45
+ ## Practical configuration example
46
+ This example creates a concise assistant that notifies the owner about relevant openings but accepts that the office cover may stay open:
47
+
48
+ | Editor field | Example value | Result |
49
+ |---|---|---|
50
+ | **Enable proactive home notifications** (`proactiveEnabled`) | enabled | The node evaluates reliably recognized open cover/window/door states. |
51
+ | **Primary recipient / chat ID** (`proactiveRecipient`) | `123456789` | Unsolicited messages go to this chat. Leave it empty to remember the most recent Ask session. |
52
+ | **Notify after open** (`proactiveOpenMinutes`) | `120` | A candidate notification is considered after two hours. |
53
+ | **Quiet hours start / end** | `23:00` / `07:00` | No proactive message is emitted during the night. |
54
+ | **Repeat cooldown** (`proactiveCooldownMinutes`) | `360` | The same object cannot notify again for six hours. |
55
+ | **Maximum home-memory file** (`homeMemoryMaxKb`) | `256` | The per-node Markdown reference can never exceed 256 KB. |
56
+
57
+ Example for **AI Education** (`aiEducation`):
58
+
59
+ ```text
60
+ Call me Alex and answer in the same language I use.
61
+ Keep replies short unless I ask for technical details.
62
+ The office cover may remain open during the day: do not notify me about it.
63
+ Notify me when another cover, window, or door remains open unusually long.
64
+ When "living-room light" is ambiguous, ask which light I mean.
65
+ Never say that an actuator changed until a KNX status object confirms it.
66
+ ```
67
+
68
+ With these settings:
69
+
70
+ 1. If the living-room cover status remains open for 120 minutes outside quiet hours, output 3 can emit a localized `proactive_notification`.
71
+ 2. If the office cover remains open, the LLM reads Education and suppresses that candidate notification.
72
+ 3. If Alex later asks to close the living-room cover, KNX AI prepares the exact ETS command and still follows normal validation and confirmation before output 4.
73
+
74
+ Use descriptive ETS hierarchy/object names and correct status/command roles. Education can personalize decisions and wording, but it cannot authorize an invented group address, change a DPT, or bypass KNX validation.
14
75
 
15
- For `ask`, provide the question in `msg.prompt` (preferred) or `msg.payload` (string).
76
+ ## Quick workflow: KNX control
77
+ 1. Import the ETS CSV into the gateway and configure the LLM provider, model, and credentials.
78
+ 2. Enable **LLM assistant** and **KNX state reads and actuator control**; leave confirmation enabled.
79
+ 3. Connect the chat input to KNX AI while preserving a stable session/chat ID.
80
+ 4. Connect output 3 to the chat reply and output 4 to KNX Ultimate in **Universal mode**.
81
+ 5. The user sends a request; fresh state requests are read immediately, while writes first show the proposed GA, DPT, and value without writing to the bus.
82
+ 6. Within 5 minutes, the same chat replies exactly `CONFIRM` or `CANCEL`.
83
+ 7. Only `CONFIRM` revalidates and emits commands on output 4; verify execution through a KNX status GA.
16
84
 
17
85
  ## Configuration fields
18
86
  All fields exposed in the KNX AI editor are listed below.
@@ -53,7 +121,20 @@ All fields exposed in the KNX AI editor are listed below.
53
121
  - **Endpoint URL**: Chat/completions endpoint URL.
54
122
  - **API key**: API key (not required for local Ollama).
55
123
  - **Model**: Model ID/name.
124
+ - **Chat model compatibility**: The selected model must support the configured Chat Completions endpoint. Legacy completion-only models such as `gpt-3.5-turbo-instruct` are excluded when the model list is refreshed. If the provider rejects a custom temperature or token-limit parameter, KNX AI retries after removing or replacing only that incompatible field.
56
125
  - **System prompt**: Global instruction for KNX analysis behavior (Advanced).
126
+ - **Allow AI to read KNX states and control actuators**: Enables output 4 and is off by default. Exact ETS catalog objects may be read; writes are accepted only for objects classified as `command`. Unknown, DPT-mismatched, invalid, or excessive operations and writes to status/neutral objects are rejected locally.
127
+ - **Ask for confirmation before sending KNX commands**: Enabled by default. Shows the validated changes first and emits no KNX command until the same chat session confirms them. Whenever commands are awaiting confirmation, the response always appends the exact confirmation/cancellation instructions in the language of the current request. Commands are validated again immediately before output.
128
+ - **Adapter preset**: Loads an input/output mapping pair from the packaged chat-adapter file. Selecting a preset intentionally replaces both mapping text boxes; they remain editable afterwards.
129
+ - **Input mapping (chat → KNX AI)**: Synchronous JavaScript applied before input command processing.
130
+ - **Output mapping (KNX AI → chat)**: Synchronous JavaScript applied only to messages on output 3.
131
+ - **Enable proactive home notifications**: Opt-in detector for reliably recognized open cover/window/door states; it never writes autonomously to KNX.
132
+ - **Primary recipient / chat ID**: Optional destination for unsolicited chat messages; otherwise the most recent Ask session is remembered.
133
+ - **Notify after open (minutes)**: Open-duration threshold before a proactive notification can be considered.
134
+ - **Quiet hours start / end**: Daily interval in which proactive messages are suppressed.
135
+ - **AI Education**: User-only, authoritative guidance read by the AI and never modified by it.
136
+ - **Repeat cooldown (minutes)**: Minimum interval before the same object may notify again.
137
+ - **Maximum home-memory file (KB)**: Hard size limit from 64 to 1,024 KB; 256 KB by default.
57
138
  - If disk archive is enabled, **Ask** uses the archive by default: explicit dates/ranges are honored, otherwise the assistant searches the last 24 hours plus current RAM events.
58
139
  - **Include raw payload hex**: Include raw telegram hex in prompt.
59
140
  - **Include Node-RED project inventory**: Include the whole Node-RED project inventory in the prompt, including KNX nodes and other useful nodes such as function/change/inject/template when they contain KNX-related logic or group addresses.
@@ -84,5 +165,5 @@ All fields exposed in the KNX AI editor are listed below.
84
165
  - If Node-RED runs in Docker, use `host.docker.internal` instead of `localhost` in the endpoint URL.
85
166
 
86
167
  ## Security note
87
- If LLM is enabled, KNX traffic context can be sent to the configured endpoint. Use local providers if you need strict on-prem data handling.
168
+ If LLM is enabled, KNX traffic context can be sent to the configured endpoint. Use local providers if you need strict on-prem data handling. A command emitted on output 4 passed local validation and was forwarded to the flow; it is not proof that the actuator executed it. Use a KNX status GA when confirmation is required.
88
169
  </script>
@@ -2,12 +2,19 @@
2
2
  "knxUltimateAI": {
3
3
  "title": "KNX AI (Traffic Analyzer)",
4
4
  "sections": {
5
- "capture": "Capture",
6
- "storage": "Storage & Summary",
7
- "detection": "Detection & Alerts",
5
+ "groupAssistant": "AI assistant",
6
+ "groupChatHome": "Conversations & home",
7
+ "groupKnxAnalysis": "KNX traffic analysis",
8
+ "quickSetup": "Assistant setup",
9
+ "capture": "Bus telegram input",
10
+ "storage": "KNX history & summaries",
11
+ "detection": "Anomalies & patterns",
8
12
  "llmConnection": "AI Assistant Connection",
9
- "llmContext": "AI Assistant Context",
10
- "advanced": "Advanced Tuning"
13
+ "llmContext": "AI knowledge & context",
14
+ "chatAdapter": "Chat channels",
15
+ "homeIntelligence": "Proactive home & memory",
16
+ "homeIntelligenceAdvanced": "Advanced proactive settings",
17
+ "advanced": "Provider & limits"
11
18
  },
12
19
  "properties": {
13
20
  "server": "Gateway",
@@ -39,19 +46,36 @@
39
46
  "llmSystemPrompt": "System prompt",
40
47
  "llmIncludeRaw": "Include raw payload hex",
41
48
  "llmIncludeFlowContext": "Include Node-RED project inventory",
49
+ "llmAllowKnxCommands": "Allow AI to read KNX states and control actuators",
50
+ "llmRequireCommandConfirmation": "Ask for confirmation before sending KNX commands",
51
+ "chatAdapterPreset": "Adapter preset",
52
+ "chatInputCode": "Input mapping (chat → KNX AI)",
53
+ "chatOutputCode": "Output mapping (KNX AI → chat)",
54
+ "proactiveEnabled": "Enable proactive home notifications",
55
+ "proactiveRecipient": "Primary recipient / chat ID",
56
+ "proactiveOpenMinutes": "Notify after open (minutes)",
57
+ "proactiveCooldownMinutes": "Repeat cooldown (minutes)",
58
+ "proactiveQuietStart": "Quiet hours start",
59
+ "proactiveQuietEnd": "Quiet hours end",
60
+ "homeMemoryMaxKb": "Maximum home-memory file (KB)",
61
+ "aiEducation": "AI Education (user managed)",
42
62
  "llmIncludeDocsSnippets": "Include documentation snippets (help/README/examples)",
43
63
  "llmDocsLanguage": "Docs language"
44
64
  },
45
65
  "outputs": {
46
66
  "summary": "Summary/Stats",
47
67
  "anomalies": "Anomalies",
48
- "assistant": "AI Assistant"
68
+ "assistant": "AI Assistant",
69
+ "knxCommands": "KNX operations"
49
70
  },
50
71
  "selectlists": {
51
72
  "llmProvider": {
52
73
  "openai_compat": "OpenAI-compatible (chat/completions)",
53
74
  "anthropic": "Anthropic (Claude)",
54
75
  "ollama": "Ollama (local, beta)"
76
+ },
77
+ "chatAdapter": {
78
+ "none": "No adapter"
55
79
  }
56
80
  },
57
81
  "buttons": {
@@ -69,13 +93,20 @@
69
93
  "installedOllamaModel": "Ollama model installed",
70
94
  "installOllamaModelFailed": "Failed to install Ollama model",
71
95
  "ollamaInstallSteps": "1) Open the model library and copy the model name (for example llama3.1). 2) Put the name in the Model field and click Install it.",
72
- "ollamaStartedAuto": "Ollama server started automatically."
96
+ "ollamaStartedAuto": "Ollama server started automatically.",
97
+ "chatAdapterIntro": "Choose a mapping preset to insert its input and output code. The list is loaded from the packaged chat-adapter mappings file; the generated code remains editable.",
98
+ "chatAdapterCodeHelp": "Mappings run synchronously. Return msg to continue or return no value to discard it. Errors are caught and reported without stopping Node-RED.",
99
+ "homeIntelligenceIntro": "The node builds a multilingual semantic ETS model and can notify the chat when a reliably recognized cover, window, or door remains open. It never sends a KNX command proactively.",
100
+ "aiEducationHelp": "Only the user can edit this section. The AI reads it as authoritative guidance, but learned-memory updates can never overwrite it. Maximum 16,000 characters.",
101
+ "homeMemoryLimitHelp": "The Markdown memory is rewritten atomically every 15 minutes and is always capped between 64 and 1,024 KB. Old observations are pruned before habits and semantic objects."
73
102
  },
74
103
  "placeholder": {
75
104
  "llmBaseUrl": "https://api.openai.com/v1/chat/completions (or your compatible endpoint)",
76
105
  "llmApiKey": "Paste API key (starts with sk-)",
77
106
  "llmModel": "e.g. gpt-4o-mini",
78
- "llmSystemPrompt": "Optional. Leave empty for default."
107
+ "llmSystemPrompt": "Optional. Leave empty for default.",
108
+ "proactiveRecipient": "Optional: Telegram chat ID; otherwise the most recent chat session is remembered",
109
+ "aiEducation": "Example: Do not notify me between 23:00 and 07:00. The office shutter may remain open at night."
79
110
  },
80
111
  "sidebar": {
81
112
  "ui": {
@@ -1,18 +1,82 @@
1
1
  <script type="text/markdown" data-help-name="knxUltimateAI">
2
2
  Este nodo escucha **todos los telegramas KNX** del gateway KNX Ultimate seleccionado, genera estadísticas de tráfico, detecta anomalías y puede consultar opcionalmente un LLM.
3
3
 
4
+ El editor utiliza tres secciones principales en acordeón: **Asistente IA** contiene configuración, conocimiento/contexto y límites del proveedor; **Conversaciones y hogar** contiene canales de chat, hogar proactivo y memoria limitada; **Análisis del tráfico KNX** contiene telegramas del bus, historial/resúmenes y anomalías/patrones. Al abrir una sección principal se muestran juntas todas sus opciones. Los ID y valores guardados permanecen intactos.
5
+
4
6
  ## Salidas
5
7
  1. **Resumen/Estadísticas** (`msg.payload` JSON)
6
8
  2. **Anomalías** (`msg.payload` JSON)
7
9
  3. **Asistente IA** (`msg.payload` texto, con `msg.summary`)
10
+ 4. **Operaciones KNX** (un mensaje Universal Mode por cada lectura o escritura validada)
11
+
12
+ Cada mensaje emitido por las salidas 3 y 4 también contiene una copia del mensaje de entrada original en `msg.inputMessage`. Así, el payload, el topic, los metadatos del chat y cualquier otra propiedad de entrada permanecen disponibles para los nodos posteriores. Los errores de clonación o envío se interceptan y notifican sin propagarse al runtime de Node-RED.
8
13
 
9
14
  ## Comandos (entrada)
10
15
  Envía `msg.topic`:
11
16
  - `summary` (o vacío): emite el resumen inmediatamente
12
- - `reset`: limpia historial y contadores internos
17
+ - `reset`: borra el historial, los contadores y la memoria del hogar aprendida; la Educación de la IA permanece sin cambios
13
18
  - `ask`: envía una pregunta al LLM configurado
19
+ - `confirm` / `cancel`: confirma o cancela los comandos KNX pendientes sin volver a llamar al LLM
20
+ - `clear_chat`: borra la memoria de conversación de la sesión actual
21
+
22
+ Para `ask`, envía la pregunta en `msg.prompt` (recomendado), `msg.payload` (string), o los campos comunes de Telegram `msg.payload.content` / `msg.payload.text`.
23
+
24
+ Cuando el control KNX está habilitado, los turnos recientes se guardan en RAM por `msg.knxAi.sessionId`, `msg.sessionId` o el ID de chat Telegram detectado. Conecta la salida 3 al nodo emisor del chat y la salida 4 a un nodo KNX Ultimate en **modo universal**. Con la confirmación activa, la primera respuesta muestra GA, DPT y payload sin emitir escrituras; la misma sesión debe responder `CONFIRMAR` o `CANCELAR` en 5 minutos. Una solicitud nueva sustituye cualquier plan anterior. Cada comando confirmado contiene `msg.destination`, `msg.dpt`, `msg.payload` y `msg.event = "GroupValue_Write"`.
25
+ Para las escrituras DPT 1.xxx, los equivalentes seguros producidos por la IA `true`/`false`, `1`/`0` y `on`/`off` se normalizan a booleanos reales antes de la validación local y la salida.
26
+
27
+ ### Lecturas KNX actualizadas
28
+ Cuando el usuario solicita explícitamente un estado actual o actualizado, la IA puede consultar objetos exactos del catálogo ETS importado, incluidos objetos de estado y otros objetos de solo lectura. La salida 4 emite `msg.destination`, `msg.dpt`, `msg.event = "GroupValue_Read"` y `msg.readstatus = true`. El nodo espera hasta 6 segundos cada `GroupValue_Response` o escritura reciente, devuelve los valores decodificados por la salida 3 y expone los detalles en `msg.knxAi.readResults`. Las lecturas nunca requieren confirmación ni se convierten en escrituras.
29
+
30
+ ### Solicitud de confirmación para botones de chat
31
+ Mientras un plan está pendiente, la salida 3 contiene `msg.knxAi.confirmationRequest`. El objeto incluye `required`, `status`, `sessionId`, `expiresAt`, `commandCount` y dos elementos en `actions`. Usa `action.label` como texto del botón de Telegram, `action.callbackData` como callback y devuelve `action.message` a KNX AI para confirmar o cancelar sin escribir texto.
32
+
33
+ ### Preajustes del adaptador de chat
34
+ La pestaña **Adaptadores de chat** carga sus mapeos seleccionables desde `resources/KNXAIChatAdapterMappings.js`. Al elegir un preajuste se insertan dos mapeos JavaScript síncronos y editables en cuadros de texto de ancho completo: uno antes de que KNX AI procese la entrada y otro antes de emitir por la salida 3. Devuelve `msg` para continuar o ningún valor para descartar el mensaje. Los errores de sintaxis y ejecución se capturan y notifican sin detener Node-RED.
35
+
36
+ El preajuste incluido **windkh/node-red-contrib-telegrambot** sigue el contrato receiver/sender del paquete. Conecta directamente un `telegram receiver` a KNX AI y la salida 3 a un `telegram sender`. Para los botones inline de confirmación, conecta también un `telegram event` configurado como `callback_query` a la misma entrada KNX AI. El mapeo de entrada extrae `msg.payload.content`, `msg.payload.chatId` y el idioma de Telegram. El mapeo de salida crea `msg.payload.chatId`, `type` y `content`, y añade `options.reply_markup` desde `msg.knxAi.confirmationRequest` cuando una escritura espera confirmación. El paquete Telegram sigue siendo una dependencia opcional separada.
37
+
38
+ ## Inteligencia doméstica proactiva y memoria limitada
39
+ La subsección **Hogar proactivo y memoria** dentro de **Conversaciones y hogar** activa las notificaciones proactivas de forma opcional. A partir de la jerarquía ETS, nombres, roles y DPT, el nodo crea un modelo semántico determinista para persianas, ventanas, puertas, luces, temperatura, clima, presencia y alarmas usando términos italianos, ingleses, alemanes, franceses, españoles y chinos. El primer detector proactivo vigila únicamente estados que no sean de comando de persianas/ventanas/puertas reconocidos con suficiente fiabilidad. Tras el tiempo abierto configurado y fuera de las horas silenciosas, la salida 3 emite un mensaje localizado con `msg.knxAi.type = "proactive_notification"`. Nunca emite por la salida 4 ni modifica KNX de manera autónoma; una solicitud posterior del usuario sigue pasando por la validación y confirmación normales.
40
+
41
+ La última sesión de chat se recuerda como propietario, o **Destinatario principal / ID de chat** permite definirla explícitamente. Un `msg.inputMessage` sintético conserva el destinatario para que el adaptador de Telegram pueda enviar una notificación espontánea. El tiempo de espera y el máximo de tres notificaciones proactivas por hora evitan inundar el chat.
42
+
43
+ La referencia aprendida se carga al arrancar desde `<userDir>/knxai/memory/knxai-home-memory-<node-id>.md`, se reescribe atómicamente cada 15 minutos y queda estrictamente limitada entre 64 y 1.024 KB configurables (256 KB de forma predeterminada). Conserva como máximo 120 observaciones importantes, 80 hábitos agregados, 80 notificaciones y 300 objetos ETS semánticos, nunca un flujo ilimitado de telegramas raw. Los elementos antiguos y de menor prioridad se eliminan primero. **Educación IA** está limitada a 16.000 caracteres y siempre procede de la configuración del nodo: la IA puede leerla como instrucción autoritativa, pero no modificarla ni sobrescribirla. Si existe Educación pero el LLM no puede evaluarla, la notificación candidata se suprime en lugar de arriesgarse a contradecirla.
44
+
45
+ ## Ejemplo práctico de configuración
46
+ Este ejemplo crea un asistente conciso que avisa sobre aperturas importantes, pero acepta que la persiana del despacho permanezca abierta:
47
+
48
+ | Campo del editor | Valor de ejemplo | Resultado |
49
+ |---|---|---|
50
+ | **Activar notificaciones proactivas del hogar** (`proactiveEnabled`) | activado | El nodo evalúa estados abiertos fiables de persianas, ventanas y puertas. |
51
+ | **Destinatario principal / ID de chat** (`proactiveRecipient`) | `123456789` | Los mensajes espontáneos van a este chat; déjalo vacío para recordar la última sesión Ask. |
52
+ | **Avisar después de abierta** (`proactiveOpenMinutes`) | `120` | Se evalúa una posible notificación después de dos horas. |
53
+ | **Inicio / fin de horas silenciosas** | `23:00` / `07:00` | No se emiten mensajes proactivos durante la noche. |
54
+ | **Tiempo de espera de repetición** (`proactiveCooldownMinutes`) | `360` | El mismo objeto no vuelve a avisar durante seis horas. |
55
+ | **Archivo máximo de memoria del hogar** (`homeMemoryMaxKb`) | `256` | La referencia Markdown de este nodo permanece por debajo de 256 KB. |
56
+
57
+ Ejemplo para **Educación IA** (`aiEducation`):
58
+
59
+ ```text
60
+ Llámame Alex y responde en el mismo idioma que uso.
61
+ Responde brevemente, salvo que pida detalles técnicos.
62
+ La persiana del despacho puede permanecer abierta durante el día: no me avises.
63
+ Avísame si otra persiana, ventana o puerta permanece abierta demasiado tiempo.
64
+ Si «luz del salón» es ambiguo, pregúntame a qué luz me refiero.
65
+ Nunca afirmes que un actuador cambió hasta que lo confirme un objeto de estado KNX.
66
+ ```
67
+
68
+ Con estos ajustes, la salida 3 puede emitir una `proactive_notification` localizada después de 120 minutos para la persiana del salón, mientras que Educación suprime el aviso de la persiana del despacho. Si Alex pide después cerrar la persiana del salón, KNX AI prepara el comando ETS exacto, pero mantiene la validación y confirmación normales antes de la salida 4.
69
+
70
+ Usa jerarquías y nombres de objetos ETS descriptivos, con roles de estado/comando correctos. Educación personaliza decisiones y texto, pero no puede inventar una dirección de grupo, cambiar un DPT ni evitar la validación KNX.
14
71
 
15
- Para `ask`, envía la pregunta en `msg.prompt` (recomendado) o `msg.payload` (string).
72
+ ## Flujo rápido: control KNX
73
+ 1. Importa el CSV de ETS en el gateway y configura el proveedor, el modelo y las credenciales LLM.
74
+ 2. Activa **Asistente LLM** y **lectura de estados KNX y control de actuadores**; deja activada la confirmación.
75
+ 3. Conecta la entrada del chat a KNX AI manteniendo un ID de sesión/chat estable.
76
+ 4. Conecta la salida 3 a la respuesta del chat y la salida 4 a KNX Ultimate en **modo universal**.
77
+ 5. El usuario envía una solicitud; los estados actuales se leen inmediatamente, mientras que las escrituras muestran primero GA, DPT y valor sin escribir en el bus.
78
+ 6. En un plazo de 5 minutos, el mismo chat responde exactamente `CONFIRMAR` o `CANCELAR`.
79
+ 7. Solo `CONFIRMAR` vuelve a validar y emite los comandos por la salida 4; verifica la ejecución mediante una GA de estado KNX.
16
80
 
17
81
  ## Campos de configuración
18
82
  Aquí tienes todos los campos tal como se muestran en el editor de KNX AI.
@@ -53,7 +117,20 @@ Aquí tienes todos los campos tal como se muestran en el editor de KNX AI.
53
117
  - **Endpoint URL**: URL endpoint chat/completions.
54
118
  - **API key**: clave API (no requerida con Ollama local).
55
119
  - **Model**: ID/nombre de modelo.
120
+ - **Compatibilidad del modelo de chat**: el modelo seleccionado debe admitir el endpoint Chat Completions configurado. Los modelos antiguos disponibles solo mediante completions, como `gpt-3.5-turbo-instruct`, se excluyen al actualizar la lista. Si el proveedor rechaza un valor personalizado de temperatura o el parámetro de límite de tokens, KNX AI vuelve a intentarlo eliminando o sustituyendo únicamente el campo incompatible.
56
121
  - **System prompt**: instrucción global para análisis KNX (Advanced).
122
+ - **Permitir que la IA lea estados KNX y controle actuadores**: habilita la salida 4 y está desactivado por defecto. Los objetos exactos del catálogo ETS se pueden leer; solo se aceptan escrituras hacia objetos clasificados como `command`. Las operaciones desconocidas, con DPT distinto, inválidas o excesivas, y las escrituras hacia objetos de estado o neutrales, se rechazan localmente.
123
+ - **Pedir confirmación antes de enviar comandos KNX**: activado por defecto. Muestra primero los cambios validados y no emite comandos hasta que la misma sesión de chat los confirme. Cuando hay comandos pendientes, la respuesta añade siempre las instrucciones exactas para confirmar o cancelar en el idioma de la solicitud actual. Los comandos se validan de nuevo justo antes de la salida.
124
+ - **Preajuste del adaptador**: carga una pareja de mapeos entrada/salida desde el archivo de adaptadores de chat incluido. La selección sustituye intencionadamente ambos cuadros de texto; el código sigue siendo editable.
125
+ - **Mapeo de entrada (chat → KNX AI)**: JavaScript síncrono aplicado antes de procesar el comando de entrada.
126
+ - **Mapeo de salida (KNX AI → chat)**: JavaScript síncrono aplicado solo a los mensajes de la salida 3.
127
+ - **Activar notificaciones proactivas del hogar**: detector opcional de estados abiertos de persiana/ventana/puerta reconocidos de forma fiable; nunca escribe de manera autónoma en KNX.
128
+ - **Destinatario principal / ID de chat**: destino opcional de mensajes espontáneos; de lo contrario se recuerda la última sesión Ask.
129
+ - **Avisar después de abierta (minutos)**: umbral de duración antes de considerar una notificación proactiva.
130
+ - **Inicio / fin de horas silenciosas**: intervalo diario en el que se suprimen los mensajes proactivos.
131
+ - **Educación de la IA**: instrucciones vinculantes gestionadas solo por el usuario, leídas por la IA y nunca modificadas.
132
+ - **Tiempo de espera de repetición (minutos)**: intervalo mínimo antes de que el mismo objeto pueda volver a avisar.
133
+ - **Archivo máximo de memoria del hogar (KB)**: límite estricto de 64 a 1.024 KB; 256 KB por defecto.
57
134
  - Si el archivo en disco esta activo, **Ask** lo usa por defecto: respeta fechas/rangos explicitos y, si no los indicas, busca en las ultimas 24 horas mas los eventos actuales en RAM.
58
135
  - **Include raw payload hex**: incluye payload hex raw en el prompt.
59
136
  - **Incluir inventario del proyecto Node-RED**: incluye en el prompt el inventario de todo el proyecto Node-RED, con nodos KNX y otros nodos utiles como function/change/inject/template cuando contienen logica KNX o direcciones de grupo.
@@ -84,5 +161,5 @@ Aquí tienes todos los campos tal como se muestran en el editor de KNX AI.
84
161
  - Si Node-RED se ejecuta en Docker, usa `host.docker.internal` en lugar de `localhost` en el endpoint.
85
162
 
86
163
  ## Nota de seguridad
87
- Si el LLM está habilitado, el contexto de tráfico KNX puede enviarse al endpoint configurado. Para privacidad on-premise, usa proveedores locales.
164
+ Si el LLM está habilitado, el contexto de tráfico KNX puede enviarse al endpoint configurado. Para privacidad on-premise, usa proveedores locales. Un comando emitido por la salida 4 superó la validación local y fue enviado al flow, pero no confirma que el actuador lo ejecutara. Usa una GA de estado KNX para confirmarlo.
88
165
  </script>