halyn 0.2.3__tar.gz → 0.3.1__tar.gz

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 (53) hide show
  1. halyn-0.3.1/PKG-INFO +178 -0
  2. halyn-0.3.1/README.md +142 -0
  3. {halyn-0.2.3 → halyn-0.3.1}/pyproject.toml +3 -2
  4. halyn-0.3.1/src/halyn/integrations/telegram.py +193 -0
  5. halyn-0.3.1/src/halyn/mcp_serve.py +378 -0
  6. halyn-0.3.1/src/halyn/py.typed +0 -0
  7. halyn-0.3.1/src/halyn.egg-info/PKG-INFO +178 -0
  8. {halyn-0.2.3 → halyn-0.3.1}/src/halyn.egg-info/SOURCES.txt +3 -0
  9. {halyn-0.2.3 → halyn-0.3.1}/src/halyn.egg-info/entry_points.txt +1 -0
  10. {halyn-0.2.3 → halyn-0.3.1}/tests/test_halyn.py +1 -1
  11. halyn-0.2.3/PKG-INFO +0 -247
  12. halyn-0.2.3/README.md +0 -211
  13. halyn-0.2.3/src/halyn.egg-info/PKG-INFO +0 -247
  14. {halyn-0.2.3 → halyn-0.3.1}/LICENSE +0 -0
  15. {halyn-0.2.3 → halyn-0.3.1}/setup.cfg +0 -0
  16. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/__init__.py +0 -0
  17. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/__main__.py +0 -0
  18. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/audit.py +0 -0
  19. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/auth.py +0 -0
  20. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/autonomy.py +0 -0
  21. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/cli.py +0 -0
  22. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/config.py +0 -0
  23. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/consent.py +0 -0
  24. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/control_plane.py +0 -0
  25. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/discovery.py +0 -0
  26. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/__init__.py +0 -0
  27. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/browser.py +0 -0
  28. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/dds.py +0 -0
  29. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/docker.py +0 -0
  30. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/http_auto.py +0 -0
  31. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/mqtt.py +0 -0
  32. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/opcua.py +0 -0
  33. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/ros2.py +0 -0
  34. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/serial.py +0 -0
  35. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/socket_raw.py +0 -0
  36. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/ssh.py +0 -0
  37. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/unitree.py +0 -0
  38. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/drivers/websocket.py +0 -0
  39. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/engine.py +0 -0
  40. {halyn-0.2.3/src/halyn/memory → halyn-0.3.1/src/halyn/integrations}/__init__.py +0 -0
  41. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/intent.py +0 -0
  42. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/llm.py +0 -0
  43. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/mcp.py +0 -0
  44. /halyn-0.2.3/src/halyn/py.typed → /halyn-0.3.1/src/halyn/memory/__init__.py +0 -0
  45. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/memory/store.py +0 -0
  46. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/nrp_bridge.py +0 -0
  47. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/sanitizer.py +0 -0
  48. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/server.py +0 -0
  49. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/types.py +0 -0
  50. {halyn-0.2.3 → halyn-0.3.1}/src/halyn/watchdog.py +0 -0
  51. {halyn-0.2.3 → halyn-0.3.1}/src/halyn.egg-info/dependency_links.txt +0 -0
  52. {halyn-0.2.3 → halyn-0.3.1}/src/halyn.egg-info/requires.txt +0 -0
  53. {halyn-0.2.3 → halyn-0.3.1}/src/halyn.egg-info/top_level.txt +0 -0
