chimericmesh 0.2.2__py3-none-any.whl

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 (147) hide show
  1. chimericmesh/__init__.py +3 -0
  2. chimericmesh/__main__.py +119 -0
  3. chimericmesh/agent/__init__.py +21 -0
  4. chimericmesh/agent/codesearch.py +131 -0
  5. chimericmesh/agent/digest.py +131 -0
  6. chimericmesh/agent/errors.py +38 -0
  7. chimericmesh/agent/feed.py +47 -0
  8. chimericmesh/agent/limits.py +98 -0
  9. chimericmesh/agent/ports.py +32 -0
  10. chimericmesh/agent/routes.py +92 -0
  11. chimericmesh/agent/service.py +116 -0
  12. chimericmesh/agent/snippet.py +135 -0
  13. chimericmesh/agent/verify.py +215 -0
  14. chimericmesh/agent/watch.py +156 -0
  15. chimericmesh/api.py +626 -0
  16. chimericmesh/approvals/__init__.py +25 -0
  17. chimericmesh/approvals/errors.py +72 -0
  18. chimericmesh/approvals/format.py +76 -0
  19. chimericmesh/approvals/irc.py +54 -0
  20. chimericmesh/approvals/ledger.py +149 -0
  21. chimericmesh/approvals/limits.py +87 -0
  22. chimericmesh/approvals/manager.py +935 -0
  23. chimericmesh/approvals/matching.py +107 -0
  24. chimericmesh/approvals/models.py +251 -0
  25. chimericmesh/approvals/ports.py +36 -0
  26. chimericmesh/approvals/routes.py +220 -0
  27. chimericmesh/approvals/rulebook.py +337 -0
  28. chimericmesh/approvals/schema.py +64 -0
  29. chimericmesh/approvals/scope.py +104 -0
  30. chimericmesh/approvals/validate.py +215 -0
  31. chimericmesh/catalog/demo_apps.json +41 -0
  32. chimericmesh/catalog/legacy_apps.json +612 -0
  33. chimericmesh/commands.py +223 -0
  34. chimericmesh/connectors/__init__.py +1 -0
  35. chimericmesh/connectors/config.py +55 -0
  36. chimericmesh/connectors/framing.py +132 -0
  37. chimericmesh/connectors/limiter.py +42 -0
  38. chimericmesh/connectors/manager.py +252 -0
  39. chimericmesh/connectors/offsets.py +157 -0
  40. chimericmesh/connectors/schema.py +31 -0
  41. chimericmesh/connectors/submit.py +26 -0
  42. chimericmesh/connectors/syslog_tcp.py +141 -0
  43. chimericmesh/connectors/tailer.py +236 -0
  44. chimericmesh/connectors/tailread.py +288 -0
  45. chimericmesh/demo/__init__.py +1 -0
  46. chimericmesh/demo/agent.py +32 -0
  47. chimericmesh/demo/apps/__init__.py +1 -0
  48. chimericmesh/demo/apps/__main__.py +83 -0
  49. chimericmesh/demo/apps/common.py +163 -0
  50. chimericmesh/demo/apps/mail_bridge.py +48 -0
  51. chimericmesh/demo/apps/orders_api.py +31 -0
  52. chimericmesh/demo/apps/spooler.py +28 -0
  53. chimericmesh/demo/config.py +38 -0
  54. chimericmesh/demo/engine.py +68 -0
  55. chimericmesh/demo/env.py +46 -0
  56. chimericmesh/demo/hub.py +172 -0
  57. chimericmesh/demo/launcher.py +165 -0
  58. chimericmesh/demo/ports.py +44 -0
  59. chimericmesh/demo/routes.py +81 -0
  60. chimericmesh/demo/samples.py +32 -0
  61. chimericmesh/demo/scenario.py +95 -0
  62. chimericmesh/demo/supervisor.py +267 -0
  63. chimericmesh/demo/watch.py +46 -0
  64. chimericmesh/diagnostics.py +253 -0
  65. chimericmesh/discovery/__init__.py +17 -0
  66. chimericmesh/discovery/accept.py +131 -0
  67. chimericmesh/discovery/catalog.py +313 -0
  68. chimericmesh/discovery/collect.py +131 -0
  69. chimericmesh/discovery/dismissals.py +46 -0
  70. chimericmesh/discovery/engine.py +41 -0
  71. chimericmesh/discovery/errors.py +34 -0
  72. chimericmesh/discovery/expand.py +151 -0
  73. chimericmesh/discovery/manager.py +220 -0
  74. chimericmesh/discovery/match.py +177 -0
  75. chimericmesh/discovery/models.py +174 -0
  76. chimericmesh/discovery/parse.py +166 -0
  77. chimericmesh/discovery/probe.py +69 -0
  78. chimericmesh/discovery/routes.py +129 -0
  79. chimericmesh/discovery/runner.py +147 -0
  80. chimericmesh/discovery/schema.py +25 -0
  81. chimericmesh/discovery/text.py +53 -0
  82. chimericmesh/events.py +74 -0
  83. chimericmesh/fsperms.py +72 -0
  84. chimericmesh/hub.py +757 -0
  85. chimericmesh/listeners.py +162 -0
  86. chimericmesh/mcp_server.py +199 -0
  87. chimericmesh/mute/__init__.py +10 -0
  88. chimericmesh/mute/models.py +14 -0
  89. chimericmesh/mute/mutelist.py +51 -0
  90. chimericmesh/mute/routes.py +49 -0
  91. chimericmesh/mute/schema.py +29 -0
  92. chimericmesh/mute/store.py +94 -0
  93. chimericmesh/notify.py +47 -0
  94. chimericmesh/parsers/__init__.py +12 -0
  95. chimericmesh/parsers/formats.py +23 -0
  96. chimericmesh/parsers/irc.py +91 -0
  97. chimericmesh/parsers/logctx.py +143 -0
  98. chimericmesh/parsers/ncsa.py +57 -0
  99. chimericmesh/parsers/plain.py +17 -0
  100. chimericmesh/parsers/syslog.py +82 -0
  101. chimericmesh/parsers/syslogtext.py +62 -0
  102. chimericmesh/parsers/telnet.py +56 -0
  103. chimericmesh/parsers/w3c.py +58 -0
  104. chimericmesh/parsers/xferlog.py +31 -0
  105. chimericmesh/replay.py +108 -0
  106. chimericmesh/replay_irc.py +202 -0
  107. chimericmesh/services/__init__.py +39 -0
  108. chimericmesh/services/access.py +224 -0
  109. chimericmesh/services/asgi.py +107 -0
  110. chimericmesh/services/deps.py +42 -0
  111. chimericmesh/services/errors.py +49 -0
  112. chimericmesh/services/limiter.py +130 -0
  113. chimericmesh/services/models.py +160 -0
  114. chimericmesh/services/paths.py +139 -0
  115. chimericmesh/services/registry.py +638 -0
  116. chimericmesh/services/routes.py +161 -0
  117. chimericmesh/services/schema.py +48 -0
  118. chimericmesh/services/status.py +239 -0
  119. chimericmesh/services/tagging.py +63 -0
  120. chimericmesh/services/token.py +129 -0
  121. chimericmesh/services/validate.py +184 -0
  122. chimericmesh/store/__init__.py +43 -0
  123. chimericmesh/store/audit.py +89 -0
  124. chimericmesh/store/config.py +88 -0
  125. chimericmesh/store/connection.py +98 -0
  126. chimericmesh/store/errors.py +65 -0
  127. chimericmesh/store/events.py +430 -0
  128. chimericmesh/store/incidents.py +292 -0
  129. chimericmesh/store/migrations.py +109 -0
  130. chimericmesh/store/models.py +49 -0
  131. chimericmesh/store/ports.py +61 -0
  132. chimericmesh/store/proposals.py +215 -0
  133. chimericmesh/store/schema.py +102 -0
  134. chimericmesh/store/store.py +173 -0
  135. chimericmesh/store/tx.py +143 -0
  136. chimericmesh/store/writer.py +315 -0
  137. chimericmesh/web/__init__.py +1 -0
  138. chimericmesh/web/feed.py +212 -0
  139. chimericmesh/web/index.html +3775 -0
  140. chimericmesh/web/sse.py +74 -0
  141. chimericmesh/web/stream.py +64 -0
  142. chimericmesh-0.2.2.dist-info/METADATA +537 -0
  143. chimericmesh-0.2.2.dist-info/RECORD +147 -0
  144. chimericmesh-0.2.2.dist-info/WHEEL +5 -0
  145. chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
  146. chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
  147. chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,162 @@
