irmy-sdk 1.0.0__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.
irmy_sdk-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bendyna V. S.R.L.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.4
2
+ Name: irmy-sdk
3
+ Version: 1.0.0
4
+ Summary: SDK for building IRMy plugins
5
+ Author-email: "Bendyna V. S.R.L." <info@irmy.tech>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://irmy.tech
8
+ Project-URL: Documentation, https://irmy.tech/docs/
9
+ Project-URL: Source, https://github.com/IRMy-tech/irmy-sdk
10
+ Project-URL: Issues, https://github.com/IRMy-tech/irmy-sdk/issues
11
+ Project-URL: Changelog, https://github.com/IRMy-tech/irmy-sdk/blob/main/CHANGELOG.md
12
+ Keywords: irmy,plugin,sdk,incident-management,alerting
13
+ Classifier: Development Status :: 5 - Production/Stable
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: pydantic<3,>=2.13.5
25
+ Requires-Dist: irmy-events<2,>=1.0.0
26
+ Provides-Extra: test
27
+ Requires-Dist: pytest>=8; extra == "test"
28
+ Dynamic: license-file
29
+
30
+ # irmy-sdk
31
+
32
+ SDK for building IRMy plugins hosted by `plugin_management`.
33
+
34
+ Provides the base plugin contract, the manifest model plugins declare their
35
+ config/capabilities/rules against, the HostApi surface a plugin receives at
36
+ construction, and the request/response models for a plugin's inbound HTTP
37
+ endpoints. Intended for use by 3rd-party and in-house plugin authors.
38
+
39
+ ---
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install irmy-sdk
45
+ ```
46
+
47
+ Requires Python 3.12+ (plugins run on Python 3.13 in the host — see
48
+ [`docs/runtime.md`](irmy_sdk/docs/runtime.md)). The import package is `irmy_sdk`. It depends on
49
+ `pydantic` and `irmy-events` (routing keys / event category enums and event
50
+ payload models referenced by manifests and rules).
51
+
52
+ ---
53
+
54
+ ## Package layout
55
+
56
+ ```
57
+ irmy_sdk/
58
+ ├── base.py # BasePlugin, PluginHealthcheck, ActionResult
59
+ ├── manifest.py # PluginManifest, ConfigField, PluginCapability, Placement,
60
+ │ # InboundEndpoint, DefaultRule, DefaultRuleStep, ...
61
+ ├── response.py # Response
62
+ ├── inbound.py # InboundRequest, InboundResponse
63
+ ├── exceptions.py
64
+ │
65
+ └── hostApi/
66
+ ├── hostApi.py # HostApi — keystore, permanent_storage, host_methods, commands, platform
67
+ └── models.py
68
+ ```
69
+
70
+ ## Usage
71
+
72
+ Every plugin subclasses `BasePlugin` and implements `get_manifest()`:
73
+
74
+ ```python
75
+ from irmy_sdk import BasePlugin, PluginManifest, PluginHealthcheck
76
+
77
+ class MyPlugin(BasePlugin):
78
+ @classmethod
79
+ def get_manifest(cls) -> PluginManifest:
80
+ return PluginManifest(...)
81
+
82
+ async def get_health(self) -> PluginHealthcheck:
83
+ return PluginHealthcheck(healthy=True)
84
+ ```
85
+
86
+ An installed package can back several named **integrations** (e.g. two Slack
87
+ workspaces). The host creates one instance of your class per integration on
88
+ every replica, with that integration's `global_config` (resolved config values)
89
+ and its own `host_api` (namespaced access to a logger, keystore, permanent and
90
+ secret storage, read-side host methods, command publishing, and the
91
+ installation's public URLs) — see `hostApi/hostApi.py` and
92
+ [Packages and integrations](irmy_sdk/docs/overview.md#packages-and-integrations).
93
+ Keep integration state on the instance: module globals are shared by every
94
+ integration of the package.
95
+ Log through `self.log` (`self.log.info("posted", channel=channel_id)`): the lines reach the
96
+ host's log and, from the integration's log level up, the integration's log in the IRMy UI.
97
+
98
+ ## Documentation
99
+
100
+ - [`docs/overview.md`](irmy_sdk/docs/overview.md) — concepts: how this SDK, `plugin_management`, and `irmy_events` fit together, and reactions vs. manual actions.
101
+ - [`docs/writing_plugins.md`](irmy_sdk/docs/writing_plugins.md) — rules and checklist for building a plugin.
102
+ - [`docs/reference.md`](irmy_sdk/docs/reference.md) — field-by-field technical reference.
103
+ - [`docs/inbound.md`](irmy_sdk/docs/inbound.md) — exposing public HTTP endpoints to 3rd-party callers.
104
+ - [`docs/runtime.md`](irmy_sdk/docs/runtime.md) — the Python version and the libraries a plugin can import.
105
+ - [`docs/example_plugin.md`](irmy_sdk/docs/example_plugin.md) — a complete plugin, from manifest to `.zip`.
106
+ - [`docs/testing.md`](irmy_sdk/docs/testing.md) — testing a plugin with a fake HostApi.
107
+
108
+ ---
109
+
110
+ ## Development
111
+
112
+ ```bash
113
+ python3 -m venv venv
114
+ . venv/bin/activate
115
+ pip install -e ".[test]"
116
+ python -m pytest
117
+ ```
@@ -0,0 +1,88 @@
1
+ # irmy-sdk
2
+
3
+ SDK for building IRMy plugins hosted by `plugin_management`.
4
+
5
+ Provides the base plugin contract, the manifest model plugins declare their
6
+ config/capabilities/rules against, the HostApi surface a plugin receives at
7
+ construction, and the request/response models for a plugin's inbound HTTP
8
+ endpoints. Intended for use by 3rd-party and in-house plugin authors.
9
+
10
+ ---
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pip install irmy-sdk
16
+ ```
17
+
18
+ Requires Python 3.12+ (plugins run on Python 3.13 in the host — see
19
+ [`docs/runtime.md`](irmy_sdk/docs/runtime.md)). The import package is `irmy_sdk`. It depends on
20
+ `pydantic` and `irmy-events` (routing keys / event category enums and event
21
+ payload models referenced by manifests and rules).
22
+
23
+ ---
24
+
25
+ ## Package layout
26
+
27
+ ```
28
+ irmy_sdk/
29
+ ├── base.py # BasePlugin, PluginHealthcheck, ActionResult
30
+ ├── manifest.py # PluginManifest, ConfigField, PluginCapability, Placement,
31
+ │ # InboundEndpoint, DefaultRule, DefaultRuleStep, ...
32
+ ├── response.py # Response
33
+ ├── inbound.py # InboundRequest, InboundResponse
34
+ ├── exceptions.py
35
+ │
36
+ └── hostApi/
37
+ ├── hostApi.py # HostApi — keystore, permanent_storage, host_methods, commands, platform
38
+ └── models.py
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ Every plugin subclasses `BasePlugin` and implements `get_manifest()`:
44
+
45
+ ```python
46
+ from irmy_sdk import BasePlugin, PluginManifest, PluginHealthcheck
47
+
48
+ class MyPlugin(BasePlugin):
49
+ @classmethod
50
+ def get_manifest(cls) -> PluginManifest:
51
+ return PluginManifest(...)
52
+
53
+ async def get_health(self) -> PluginHealthcheck:
54
+ return PluginHealthcheck(healthy=True)
55
+ ```
56
+
57
+ An installed package can back several named **integrations** (e.g. two Slack
58
+ workspaces). The host creates one instance of your class per integration on
59
+ every replica, with that integration's `global_config` (resolved config values)
60
+ and its own `host_api` (namespaced access to a logger, keystore, permanent and
61
+ secret storage, read-side host methods, command publishing, and the
62
+ installation's public URLs) — see `hostApi/hostApi.py` and
63
+ [Packages and integrations](irmy_sdk/docs/overview.md#packages-and-integrations).
64
+ Keep integration state on the instance: module globals are shared by every
65
+ integration of the package.
66
+ Log through `self.log` (`self.log.info("posted", channel=channel_id)`): the lines reach the
67
+ host's log and, from the integration's log level up, the integration's log in the IRMy UI.
68
+
69
+ ## Documentation
70
+
71
+ - [`docs/overview.md`](irmy_sdk/docs/overview.md) — concepts: how this SDK, `plugin_management`, and `irmy_events` fit together, and reactions vs. manual actions.
72
+ - [`docs/writing_plugins.md`](irmy_sdk/docs/writing_plugins.md) — rules and checklist for building a plugin.
73
+ - [`docs/reference.md`](irmy_sdk/docs/reference.md) — field-by-field technical reference.
74
+ - [`docs/inbound.md`](irmy_sdk/docs/inbound.md) — exposing public HTTP endpoints to 3rd-party callers.
75
+ - [`docs/runtime.md`](irmy_sdk/docs/runtime.md) — the Python version and the libraries a plugin can import.
76
+ - [`docs/example_plugin.md`](irmy_sdk/docs/example_plugin.md) — a complete plugin, from manifest to `.zip`.
77
+ - [`docs/testing.md`](irmy_sdk/docs/testing.md) — testing a plugin with a fake HostApi.
78
+
79
+ ---
80
+
81
+ ## Development
82
+
83
+ ```bash
84
+ python3 -m venv venv
85
+ . venv/bin/activate
86
+ pip install -e ".[test]"
87
+ python -m pytest
88
+ ```
@@ -0,0 +1,14 @@
1
+ from irmy_sdk.base import BasePlugin, PluginHealthcheck, ActionResult, ActionState
2
+ from irmy_sdk.manifest import (
3
+ PluginManifest, FieldType, Handler, ConfigField, PluginCapability, Placement, InboundEndpoint,
4
+ DefaultRule, DefaultRuleStep, RuleOwner, RuleOwnerType, InstructionPlaceholder, render_instructions,
5
+ MAX_CAPABILITY_TIMEOUT_SECONDS,
6
+ )
7
+ from irmy_sdk.response import Response
8
+ from irmy_sdk.inbound import InboundRequest, InboundResponse
9
+
10
+ __all__ = ["BasePlugin", "PluginManifest", "PluginHealthcheck", "ActionResult", "ActionState",
11
+ "FieldType", "Handler", "ConfigField", "PluginCapability", "Placement",
12
+ "InboundEndpoint", "InboundRequest", "InboundResponse", "Response",
13
+ "DefaultRule", "DefaultRuleStep", "RuleOwner", "RuleOwnerType",
14
+ "InstructionPlaceholder", "render_instructions", "MAX_CAPABILITY_TIMEOUT_SECONDS"]
@@ -0,0 +1,107 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional, Any, TYPE_CHECKING
3
+ from pydantic import BaseModel
4
+
5
+ from irmy_sdk.manifest import PluginManifest
6
+
7
+ if TYPE_CHECKING:
8
+ from irmy_sdk.hostApi.hostApi import HostApi, PluginLogger
9
+
10
+
11
+ class PluginHealthcheck(BaseModel):
12
+ """Result of ``BasePlugin.get_health()``. ``healthy=False`` marks the plugin
13
+ replica FAILED; ``error_message`` explains why (surfaced in the admin API)."""
14
+
15
+ healthy: bool
16
+ error_message: Optional[str] = None
17
+
18
+
19
+ class ActionResult(BaseModel):
20
+ """Outcome a manual-action / verify handler returns to the host UI.
21
+ ``success`` drives the success/failure banner, ``message`` is the shown text,
22
+ and ``details`` carries optional structured extras for display."""
23
+
24
+ success: bool
25
+ message: Optional[str] = None
26
+ details: Optional[dict[str, Any]] = None
27
+
28
+
29
+ class ActionState(BaseModel):
30
+ """What a manual action looks like for one target right now (e.g. one
31
+ incident), returned by a capability's ``state_handler`` so the host UI can
32
+ show it next to -- or instead of -- the action's button.
33
+
34
+ ``done``: the action's effect already exists for this target (e.g. the
35
+ incident's Slack channel was created) -- the UI shows ``message`` / ``url``
36
+ rather than offering the button again. ``available``: whether the action
37
+ can be run now (False greys the button out, ``message`` saying why).
38
+ ``url``: where the result lives (e.g. the channel), shown as a link."""
39
+
40
+ done: bool = False
41
+ available: bool = True
42
+ message: Optional[str] = None
43
+ url: Optional[str] = None
44
+
45
+
46
+ class BasePlugin(ABC):
47
+
48
+ def __init__(self, global_config: dict[str, Any], host_api: "HostApi") -> None:
49
+ """Canonical plugin constructor.
50
+
51
+ The host creates one instance per integration (named instance of the
52
+ plugin) on every replica, always with exactly these two arguments:
53
+
54
+ - ``global_config`` — that integration's resolved global config
55
+ (init-time secrets/URLs), never present in event payloads. A field
56
+ with no saved value and no ``default`` is absent from the dict.
57
+ - ``host_api`` — a per-integration HostApi granting namespaced access
58
+ to platform capabilities (keystore, host methods, ...).
59
+
60
+ Keep integration state on the instance or in the HostApi stores:
61
+ module globals and class attributes are shared by every integration
62
+ of the package in the process.
63
+
64
+ Subclasses may override this to unpack ``global_config`` into their own
65
+ attributes, but should call ``super().__init__(global_config, host_api)``
66
+ so ``self.global_config`` / ``self.host_api`` stay available.
67
+ """
68
+ self.global_config = global_config
69
+ self.host_api = host_api
70
+
71
+ @property
72
+ def log(self) -> "PluginLogger":
73
+ """This plugin's logger -- ``host_api.logger``:
74
+ ``self.log.info("posted", channel=channel_id)``. Its lines go to the
75
+ host's log and, from the integration's log level up, to the
76
+ integration's log in the IRMy UI."""
77
+ return self.host_api.logger
78
+
79
+ @classmethod
80
+ @abstractmethod
81
+ def get_manifest(cls) -> PluginManifest:
82
+ """Return the plugin's static contract (``PluginManifest``): its identity,
83
+ config schemas, event reactions, manual actions and published commands.
84
+
85
+ Called at load time **before** any instance exists (hence a classmethod).
86
+ Building the manifest is itself the validation step — an invalid manifest
87
+ raises here — so the host rejects a bad plugin before running it.
88
+ """
89
+ raise NotImplementedError("Method `get_manifest()` not implemented")
90
+
91
+ @abstractmethod
92
+ async def get_health(self) -> PluginHealthcheck:
93
+ """Report whether this plugin instance is healthy right now.
94
+
95
+ Called on a schedule by the host's health monitor and on demand; return
96
+ ``PluginHealthcheck(healthy=False, error_message=...)`` to signal the
97
+ replica is degraded (e.g. its upstream is unreachable).
98
+ """
99
+ raise NotImplementedError("Method `get_health()` not implemented")
100
+
101
+ async def on_startup(self) -> None:
102
+ """Optional lifecycle hook, called right after the plugin instance is
103
+ created. Override in a plugin if needed; the default is a no-op."""
104
+
105
+ async def on_shutdown(self) -> None:
106
+ """Optional lifecycle hook, called before the plugin instance is
107
+ destroyed. Override in a plugin if needed; the default is a no-op."""
@@ -0,0 +1,230 @@
1
+ # Example: a complete plugin
2
+
3
+ A small but complete plugin, **Chat Webhook**: it posts IRMy notifications to a
4
+ chat's incoming webhook and lets people acknowledge an alert from the chat. It
5
+ uses every part of the contract — configuration with secrets, a rule-triggered
6
+ capability with templated settings, a "Test connection" button, an inbound
7
+ endpoint with signature verification, a published command, a default rule —
8
+ and follows the rules in [`writing_plugins.md`](./writing_plugins.md). Tests
9
+ for it are in [`testing.md`](./testing.md).
10
+
11
+ ## Layout
12
+
13
+ ```
14
+ chat_webhook@1.0.0/ # {name}@{version} — must match the manifest
15
+ ├── __init__.py # exports the class as `Plugin`
16
+ └── plugin.py
17
+ ```
18
+
19
+ `__init__.py`:
20
+
21
+ ```python
22
+ from .plugin import ChatWebhookPlugin as Plugin
23
+ ```
24
+
25
+ ## `plugin.py`
26
+
27
+ ```python
28
+ import hashlib
29
+ import hmac
30
+ import re
31
+ import time
32
+ from typing import Any
33
+ from uuid import UUID
34
+
35
+ import httpx
36
+ from irmy_events import EventCategory, RoutingKeys
37
+ from irmy_events.conditions import MISSING, resolve_path
38
+ from irmy_sdk import (
39
+ ActionResult, BasePlugin, ConfigField, DefaultRule, DefaultRuleStep, FieldType,
40
+ InboundEndpoint, InboundRequest, InboundResponse, Placement, PluginCapability,
41
+ PluginHealthcheck, PluginManifest,
42
+ )
43
+
44
+ _PLACEHOLDER = re.compile(r"\{([A-Za-z0-9_.]+)\}")
45
+ DEFAULT_TEXT = "[{service.name} / {environment.name}] {incident.title} ({incident.severity})"
46
+
47
+
48
+ def render(template: str, event: Any) -> str:
49
+ """Replace {path.to.field} with values from the event; a missing field becomes ''."""
50
+ resolve = resolve_path(event)
51
+
52
+ def one(match: re.Match) -> str:
53
+ value = resolve(match.group(1))
54
+ return "" if value is MISSING or value is None else str(value)
55
+
56
+ return _PLACEHOLDER.sub(one, template)
57
+
58
+
59
+ class ChatWebhookPlugin(BasePlugin):
60
+ @classmethod
61
+ def get_manifest(cls) -> PluginManifest:
62
+ return PluginManifest(
63
+ name="chat_webhook",
64
+ version="1.0.0",
65
+ display_name="Chat Webhook",
66
+ description="Posts IRMy notifications to a chat incoming webhook.",
67
+ author="Example",
68
+ instructions=(
69
+ "1. Create an incoming webhook in your chat and paste its URL below.\n"
70
+ "2. To acknowledge alerts from the chat, point its button callbacks at "
71
+ "`{{IRMY_PLUGIN_INBOUND_URL}}/ack` and paste the signing secret below."
72
+ ),
73
+ global_config_schema=[
74
+ ConfigField(key="webhook_url", type=FieldType.SECRET, label="Webhook URL", required=True),
75
+ ConfigField(key="signing_secret", type=FieldType.SECRET, label="Signing secret"),
76
+ ],
77
+ capabilities=[
78
+ PluginCapability(
79
+ action_id="notify",
80
+ display_name="Post to chat",
81
+ handler=cls.notify,
82
+ supported_event_domains=[EventCategory.INCIDENT, EventCategory.ALERT],
83
+ config_schema=[
84
+ ConfigField(
85
+ key="text", type=FieldType.TEXT, label="Message", default=DEFAULT_TEXT,
86
+ description="Event fields as {path.to.field}; a missing field is left empty.",
87
+ ),
88
+ ],
89
+ ),
90
+ PluginCapability(
91
+ action_id="test_connection",
92
+ display_name="Test connection",
93
+ handler=cls.test_connection,
94
+ placements=[Placement.GLOBAL_CONFIG],
95
+ ),
96
+ ],
97
+ inbound_endpoints=[
98
+ InboundEndpoint(path="/ack", methods=["POST"], handler=cls.on_ack,
99
+ description="Acknowledges an alert from a chat button."),
100
+ ],
101
+ default_rules=[
102
+ DefaultRule(
103
+ key="incident_created",
104
+ events=[RoutingKeys.INCIDENT_CREATED],
105
+ steps=[DefaultRuleStep(capability="notify", fields={"text": DEFAULT_TEXT})],
106
+ ),
107
+ ],
108
+ published_commands=[RoutingKeys.ALERT_COMMAND_ACKNOWLEDGE],
109
+ )
110
+
111
+ # ── lifecycle ───────────────────────────────────────────────────────────
112
+ async def on_startup(self) -> None:
113
+ self._http = httpx.AsyncClient(timeout=5.0)
114
+
115
+ async def on_shutdown(self) -> None:
116
+ await self._http.aclose()
117
+
118
+ async def get_health(self) -> PluginHealthcheck:
119
+ if not self.global_config.get("webhook_url"):
120
+ return PluginHealthcheck(healthy=False, error_message="Webhook URL is not set")
121
+ return PluginHealthcheck(healthy=True)
122
+
123
+ # ── capabilities ────────────────────────────────────────────────────────
124
+ async def notify(self, event, routing_key, context, config, responses, actor, rule_owner, rule_id) -> ActionResult:
125
+ alert = getattr(event, "alert", None)
126
+ if alert is not None and not getattr(alert, "shouldNotify", True):
127
+ return ActionResult(success=True, message="skipped: silenced (shouldNotify is false)")
128
+
129
+ text = render(config.get("text") or DEFAULT_TEXT, event)
130
+ if hasattr(event, "incident"):
131
+ text += f"\n{self.host_api.platform.get_incident_url(UUID(event.incident.id))}"
132
+ else:
133
+ text += f"\n{self.host_api.platform.get_alert_url(UUID(alert.id))}"
134
+
135
+ # At-least-once delivery: don't post the same message for the same rule twice.
136
+ digest = hashlib.sha256(text.encode()).hexdigest()[:16]
137
+ dedup_key = f"posted:{rule_id}:{routing_key}:{digest}"
138
+ if await self.host_api.keystore.get(dedup_key):
139
+ return ActionResult(success=True, message="skipped: already posted")
140
+
141
+ response = await self._http.post(self.global_config["webhook_url"], json={"text": text})
142
+ if response.status_code >= 300:
143
+ self.log.warning("chat rejected the message", status=response.status_code)
144
+ return ActionResult(success=False, message=f"chat answered {response.status_code}")
145
+
146
+ await self.host_api.keystore.set(dedup_key, "1", ttl_seconds=86400)
147
+ return ActionResult(success=True, message="posted", details={"text": text})
148
+
149
+ async def test_connection(self, event, routing_key, context, config, responses, actor, rule_owner,
150
+ rule_id) -> ActionResult:
151
+ # The form's values, saved or not; an unchanged secret is not sent.
152
+ url = config.get("webhook_url") or self.global_config.get("webhook_url")
153
+ if not url:
154
+ return ActionResult(success=False, message="Webhook URL is not set")
155
+ try:
156
+ async with httpx.AsyncClient(timeout=5.0) as client:
157
+ response = await client.post(url, json={"text": "IRMy test message"})
158
+ except httpx.HTTPError as exc:
159
+ return ActionResult(success=False, message=f"cannot reach the webhook: {exc}")
160
+ ok = response.status_code < 300
161
+ return ActionResult(success=ok, message="connected" if ok else f"chat answered {response.status_code}")
162
+
163
+ # ── inbound ─────────────────────────────────────────────────────────────
164
+ async def on_ack(self, request: InboundRequest) -> InboundResponse:
165
+ secret = self.global_config.get("signing_secret")
166
+ timestamp = request.headers.get("x-timestamp", "")
167
+ if not secret or not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
168
+ return InboundResponse(status_code=401, body={"error": "unauthorized"})
169
+ expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + request.body, hashlib.sha256).hexdigest()
170
+ if not hmac.compare_digest(request.headers.get("x-signature", ""), expected):
171
+ return InboundResponse(status_code=401, body={"error": "unauthorized"})
172
+
173
+ payload = request.json() or {}
174
+ try:
175
+ alert_id = UUID(payload["alertId"])
176
+ except (KeyError, ValueError, TypeError):
177
+ return InboundResponse(status_code=400, body={"error": "alertId is required"})
178
+ await self.host_api.commands.alert_acknowledge(alert_id)
179
+ return InboundResponse(status_code=200, body={"ok": True})
180
+ ```
181
+
182
+ ## What each part does
183
+
184
+ - **`global_config_schema`** — two `SECRET` fields, filled per integration and
185
+ encrypted at rest. `get_health()` reports the missing URL instead of
186
+ `__init__` raising, so the integration still exists and its "Test
187
+ connection" button stays usable.
188
+ - **`notify`** — rule-triggered only (`placements` empty). It claims the whole
189
+ `incident` and `alert` domains, so the rule editor offers it for any of
190
+ their events; every one of those payloads has `event.incident` or
191
+ `event.alert`. It:
192
+ - returns early, with `success=True`, when `shouldNotify` is `False`;
193
+ - renders `{path.to.field}` itself with `irmy_events.conditions.resolve_path`
194
+ — the host passes `config` verbatim;
195
+ - deduplicates in the keystore, because delivery is at-least-once;
196
+ - returns `success=False` when the chat rejects the post, so the host retries
197
+ the step (up to 3 attempts).
198
+ - **`test_connection`** — a `GLOBAL_CONFIG` button. Its `config` holds only
199
+ what the form sent, so it falls back to the saved URL; it uses its own
200
+ short-lived client because `on_startup()` may never have succeeded.
201
+ - **`on_ack`** — `POST /api/interface/<integration UUID>/ack`. It verifies a
202
+ timestamped HMAC-SHA256 signature over the **raw** body in constant time and
203
+ rejects stale requests before acting, then publishes
204
+ `alert.command.acknowledge` — declared in `published_commands`. The command
205
+ returns immediately; the platform announces `alert.state.acknowledge` with
206
+ `actorType == "plugin"`.
207
+ - **`default_rules`** — seeded once, for the first integration created from
208
+ the package: post every new incident.
209
+ - **`instructions`** — shown on the integration's page;
210
+ `{{IRMY_PLUGIN_INBOUND_URL}}` becomes that integration's inbound base URL.
211
+
212
+ ## Build and install
213
+
214
+ ```bash
215
+ cd my-plugins
216
+ zip -r chat_webhook-1.0.0.zip "chat_webhook@1.0.0" -x "*/__pycache__/*"
217
+ ```
218
+
219
+ 1. System → Plugins → **Install Plugin**: upload the `.zip` (at most 5 MiB) or
220
+ give a URL to it.
221
+ 2. System → Integrations → **+ Add new integration**: pick *Chat Webhook*, name
222
+ it, save the webhook URL, enable it, press **Test connection**.
223
+ 3. Rules → Event rules: the default *incident_created* rule already targets the
224
+ first integration; add rules for alerts with your own message, e.g.
225
+ `{service.name}: {alert.subject} (P{alert.priority})`.
226
+
227
+ To ship a new version, bump `version` in the manifest **and** the directory
228
+ name, then use **Update plugin**; renaming `notify` or narrowing its domains
229
+ would drop it from existing rules (see
230
+ [Update compatibility](./writing_plugins.md#update-compatibility-what-breaks-existing-rules)).