halyn-0.3.1/PKG-INFO ADDED
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: halyn
3
+ Version: 0.3.1
4
+ Summary: Halyn — NRP control plane with domain-scoped authorization.
5
+ Author-email: Elmadani SALKA <contact@halyn.dev>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/ElmadaniS/halyn
8
+ Project-URL: Repository, https://github.com/ElmadaniS/halyn
9
+ Project-URL: Issues, https://github.com/ElmadaniS/halyn/issues
10
+ Keywords: ai,browser,robotics,iot,mcp,nrp,llm,infrastructure,devops
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: Topic :: System :: Systems Administration
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: nrprotocol>=0.1.0
20
+ Requires-Dist: aiohttp>=3.9
21
+ Provides-Extra: enterprise
22
+ Requires-Dist: grpcio>=1.60; extra == "enterprise"
23
+ Requires-Dist: psycopg2-binary; extra == "enterprise"
24
+ Requires-Dist: redis; extra == "enterprise"
25
+ Provides-Extra: robotics
26
+ Requires-Dist: rclpy; extra == "robotics"
27
+ Requires-Dist: unitree-sdk2py; extra == "robotics"
28
+ Provides-Extra: iot
29
+ Requires-Dist: paho-mqtt; extra == "iot"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest; extra == "dev"
32
+ Requires-Dist: pytest-asyncio; extra == "dev"
33
+ Requires-Dist: mypy; extra == "dev"
34
+ Requires-Dist: ruff; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ <div align="center">
38
+
39
+ # Halyn
40
+
41
+ **Connect any device to any AI.**
42
+
43
+ [![PyPI](https://img.shields.io/pypi/v/halyn?style=flat-square&color=0a6e3f)](https://pypi.org/project/halyn/)
44
+ [![License](https://img.shields.io/badge/license-MIT-0a6e3f?style=flat-square)](LICENSE)
45
+ [![Python](https://img.shields.io/badge/python-3.10+-0a6e3f?style=flat-square)](https://pypi.org/project/halyn/)
46
+
47
+ MCP Server · 12 drivers · Shield rules · Audit chain · 5 autonomy levels
48
+
49
+ [Website](https://halyn.dev) · [Quickstart](#quickstart) · [MCP Server](#mcp-server) · [Tutorials](https://halyn.dev#tutorials)
50
+
51
+ </div>
52
+
53
+ ---
54
+
55
+ ## The Problem
56
+
57
+ MCP connects AI to software. But AI is entering the physical world — robots, drones, factories, farms, hospitals. There's no universal standard for how AI safely controls hardware.
58
+
59
+ **Halyn connects AI to everything else.** Servers, sensors, robots, industrial machines, smart homes — with safety rules the AI cannot break.
60
+
61
+ ## Quickstart
62
+
63
+ ```bash
64
+ pip install halyn
65
+ ```
66
+
67
+ ```python
68
+ from halyn import ControlPlane, SSHDriver
69
+
70
+ cp = ControlPlane()
71
+ cp.connect(SSHDriver("192.168.1.10", "admin"))
72
+
73
+ # Safety rules — the AI physically cannot bypass these
74
+ cp.shield("deny * delete *")
75
+ cp.shield("deny * write /etc/*")
76
+
77
+ # Observe
78
+ state = cp.observe()
79
+ print(state) # {"cpu": 23.4, "mem": 67.2, ...}
80
+
81
+ # Act (within shield rules)
82
+ cp.act("restart nginx") # ✓ allowed
83
+ cp.act("rm -rf /etc") # ✗ blocked by shield
84
+ ```
85
+
86
+ ## MCP Server
87
+
88
+ Connect Claude.ai, ChatGPT, Cursor, or any MCP client directly to your devices:
89
+
90
+ ```bash
91
+ # Start the MCP Server
92
+ halyn-mcp --port 8935
93
+
94
+ # In Claude.ai → Settings → MCP → Add Server
95
+ # URL: http://your-server:8935/mcp
96
+ ```
97
+
98
+ Then just talk:
99
+ - *"Show me the status of all connected devices"*
100
+ - *"What's the temperature in the greenhouse?"*
101
+ - *"Restart nginx on server-01"*
102
+ - *"Show me the audit trail"*
103
+
104
+ The AI sees your devices as tools. Shield rules still apply. Every action is audited.
105
+
106
+ ## 12 Drivers
107
+
108
+ | Driver | Target | Protocol |
109
+ |--------|--------|----------|
110
+ | `SSHDriver` | Linux/Mac servers | SSH |
111
+ | `HTTPDriver` | REST APIs, webhooks | HTTP |
112
+ | `WebSocketDriver` | Real-time streams | WebSocket |
113
+ | `SerialDriver` | Arduino, Pi, PLCs | Serial |
114
+ | `MQTTDriver` | IoT sensors | MQTT |
115
+ | `OPCUADriver` | Industrial machines | OPC-UA |
116
+ | `ROS2Driver` | Robots, drones | ROS2/DDS |
117
+ | `DDSDriver` | Real-time systems | DDS |
118
+ | `DockerDriver` | Containers | Docker API |
119
+ | `BrowserDriver` | Web automation | Chrome CDP |
120
+ | `UnitreeDriver` | Unitree robots | UDP |
121
+ | `SocketDriver` | Raw TCP/UDP | Socket |
122
+
123
+ ## Safety
124
+
125
+ **Shield Rules** — Constraints enforced at protocol level. The AI has no power to override them.
126
+
127
+ ```python
128
+ cp.shield("deny * delete *") # no deletions
129
+ cp.shield("deny * write temperature > 180") # thermal limit
130
+ cp.shield("deny lock unlock between 23:00-06:00") # doors locked at night
131
+ ```
132
+
133
+ **Audit Chain** — Every action recorded in SHA-256 hash chain. Tamper-evident. Append-only.
134
+
135
+ **Consent Protocol** — Devices and AI negotiate permissions before any interaction.
136
+
137
+ **5 Autonomy Levels** — From fully manual to fully autonomous. You choose.
138
+
139
+ | Level | Name | Who Decides |
140
+ |-------|------|-------------|
141
+ | 0 | Manual | Human does everything |
142
+ | 1 | Advisory | AI suggests, human acts |
143
+ | 2 | Supervised | AI acts, human approves |
144
+ | 3 | Monitored | AI acts freely, human watches |
145
+ | 4 | Autonomous | AI decides within shield rules |
146
+
147
+ ## Works with Every LLM
148
+
149
+ ```python
150
+ # Claude
151
+ import anthropic
152
+ client = anthropic.Anthropic()
153
+ response = client.messages.create(model="claude-sonnet-4-6", ...)
154
+ cp.act(response.content[0].text)
155
+
156
+ # GPT
157
+ from openai import OpenAI
158
+ client = OpenAI()
159
+ response = client.chat.completions.create(model="gpt-5", ...)
160
+
161
+ # Local (Ollama — no internet needed)
162
+ import ollama
163
+ response = ollama.chat(model="llama4", ...)
164
+
165
+ # All use the same shield rules. Same audit chain.
166
+ ```
167
+
168
+ ## Built on NRP
169
+
170
+ Halyn implements [NRP (Node Reach Protocol)](https://nrprotocol.dev) — the open standard for AI-to-device communication. 6 primitives: Manifest, Observe, Act, Shield, Audit, Consent.
171
+
172
+ ## Free. Open Source. Forever.
173
+
174
+ MIT licensed. Use it for anything. Modify it. Build a company on it. No fees, no limits, no lock-in.
175
+
176
+ ---
177
+
178
+ [halyn.dev](https://halyn.dev) · [nrprotocol.dev](https://nrprotocol.dev) · [PyPI](https://pypi.org/project/halyn/) · [contact@halyn.dev](mailto:contact@halyn.dev)
halyn-0.3.1/README.md ADDED
@@ -0,0 +1,142 @@
1
+ <div align="center">
2
+
3
+ # Halyn
4
+
5
+ **Connect any device to any AI.**
6
+
7
+ [![PyPI](https://img.shields.io/pypi/v/halyn?style=flat-square&color=0a6e3f)](https://pypi.org/project/halyn/)
8
+ [![License](https://img.shields.io/badge/license-MIT-0a6e3f?style=flat-square)](LICENSE)
9
+ [![Python](https://img.shields.io/badge/python-3.10+-0a6e3f?style=flat-square)](https://pypi.org/project/halyn/)
10
+
11
+ MCP Server · 12 drivers · Shield rules · Audit chain · 5 autonomy levels
12
+
13
+ [Website](https://halyn.dev) · [Quickstart](#quickstart) · [MCP Server](#mcp-server) · [Tutorials](https://halyn.dev#tutorials)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## The Problem
20
+
21
+ MCP connects AI to software. But AI is entering the physical world — robots, drones, factories, farms, hospitals. There's no universal standard for how AI safely controls hardware.
22
+
23
+ **Halyn connects AI to everything else.** Servers, sensors, robots, industrial machines, smart homes — with safety rules the AI cannot break.
24
+
25
+ ## Quickstart
26
+
27
+ ```bash
28
+ pip install halyn
29
+ ```
30
+
31
+ ```python
32
+ from halyn import ControlPlane, SSHDriver
33
+
34
+ cp = ControlPlane()
35
+ cp.connect(SSHDriver("192.168.1.10", "admin"))
36
+
37
+ # Safety rules — the AI physically cannot bypass these
38
+ cp.shield("deny * delete *")
39
+ cp.shield("deny * write /etc/*")
40
+
41
+ # Observe
42
+ state = cp.observe()
43
+ print(state) # {"cpu": 23.4, "mem": 67.2, ...}
44
+
45
+ # Act (within shield rules)
46
+ cp.act("restart nginx") # ✓ allowed
47
+ cp.act("rm -rf /etc") # ✗ blocked by shield
48
+ ```
49
+
50
+ ## MCP Server
51
+
52
+ Connect Claude.ai, ChatGPT, Cursor, or any MCP client directly to your devices:
53
+
54
+ ```bash
55
+ # Start the MCP Server
56
+ halyn-mcp --port 8935
57
+
58
+ # In Claude.ai → Settings → MCP → Add Server
59
+ # URL: http://your-server:8935/mcp
60
+ ```
61
+
62
+ Then just talk:
63
+ - *"Show me the status of all connected devices"*
64
+ - *"What's the temperature in the greenhouse?"*
65
+ - *"Restart nginx on server-01"*
66
+ - *"Show me the audit trail"*
67
+
68
+ The AI sees your devices as tools. Shield rules still apply. Every action is audited.
69
+
70
+ ## 12 Drivers
71
+
72
+ | Driver | Target | Protocol |
73
+ |--------|--------|----------|
74
+ | `SSHDriver` | Linux/Mac servers | SSH |
75
+ | `HTTPDriver` | REST APIs, webhooks | HTTP |
76
+ | `WebSocketDriver` | Real-time streams | WebSocket |
77
+ | `SerialDriver` | Arduino, Pi, PLCs | Serial |
78
+ | `MQTTDriver` | IoT sensors | MQTT |
79
+ | `OPCUADriver` | Industrial machines | OPC-UA |
80
+ | `ROS2Driver` | Robots, drones | ROS2/DDS |
81
+ | `DDSDriver` | Real-time systems | DDS |
82
+ | `DockerDriver` | Containers | Docker API |
83
+ | `BrowserDriver` | Web automation | Chrome CDP |
84
+ | `UnitreeDriver` | Unitree robots | UDP |
85
+ | `SocketDriver` | Raw TCP/UDP | Socket |
86
+
87
+ ## Safety
88
+
89
+ **Shield Rules** — Constraints enforced at protocol level. The AI has no power to override them.
90
+
91
+ ```python
92
+ cp.shield("deny * delete *") # no deletions
93
+ cp.shield("deny * write temperature > 180") # thermal limit
94
+ cp.shield("deny lock unlock between 23:00-06:00") # doors locked at night
95
+ ```
96
+
97
+ **Audit Chain** — Every action recorded in SHA-256 hash chain. Tamper-evident. Append-only.
98
+
99
+ **Consent Protocol** — Devices and AI negotiate permissions before any interaction.
100
+
101
+ **5 Autonomy Levels** — From fully manual to fully autonomous. You choose.
102
+
103
+ | Level | Name | Who Decides |
104
+ |-------|------|-------------|
105
+ | 0 | Manual | Human does everything |
106
+ | 1 | Advisory | AI suggests, human acts |
107
+ | 2 | Supervised | AI acts, human approves |
108
+ | 3 | Monitored | AI acts freely, human watches |
109
+ | 4 | Autonomous | AI decides within shield rules |
110
+
111
+ ## Works with Every LLM
112
+
113
+ ```python
114
+ # Claude
115
+ import anthropic
116
+ client = anthropic.Anthropic()
117
+ response = client.messages.create(model="claude-sonnet-4-6", ...)
118
+ cp.act(response.content[0].text)
119
+
120
+ # GPT
121
+ from openai import OpenAI
122
+ client = OpenAI()
123
+ response = client.chat.completions.create(model="gpt-5", ...)
124
+
125
+ # Local (Ollama — no internet needed)
126
+ import ollama
127
+ response = ollama.chat(model="llama4", ...)
128
+
129
+ # All use the same shield rules. Same audit chain.
130
+ ```
131
+
132
+ ## Built on NRP
133
+
134
+ Halyn implements [NRP (Node Reach Protocol)](https://nrprotocol.dev) — the open standard for AI-to-device communication. 6 primitives: Manifest, Observe, Act, Shield, Audit, Consent.
135
+
136
+ ## Free. Open Source. Forever.
137
+
138
+ MIT licensed. Use it for anything. Modify it. Build a company on it. No fees, no limits, no lock-in.
139
+
140
+ ---
141
+
142
+ [halyn.dev](https://halyn.dev) · [nrprotocol.dev](https://nrprotocol.dev) · [PyPI](https://pypi.org/project/halyn/) · [contact@halyn.dev](mailto:contact@halyn.dev)
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "halyn"
3
- version = "0.2.3"
3
+ version = "0.3.1"
4
4
  description = "Halyn — NRP control plane with domain-scoped authorization."
5
5
  requires-python = ">=3.10"
6
6
  license = {text = "MIT"}
7
- authors = [{name = "Elmadani SALKA", email = "Elmadani.SALKA@proton.me"}]
7
+ authors = [{name = "Elmadani SALKA", email = "contact@halyn.dev"}]
8
8
  readme = "README.md"
9
9
  keywords = ["ai", "browser", "robotics", "iot", "mcp", "nrp", "llm", "infrastructure", "devops"]
10
10
  classifiers = [
@@ -27,6 +27,7 @@ iot = ["paho-mqtt"]
27
27
  dev = ["pytest", "pytest-asyncio", "mypy", "ruff"]
28
28
 
29
29
  [project.scripts]
30
+ halyn-mcp = "halyn.mcp_serve:main"
30
31
  halyn = "halyn.cli:main"
31
32
 
32
33
  [project.urls]
@@ -0,0 +1,193 @@
1
+ # Copyright (c) 2026 Elmadani SALKA. All rights reserved.
2
+ # Licensed under the MIT License. See LICENSE file.
3
+ """
4
+ Telegram integration — Halyn in your pocket.
5
+
6
+ Users interact with the control plane through Telegram.
7
+ Every message goes through the full pipeline:
8
+ auth > autonomy > shield > execute > audit > intent.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import json
15
+ import logging
16
+ import os
17
+ import time
18
+ from typing import Any
19
+
20
+ import aiohttp
21
+
22
+ log = logging.getLogger("halyn.telegram")
23
+
24
+ TELEGRAM_API = "https://api.telegram.org/bot{token}"
25
+
26
+
27
+ class TelegramBridge:
28
+ """
29
+ Bidirectional bridge between Telegram and the Halyn ControlPlane.
30
+ """
31
+
32
+ def __init__(self, control_plane, bot_token="", allowed_users=None):
33
+ self.cp = control_plane
34
+ self.token = bot_token or os.environ.get("HALYN_TELEGRAM_TOKEN", "")
35
+ self.allowed_users = set(allowed_users or [])
36
+ self._api = TELEGRAM_API.format(token=self.token)
37
+ self._session = None
38
+ self._offset = 0
39
+ self._running = False
40
+
41
+ async def start(self):
42
+ if not self.token:
43
+ log.warning("telegram: no token (set HALYN_TELEGRAM_TOKEN)")
44
+ return
45
+ self._session = aiohttp.ClientSession()
46
+ self._running = True
47
+ me = await self._call("getMe")
48
+ if me.get("ok"):
49
+ log.info("telegram.connected bot=@%s", me["result"].get("username"))
50
+ asyncio.create_task(self._poll_loop())
51
+
52
+ async def stop(self):
53
+ self._running = False
54
+ if self._session:
55
+ await self._session.close()
56
+
57
+ async def send(self, chat_id, text, parse_mode="Markdown"):
58
+ for chunk in [text[i:i+4000] for i in range(0, len(text), 4000)]:
59
+ await self._call("sendMessage", {"chat_id": chat_id, "text": chunk, "parse_mode": parse_mode})
60
+
61
+ async def _poll_loop(self):
62
+ while self._running:
63
+ try:
64
+ updates = await self._call("getUpdates", {"offset": self._offset, "timeout": 30})
65
+ if updates.get("ok"):
66
+ for u in updates.get("result", []):
67
+ self._offset = u["update_id"] + 1
68
+ await self._handle(u)
69
+ except asyncio.CancelledError:
70
+ break
71
+ except Exception as e:
72
+ log.error("telegram.poll: %s", e)
73
+ await asyncio.sleep(5)
74
+
75
+ async def _handle(self, update):
76
+ msg = update.get("message", {})
77
+ text = msg.get("text", "").strip()
78
+ chat_id = msg.get("chat", {}).get("id", 0)
79
+ user_id = msg.get("from", {}).get("id", 0)
80
+ username = msg.get("from", {}).get("username", "")
81
+ if not text or not chat_id:
82
+ return
83
+ if self.allowed_users and user_id not in self.allowed_users:
84
+ await self.send(chat_id, "Access denied.")
85
+ return
86
+ log.info("telegram.msg user=%s text=%s", username, text[:60])
87
+ if text.startswith("/"):
88
+ await self._cmd(chat_id, text, user_id, username)
89
+ else:
90
+ await self._natural(chat_id, text, user_id, username)
91
+
92
+ async def _cmd(self, chat_id, text, user_id, username):
93
+ cmd = text.split()[0].lower()
94
+ args = text[len(cmd):].strip()
95
+
96
+ if cmd == "/start":
97
+ s = self.cp.status()
98
+ await self.send(chat_id,
99
+ f"*Halyn Control Plane*\n"
100
+ f"Nodes: {s['nodes']} | Tools: {s['tools']}\n"
101
+ f"Audit: {s['audit_entries']} entries\n"
102
+ f"Watchdog: {s['watchdog']['overall']}\n\n"
103
+ f"Commands: /status /nodes /scan /audit /stop /resume\n"
104
+ f"Or type naturally: _check server load_")
105
+
106
+ elif cmd == "/status":
107
+ s = self.cp.status()
108
+ await self.send(chat_id,
109
+ f"*Status*\nNodes: {s['nodes']}\nTools: {s['tools']}\n"
110
+ f"Emergency: {s['emergency_stop']}\nAudit: {s['audit_entries']}\n"
111
+ f"Chain: {'valid' if s['audit_chain_valid'] else 'BROKEN'}\n"
112
+ f"Watchdog: {s['watchdog']['overall']}")
113
+
114
+ elif cmd == "/nodes":
115
+ nodes = []
116
+ for nid, m in self.cp._manifests.items():
117
+ nodes.append(f" {nid} ({len(m.observe)}ch, {len(m.act)}act)")
118
+ await self.send(chat_id, "*Nodes*\n" + "\n".join(nodes) if nodes else "No nodes.")
119
+
120
+ elif cmd == "/scan":
121
+ await self.send(chat_id, "Scanning...")
122
+ found = await self.cp.scan()
123
+ if found:
124
+ lines = [f"*Found {len(found)}:*"]
125
+ for n in found:
126
+ lines.append(f" {n.suggested_nrp_id} ({n.protocol})")
127
+ await self.send(chat_id, "\n".join(lines))
128
+ else:
129
+ await self.send(chat_id, "No devices found.")
130
+
131
+ elif cmd == "/audit":
132
+ entries = self.cp.audit.query(limit=5)
133
+ valid, count, info = self.cp.audit.verify_chain()
134
+ lines = [f"*Audit* ({count} entries, {info})"]
135
+ for e in entries:
136
+ lines.append(f" [{e.status}] {e.tool}")
137
+ await self.send(chat_id, "\n".join(lines))
138
+
139
+ elif cmd == "/stop":
140
+ await self.cp.emergency_stop()
141
+ await self.send(chat_id, "EMERGENCY STOP. All nodes halted.")
142
+
143
+ elif cmd == "/resume":
144
+ await self.cp.resume()
145
+ await self.send(chat_id, "Resumed.")
146
+
147
+ elif cmd == "/exec":
148
+ if not args:
149
+ await self.send(chat_id, "Usage: /exec tool_name {\"arg\": \"value\"}")
150
+ return
151
+ parts = args.split(" ", 1)
152
+ tool = parts[0]
153
+ tool_args = json.loads(parts[1]) if len(parts) > 1 else {}
154
+ result = await self.cp.execute(tool, tool_args, user_id=str(user_id),
155
+ intent_text=f"telegram:{username} /exec {tool}")
156
+ if result.ok:
157
+ await self.send(chat_id, f"```\n{json.dumps(result.data, indent=2, default=str)}\n```")
158
+ else:
159
+ await self.send(chat_id, f"Blocked: {result.error}")
160
+
161
+ async def _natural(self, chat_id, text, user_id, username):
162
+ tl = text.lower()
163
+ if any(w in tl for w in ["status", "health"]):
164
+ await self._cmd(chat_id, "/status", user_id, username); return
165
+ if any(w in tl for w in ["nodes", "devices"]):
166
+ await self._cmd(chat_id, "/nodes", user_id, username); return
167
+ if any(w in tl for w in ["scan", "discover"]):
168
+ await self._cmd(chat_id, "/scan", user_id, username); return
169
+ if any(w in tl for w in ["audit", "log", "trail"]):
170
+ await self._cmd(chat_id, "/audit", user_id, username); return
171
+ if any(w in tl for w in ["stop", "halt", "emergency"]):
172
+ await self._cmd(chat_id, "/stop", user_id, username); return
173
+
174
+ tools = sorted(self.cp.engine.registry.tool_names)
175
+ for tool in tools:
176
+ parts = tool.replace("/", " ").replace(".", " ").split()
177
+ if any(p in tl for p in parts if len(p) > 2):
178
+ result = await self.cp.execute(tool, {},
179
+ user_id=str(user_id), intent_text=f"telegram:{username}: {text}")
180
+ if result.ok:
181
+ await self.send(chat_id, f"```\n{json.dumps(result.data, indent=2, default=str)}\n```")
182
+ else:
183
+ await self.send(chat_id, f"Blocked: {result.error}")
184
+ return
185
+
186
+ await self.send(chat_id, f"{len(tools)} tools available. Try /nodes or /exec <tool>")
187
+
188
+ async def _call(self, method, data=None):
189
+ try:
190
+ async with self._session.post(f"{self._api}/{method}", json=data or {}) as r:
191
+ return await r.json()
192
+ except Exception as e:
193
+ return {"ok": False, "error": str(e)}