1
+ """Asyncio listeners speaking the legacy protocols: Syslog/UDP, Telnet/TCP, IRC/TCP."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import re
8
+ import socket
9
+
10
+ from .commands import handle_command, parse_command
11
+ from .hub import Hub
12
+ from .services.access import OperatorVerdict, is_reserved_nick
13
+ from .store.proposals import is_reserved_decider
14
+ from .parsers import format_privmsg, irc_to_event, parse_irc_line, parse_syslog, telnet_to_event
15
+
16
+ log = logging.getLogger("chimericmesh.listeners")
17
+ MAX_READ = 4096
18
+ MAX_PASS = 200
19
+ _CTRL = re.compile(r"[\r\n\x00]")
20
+
21
+
22
+ class SyslogProtocol(asyncio.DatagramProtocol):
23
+ def __init__(self, hub: Hub) -> None:
24
+ self.hub = hub
25
+
26
+ def datagram_received(self, data: bytes, addr) -> None:
27
+ text = data.decode("utf-8", errors="replace")
28
+ for line in text.splitlines() or [text]:
29
+ if line.strip():
30
+ event = parse_syslog(line, default_host=addr[0])
31
+ asyncio.ensure_future(self.hub.ingest(event))
32
+
33
+
34
+ SYSLOG_RCVBUF = 4 * 1024 * 1024 # absorb bursts; the OS default drops datagrams early
35
+
36
+
37
+ async def start_syslog(hub: Hub, host: str, port: int):
38
+ loop = asyncio.get_running_loop()
39
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
40
+ try:
41
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SYSLOG_RCVBUF)
42
+ sock.bind((host, port))
43
+ sock.setblocking(False)
44
+ except OSError:
45
+ sock.close()
46
+ raise
47
+ transport, _ = await loop.create_datagram_endpoint(lambda: SyslogProtocol(hub), sock=sock)
48
+ return transport
49
+
50
+
51
+ async def start_telnet(hub: Hub, host: str, port: int) -> asyncio.Server:
52
+ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
53
+ peer = (writer.get_extra_info("peername") or ("telnet-peer",))[0]
54
+ writer.write(b"ChimericMesh telnet intake. Type a log line, ENTER to send.\r\n")
55
+ try:
56
+ while data := await reader.readline():
57
+ event = telnet_to_event(data[:MAX_READ], host=str(peer))
58
+ if event:
59
+ await hub.ingest(event)
60
+ writer.write(b"ack\r\n")
61
+ await writer.drain()
62
+ except (ConnectionError, asyncio.IncompleteReadError):
63
+ pass
64
+ finally:
65
+ writer.close()
66
+
67
+ return await asyncio.start_server(handle, host, port)
68
+
69
+
70
+ class IrcServer:
71
+ """A tiny IRC server: registration, JOIN, PING, PRIVMSG ingestion and broadcast."""
72
+
73
+ def __init__(self, hub: Hub, name: str = "chimeric.mesh") -> None:
74
+ self.hub, self.name = hub, name
75
+ self.clients: dict[asyncio.StreamWriter, dict] = {}
76
+ hub.irc_broadcast = self.broadcast
77
+
78
+ async def broadcast(self, channel: str, text: str) -> None:
79
+ for line in format_privmsg(channel, text):
80
+ for writer, info in list(self.clients.items()):
81
+ if channel in info["channels"]:
82
+ self._send(writer, f":ChimericBot!bot@{self.name} {line}")
83
+
84
+ def _send(self, writer: asyncio.StreamWriter, line: str) -> None:
85
+ try:
86
+ writer.write((line[:510] + "\r\n").encode())
87
+ except (ConnectionError, RuntimeError):
88
+ self.clients.pop(writer, None)
89
+
90
+ async def handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
91
+ info = {"nick": "*", "channels": set(), "registered": False, "pass_ok": False}
92
+ self.clients[writer] = info
93
+ try:
94
+ while data := await reader.readline():
95
+ line = data[:MAX_READ].decode("utf-8", errors="replace")
96
+ msg = parse_irc_line(line)
97
+ if msg is None:
98
+ continue
99
+ await self._dispatch(writer, info, msg, line)
100
+ await writer.drain()
101
+ except (ConnectionError, asyncio.IncompleteReadError):
102
+ pass
103
+ finally:
104
+ self.clients.pop(writer, None)
105
+ writer.close()
106
+
107
+ async def _dispatch(self, writer, info, msg, line: str) -> None:
108
+ cmd, params = msg.command, msg.params
109
+ enforce = self.hub.enforce_access
110
+ if cmd == "PASS" and params and enforce and not info["registered"]:
111
+ # The value is compared and dropped: never stored, echoed, logged or recorded.
112
+ access = self.hub.access
113
+ value = params[0]
114
+ info["pass_ok"] = bool(access is not None and len(value) <= MAX_PASS and access.verify_pass(value))
115
+ if not info["pass_ok"]:
116
+ self._send(writer, f":{self.name} 464 {info['nick']} :Password incorrect")
117
+ elif cmd == "NICK" and params:
118
+ nick = _CTRL.sub("", params[0])[:30]
119
+ if not nick:
120
+ self._send(writer, f":{self.name} 431 {info['nick']} :No nickname given")
121
+ return
122
+ if enforce and (is_reserved_nick(nick) or is_reserved_decider(nick)):
123
+ self._send(writer, f":{self.name} 433 {info['nick']} {nick} :Nickname is already in use")
124
+ return
125
+ info["nick"] = nick
126
+ if not info["registered"]:
127
+ info["registered"] = True
128
+ self._send(writer, f":{self.name} 001 {info['nick']} :Welcome to ChimericMesh")
129
+ elif cmd == "JOIN" and params:
130
+ for chan in params[0].split(","):
131
+ if chan.startswith("#"):
132
+ info["channels"].add(chan)
133
+ self._send(writer, f":{info['nick']}!u@h JOIN {chan}")
134
+ elif cmd == "PING":
135
+ self._send(writer, f":{self.name} PONG {self.name} :{params[0] if params else ''}")
136
+ elif cmd in {"PRIVMSG", "NOTICE"}:
137
+ # Never trust a client-supplied prefix: the sender is the registered nick.
138
+ if info["registered"] and len(params) >= 2:
139
+ if params[-1].startswith("!"):
140
+ # Commands are operator input, not log data: run, never ingest.
141
+ command = parse_command(params[-1])
142
+ if command is not None:
143
+ self.hub.record(info["nick"], params[-1], "user")
144
+ await handle_command(self.hub, info["nick"], params[0], command,
145
+ verdict=self._verdict(info))
146
+ return
147
+ tagged = f":{info['nick']}!u@h {cmd} {params[0]} :{params[-1]}"
148
+ event = irc_to_event(tagged)
149
+ if event:
150
+ await self.hub.ingest(event)
151
+ elif cmd == "QUIT":
152
+ raise ConnectionError
153
+
154
+ def _verdict(self, info: dict) -> OperatorVerdict | None:
155
+ """The operator verdict for this connection; ``None`` (baseline) while enforcement is off."""
156
+ access = self.hub.access
157
+ if not self.hub.enforce_access or access is None:
158
+ return None # off: baseline rule. On without access: handle_command fails closed.
159
+ return access.operator_verdict(info["nick"], operators=self.hub.operators, pass_ok=info["pass_ok"])
160
+
161
+ async def start(self, host: str, port: int) -> asyncio.Server:
162
+ return await asyncio.start_server(self.handle, host, port)
@@ -0,0 +1,199 @@
1
+ """MCP server: exposes the mesh to Kiro agents. Talks to the running hub over REST.
2
+
3
+ Run with: ``python -m chimericmesh.mcp_server`` (stdio transport).
4
+ Set CHIMERICMESH_URL if the hub is not at http://127.0.0.1:8000.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from typing import Any
11
+ from urllib.parse import quote
12
+
13
+ import httpx
14
+ from mcp.server.mcpserver import MCPServer
15
+
16
+ BASE_URL = os.environ.get("CHIMERICMESH_URL", "http://127.0.0.1:8000")
17
+
18
+ # Tests inject an ASGI-backed client here; production builds one per call.
19
+ _client_factory = lambda: httpx.AsyncClient(base_url=BASE_URL, timeout=10.0) # noqa: E731
20
+
21
+ mcp = MCPServer(
22
+ "chimericmesh",
23
+ instructions=(
24
+ "Bridge to legacy infrastructure (Syslog, IRC, Telnet). Remediation loop: "
25
+ "list_incidents -> investigate with get_incident and find_code_for_incident -> "
26
+ "propose_remediation (a human decides on IRC with !approve/!deny) -> poll get_proposal "
27
+ "until status is approved; never act while pending or denied -> do the work yourself "
28
+ "-> complete_proposal -> resolve_incident. The mesh never executes actions; it only "
29
+ "records the human decision. Use announce_to_irc for status messages. "
30
+ "To watch for work, call wait_for_work in a loop: it holds up to about 25 seconds and "
31
+ "returns incidents or approved proposals when there are any."
32
+ ),
33
+ )
34
+
35
+ WAIT_READ_TIMEOUT = 35.0 # wait_for_work holds the request up to 25 s; every other tool keeps the factory default
36
+
37
+
38
+ def _seg(value: str) -> str:
39
+ """One path segment: nothing in it can change the route."""
40
+ return quote(str(value), safe="")
41
+
42
+
43
+ def _error(resp: httpx.Response) -> dict[str, Any]:
44
+ try:
45
+ body = resp.json()
46
+ except ValueError:
47
+ return {"error": resp.status_code, "detail": resp.text}
48
+ if not isinstance(body, dict):
49
+ return {"error": resp.status_code, "detail": body}
50
+ return {**body, "error": resp.status_code, "detail": body.get("detail", resp.text)}
51
+
52
+
53
+ async def _call(method: str, path: str, timeout: float | None = None, **kwargs: Any) -> Any:
54
+ if timeout is not None:
55
+ kwargs["timeout"] = timeout
56
+ async with _client_factory() as client:
57
+ resp = await client.request(method, path, **kwargs)
58
+ if resp.status_code >= 400:
59
+ return _error(resp)
60
+ return resp.json()
61
+
62
+
63
+ @mcp.tool()
64
+ async def list_incidents() -> Any:
65
+ """List detected incidents across all legacy sources, most severe first."""
66
+ return await _call("GET", "/api/incidents")
67
+
68
+
69
+ @mcp.tool()
70
+ async def get_incident(incident_id: str) -> Any:
71
+ """Get one incident with hypothesis and remediation steps."""
72
+ return await _call("GET", f"/api/incidents/{incident_id}")
73
+
74
+
75
+ @mcp.tool()
76
+ async def find_code_for_incident(incident_id: str) -> Any:
77
+ """Search the configured code root for the source line that emits an incident's message."""
78
+ return await _call("GET", f"/api/incidents/{incident_id}/code")
79
+
80
+
81
+ @mcp.tool()
82
+ async def recent_events(limit: int = 25, source: str | None = None) -> Any:
83
+ """Recent raw events. source may be syslog, irc, or telnet."""
84
+ params: dict[str, Any] = {"limit": limit}
85
+ if source:
86
+ params["source"] = source
87
+ return await _call("GET", "/api/events", params=params)
88
+
89
+
90
+ @mcp.tool()
91
+ async def announce_to_irc(text: str, channel: str = "#ops") -> Any:
92
+ """Post a message to an IRC channel so legacy operators see agent findings."""
93
+ return await _call("POST", "/api/irc/say", json={"channel": channel, "text": text})
94
+
95
+
96
+ @mcp.tool()
97
+ async def resolve_incident(incident_id: str, note: str = "") -> Any:
98
+ """Mark an incident resolved and announce it on IRC."""
99
+ return await _call("POST", f"/api/incidents/{incident_id}/resolve", json={"note": note})
100
+
101
+
102
+ @mcp.tool()
103
+ async def propose_remediation(incident_id: str, action: str, details: str = "",
104
+ files: list[str] | None = None, estimated_lines: int | None = None,
105
+ verification: str | None = None, kind: str | None = None) -> Any:
106
+ """Ask the human operators to approve a remediation (announced on IRC). Does NOT run it.
107
+
108
+ Only act after get_proposal reports status "approved". files, estimated_lines, verification
109
+ and kind describe the planned change.
110
+ """
111
+ body: dict[str, Any] = {"incident_id": incident_id, "action": action, "details": details}
112
+ for key, value in (("files", files), ("estimated_lines", estimated_lines),
113
+ ("verification", verification), ("kind", kind)):
114
+ if value is not None:
115
+ body[key] = value
116
+ return await _call("POST", "/api/proposals", json=body)
117
+
118
+
119
+ @mcp.tool()
120
+ async def get_proposal(proposal_id: str) -> Any:
121
+ """Get a proposal's status: pending, approved, denied or done. Act only when approved."""
122
+ return await _call("GET", f"/api/proposals/{proposal_id}")
123
+
124
+
125
+ @mcp.tool()
126
+ async def list_proposals(status: str | None = None) -> Any:
127
+ """List proposals, optionally filtered by status (pending, approved, denied, done)."""
128
+ params = {"status": status} if status else None
129
+ return await _call("GET", "/api/proposals", params=params)
130
+
131
+
132
+ @mcp.tool()
133
+ async def complete_proposal(proposal_id: str, note: str = "", files_changed: list[str] | None = None,
134
+ lines_changed: int | None = None, verification_result: str | None = None) -> Any:
135
+ """Report that an approved proposal's work is finished (announced on IRC)."""
136
+ body: dict[str, Any] = {"note": note}
137
+ for key, value in (("files_changed", files_changed), ("lines_changed", lines_changed),
138
+ ("verification_result", verification_result)):
139
+ if value is not None:
140
+ body[key] = value
141
+ return await _call("POST", f"/api/proposals/{proposal_id}/complete", json=body)
142
+
143
+
144
+ @mcp.tool()
145
+ async def list_services() -> Any:
146
+ """List the registered services."""
147
+ return await _call("GET", "/api/services")
148
+
149
+
150
+ @mcp.tool()
151
+ async def get_service(service_id: str) -> Any:
152
+ """Get one service, including its code folder."""
153
+ return await _call("GET", f"/api/services/{_seg(service_id)}")
154
+
155
+
156
+ @mcp.tool()
157
+ async def service_events(service_id: str, limit: int = 25, after_id: int | None = None,
158
+ min_severity: int | None = None) -> Any:
159
+ """Events of one service, oldest first. Pass the last id back as after_id to page."""
160
+ params: dict[str, Any] = {"limit": limit}
161
+ if after_id is not None:
162
+ params["after_id"] = after_id
163
+ if min_severity is not None:
164
+ params["min_severity"] = min_severity
165
+ return await _call("GET", f"/api/services/{_seg(service_id)}/events", params=params)
166
+
167
+
168
+ @mcp.tool()
169
+ async def explain_log_window(service_id: str, minutes: int = 15) -> Any:
170
+ """Digest of one service's recent log window: counts, top signatures, samples."""
171
+ return await _call("GET", f"/api/services/{_seg(service_id)}/digest", params={"minutes": minutes})
172
+
173
+
174
+ @mcp.tool()
175
+ async def find_code_for_service(service_id: str, query: str) -> Any:
176
+ """Search a service's code folder for a literal text."""
177
+ return await _call("GET", f"/api/services/{_seg(service_id)}/code-search", params={"query": query})
178
+
179
+
180
+ @mcp.tool()
181
+ async def verify_proposal(proposal_id: str, files: list[str]) -> Any:
182
+ """Check that the files may be changed under a proposal. Change nothing unless ok is true."""
183
+ return await _call("POST", f"/api/proposals/{_seg(proposal_id)}/verify", json={"files": files})
184
+
185
+
186
+ @mcp.tool()
187
+ async def wait_for_work(timeout_seconds: int = 25, service_id: str | None = None,
188
+ exclude_ids: list[str] | None = None) -> Any:
189
+ """Wait up to about 25 seconds for incidents or approved proposals; status is work or timeout."""
190
+ params: dict[str, Any] = {"timeout_seconds": timeout_seconds}
191
+ if service_id is not None:
192
+ params["service_id"] = service_id
193
+ if exclude_ids:
194
+ params["exclude_ids"] = list(exclude_ids)
195
+ return await _call("GET", "/api/watch/next", timeout=WAIT_READ_TIMEOUT, params=params)
196
+
197
+
198
+ if __name__ == "__main__":
199
+ mcp.run()
@@ -0,0 +1,10 @@
1
+ """Mute: silence a service without deleting it. Dropped events are counted and nothing else.
2
+
3
+ This file imports no web framework; ``mute.routes`` is imported by ``api.py`` only.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ from .models import MutesNotMigrated, UnknownKey
8
+ from .mutelist import UNASSIGNED, MuteList
9
+
10
+ __all__ = ["UNASSIGNED", "MuteList", "MutesNotMigrated", "UnknownKey"]
@@ -0,0 +1,14 @@
1
+ """Mute errors."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class UnknownKey(Exception):
6
+ """The key is neither a service id nor ``unassigned`` (REST 404)."""
7
+
8
+ def __init__(self, key: str) -> None:
9
+ self.key = key
10
+ super().__init__(f"unknown service {key!r}")
11
+
12
+
13
+ class MutesNotMigrated(Exception):
14
+ """The store has no ``service_mutes`` table: mute stays off, like approvals without their tables."""
@@ -0,0 +1,51 @@
1
+ """The in-memory mute set and drop counters. Pure: no I/O, loop thread only (R3.2)."""
2
+ from __future__ import annotations
3
+
4
+ from collections import Counter
5
+
6
+ UNASSIGNED = "unassigned"
7
+
8
+
9
+ class MuteList:
10
+ """Muted keys (service id or ``unassigned``) with their start time, and a drop count per key.
11
+
12
+ The counter holds only a number: no message text and no sample of a dropped event.
13
+ """
14
+
15
+ def __init__(self) -> None:
16
+ self.muted: dict[str, float] = {}
17
+ self.dropped: Counter[str] = Counter()
18
+
19
+ def is_muted(self, key: str) -> bool:
20
+ return key in self.muted
21
+
22
+ def drop(self, key: str) -> bool:
23
+ """Count one event for ``key`` when it is muted. Returns whether the event must be dropped."""
24
+ if key not in self.muted:
25
+ return False
26
+ self.dropped[key] += 1
27
+ return True
28
+
29
+ def mute(self, key: str, now: float) -> bool:
30
+ """Returns False when the key was already muted (the first time is kept)."""
31
+ if key in self.muted:
32
+ return False
33
+ self.muted[key] = float(now)
34
+ return True
35
+
36
+ def unmute(self, key: str) -> bool:
37
+ return self.muted.pop(key, None) is not None
38
+
39
+ def forget(self, key: str) -> None:
40
+ """A deleted service leaves no mute and no counter."""
41
+ self.muted.pop(key, None)
42
+ self.dropped.pop(key, None)
43
+
44
+ def view(self, key: str) -> tuple[bool, int]:
45
+ return key in self.muted, self.dropped.get(key, 0)
46
+
47
+ def snapshot(self) -> dict:
48
+ return {
49
+ "muted": [{"service_id": k, "muted_at": t} for k, t in sorted(self.muted.items())],
50
+ "dropped": {k: n for k, n in sorted(self.dropped.items()) if n},
51
+ }
@@ -0,0 +1,49 @@
1
+ """REST routes of the mute module. The only file of the module that may import FastAPI.
2
+
3
+ Mute needs the admin token. Unmute does not: it only brings events back (the same side as pause and
4
+ revoke in auto-approval). A store failure is left to the app's ``StoreError`` handler (503).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Callable
9
+
10
+ from fastapi import APIRouter, Depends, Request
11
+ from fastapi.responses import JSONResponse
12
+
13
+ from chimericmesh.services.routes import default_actor
14
+
15
+ from .models import UnknownKey
16
+ from .store import MuteStore
17
+
18
+
19
+ def _answer(mutes: MuteStore, key: str) -> dict:
20
+ muted, dropped = mutes.mutes.view(key)
21
+ return {"service_id": key, "muted": muted, "events_dropped": dropped}
22
+
23
+
24
+ def build_router(mutes: MuteStore, require_admin: Callable,
25
+ *, audit_actor: Callable[[Request], str] = default_actor) -> APIRouter:
26
+ router = APIRouter()
27
+ not_found = JSONResponse({"detail": "not found"}, status_code=404)
28
+
29
+ @router.put("/api/services/{service_id}/mute", dependencies=[Depends(require_admin)])
30
+ async def mute(service_id: str, request: Request):
31
+ try:
32
+ await mutes.mute(service_id, audit_actor(request))
33
+ except UnknownKey:
34
+ return not_found
35
+ return _answer(mutes, service_id)
36
+
37
+ @router.delete("/api/services/{service_id}/mute")
38
+ async def unmute(service_id: str, request: Request):
39
+ try:
40
+ await mutes.unmute(service_id, audit_actor(request))
41
+ except UnknownKey:
42
+ return not_found
43
+ return _answer(mutes, service_id)
44
+
45
+ @router.get("/api/mutes")
46
+ async def list_mutes():
47
+ return mutes.mutes.snapshot()
48
+
49
+ return router
@@ -0,0 +1,29 @@
1
+ """Migration ``mute:0700-service-mutes``: the only table this module adds.
2
+
3
+ The design text says ``0100``, but version 100 is the services block, so mute has its own block 700-799.
4
+ The key has no foreign key: ``unassigned`` is not a service row. Deleting a service removes its row
5
+ through a services subscription, in the same transaction.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from chimericmesh.services.schema import services_registry
10
+ from chimericmesh.store.migrations import MigrationRegistry
11
+
12
+ MUTES_DDL: tuple[str, ...] = (
13
+ """CREATE TABLE service_mutes (
14
+ service_id TEXT PRIMARY KEY CHECK (length(service_id) BETWEEN 1 AND 40),
15
+ muted_at REAL NOT NULL,
16
+ actor TEXT NOT NULL
17
+ )""",
18
+ )
19
+
20
+
21
+ def register_migrations(registry: MigrationRegistry) -> None:
22
+ registry.register("mute", 700, "mute:0700-service-mutes", MUTES_DDL)
23
+
24
+
25
+ def mute_registry() -> MigrationRegistry:
26
+ """Core, services and mute migrations."""
27
+ registry = services_registry()
28
+ register_migrations(registry)
29
+ return registry
@@ -0,0 +1,94 @@
1
+ """Mute persistence: the write commits first, memory changes after (R3.4).
2
+
3
+ Every SQL statement is a string literal with ``?`` parameters. A failed write raises the store's
4
+ error and leaves the in-memory list as it was. Audit rows carry the actor and the key, nothing else.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import weakref
9
+
10
+ from chimericmesh.services.models import ServiceChange
11
+ from chimericmesh.services.registry import ServiceRegistry
12
+ from chimericmesh.store import Store, Tx
13
+
14
+ from .models import MutesNotMigrated, UnknownKey
15
+ from .mutelist import UNASSIGNED, MuteList
16
+
17
+ _HAS_TABLE = "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'service_mutes'"
18
+ _SELECT_ALL = "SELECT service_id, muted_at FROM service_mutes"
19
+ _SERVICE_EXISTS = "SELECT 1 FROM services WHERE id = ?"
20
+ _INSERT = "INSERT OR IGNORE INTO service_mutes (service_id, muted_at, actor) VALUES (?, ?, ?)"
21
+ _DELETE = "DELETE FROM service_mutes WHERE service_id = ?"
22
+
23
+
24
+ class MuteStore:
25
+ def __init__(self, store: Store, mutes: MuteList | None = None) -> None:
26
+ # Weak, like the registry's: the hub holds ``gate``, and a strong store reference here would keep a
27
+ # private ``:memory:`` store (and its writer thread) alive after the app that owns it is dropped.
28
+ self._store_ref = weakref.ref(store)
29
+ self.mutes = mutes if mutes is not None else MuteList()
30
+
31
+ @classmethod
32
+ def load(cls, store: Store) -> "MuteStore":
33
+ """Read every stored mute once, at start. Blocks once, like the other loaders."""
34
+ def read(tx: Tx) -> list[tuple[str, float]] | None:
35
+ if tx.one(_HAS_TABLE) is None:
36
+ return None
37
+ return [(r["service_id"], float(r["muted_at"])) for r in tx.all(_SELECT_ALL)]
38
+ rows = store.read_sync(read, allow_blocking=True)
39
+ if rows is None:
40
+ raise MutesNotMigrated("open the store with mute.schema.register_migrations")
41
+ mutes = MuteList()
42
+ for key, at in rows:
43
+ mutes.mute(key, at)
44
+ return cls(store, mutes)
45
+
46
+ @property
47
+ def _store(self) -> Store:
48
+ store = self._store_ref()
49
+ if store is None:
50
+ raise RuntimeError("the mute store was used after its store was dropped")
51
+ return store
52
+
53
+ def attach(self, registry: ServiceRegistry) -> None:
54
+ """Deleting a service removes its mute row in the same transaction, then its memory entry."""
55
+ registry.subscribe(on_service_deleted=self._on_deleted, after_commit=self._after_commit, name="mute")
56
+
57
+ @staticmethod
58
+ def _on_deleted(tx: Tx, change: ServiceChange) -> None:
59
+ tx.execute(_DELETE, (change.service_id,))
60
+
61
+ def _after_commit(self, change: ServiceChange) -> None:
62
+ if change.kind == "service_deleted":
63
+ self.mutes.forget(change.service_id)
64
+
65
+ async def mute(self, key: str, actor: str) -> bool:
66
+ """True when this call changed the state. Raises ``UnknownKey`` or the store's error."""
67
+ now = float(self._store.now())
68
+
69
+ def work(tx: Tx) -> bool:
70
+ if key != UNASSIGNED and tx.one(_SERVICE_EXISTS, (key,)) is None:
71
+ raise UnknownKey(key)
72
+ if tx.execute(_INSERT, (key, now, actor)).rowcount != 1:
73
+ return False
74
+ self._store.audit.append_tx(tx, actor, "service_muted", key, service_id=key)
75
+ return True
76
+ changed = await self._store.transact(work)
77
+ self.mutes.mute(key, now)
78
+ return changed
79
+
80
+ async def unmute(self, key: str, actor: str) -> bool:
81
+ def work(tx: Tx) -> bool:
82
+ if key != UNASSIGNED and tx.one(_SERVICE_EXISTS, (key,)) is None:
83
+ raise UnknownKey(key)
84
+ if tx.execute(_DELETE, (key,)).rowcount != 1:
85
+ return False
86
+ self._store.audit.append_tx(tx, actor, "service_unmuted", key, service_id=key)
87
+ return True
88
+ changed = await self._store.transact(work)
89
+ self.mutes.unmute(key)
90
+ return changed
91
+
92
+ def gate(self, event) -> bool:
93
+ """The ``Hub.gate`` callable: True means drop. One dict lookup on the hot path."""
94
+ return self.mutes.drop(event.service_id or UNASSIGNED)
chimericmesh/notify.py ADDED
@@ -0,0 +1,47 @@
1
+ """Outbound notifications: modern webhooks and legacy IRC announcements."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from urllib.parse import urlparse
6
+
7
+ import httpx
8
+
9
+ from .diagnostics import Incident
10
+ from .events import SEVERITY_NAMES
11
+
12
+
13
+ def webhook_payload(incident: Incident, event_type: str = "incident.opened") -> dict:
14
+ return {
15
+ "type": event_type,
16
+ "incident": incident.to_dict(),
17
+ "severity_name": SEVERITY_NAMES[incident.severity],
18
+ "text": irc_summary(incident),
19
+ }
20
+
21
+
22
+ def irc_summary(incident: Incident) -> str:
23
+ return (
24
+ f"[{SEVERITY_NAMES[incident.severity].upper()}] {incident.category} on {incident.host} "
25
+ f"x{incident.count} (id {incident.id}): {incident.hypothesis}"
26
+ )
27
+
28
+
29
+ def is_safe_webhook_url(url: str) -> bool:
30
+ parsed = urlparse(url)
31
+ return parsed.scheme in {"http", "https"} and bool(parsed.hostname)
32
+
33
+
34
+ async def send_webhook(url: str, payload: dict, client: httpx.AsyncClient | None = None) -> bool:
35
+ """POST JSON to ``url``. Returns True on 2xx. Never raises on network errors."""
36
+ if not is_safe_webhook_url(url):
37
+ return False
38
+ owns = client is None
39
+ client = client or httpx.AsyncClient(timeout=5.0)
40
+ try:
41
+ resp = await client.post(url, json=payload)
42
+ return resp.is_success
43
+ except httpx.HTTPError:
44
+ return False
45
+ finally:
46
+ if owns:
47
+ await client.aclose()
@@ -0,0 +1,12 @@
1
+ from .irc import format_privmsg, irc_to_event, parse_irc_line
2
+ from .syslog import parse_syslog
3
+ from .telnet import strip_telnet, telnet_to_event
4
+
5
+ __all__ = [
6
+ "format_privmsg",
7
+ "irc_to_event",
8
+ "parse_irc_line",
9
+ "parse_syslog",
10
+ "strip_telnet",
11
+ "telnet_to_event",
12
+ ]