AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(blocks): add All Quiet incident management blocks (#14053)
Nicholas Tindle765e777162b4
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex d9e00c6e10..1ce9d97473 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -301,6 +301,9 @@ POSTHOG_HOST=https://eu.i.posthog.comTALLY_API_KEY=# Other Services+# All Quiet incident management / on-call. The Public API is only available on+# the PRO and ENTERPRISE plans; generate the key in your organization settings.+ALLQUIET_API_KEY=AUTOMOD_API_KEY=## ===== ONBOARDING BRAIN DUMP ===== ##diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_api.py b/autogpt_platform/backend/backend/blocks/allquiet/_api.pynew file mode 100644index 0000000000..74d981f167--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_api.py@@ -0,0 +1,350 @@+"""Async client for the All Quiet Public API v1."""++from typing import Any, Optional++from pydantic import BaseModel, TypeAdapter, ValidationError++from backend.sdk import APIKeyCredentials, Requests, json+from backend.util.request import Response++from ._types import (+ AllQuietRegion,+ Incident,+ IncidentSeverity,+ IncidentSortBy,+ IncidentStatus,+ OnCallShift,+ Team,+)++REGION_HOSTS: dict[AllQuietRegion, str] = {+ AllQuietRegion.US: "https://allquiet.app",+ AllQuietRegion.EU: "https://allquiet.eu",+}+++class _ListedError(BaseModel):+ """One entry of All Quiet's list-shaped ``errors`` envelope."""++ description: str = ""+++_JSON_OBJECT = TypeAdapter(dict[str, Any])+_FIELD_ERRORS = TypeAdapter(dict[str, list[str]])+_LISTED_ERRORS = TypeAdapter(list[_ListedError])++# Membership sets for defensive coercion of live event data.+_STATUS_VALUES = {member.value for member in IncidentStatus}+_SEVERITY_VALUES = {member.value for member in IncidentSeverity}+++class AllQuietClient:+ """Thin wrapper over the All Quiet Public API.++ Responses are validated into the models in ``_types`` so blocks never hand+ raw dicts to downstream nodes.+ """++ def __init__(+ self,+ credentials: APIKeyCredentials,+ region: AllQuietRegion = AllQuietRegion.US,+ ):+ self.host = REGION_HOSTS[region]+ self.base_url = f"{self.host}/api/public/v1"+ self.requests = Requests(+ trusted_origins=list(REGION_HOSTS.values()),+ raise_for_status=False,+ extra_headers={+ "X-Api-Key": credentials.api_key.get_secret_value(),+ "Content-Type": "application/json",+ },+ )++ async def _request(+ self,+ method: str,+ path: str,+ *,+ params: Optional[dict[str, Any]] = None,+ body: Optional[dict[str, Any]] = None,+ ) -> Any:+ response = await self.requests.request(+ method,+ f"{self.base_url}{path}",+ params=_clean_params(params or {}),+ json=body,+ )+ body_text = _raise_for_status(response)+ if not body_text:+ return None+ try:+ return response.json()+ except ValueError as exc:+ # A 2xx with a non-JSON body means the endpoint or a proxy in front+ # of it returned something unexpected; surface it as a readable+ # client error rather than an unhandled decode crash.+ raise RuntimeError(+ f"All Quiet returned a {response.status} with a body that is not "+ f"JSON: {body_text[:200]}"+ ) from exc++ async def create_incident(+ self,+ *,+ title: str,+ status: IncidentStatus,+ severity: IncidentSeverity,+ message: str = "",+ message_is_public: bool = False,+ team_ids: Optional[list[str]] = None,+ service_ids: Optional[list[str]] = None,+ user_ids: Optional[list[str]] = None,+ attributes: Optional[dict[str, str]] = None,+ ) -> Incident:+ payload: dict[str, Any] = {+ "title": title,+ "status": status.value,+ "severity": severity.value,+ }+ if message:+ payload["message"] = message+ payload["messageIsPublic"] = message_is_public+ if team_ids:+ payload["teamIds"] = team_ids+ if service_ids:+ payload["serviceIds"] = service_ids+ if user_ids:+ payload["userAssignments"] = [{"userId": uid} for uid in user_ids]+ if attributes:+ payload["attributes"] = [+ {"name": name, "value": value} for name, value in attributes.items()+ ]++ data = await self._request("POST", "/incident", body=payload)+ return _to_incident(data)++ async def get_incident(self, incident_id: str) -> Incident:+ data = await self._request("GET", f"/incident/search/{incident_id}")+ return _to_incident(data)++ async def get_incident_markdown(self, incident_id: str) -> str:+ response = await self.requests.get(+ f"{self.base_url}/incident/search/{incident_id}/markdown"+ )+ return _raise_for_status(response)++ async def list_incidents(+ self,+ *,+ statuses: Optional[list[IncidentStatus]] = None,+ severities: Optional[list[IncidentSeverity]] = None,+ team_ids: Optional[list[str]] = None,+ user_ids: Optional[list[str]] = None,+ search_term: str = "",+ unattended: Optional[bool] = None,+ created_from: str = "",+ created_until: str = "",+ limit: int = 25,+ offset: int = 0,+ sort_by: IncidentSortBy = IncidentSortBy.CREATED,+ ascending: bool = False,+ ) -> tuple[list[Incident], bool]:+ """Return the matching incidents and whether more pages are available."""+ params: dict[str, Any] = {+ "Statuses": [s.value for s in statuses or []],+ "Severities": [s.value for s in severities or []],+ "TeamIds": team_ids or [],+ "UserIds": user_ids or [],+ "SearchTerm": search_term,+ "Unattended": _bool_param(unattended),+ "CreatedFrom": created_from,+ "CreatedUntil": created_until,+ "Limit": limit,+ "Offset": offset,+ "SortBy": sort_by.value,+ "Asc": _bool_param(ascending),+ }+ data = await self._request("GET", "/incident/search/list", params=params)+ incidents = [_to_incident(item) for item in (data or {}).get("incidents", [])]+ return incidents, bool((data or {}).get("hasMore", False))++ async def append_intent(+ self,+ incident_id: str,+ *,+ intent: str,+ message: str = "",+ message_is_public: bool = False,+ severity: Optional[IncidentSeverity] = None,+ ) -> None:+ """Apply an intent (and optionally a new severity) to an incident.++ The patch endpoint returns a list payload rather than the updated+ incident, so callers re-read the incident to observe the new state.++ The intent is applied before that re-read, so a failed re-read reports+ an error even though the write landed — and a naive retry would apply+ the intent twice, leaving a duplicate Commented/Escalated entry on the+ timeline. Retry only after confirming the incident's current state.+ """+ operations: dict[str, Any] = {+ "appendIntent": {+ "intent": intent,+ "message": message,+ "messageIsPublic": message_is_public,+ }+ }+ if severity is not None:+ operations["changeSeverity"] = {"severity": severity.value}++ await self._request(+ "PATCH", f"/incident/{incident_id}", body={"operations": operations}+ )++ async def get_on_call(+ self,+ *,+ team_ids: Optional[list[str]] = None,+ user_ids: Optional[list[str]] = None,+ timestamp: str = "",+ ) -> list[OnCallShift]:+ params = {+ "TeamIds": team_ids or [],+ "UserIds": user_ids or [],+ "Timestamp": timestamp,+ }+ data = await self._request("GET", "/on-call", params=params)+ return [+ OnCallShift.model_validate(m) for m in (data or {}).get("memberships", [])+ ]++ async def list_teams(+ self,+ *,+ display_name: str = "",+ limit: int = 50,+ offset: int = 0,+ ) -> tuple[list[Team], bool]:+ params = {"DisplayName": display_name, "Limit": limit, "Offset": offset}+ data = await self._request("GET", "/team/search/list", params=params)+ teams = [Team.model_validate(t) for t in (data or {}).get("teams", [])]+ return teams, bool((data or {}).get("hasMore", False))+++def _raise_for_status(response: Response) -> str:+ """Return the body text, raising a readable error on any non-2xx status."""+ body_text = response.text()+ if not response.ok:+ raise RuntimeError(_error_message(response.status, body_text))+ return body_text+++def _clean_params(params: dict[str, Any]) -> dict[str, Any]:+ """Drop unset params so All Quiet does not reject empty filter values."""+ return {+ key: value+ for key, value in params.items()+ if value is not None and value != "" and value != []+ }+++def _bool_param(value: Optional[bool]) -> Optional[str]:+ """Render an optional flag as a query value.++ aiohttp's URL layer refuses raw ``bool`` query values, and All Quiet expects+ the lowercase spellings, so flags travel as ``"true"``/``"false"`` strings.+ ``None`` is passed through for ``_clean_params`` to drop.+ """+ if value is None:+ return None+ return "true" if value else "false"+++def _to_incident(data: Optional[dict[str, Any]]) -> Incident:+ """Validate an incident payload, lifting status/severity off the latest event.++ All Quiet models an incident's current state as the head of its event+ timeline (newest first), so flatten it onto the incident for consumers.+ """+ if not data:+ raise RuntimeError("All Quiet returned an empty incident payload")++ incident = Incident.model_validate(data)+ events = data.get("events") or []+ if events:+ latest = events[0]+ # Coerce defensively: an unmodeled value would otherwise raise+ # ValueError on every read of that incident. The rest of the incident is+ # still useful, so leave the field unset rather than failing the call.+ # This mirrors the guard the trigger block already applies to payloads.+ if latest.get("status") in _STATUS_VALUES:+ incident.status = IncidentStatus(latest["status"])+ if latest.get("severity") in _SEVERITY_VALUES:+ incident.severity = IncidentSeverity(latest["severity"])+ return incident+++def _error_message(status: int, body: str) -> str:+ """Turn an All Quiet error body into a single readable line."""+ detail = _error_detail(body) or body.strip()++ if status in (401, 403):+ return (+ f"All Quiet rejected the API key ({status}). Check the key is valid and "+ f"that your plan includes the Public API. {detail}".strip()+ )+ return f"All Quiet API error {status}: {detail}"+++def _error_detail(body: str) -> str:+ """Extract the human-readable part of an All Quiet error body.++ All Quiet uses two different error shapes, so both are handled:++ * RFC 9110 problem details for request validation, where ``errors`` maps a+ field to its messages --+ ``{"errors": {"Statuses": ["Values must be one of Open,Resolved"]}}``+ * a result envelope for auth and similar failures, where ``errors`` is a+ list of objects --+ ``{"succeeded": false, "errors": [{"description": "Provided API key is invalid."}]}``++ Returns an empty string when nothing useful can be pulled out, so the caller+ can fall back to the raw body.+ """+ try:+ parsed = _JSON_OBJECT.validate_python(+ json.loads(body, fallback={}) if body else {}+ )+ except ValidationError:+ # Body parsed as JSON but isn't an object (e.g. a bare string or array).+ return ""+ if not parsed:+ return ""++ raw_errors = parsed.get("errors")++ try:+ field_errors = _FIELD_ERRORS.validate_python(raw_errors)+ except ValidationError:+ pass+ else:+ joined = "; ".join(+ f"{field}: {' '.join(messages)}" for field, messages in field_errors.items()+ )+ # An empty `errors` object validates but says nothing; fall through to+ # `title` rather than returning a blank detail.+ if joined:+ return joined++ try:+ listed_errors = _LISTED_ERRORS.validate_python(raw_errors)+ except ValidationError:+ pass+ else:+ described = [e.description for e in listed_errors if e.description]+ if described:+ return "; ".join(described)++ title = parsed.get("title")+ return str(title) if title else ""diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_api_test.py b/autogpt_platform/backend/backend/blocks/allquiet/_api_test.pynew file mode 100644index 0000000000..3710df512a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_api_test.py@@ -0,0 +1,434 @@+"""Unit tests for the All Quiet API client's request shaping and error handling."""++from typing import Any, Optional+from unittest.mock import AsyncMock++import pytest+from pydantic import SecretStr++from backend.blocks.allquiet._api import (+ REGION_HOSTS,+ AllQuietClient,+ _bool_param,+ _clean_params,+ _error_message,+ _to_incident,+)+from backend.blocks.allquiet._types import (+ AllQuietRegion,+ IncidentSeverity,+ IncidentStatus,+)+from backend.data.model import APIKeyCredentials+++def _credentials() -> APIKeyCredentials:+ return APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="allquiet",+ api_key=SecretStr("test-key"),+ title="Test key",+ expires_at=None,+ )+++class _FakeResponse:+ def __init__(self, status: int = 200, payload: Any = None, body: str = ""):+ self.status = status+ self._payload = payload+ self._body = body++ @property+ def ok(self) -> bool:+ return 200 <= self.status < 300++ def json(self) -> Any:+ if self._payload is None and self._body:+ raise ValueError("not JSON")+ return self._payload++ def text(self) -> str:+ if self._body:+ return self._body+ return "{}" if self._payload is not None else ""+++def _client_with(response: _FakeResponse) -> tuple[AllQuietClient, AsyncMock]:+ """Build a client whose HTTP layer is swapped for a recording mock."""+ client = AllQuietClient(_credentials())+ request = AsyncMock(return_value=response)+ # Patch the transport itself so the tests cover the client's own request+ # shaping (params, body, error handling) without any network access.+ requests: Any = client.requests+ requests.request = request+ return client, request+++def _sent(request: AsyncMock) -> tuple[str, str, dict[str, Any], Optional[dict]]:+ method, url = request.await_args.args+ kwargs = request.await_args.kwargs+ return method, url, kwargs.get("params") or {}, kwargs.get("json")+++def _incident_payload(status: str = "Open", severity: str = "Critical") -> dict:+ return {+ "id": "inc-1",+ "title": "Checkout latency above SLO",+ "createdAt": "2026-08-16T23:42:17.274Z",+ "lastUpdatedAt": "2026-08-16T23:57:59.023Z",+ "allowedIntents": ["Investigated", "Resolved"],+ "events": [+ {"status": status, "severity": severity},+ {"status": "Open", "severity": "Minor"},+ ],+ }+++class TestRegions:+ def test_us_is_the_default(self):+ client = AllQuietClient(_credentials())+ assert client.base_url == "https://allquiet.app/api/public/v1"++ def test_eu_region_targets_the_eu_host(self):+ client = AllQuietClient(_credentials(), AllQuietRegion.EU)+ assert client.base_url == "https://allquiet.eu/api/public/v1"++ def test_both_hosts_are_trusted_origins(self):+ client = AllQuietClient(_credentials())+ for host in REGION_HOSTS.values():+ assert host.removeprefix("https://") in client.requests.trusted_origins+++class TestCleanParams:+ def test_drops_unset_values(self):+ assert _clean_params({"a": None, "b": "", "c": []}) == {}++ def test_keeps_zero(self):+ # `Offset=0` is a meaningful value, not an absent one.+ assert _clean_params({"Offset": 0}) == {"Offset": 0}+++class TestBoolParam:+ def test_renders_lowercase_strings(self):+ # aiohttp's URL layer raises TypeError on raw bool query values, so+ # flags must reach it already rendered as strings.+ assert _bool_param(True) == "true"+ assert _bool_param(False) == "false"++ def test_passes_none_through_for_cleaning(self):+ assert _bool_param(None) is None+++class TestToIncident:+ def test_lifts_status_and_severity_off_the_newest_event(self):+ incident = _to_incident(_incident_payload("Resolved", "Warning"))++ assert incident.status == IncidentStatus.RESOLVED+ assert incident.severity == IncidentSeverity.WARNING++ def test_maps_camel_case_fields(self):+ incident = _to_incident(_incident_payload())++ assert incident.created_at == "2026-08-16T23:42:17.274Z"+ assert incident.allowed_intents == ["Investigated", "Resolved"]++ def test_tolerates_an_incident_with_no_events(self):+ payload = _incident_payload()+ payload["events"] = []++ incident = _to_incident(payload)++ assert incident.status is None+ assert incident.severity is None++ def test_rejects_an_empty_payload(self):+ with pytest.raises(RuntimeError, match="empty incident payload"):+ _to_incident(None)+++class TestErrorMessage:+ def test_flattens_field_validation_errors(self):+ body = (+ '{"title":"One or more validation errors occurred.","status":400,'+ '"errors":{"Statuses":["Values must be one of Open,Resolved"]}}'+ )++ message = _error_message(400, body)++ assert "Statuses: Values must be one of Open,Resolved" in message+ assert "400" in message++ def test_calls_out_a_bad_key_on_401(self):+ message = _error_message(401, "")++ assert "rejected the API key" in message++ def test_falls_back_to_the_raw_body_when_not_json(self):+ assert "upstream exploded" in _error_message(500, "upstream exploded")+++class TestCreateIncident:+ async def test_sends_only_the_fields_that_were_set(self):+ client, request = _client_with(_FakeResponse(payload=_incident_payload()))++ await client.create_incident(+ title="Checkout latency above SLO",+ status=IncidentStatus.OPEN,+ severity=IncidentSeverity.CRITICAL,+ )++ _, _, _, body = _sent(request)+ assert body == {+ "title": "Checkout latency above SLO",+ "status": "Open",+ "severity": "Critical",+ }++ async def test_maps_attributes_and_user_assignments(self):+ client, request = _client_with(_FakeResponse(payload=_incident_payload()))++ await client.create_incident(+ title="t",+ status=IncidentStatus.OPEN,+ severity=IncidentSeverity.MINOR,+ user_ids=["u1"],+ attributes={"host": "web-01"},+ )++ _, _, _, body = _sent(request)+ assert body is not None+ assert body["userAssignments"] == [{"userId": "u1"}]+ assert body["attributes"] == [{"name": "host", "value": "web-01"}]++ async def test_raises_a_readable_error_on_failure(self):+ client, _ = _client_with(+ _FakeResponse(status=400, body='{"title":"Bad request"}')+ )++ with pytest.raises(RuntimeError, match="Bad request"):+ await client.create_incident(+ title="t",+ status=IncidentStatus.OPEN,+ severity=IncidentSeverity.MINOR,+ )+++class TestListIncidents:+ async def test_serialises_enum_filters_and_reports_paging(self):+ client, request = _client_with(+ _FakeResponse(payload={"incidents": [_incident_payload()], "hasMore": True})+ )++ incidents, has_more = await client.list_incidents(+ statuses=[IncidentStatus.OPEN],+ severities=[IncidentSeverity.CRITICAL, IncidentSeverity.WARNING],+ limit=10,+ )++ _, _, params, _ = _sent(request)+ assert params["Statuses"] == ["Open"]+ assert params["Severities"] == ["Critical", "Warning"]+ assert len(incidents) == 1+ assert has_more is True++ async def test_omits_empty_filters(self):+ client, request = _client_with(_FakeResponse(payload={"incidents": []}))++ await client.list_incidents()++ _, _, params, _ = _sent(request)+ assert "Statuses" not in params+ assert "SearchTerm" not in params++ async def test_sends_flags_as_strings_not_bools(self):+ # Regression: raw bools reach yarl and raise+ # "Invalid variable type: value should be str, int or float".+ client, request = _client_with(_FakeResponse(payload={"incidents": []}))++ await client.list_incidents(unattended=True, ascending=False)++ _, _, params, _ = _sent(request)+ assert params["Unattended"] == "true"+ assert params["Asc"] == "false"+ assert not any(value is True or value is False for value in params.values())++ async def test_omits_the_unattended_filter_when_unset(self):+ client, request = _client_with(_FakeResponse(payload={"incidents": []}))++ await client.list_incidents()++ _, _, params, _ = _sent(request)+ assert "Unattended" not in params+++class TestAppendIntent:+ async def test_wraps_the_intent_in_an_operations_object(self):+ client, request = _client_with(_FakeResponse(payload={"incidents": []}))++ await client.append_intent("inc-1", intent="Resolved", message="fixed")++ method, url, _, body = _sent(request)+ assert method == "PATCH"+ assert url.endswith("/incident/inc-1")+ assert body == {+ "operations": {+ "appendIntent": {+ "intent": "Resolved",+ "message": "fixed",+ "messageIsPublic": False,+ }+ }+ }++ async def test_adds_a_severity_change_when_requested(self):+ client, request = _client_with(_FakeResponse(payload={"incidents": []}))++ await client.append_intent(+ "inc-1", intent="Commented", severity=IncidentSeverity.CRITICAL+ )++ _, _, _, body = _sent(request)+ assert body is not None+ assert body["operations"]["changeSeverity"] == {"severity": "Critical"}+++class TestOnCallAndTeams:+ async def test_parses_on_call_memberships(self):+ client, _ = _client_with(+ _FakeResponse(+ payload={+ "memberships": [+ {+ "user": {"id": "u1", "displayName": "Ada"},+ "team": {"id": "t1", "displayName": "Platform"},+ "availabilities": [{"tier": 1, "isOnline": True}],+ }+ ]+ }+ )+ )++ shifts = await client.get_on_call()++ assert len(shifts) == 1+ assert shifts[0].user is not None and shifts[0].user.display_name == "Ada"+ assert shifts[0].availabilities[0].is_online is True++ async def test_parses_teams(self):+ client, _ = _client_with(+ _FakeResponse(+ payload={+ "teams": [+ {"id": "t1", "displayName": "Platform", "timeZoneId": "UTC"}+ ],+ "hasMore": False,+ }+ )+ )++ teams, has_more = await client.list_teams()++ assert teams[0].display_name == "Platform"+ assert teams[0].time_zone_id == "UTC"+ assert has_more is False+++class TestListShapedErrors:+ """All Quiet returns `errors` as a list for auth failures, not a dict."""++ def test_flattens_the_list_envelope_used_by_auth_failures(self):+ # Captured verbatim from a real 401 against the live API.+ body = (+ '{"succeeded":false,'+ '"errors":[{"description":"Provided API key is invalid."}]}'+ )++ message = _error_message(401, body)++ assert "Provided API key is invalid." in message+ assert "rejected the API key" in message++ def test_joins_multiple_listed_errors(self):+ body = '{"errors":[{"description":"first"},{"description":"second"}]}'++ assert "first; second" in _error_message(400, body)++ def test_still_flattens_the_dict_envelope_used_by_validation(self):+ body = '{"errors":{"Statuses":["Values must be one of Open,Resolved"]}}'++ assert "Statuses: Values must be one of Open,Resolved" in _error_message(+ 400, body+ )++ def test_falls_back_to_title_when_errors_is_unusable(self):+ body = '{"title":"One or more validation errors occurred.","errors":42}'++ assert "One or more validation errors occurred." in _error_message(400, body)++ def test_falls_back_to_the_raw_body_for_a_non_object_payload(self):+ assert "just a string" in _error_message(500, '"just a string"')+++class TestGetIncidentMarkdown:+ async def test_returns_the_markdown_report(self):+ report = "# Checkout latency above SLO\n\n- **Status**: Open\n"+ client = AllQuietClient(_credentials())+ get = AsyncMock(return_value=_FakeResponse(body=report))+ requests: Any = client.requests+ requests.get = get++ assert await client.get_incident_markdown("inc-1") == report+ assert get.await_args.args[0].endswith("/incident/search/inc-1/markdown")++ async def test_raises_a_readable_error_when_the_report_fails(self):+ client = AllQuietClient(_credentials())+ requests: Any = client.requests+ requests.get = AsyncMock(+ return_value=_FakeResponse(status=404, body='{"title":"Not found"}')+ )++ with pytest.raises(RuntimeError, match="Not found"):+ await client.get_incident_markdown("nope")+++class TestUnmodeledEnumValues:+ """Live event data may carry values beyond what the enums model."""++ def test_ignores_an_unmodeled_status_instead_of_raising(self):+ # Regression: bare IncidentStatus(...) coercion raised ValueError on+ # every read of such an incident, losing an otherwise usable payload.+ incident = _to_incident(_incident_payload(status="Acknowledged"))++ assert incident.status is None+ assert incident.title == "Checkout latency above SLO"++ def test_ignores_an_unmodeled_severity_instead_of_raising(self):+ incident = _to_incident(_incident_payload(severity="Fatal"))++ assert incident.severity is None+ assert incident.id == "inc-1"++ def test_still_maps_the_half_it_recognizes(self):+ incident = _to_incident(+ _incident_payload(status="Resolved", severity="Catastrophic")+ )++ assert incident.status == IncidentStatus.RESOLVED+ assert incident.severity is None+++class TestNonJsonSuccessBody:+ async def test_a_2xx_with_a_non_json_body_raises_a_readable_error(self):+ # Guards against an unhandled JSONDecodeError crashing the block when a+ # proxy or the endpoint returns HTML on a 200.+ client, _ = _client_with(_FakeResponse(status=200, body="<html>oops</html>"))++ with pytest.raises(RuntimeError, match="not JSON"):+ await client.list_teams()+++class TestEmptyErrorsObject:+ def test_falls_back_to_title_when_errors_is_empty(self):+ body = '{"title":"Something went wrong","errors":{}}'++ assert "Something went wrong" in _error_message(400, body)diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_config.py b/autogpt_platform/backend/backend/blocks/allquiet/_config.pynew file mode 100644index 0000000000..5dab305ba9--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_config.py@@ -0,0 +1,44 @@+"""Shared configuration for all All Quiet blocks."""++from backend.sdk import APIKeyCredentials, ProviderBuilder, SchemaField, SecretStr++from ._types import AllQuietRegion+from ._webhook import AllQuietWebhooksManager++# All Quiet bills the Public API as part of the flat PRO/ENTERPRISE subscription+# rather than per request, so there is no base cost to pass through here.+allquiet = (+ ProviderBuilder("allquiet")+ .with_description("Incident management and on-call scheduling")+ .with_api_key("ALLQUIET_API_KEY", "All Quiet API Key")+ .with_webhook_manager(AllQuietWebhooksManager)+ .build()+)++TEST_CREDENTIALS = APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="allquiet",+ api_key=SecretStr("mock-allquiet-api-key"),+ title="Mock All Quiet API key",+ expires_at=None,+)++TEST_CREDENTIALS_INPUT = {+ "provider": TEST_CREDENTIALS.provider,+ "id": TEST_CREDENTIALS.id,+ "type": TEST_CREDENTIALS.type,+ "title": TEST_CREDENTIALS.title,+}+++def region_field() -> AllQuietRegion:+ """Shared input field: which All Quiet deployment to talk to."""+ return SchemaField(+ title="Region",+ description=(+ "The All Quiet deployment your API key belongs to. "+ "Use EU if you signed up on allquiet.eu."+ ),+ default=AllQuietRegion.US,+ advanced=True,+ )diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_testdata.py b/autogpt_platform/backend/backend/blocks/allquiet/_testdata.pynew file mode 100644index 0000000000..24f165bc8c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_testdata.py@@ -0,0 +1,50 @@+"""Shared block test fixtures.++Kept in its own module so block files never import test data from each other.+"""++from ._types import (+ AllQuietEntity,+ AllQuietUser,+ Incident,+ IncidentSeverity,+ IncidentStatus,+ OnCallAvailability,+ OnCallShift,+ Team,+)++TEST_INCIDENT = Incident(+ id="a1b2c3d4-0000-4000-8000-000000000001",+ title="Checkout latency above SLO",+ status=IncidentStatus.OPEN,+ severity=IncidentSeverity.CRITICAL,+ createdAt="2026-08-16T23:42:17.274Z",+ lastUpdatedAt="2026-08-16T23:42:17.274Z",+ allowedIntents=["Investigated", "Resolved", "Escalated"],+)++TEST_MARKDOWN = (+ "# Checkout latency above SLO\n\n"+ "- **Status**: Open\n"+ "- **Severity**: Critical\n"+)++TEST_TEAM = Team(+ id="7da9d74c-0000-4000-8000-000000000003",+ displayName="Platform",+ timeZoneId="UTC",+ labels=["Engineering"],+)++TEST_USER = AllQuietUser(+ id="b7c8d9e0-0000-4000-8000-000000000002",+ displayName="Ada Lovelace",+ email="[email protected]",+)++TEST_SHIFT = OnCallShift(+ user=TEST_USER,+ team=AllQuietEntity(id=TEST_TEAM.id, displayName=TEST_TEAM.display_name),+ availabilities=[OnCallAvailability(tier=1, isOnline=True, fillUp=False)],+)diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_types.py b/autogpt_platform/backend/backend/blocks/allquiet/_types.pynew file mode 100644index 0000000000..c083b92b44--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_types.py@@ -0,0 +1,145 @@+"""Shared enums and response models for the All Quiet blocks.++Field names mirror the All Quiet Public API v1 payloads so responses can be+validated straight off the wire.+"""++from enum import Enum+from typing import Optional++from backend.sdk import BaseModel, Field+++class AllQuietRegion(str, Enum):+ """All Quiet runs separate US and EU deployments; an API key is valid on one."""++ US = "us"+ EU = "eu"+++class IncidentStatus(str, Enum):+ """The only two statuses the API accepts (`Values must be one of Open,Resolved`)."""++ OPEN = "Open"+ RESOLVED = "Resolved"+++class IncidentSeverity(str, Enum):+ """Severity ladder used for routing and escalation."""++ CRITICAL = "Critical"+ WARNING = "Warning"+ MINOR = "Minor"+++class IncidentIntent(str, Enum):+ """Intents accepted by the incident patch endpoint's `appendIntent` operation.++ Which intents an incident accepts depends on its current status: an Open+ incident allows e.g. `Investigated`/`Resolved`/`Escalated`, while a Resolved+ one allows `Unresolved`. `GetIncident` surfaces the current set on+ `allowed_intents`.+ """++ INVESTIGATED = "Investigated"+ RESOLVED = "Resolved"+ UNRESOLVED = "Unresolved"+ ESCALATED = "Escalated"+ COMMENTED = "Commented"+ SNOOZED = "Snoozed"+ ARCHIVED = "Archived"+++class IncidentSortBy(str, Enum):+ """Sort fields the incident search accepts.++ (`Value must be one of Urgency,LatestInteraction,LastUpdatedAt,Created,Title`)+ """++ CREATED = "Created"+ LAST_UPDATED_AT = "LastUpdatedAt"+ LATEST_INTERACTION = "LatestInteraction"+ URGENCY = "Urgency"+ TITLE = "Title"+++class AllQuietEntity(BaseModel):+ """A named reference to a team, service or integration."""++ id: str = ""+ display_name: str = Field(default="", alias="displayName")++ model_config = {"populate_by_name": True}+++class AllQuietUser(BaseModel):+ id: str = ""+ display_name: str = Field(default="", alias="displayName")+ email: str = ""+ avatar_url: str = Field(default="", alias="avatarUrl")++ model_config = {"populate_by_name": True}+++class IncidentAttribute(BaseModel):+ """A key/value pair carried on an incident, e.g. `host: web-01`."""++ name: str = ""+ value: str = ""+ is_image: bool = Field(default=False, alias="isImage")+ is_grouping_key: bool = Field(default=False, alias="isGroupingKey")+ hide_in_previews: bool = Field(default=False, alias="hideInPreviews")++ model_config = {"populate_by_name": True}+++class Incident(BaseModel):+ """An All Quiet incident.++ Status and severity live on the incident's event history rather than the+ incident itself, so they are flattened here from the most recent event.+ """++ id: str = ""+ title: str = ""+ status: Optional[IncidentStatus] = None+ severity: Optional[IncidentSeverity] = None+ created_at: str = Field(default="", alias="createdAt")+ last_updated_at: str = Field(default="", alias="lastUpdatedAt")+ integration: Optional[AllQuietEntity] = None+ teams: list[AllQuietEntity] = Field(default_factory=list)+ services: list[AllQuietEntity] = Field(default_factory=list)+ on_call_users: list[AllQuietUser] = Field(default_factory=list, alias="onCallUsers")+ attributes: list[IncidentAttribute] = Field(default_factory=list)+ allowed_intents: list[str] = Field(default_factory=list, alias="allowedIntents")+ unattended: bool = False+ is_archived: bool = Field(default=False, alias="isArchived")++ model_config = {"populate_by_name": True}+++class OnCallAvailability(BaseModel):+ """One escalation tier a user covers for a team."""++ tier: int = 0+ is_online: bool = Field(default=False, alias="isOnline")+ fill_up: bool = Field(default=False, alias="fillUp")++ model_config = {"populate_by_name": True}+++class OnCallShift(BaseModel):+ """A user's on-call coverage for one team at the requested point in time."""++ user: Optional[AllQuietUser] = None+ team: Optional[AllQuietEntity] = None+ availabilities: list[OnCallAvailability] = Field(default_factory=list)+++class Team(BaseModel):+ id: str = ""+ display_name: str = Field(default="", alias="displayName")+ time_zone_id: str = Field(default="", alias="timeZoneId")+ labels: list[str] = Field(default_factory=list)++ model_config = {"populate_by_name": True}diff --git a/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py b/autogpt_platform/backend/backend/blocks/allquiet/_webhook.pynew file mode 100644index 0000000000..3d4e8a6d7f--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_webhook.py@@ -0,0 +1,242 @@+"""Webhook manager for All Quiet outbound integrations.++All Quiet can optionally sign each delivery. The signature is+``HMAC-SHA256(secret, "<timestamp>:<body>")``, base64-encoded, and All Quiet+sends it under one of two header pairs depending on the format chosen on the+outbound integration:++* All Quiet — ``x-aq-signature`` / ``x-aq-timestamp``+* AWS — ``x-amzn-event-signature`` / ``x-amzn-event-timestamp``++Both are accepted here so either format works without reconfiguring the block.+"""++import base64+import hashlib+import hmac+import logging+from datetime import datetime, timedelta, timezone+from typing import Optional++from fastapi import HTTPException, Request+from pydantic import SecretStr, TypeAdapter, ValidationError+from strenum import StrEnum++from backend.data.integrations import Webhook, WebhookWithRelations+from backend.sdk import Credentials, ManualWebhookManagerBase++logger = logging.getLogger(__name__)++# Header pairs All Quiet may sign with, in (signature, timestamp) order.+SIGNATURE_HEADER_PAIRS = (+ ("x-aq-signature", "x-aq-timestamp"),+ ("x-amzn-event-signature", "x-amzn-event-timestamp"),+)++# How far a signed delivery's timestamp may drift before it is treated as a+# replay. Only enforced when the timestamp parses; the signature itself is+# always checked.+MAX_TIMESTAMP_SKEW = timedelta(minutes=5)++_OPTIONAL_SECRET = TypeAdapter(Optional[SecretStr])+_JSON_OBJECT = TypeAdapter(dict)+++class AllQuietWebhookType(StrEnum):+ INCIDENT = "incident"+++class AllQuietWebhooksManager(ManualWebhookManagerBase):+ WebhookType = AllQuietWebhookType++ # Name of the input field on the trigger block carrying the signing secret.+ # Read at verification time rather than snapshotted at registration, so+ # rotating the secret on the block takes effect immediately.+ SIGNING_SECRET_INPUT = "signing_secret" # pragma: allowlist secret++ @classmethod+ async def validate_payload(+ cls,+ webhook: Webhook,+ request: Request,+ credentials: Credentials | None = None,+ ) -> tuple[dict, str]:+ """Parse the delivery body.++ All Quiet's outbound webhook body is whatever Handlebars template the+ user configured, so the shape is not fixed — the trigger block reads the+ well-known keys and passes the rest through. Only one event type exists;+ callers filter on the payload's own status/intent instead.+ """+ try:+ payload = _JSON_OBJECT.validate_python(await request.json())+ except (ValueError, ValidationError) as exc:+ raise HTTPException(+ status_code=400,+ detail=(+ "All Quiet webhook body must be a JSON object. Check the "+ "body template on the outbound integration."+ ),+ ) from exc++ return payload, AllQuietWebhookType.INCIDENT++ @classmethod+ async def verify_signature(+ cls, webhook: WebhookWithRelations, request: Request+ ) -> None:+ secret = cls._configured_secret(webhook)+ if not secret:+ # Signing is opt-in on the All Quiet side. With no secret+ # configured the webhook URL is the only credential, matching the+ # platform's other manual webhooks.+ return++ signature, timestamp = cls._signed_headers(request)+ body = await request.body()+ expected = base64.b64encode(+ hmac.new(+ secret.encode("utf-8"),+ msg=f"{timestamp}:".encode("utf-8") + body,+ digestmod=hashlib.sha256,+ ).digest()+ )++ # Compare as bytes: hmac.compare_digest raises TypeError on a str+ # containing non-ASCII, which would escape as a 500 instead of a 403.+ if not hmac.compare_digest(expected, signature.encode("utf-8", "ignore")):+ raise HTTPException(status_code=403, detail="Invalid webhook signature")++ cls._reject_stale_timestamp(timestamp)++ @classmethod+ def _signed_headers(cls, request: Request) -> tuple[str, str]:+ """Return the (signature, timestamp) pair All Quiet signed this with."""+ for signature_header, timestamp_header in SIGNATURE_HEADER_PAIRS:+ signature = request.headers.get(signature_header)+ timestamp = request.headers.get(timestamp_header)+ if signature and timestamp:+ return signature, timestamp++ accepted = ", ".join(pair[0] for pair in SIGNATURE_HEADER_PAIRS)+ raise HTTPException(+ status_code=403,+ detail=(+ "Webhook is configured with a signing secret but the request "+ f"carries no signature. Expected one of: {accepted} (with its "+ "matching timestamp header)."+ ),+ )++ @classmethod+ def _reject_stale_timestamp(cls, timestamp: str) -> None:+ """Reject replays of an otherwise validly signed delivery.++ Fails closed: a signing secret is configured, so a timestamp we cannot+ place in time is treated as a failed check rather than waved through.+ Letting it pass would leave the replay window permanently open for any+ sender that varies its timestamp format.+ """+ sent_at = _parse_timestamp(timestamp)+ if sent_at is None:+ raise HTTPException(+ status_code=403,+ detail=(+ "Webhook timestamp is not in a recognized format, so the "+ "delivery cannot be checked for replay."+ ),+ )++ if abs(datetime.now(timezone.utc) - sent_at) > MAX_TIMESTAMP_SKEW:+ raise HTTPException(+ status_code=403,+ detail="Webhook timestamp is outside the accepted window",+ )++ @classmethod+ def _configured_secret(cls, webhook: WebhookWithRelations) -> str | None:+ """Find the signing secret set on any node or preset using this webhook."""+ sources = [node.input_default for node in webhook.triggered_nodes] + [+ preset.inputs for preset in webhook.triggered_presets+ ]++ found: list[str] = []+ for source in sources:+ raw = source.get(cls.SIGNING_SECRET_INPUT)+ # Stored values arrive as plain strings or SecretStr depending on+ # the serialization path; coerce both to a plain string.+ try:+ secret = _OPTIONAL_SECRET.validate_python(raw)+ except ValidationError as exc:+ # A secret is configured but unreadable. Treating that as "no+ # secret" would silently downgrade to accepting any delivery,+ # so fail closed instead.+ raise HTTPException(+ status_code=403,+ detail=(+ "A signing secret is configured on this webhook but "+ "could not be read, so the delivery cannot be verified."+ ),+ ) from exc+ if secret and secret.get_secret_value().strip():+ found.append(secret.get_secret_value())++ if not found:+ return None++ # Compute the distinct count before logging so no secret-derived value+ # flows into the logger call args.+ distinct_count = len(set(found))+ if distinct_count > 1:+ # Only one signature can be checked, so picking a winner would make+ # verification depend on node ordering. Refuse instead of silently+ # enforcing one target's secret against every delivery.+ logger.warning(+ "Webhook %s has %d distinct signing_secret values across "+ "attached targets; refusing the delivery.",+ webhook.id,+ distinct_count,+ )+ raise HTTPException(+ status_code=403,+ detail=(+ "This webhook is attached to targets configured with "+ "different signing secrets. All targets sharing a webhook "+ "must use the same secret."+ ),+ )+ return found[0]+++def _parse_timestamp(timestamp: str) -> Optional[datetime]:+ """Parse the timestamp formats All Quiet signs with, as an aware UTC datetime.++ Covers the ISO-8601 spellings used by the All Quiet header pair+ (``2023-12-17T11:51:08.844Z``, and the ``...T11:51:08.000Z`` form the AWS+ pair documents) plus epoch seconds/milliseconds, which AWS-style senders+ commonly use. Returns None when the value matches none of them.+ """+ candidate = timestamp.strip()+ if not candidate:+ return None++ try:+ parsed = datetime.fromisoformat(candidate.replace("Z", "+00:00"))+ except ValueError:+ pass+ else:+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)++ try:+ epoch = float(candidate)+ except ValueError:+ return None++ # Heuristic: values this large can only be milliseconds. 1e11 seconds is+ # year 5138, while 1e11 ms is 1973, so the split is unambiguous in practice.+ if abs(epoch) >= 1e11:+ epoch /= 1000.0+ try:+ return datetime.fromtimestamp(epoch, tz=timezone.utc)+ except (OverflowError, OSError, ValueError):+ return Nonediff --git a/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py b/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.pynew file mode 100644index 0000000000..010544c811--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/_webhook_test.py@@ -0,0 +1,379 @@+"""Tests for All Quiet webhook signature verification."""++import base64+import hashlib+import hmac+import json+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace+from typing import Any++import pytest+from fastapi import HTTPException+from pydantic import SecretStr+from starlette.requests import Request++from backend.blocks.allquiet._webhook import (+ AllQuietWebhooksManager,+ AllQuietWebhookType,+)+from backend.blocks.allquiet.triggers import AllQuietIncidentTriggerBlock++SECRET = "s3cr3t-signing-key"+BODY = b'{"id":"81cd20be","title":"RAM above 60%"}'+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")+++def _sign(body: bytes, timestamp: str, secret: str = SECRET) -> str:+ return base64.b64encode(+ hmac.new(+ secret.encode("utf-8"),+ msg=f"{timestamp}:".encode("utf-8") + body,+ digestmod=hashlib.sha256,+ ).digest()+ ).decode("utf-8")+++def _request(headers: dict[str, str], body: bytes = BODY) -> Request:+ scope = {+ "type": "http",+ "method": "POST",+ "path": "/",+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],+ }++ async def receive() -> dict[str, Any]:+ return {"type": "http.request", "body": body, "more_body": False}++ return Request(scope, receive)+++def _webhook(+ *, node_inputs: list[dict] | None = None, preset_inputs: list[dict] | None = None+):+ return SimpleNamespace(+ id="webhook-1",+ triggered_nodes=[+ SimpleNamespace(input_default=inputs) for inputs in node_inputs or []+ ],+ triggered_presets=[+ SimpleNamespace(inputs=inputs) for inputs in preset_inputs or []+ ],+ )+++def _signed_webhook(secret: str = SECRET):+ return _webhook(node_inputs=[{"signing_secret": secret}])+++class TestManagerIsConcrete:+ def test_can_be_instantiated(self):+ # Regression: BaseWebhooksManager declares validate_payload abstract, so+ # omitting it still imports and registers fine and only explodes at+ # trigger-setup time with "Can't instantiate abstract class+ # AllQuietWebhooksManager without an implementation for abstract method+ # 'validate_payload'". The block test harness never instantiates the+ # manager, so nothing else catches this.+ AllQuietWebhooksManager()++ def test_implements_every_abstract_method(self):+ assert not getattr(AllQuietWebhooksManager, "__abstractmethods__", frozenset())+++class TestValidatePayload:+ async def test_returns_the_body_and_the_incident_event_type(self):+ body = {"id": "inc-1", "title": "RAM above 60%"}+ request = _request({}, body=json.dumps(body).encode())++ payload, event_type = await AllQuietWebhooksManager.validate_payload(+ _webhook(), request+ )++ assert payload == body+ assert event_type == AllQuietWebhookType.INCIDENT++ async def test_rejects_a_body_that_is_not_json(self):+ request = _request({}, body=b"not json at all")++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.validate_payload(_webhook(), request)+ assert exc.value.status_code == 400++ async def test_rejects_a_json_body_that_is_not_an_object(self):+ # A malformed Handlebars template can render a bare array or string.+ request = _request({}, body=b'["not", "an", "object"]')++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.validate_payload(_webhook(), request)+ assert exc.value.status_code == 400+ assert "JSON object" in exc.value.detail+++class TestUnsignedWebhooks:+ async def test_accepts_anything_when_no_secret_is_configured(self):+ # Signing is opt-in in All Quiet; the URL is the only credential.+ await AllQuietWebhooksManager.verify_signature(_webhook(), _request({}))++ async def test_treats_a_blank_secret_as_unconfigured(self):+ webhook = _webhook(node_inputs=[{"signing_secret": " "}])++ await AllQuietWebhooksManager.verify_signature(webhook, _request({}))+++class TestSignedWebhooks:+ async def test_accepts_a_valid_allquiet_format_signature(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )++ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)++ async def test_accepts_a_valid_aws_format_signature(self):+ timestamp = _now()+ request = _request(+ {+ "x-amzn-event-signature": _sign(BODY, timestamp),+ "x-amzn-event-timestamp": timestamp,+ }+ )++ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)++ async def test_rejects_a_signature_made_with_the_wrong_secret(self):+ timestamp = _now()+ request = _request(+ {+ "x-aq-signature": _sign(BODY, timestamp, secret="not-the-secret"),+ "x-aq-timestamp": timestamp,+ }+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert exc.value.status_code == 403++ async def test_rejects_a_tampered_body(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp},+ body=b'{"id":"attacker-controlled"}',+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert exc.value.status_code == 403++ async def test_rejects_a_signature_bound_to_a_different_timestamp(self):+ # The timestamp is part of the signed material, so swapping it must fail.+ request = _request(+ {+ "x-aq-signature": _sign(BODY, "2020-01-01T00:00:00.000Z"),+ "x-aq-timestamp": _now(),+ }+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert exc.value.status_code == 403++ async def test_rejects_an_unsigned_request_when_a_secret_is_set(self):+ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(+ _signed_webhook(), _request({})+ )++ assert exc.value.status_code == 403+ assert "x-aq-signature" in exc.value.detail++ async def test_rejects_a_signature_with_no_timestamp_header(self):+ timestamp = _now()+ request = _request({"x-aq-signature": _sign(BODY, timestamp)})++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert exc.value.status_code == 403+++class TestReplayProtection:+ async def test_rejects_a_stale_but_correctly_signed_delivery(self):+ old = (datetime.now(timezone.utc) - timedelta(hours=1)).strftime(+ "%Y-%m-%dT%H:%M:%S.000Z"+ )+ request = _request({"x-aq-signature": _sign(BODY, old), "x-aq-timestamp": old})++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert "window" in exc.value.detail+++class TestSecretDiscovery:+ async def test_reads_the_secret_from_a_preset(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(preset_inputs=[{"signing_secret": SECRET}])++ await AllQuietWebhooksManager.verify_signature(webhook, request)++ async def test_accepts_a_secret_stored_as_a_secretstr(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(node_inputs=[{"signing_secret": SecretStr(SECRET)}])++ await AllQuietWebhooksManager.verify_signature(webhook, request)++ async def test_ignores_nodes_without_a_secret(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(node_inputs=[{}, {"signing_secret": SECRET}])++ await AllQuietWebhooksManager.verify_signature(webhook, request)+++class TestSigningSecretFieldCoupling:+ """`SIGNING_SECRET_INPUT` is matched against the block's field name by string.++ A rename on either side would silently downgrade every signed webhook to+ "accept anything", with no type or test failure anywhere else.+ """++ def test_names_a_real_field_on_the_trigger_block(self):+ fields = AllQuietIncidentTriggerBlock().input_schema.model_fields++ assert AllQuietWebhooksManager.SIGNING_SECRET_INPUT in fields++ def test_that_field_is_marked_secret(self):+ schema = AllQuietIncidentTriggerBlock().input_schema.model_json_schema()+ field = schema["properties"][AllQuietWebhooksManager.SIGNING_SECRET_INPUT]++ assert field.get("secret") is True+++class TestTimestampFormats:+ """All Quiet's two header pairs don't share a timestamp format."""++ @pytest.mark.parametrize(+ "stamp",+ [+ datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",+ datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),+ datetime.now(timezone.utc).isoformat(),+ str(int(datetime.now(timezone.utc).timestamp())),+ str(int(datetime.now(timezone.utc).timestamp() * 1000)),+ ],+ ids=["aq-millis", "aws-iso", "iso-offset", "epoch-seconds", "epoch-millis"],+ )+ async def test_accepts_each_format_all_quiet_may_send(self, stamp: str):+ request = _request(+ {"x-aq-signature": _sign(BODY, stamp), "x-aq-timestamp": stamp}+ )++ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)++ async def test_fails_closed_on_an_unrecognized_format(self):+ # Previously this was waved through, which left the replay window+ # permanently open for any sender using an unusual timestamp format.+ odd = "17/12/2023 11:51:08"+ request = _request({"x-aq-signature": _sign(BODY, odd), "x-aq-timestamp": odd})++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert "recognized format" in exc.value.detail++ async def test_rejects_a_stale_epoch_timestamp(self):+ old = str(int(datetime.now(timezone.utc).timestamp()) - 3600)+ request = _request({"x-aq-signature": _sign(BODY, old), "x-aq-timestamp": old})++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert "window" in exc.value.detail+++class TestAmbiguousSecrets:+ async def test_refuses_when_targets_disagree_on_the_secret(self):+ # Picking a winner would make verification depend on node ordering.+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(+ node_inputs=[{"signing_secret": SECRET}, {"signing_secret": "other"}]+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(webhook, request)+ assert "different signing secrets" in exc.value.detail++ async def test_allows_targets_that_agree(self):+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(+ node_inputs=[{"signing_secret": SECRET}, {"signing_secret": SECRET}]+ )++ await AllQuietWebhooksManager.verify_signature(webhook, request)+++class TestFutureSkew:+ async def test_rejects_a_timestamp_from_the_future(self):+ # A clock-skewed or forged forward timestamp is as much a replay risk+ # as a stale one; the window is symmetric.+ ahead = (datetime.now(timezone.utc) + timedelta(hours=1)).strftime(+ "%Y-%m-%dT%H:%M:%S.000Z"+ )+ request = _request(+ {"x-aq-signature": _sign(BODY, ahead), "x-aq-timestamp": ahead}+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert "window" in exc.value.detail++ async def test_allows_small_clock_skew(self):+ near = (datetime.now(timezone.utc) + timedelta(seconds=30)).strftime(+ "%Y-%m-%dT%H:%M:%S.000Z"+ )+ request = _request(+ {"x-aq-signature": _sign(BODY, near), "x-aq-timestamp": near}+ )++ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+++class TestSignatureHeaderRobustness:+ async def test_a_non_ascii_signature_is_rejected_not_a_500(self):+ # hmac.compare_digest raises TypeError on a str with non-ASCII, which+ # would escape the handler as a 500 rather than a 403.+ timestamp = _now()+ request = _request(+ {"x-aq-signature": "ünicode-signature", "x-aq-timestamp": timestamp}+ )++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(_signed_webhook(), request)+ assert exc.value.status_code == 403++ async def test_an_unreadable_stored_secret_fails_closed(self):+ # "Configured but unreadable" must not be mistaken for "unsigned",+ # which would accept every delivery.+ timestamp = _now()+ request = _request(+ {"x-aq-signature": _sign(BODY, timestamp), "x-aq-timestamp": timestamp}+ )+ webhook = _webhook(node_inputs=[{"signing_secret": {"not": "a secret"}}])++ with pytest.raises(HTTPException) as exc:+ await AllQuietWebhooksManager.verify_signature(webhook, request)+ assert exc.value.status_code == 403+ assert "could not be read" in exc.value.detaildiff --git a/autogpt_platform/backend/backend/blocks/allquiet/blocks_test.py b/autogpt_platform/backend/backend/blocks/allquiet/blocks_test.pynew file mode 100644index 0000000000..0db9382045--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/blocks_test.py@@ -0,0 +1,270 @@+"""Block-level `run()` tests for behaviour the standard harness can't reach.++The harness exercises one canned input per block. These cover the paths it+misses: the optional markdown report, and on-call de-duplication across teams,+which is the whole point of that block and can't be seen with a single-team+fixture.+"""++from typing import Any+from unittest.mock import AsyncMock++import pytest++from backend.blocks.allquiet._api import AllQuietClient+from backend.blocks.allquiet._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.allquiet._testdata import (+ TEST_INCIDENT,+ TEST_MARKDOWN,+ TEST_SHIFT,+ TEST_USER,+)+from backend.blocks.allquiet._types import (+ AllQuietEntity,+ AllQuietUser,+ IncidentIntent,+ IncidentSeverity,+ OnCallAvailability,+ OnCallShift,+)+from backend.blocks.allquiet.incident_search import AllQuietGetIncidentBlock+from backend.blocks.allquiet.incidents import (+ AllQuietCreateIncidentBlock,+ AllQuietUpdateIncidentBlock,+)+from backend.blocks.allquiet.on_call import AllQuietGetOnCallBlock+++async def _run(block, **inputs) -> dict[str, Any]:+ collected: dict[str, Any] = {}+ async for name, value in block.run(+ block.input_schema(credentials=TEST_CREDENTIALS_INPUT, **inputs),+ credentials=TEST_CREDENTIALS,+ ):+ collected.setdefault(name, value)+ return collected+++class TestGetIncidentMarkdown:+ async def test_omits_markdown_by_default(self, monkeypatch: pytest.MonkeyPatch):+ block = AllQuietGetIncidentBlock()+ monkeypatch.setattr(+ block,+ "get_incident",+ AsyncMock(return_value=(TEST_INCIDENT, "")),+ )++ out = await _run(block, incident_id=TEST_INCIDENT.id)++ assert "markdown" not in out++ async def test_emits_markdown_when_requested(self, monkeypatch: pytest.MonkeyPatch):+ block = AllQuietGetIncidentBlock()+ monkeypatch.setattr(+ block,+ "get_incident",+ AsyncMock(return_value=(TEST_INCIDENT, TEST_MARKDOWN)),+ )++ out = await _run(block, incident_id=TEST_INCIDENT.id, include_markdown=True)++ assert out["markdown"] == TEST_MARKDOWN++ async def test_passes_the_flag_through_to_the_fetcher(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = AllQuietGetIncidentBlock()+ fetch = AsyncMock(return_value=(TEST_INCIDENT, TEST_MARKDOWN))+ monkeypatch.setattr(block, "get_incident", fetch)++ await _run(block, incident_id=TEST_INCIDENT.id, include_markdown=True)++ assert fetch.await_args.args[2].include_markdown is True+++def _shift_for(user: AllQuietUser, team_name: str, team_id: str) -> OnCallShift:+ return OnCallShift(+ user=user,+ team=AllQuietEntity(id=team_id, displayName=team_name),+ availabilities=[OnCallAvailability(tier=1, isOnline=True, fillUp=False)],+ )+++class TestOnCallDeduplication:+ async def test_a_user_on_two_teams_is_emitted_once(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ # Someone covering two rotations must not be paged twice.+ block = AllQuietGetOnCallBlock()+ shifts = [+ _shift_for(TEST_USER, "Platform", "team-1"),+ _shift_for(TEST_USER, "Website", "team-2"),+ ]+ monkeypatch.setattr(block, "get_on_call", AsyncMock(return_value=shifts))++ out = await _run(block)++ assert len(out["shifts"]) == 2, "every shift is still reported"+ assert out["user_ids"] == [TEST_USER.id]+ assert out["emails"] == [TEST_USER.email]+ assert len(out["users"]) == 1++ async def test_distinct_users_are_all_kept(self, monkeypatch: pytest.MonkeyPatch):+ block = AllQuietGetOnCallBlock()+ other = AllQuietUser(+ id="c0ffee00-0000-4000-8000-000000000009",+ displayName="Grace Hopper",+ email="[email protected]",+ )+ monkeypatch.setattr(+ block,+ "get_on_call",+ AsyncMock(+ return_value=[+ _shift_for(TEST_USER, "Platform", "team-1"),+ _shift_for(other, "Platform", "team-1"),+ ]+ ),+ )++ out = await _run(block)++ assert out["user_ids"] == [TEST_USER.id, other.id]+ assert out["has_coverage"] is True++ async def test_reports_no_coverage_when_nobody_is_on_call(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = AllQuietGetOnCallBlock()+ monkeypatch.setattr(block, "get_on_call", AsyncMock(return_value=[]))++ out = await _run(block)++ assert out["has_coverage"] is False+ assert out["users"] == []+ assert out["emails"] == []++ async def test_skips_shifts_with_no_user(self, monkeypatch: pytest.MonkeyPatch):+ block = AllQuietGetOnCallBlock()+ headless = OnCallShift(+ user=None,+ team=AllQuietEntity(id="team-1", displayName="Platform"),+ availabilities=[],+ )+ monkeypatch.setattr(+ block, "get_on_call", AsyncMock(return_value=[headless, TEST_SHIFT])+ )++ out = await _run(block)++ assert out["user_ids"] == ["b7c8d9e0-0000-4000-8000-000000000002"]+++class TestBlockErrorPaths:+ """A client failure must surface on the block's declared `error` output.++ The client is proven to raise on 4xx/5xx elsewhere; this wires that raise+ to the block boundary a graph actually sees.+ """++ async def test_get_incident_surfaces_a_client_error(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = AllQuietGetIncidentBlock()+ monkeypatch.setattr(+ block,+ "get_incident",+ AsyncMock(side_effect=RuntimeError("All Quiet API error 404: Not found")),+ )++ with pytest.raises(RuntimeError, match="Not found"):+ await _run(block, incident_id="missing")++ async def test_create_incident_surfaces_a_client_error(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = AllQuietCreateIncidentBlock()+ monkeypatch.setattr(+ block,+ "create_incident",+ AsyncMock(+ side_effect=RuntimeError(+ "All Quiet rejected the API key (401). Check the key is valid"+ )+ ),+ )++ with pytest.raises(RuntimeError, match="rejected the API key"):+ await _run(block, title="anything")++ async def test_on_call_surfaces_a_client_error(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = AllQuietGetOnCallBlock()+ monkeypatch.setattr(+ block, "get_on_call", AsyncMock(side_effect=RuntimeError("upstream down"))+ )++ with pytest.raises(RuntimeError, match="upstream down"):+ await _run(block)++ def test_every_block_declares_an_error_output(self):+ # The platform routes a raised exception to this output, so a block+ # without it would swallow failures in the builder.+ for block_cls in (+ AllQuietGetIncidentBlock,+ AllQuietCreateIncidentBlock,+ AllQuietGetOnCallBlock,+ ):+ assert "error" in block_cls().output_schema.model_fields+++class TestUpdateIncidentReadBack:+ """`update_incident` applies an intent then re-reads; both halves must run.++ The block test mocks `update_incident` wholesale, so removing the re-read+ would keep that green. These mock the two client calls separately.+ """++ async def test_applies_the_intent_then_re_reads_the_incident(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ append = AsyncMock()+ get = AsyncMock(return_value=TEST_INCIDENT)+ monkeypatch.setattr(AllQuietClient, "append_intent", append)+ monkeypatch.setattr(AllQuietClient, "get_incident", get)++ block = AllQuietUpdateIncidentBlock()+ out = await _run(+ block,+ incident_id=TEST_INCIDENT.id,+ intent=IncidentIntent.RESOLVED,+ message="fixed",+ )++ assert append.await_count == 1, "the intent must actually be applied"+ assert append.await_args.args[0] == TEST_INCIDENT.id+ assert append.await_args.kwargs["intent"] == IncidentIntent.RESOLVED.value+ assert append.await_args.kwargs["message"] == "fixed"++ assert get.await_count == 1, "the incident must be re-read afterwards"+ assert out["incident"] == TEST_INCIDENT+ assert out["allowed_intents"] == TEST_INCIDENT.allowed_intents++ async def test_passes_an_optional_severity_change_through(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ append = AsyncMock()+ monkeypatch.setattr(AllQuietClient, "append_intent", append)+ monkeypatch.setattr(+ AllQuietClient, "get_incident", AsyncMock(return_value=TEST_INCIDENT)+ )++ await _run(+ AllQuietUpdateIncidentBlock(),+ incident_id=TEST_INCIDENT.id,+ intent=IncidentIntent.COMMENTED,+ severity=IncidentSeverity.CRITICAL,+ )++ assert append.await_args.kwargs["severity"] == IncidentSeverity.CRITICALdiff --git a/autogpt_platform/backend/backend/blocks/allquiet/incident_search.py b/autogpt_platform/backend/backend/blocks/allquiet/incident_search.pynew file mode 100644index 0000000000..6be2857b1a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/incident_search.py@@ -0,0 +1,255 @@+"""Blocks that read All Quiet incidents."""++import asyncio+from typing import Optional++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import AllQuietClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT, allquiet, region_field+from ._testdata import TEST_INCIDENT+from ._types import (+ AllQuietRegion,+ Incident,+ IncidentSeverity,+ IncidentSortBy,+ IncidentStatus,+)+++class AllQuietGetIncidentBlock(Block):+ """Fetch one incident by ID, including which transitions it currently allows."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ incident_id: str = SchemaField(description="ID of the incident to fetch")+ include_markdown: bool = SchemaField(+ description=(+ "Also fetch an LLM-friendly markdown report of the incident, "+ "including its attributes and full timeline. Costs one extra "+ "API call."+ ),+ default=False,+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ incident: Incident = SchemaField(description="The incident")+ status: Optional[IncidentStatus] = SchemaField(+ description="Current status, when the incident reports one"+ )+ severity: Optional[IncidentSeverity] = SchemaField(+ description="Current severity, when the incident reports one"+ )+ allowed_intents: list[str] = SchemaField(+ description="Transitions this incident currently accepts"+ )+ markdown: str = SchemaField(+ description="Markdown report, if include_markdown was set"+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="3f8a2c7e-9d14-4e5b-b806-7a2f1c4e9d63",+ description="Fetches a single All Quiet incident by ID",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietGetIncidentBlock.Input,+ output_schema=AllQuietGetIncidentBlock.Output,+ test_input={+ "incident_id": TEST_INCIDENT.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("incident", TEST_INCIDENT),+ ("status", IncidentStatus.OPEN),+ ("severity", IncidentSeverity.CRITICAL),+ ("allowed_intents", TEST_INCIDENT.allowed_intents),+ ],+ test_mock={+ "get_incident": lambda *args, **kwargs: (TEST_INCIDENT, ""),+ },+ )++ @staticmethod+ async def get_incident(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> tuple[Incident, str]:+ client = AllQuietClient(credentials, region)+ if not input_data.include_markdown:+ return await client.get_incident(input_data.incident_id), ""++ # Two independent reads of the same incident; run them concurrently+ # rather than paying both round-trips in series.+ incident, markdown = await asyncio.gather(+ client.get_incident(input_data.incident_id),+ client.get_incident_markdown(input_data.incident_id),+ )+ return incident, markdown++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ incident, markdown = await self.get_incident(+ credentials, input_data.region, input_data+ )+ yield "incident", incident+ if incident.status:+ yield "status", incident.status+ if incident.severity:+ yield "severity", incident.severity+ yield "allowed_intents", incident.allowed_intents+ if markdown:+ yield "markdown", markdown+++class AllQuietListIncidentsBlock(Block):+ """Search incidents, e.g. "every unattended critical still open"."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ statuses: list[IncidentStatus] = SchemaField(+ description="Only return incidents in these statuses.",+ default_factory=lambda: [IncidentStatus.OPEN],+ advanced=False,+ )+ severities: list[IncidentSeverity] = SchemaField(+ description="Only return incidents at these severities.",+ default_factory=list,+ advanced=False,+ )+ team_ids: list[str] = SchemaField(+ description="Only return incidents routed to these teams.",+ default_factory=list,+ advanced=False,+ )+ search_term: str = SchemaField(+ description="Free-text match against the incident title.",+ default="",+ advanced=False,+ )+ unattended: Optional[bool] = SchemaField(+ description="Set true to return only incidents nobody has picked up.",+ default=None,+ advanced=False,+ )+ limit: int = SchemaField(+ description="Maximum number of incidents to return.",+ default=25,+ ge=1,+ le=100,+ advanced=False,+ )+ offset: int = SchemaField(+ description="Number of incidents to skip, for paging.",+ default=0,+ ge=0,+ advanced=True,+ )+ created_from: str = SchemaField(+ description="Only incidents created at or after this ISO-8601 timestamp.",+ default="",+ advanced=True,+ )+ created_until: str = SchemaField(+ description="Only incidents created at or before this ISO-8601 timestamp.",+ default="",+ advanced=True,+ )+ sort_by: IncidentSortBy = SchemaField(+ description="Field to sort the results by.",+ default=IncidentSortBy.CREATED,+ advanced=True,+ )+ ascending: bool = SchemaField(+ description="Sort oldest first instead of newest first.",+ default=False,+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ incidents: list[Incident] = SchemaField(description="All matching incidents")+ incident: Incident = SchemaField(+ description="Each matching incident, emitted one at a time"+ )+ incident_ids: list[str] = SchemaField(+ description="IDs of the matching incidents"+ )+ count: int = SchemaField(description="Number of incidents returned")+ has_more: bool = SchemaField(+ description="Whether more incidents are available beyond this page"+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="c4e91b06-7d3a-4f28-9e51-8b0a2c6d3f97",+ description="Searches All Quiet incidents by status, severity, team or text",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietListIncidentsBlock.Input,+ output_schema=AllQuietListIncidentsBlock.Output,+ test_input={+ "statuses": [IncidentStatus.OPEN.value],+ "limit": 25,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("incidents", [TEST_INCIDENT]),+ ("incident", TEST_INCIDENT),+ ("incident_ids", [TEST_INCIDENT.id]),+ ("count", 1),+ ("has_more", False),+ ],+ test_mock={+ "list_incidents": lambda *args, **kwargs: ([TEST_INCIDENT], False),+ },+ )++ @staticmethod+ async def list_incidents(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> tuple[list[Incident], bool]:+ client = AllQuietClient(credentials, region)+ return await client.list_incidents(+ statuses=input_data.statuses,+ severities=input_data.severities,+ team_ids=input_data.team_ids,+ search_term=input_data.search_term,+ unattended=input_data.unattended,+ created_from=input_data.created_from,+ created_until=input_data.created_until,+ limit=input_data.limit,+ offset=input_data.offset,+ sort_by=input_data.sort_by,+ ascending=input_data.ascending,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ incidents, has_more = await self.list_incidents(+ credentials, input_data.region, input_data+ )+ yield "incidents", incidents+ for incident in incidents:+ yield "incident", incident+ yield "incident_ids", [incident.id for incident in incidents]+ yield "count", len(incidents)+ yield "has_more", has_morediff --git a/autogpt_platform/backend/backend/blocks/allquiet/incidents.py b/autogpt_platform/backend/backend/blocks/allquiet/incidents.pynew file mode 100644index 0000000000..0be79c494e--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/incidents.py@@ -0,0 +1,251 @@+"""Blocks that create and advance All Quiet incidents."""++from typing import Optional++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import AllQuietClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT, allquiet, region_field+from ._testdata import TEST_INCIDENT+from ._types import (+ AllQuietRegion,+ AllQuietUser,+ Incident,+ IncidentIntent,+ IncidentSeverity,+ IncidentStatus,+)+++class AllQuietCreateIncidentBlock(Block):+ """Raise an incident, which routes to whoever is on call for the given teams."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ title: str = SchemaField(+ description="Short summary of what is wrong. Shown in every alert.",+ placeholder="Checkout latency above SLO",+ )+ severity: IncidentSeverity = SchemaField(+ description="How urgent the incident is.",+ default=IncidentSeverity.WARNING,+ advanced=False,+ )+ status: IncidentStatus = SchemaField(+ description=(+ "Open pages the on-call responder. Resolved records the incident "+ "without paging anyone."+ ),+ default=IncidentStatus.OPEN,+ advanced=False,+ )+ message: str = SchemaField(+ description="Longer description with context for the responder.",+ default="",+ advanced=False,+ )+ team_ids: list[str] = SchemaField(+ description=(+ "Teams to route the incident to. Leave empty to use the "+ "integration's default routing."+ ),+ default_factory=list,+ advanced=False,+ )+ service_ids: list[str] = SchemaField(+ description="Affected services, used for status pages and uptime.",+ default_factory=list,+ advanced=True,+ )+ user_ids: list[str] = SchemaField(+ description="Users to assign directly, in addition to on-call routing.",+ default_factory=list,+ advanced=True,+ )+ attributes: dict[str, str] = SchemaField(+ description="Extra key/value context, e.g. host or runbook URL.",+ default_factory=dict,+ advanced=True,+ )+ message_is_public: bool = SchemaField(+ description="Show the message on a connected public status page.",+ default=False,+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ incident: Incident = SchemaField(description="The incident that was created")+ incident_id: str = SchemaField(+ description="ID of the new incident, for later get/update calls"+ )+ on_call_users: list[AllQuietUser] = SchemaField(+ description=(+ "Users the incident was routed to. Often empty in the create "+ "response because All Quiet resolves routing asynchronously — "+ "read the incident back with Get Incident to see the responders."+ )+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="6b1f0e2a-8c4d-4a17-9f3e-2d5b7c9a1e40",+ description="Creates an incident in All Quiet and pages the on-call responder",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietCreateIncidentBlock.Input,+ output_schema=AllQuietCreateIncidentBlock.Output,+ test_input={+ "title": "Checkout latency above SLO",+ "severity": IncidentSeverity.CRITICAL.value,+ "status": IncidentStatus.OPEN.value,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("incident", TEST_INCIDENT),+ ("incident_id", TEST_INCIDENT.id),+ ("on_call_users", []),+ ],+ test_mock={"create_incident": lambda *args, **kwargs: TEST_INCIDENT},+ )++ @staticmethod+ async def create_incident(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> Incident:+ client = AllQuietClient(credentials, region)+ return await client.create_incident(+ title=input_data.title,+ status=input_data.status,+ severity=input_data.severity,+ message=input_data.message,+ message_is_public=input_data.message_is_public,+ team_ids=input_data.team_ids,+ service_ids=input_data.service_ids,+ user_ids=input_data.user_ids,+ attributes=input_data.attributes,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ incident = await self.create_incident(+ credentials, input_data.region, input_data+ )+ yield "incident", incident+ yield "incident_id", incident.id+ yield "on_call_users", incident.on_call_users+++class AllQuietUpdateIncidentBlock(Block):+ """Investigate, resolve, escalate or comment on an existing incident."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ incident_id: str = SchemaField(description="ID of the incident to update")+ intent: IncidentIntent = SchemaField(+ description=(+ "The transition to apply. An incident only accepts the intents "+ "listed in its allowed_intents — e.g. Investigated/Resolved on an "+ "open incident, Unresolved on a resolved one."+ ),+ default=IncidentIntent.INVESTIGATED,+ advanced=False,+ )+ message: str = SchemaField(+ description="Note recorded on the incident timeline with this change.",+ default="",+ advanced=False,+ )+ severity: Optional[IncidentSeverity] = SchemaField(+ description="Optionally change the severity at the same time.",+ default=None,+ advanced=True,+ )+ message_is_public: bool = SchemaField(+ description="Show the message on a connected public status page.",+ default=False,+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ incident: Incident = SchemaField(description="The incident after the update")+ allowed_intents: list[str] = SchemaField(+ description=(+ "Transitions the incident accepts after this update, so a graph "+ "can pick its next intent without re-reading the incident"+ )+ )+ status: Optional[IncidentStatus] = SchemaField(+ description="Status after the update, when the incident reports one"+ )+ severity: Optional[IncidentSeverity] = SchemaField(+ description="Severity after the update, when the incident reports one"+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="0d7c4a91-5e28-4b6f-8a03-1c9e6f2b4d75",+ description="Investigates, resolves, escalates or comments on an All Quiet incident",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietUpdateIncidentBlock.Input,+ output_schema=AllQuietUpdateIncidentBlock.Output,+ test_input={+ "incident_id": TEST_INCIDENT.id,+ "intent": IncidentIntent.RESOLVED.value,+ "message": "Rolled back the bad deploy",+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("incident", TEST_INCIDENT),+ ("allowed_intents", TEST_INCIDENT.allowed_intents),+ ("status", IncidentStatus.OPEN),+ ("severity", IncidentSeverity.CRITICAL),+ ],+ test_mock={"update_incident": lambda *args, **kwargs: TEST_INCIDENT},+ )++ @staticmethod+ async def update_incident(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> Incident:+ client = AllQuietClient(credentials, region)+ await client.append_intent(+ input_data.incident_id,+ intent=input_data.intent.value,+ message=input_data.message,+ message_is_public=input_data.message_is_public,+ severity=input_data.severity,+ )+ # The patch endpoint does not echo the updated incident, so read it back.+ return await client.get_incident(input_data.incident_id)++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ incident = await self.update_incident(+ credentials, input_data.region, input_data+ )+ yield "incident", incident+ yield "allowed_intents", incident.allowed_intents+ if incident.status:+ yield "status", incident.status+ if incident.severity:+ yield "severity", incident.severitydiff --git a/autogpt_platform/backend/backend/blocks/allquiet/on_call.py b/autogpt_platform/backend/backend/blocks/allquiet/on_call.pynew file mode 100644index 0000000000..513ff3674c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/on_call.py@@ -0,0 +1,130 @@+"""Block that reads who is currently on call."""++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import AllQuietClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT, allquiet, region_field+from ._testdata import TEST_SHIFT+from ._types import AllQuietRegion, AllQuietUser, OnCallShift+++class AllQuietGetOnCallBlock(Block):+ """Look up who is on call, now or at a chosen time."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ team_ids: list[str] = SchemaField(+ description="Limit to these teams. Leave empty for every team.",+ default_factory=list,+ advanced=False,+ )+ user_ids: list[str] = SchemaField(+ description="Limit to these users. Leave empty for every user.",+ default_factory=list,+ advanced=True,+ )+ timestamp: str = SchemaField(+ description=(+ "ISO-8601 timestamp to evaluate the rotation at. "+ "Leave empty for right now."+ ),+ default="",+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ shifts: list[OnCallShift] = SchemaField(+ description="Every matching on-call assignment"+ )+ shift: OnCallShift = SchemaField(+ description="Each on-call assignment, emitted one at a time"+ )+ users: list[AllQuietUser] = SchemaField(+ description="The on-call users, deduplicated across teams"+ )+ user_ids: list[str] = SchemaField(description="IDs of the on-call users")+ emails: list[str] = SchemaField(+ description="Email addresses of the on-call users"+ )+ users_without_email: list[AllQuietUser] = SchemaField(+ description=(+ "On-call users carrying no email address. These are counted in "+ "users/has_coverage but absent from emails, so a graph that "+ "notifies by email alone would silently skip them"+ )+ )+ has_coverage: bool = SchemaField(+ description=(+ "False when nobody is on call for the requested teams/time, so a "+ "graph can branch to a fallback instead of silently paging no one"+ )+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="8e5d3b27-1a94-4c6f-b7e0-5f9c2d8a4b16",+ description="Looks up who is on call in All Quiet, now or at a given time",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietGetOnCallBlock.Input,+ output_schema=AllQuietGetOnCallBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("shifts", [TEST_SHIFT]),+ ("shift", TEST_SHIFT),+ ("users", [TEST_SHIFT.user]),+ ("user_ids", [TEST_SHIFT.user.id if TEST_SHIFT.user else ""]),+ ("emails", ["[email protected]"]),+ ("users_without_email", []),+ ("has_coverage", True),+ ],+ test_mock={"get_on_call": lambda *args, **kwargs: [TEST_SHIFT]},+ )++ @staticmethod+ async def get_on_call(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> list[OnCallShift]:+ client = AllQuietClient(credentials, region)+ return await client.get_on_call(+ team_ids=input_data.team_ids,+ user_ids=input_data.user_ids,+ timestamp=input_data.timestamp,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ shifts = await self.get_on_call(credentials, input_data.region, input_data)+ yield "shifts", shifts+ for shift in shifts:+ yield "shift", shift++ # A user on call for several teams appears once per team; collapse them+ # so downstream notification steps do not page the same person twice.+ users_by_id: dict[str, AllQuietUser] = {}+ for shift in shifts:+ if shift.user and shift.user.id:+ users_by_id.setdefault(shift.user.id, shift.user)++ users = list(users_by_id.values())+ yield "users", users+ yield "user_ids", list(users_by_id)+ yield "emails", [user.email for user in users if user.email]+ # Surfaced separately so an email-only notification step can tell+ # "nobody on call" apart from "on call but unreachable by email".+ yield "users_without_email", [user for user in users if not user.email]+ yield "has_coverage", bool(users)diff --git a/autogpt_platform/backend/backend/blocks/allquiet/teams.py b/autogpt_platform/backend/backend/blocks/allquiet/teams.pynew file mode 100644index 0000000000..1927f5ca05--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/teams.py@@ -0,0 +1,99 @@+"""Block that lists All Quiet teams, to resolve the team IDs other blocks take."""++from backend.sdk import (+ APIKeyCredentials,+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import AllQuietClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT, allquiet, region_field+from ._testdata import TEST_TEAM+from ._types import AllQuietRegion, Team+++class AllQuietListTeamsBlock(Block):+ """List teams so other blocks can be pointed at them by ID."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = allquiet.credentials_field(+ description="The All Quiet integration requires an API Key."+ )+ display_name: str = SchemaField(+ description="Filter to teams whose name matches this text.",+ default="",+ advanced=False,+ )+ limit: int = SchemaField(+ description="Maximum number of teams to return.",+ default=50,+ ge=1,+ le=100,+ advanced=False,+ )+ offset: int = SchemaField(+ description="Number of teams to skip, for paging.",+ default=0,+ ge=0,+ advanced=True,+ )+ region: AllQuietRegion = region_field()++ class Output(BlockSchemaOutput):+ teams: list[Team] = SchemaField(description="All matching teams")+ team: Team = SchemaField(+ description="Each matching team, emitted one at a time"+ )+ team_ids: list[str] = SchemaField(+ description="IDs of the matching teams, for use as team_ids elsewhere"+ )+ has_more: bool = SchemaField(+ description="Whether more teams are available beyond this page"+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="2a6f8d13-4b70-4e29-8c5d-9e1b3f7a0c48",+ description="Lists All Quiet teams and their IDs",+ categories={BlockCategory.DEVELOPER_TOOLS, BlockCategory.ISSUE_TRACKING},+ input_schema=AllQuietListTeamsBlock.Input,+ output_schema=AllQuietListTeamsBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("teams", [TEST_TEAM]),+ ("team", TEST_TEAM),+ ("team_ids", [TEST_TEAM.id]),+ ("has_more", False),+ ],+ test_mock={"list_teams": lambda *args, **kwargs: ([TEST_TEAM], False)},+ )++ @staticmethod+ async def list_teams(+ credentials: APIKeyCredentials, region: AllQuietRegion, input_data: Input+ ) -> tuple[list[Team], bool]:+ client = AllQuietClient(credentials, region)+ return await client.list_teams(+ display_name=input_data.display_name,+ limit=input_data.limit,+ offset=input_data.offset,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ teams, has_more = await self.list_teams(+ credentials, input_data.region, input_data+ )+ yield "teams", teams+ for team in teams:+ yield "team", team+ yield "team_ids", [team.id for team in teams]+ yield "has_more", has_morediff --git a/autogpt_platform/backend/backend/blocks/allquiet/triggers.py b/autogpt_platform/backend/backend/blocks/allquiet/triggers.pynew file mode 100644index 0000000000..f0aa2c965e--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/triggers.py@@ -0,0 +1,227 @@+"""Trigger block fired by an All Quiet outbound webhook."""++import html+from typing import Any, Optional++from pydantic import BaseModel, TypeAdapter, ValidationError++from backend.sdk import (+ Block,+ BlockCategory,+ BlockManualWebhookConfig,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ ProviderName,+ SchemaField,+)++from ._config import allquiet+from ._types import IncidentSeverity, IncidentStatus+from ._webhook import AllQuietWebhookType++# Body template to paste into the All Quiet outbound webhook. It forwards the+# whole incident rather than a flattened subset, so the block can emit status,+# severity and attributes as well as the IDs.+# Goes in the `body.json` slot of an All Quiet outbound webhook, whose config is+# {"method": "POST", "url": "<this block's ingress URL>",+# "headers": {"Content-Type": "application/json"},+# "body": {"json": <this template>}}+#+# All Quiet renders it with Handlebars. Deliberately the ESCAPING `{{ }}` form,+# not triple-stash: these placeholders sit inside JSON string literals, and a+# value containing a double quote (common in alert titles) would terminate the+# string early and render the whole body invalid JSON. `{{ }}` escapes `"` to+# `"`, which is JSON-safe, and the block unescapes on the way in — so the+# escaping is round-tripped rather than leaked to the graph.+#+# All Quiet additionally exposes `attributesByName` (a map) if you'd rather pull+# named attributes directly than iterate: {{attributesByName.Environment.value}},+# or {{attributesByName.[My Attribute].value}} when the name has spaces.+RECOMMENDED_BODY_TEMPLATE = """{+ "id": "{{id}}",+ "title": "{{title}}",+ "eventId": "{{events.[0].id}}",+ "status": "{{events.[0].status}}",+ "severity": "{{events.[0].severity}}",+ "intent": "{{events.[0].modification.intent}}",+ "attributes": [+ {{#each attributes}}+ { "name": "{{this.name}}", "value": "{{this.value}}" }{{#unless @last}},{{/unless}}+ {{/each}}+ ]+}"""+++class _Attribute(BaseModel):+ """One entry of an All Quiet attribute list, as rendered by a body template."""++ name: str = ""+ value: str = ""+++_ATTRIBUTE_LIST = TypeAdapter(list[Any])++# Precomputed so `run()` doesn't rebuild them on every delivery.+_STATUS_VALUES = {member.value for member in IncidentStatus}+_SEVERITY_VALUES = {member.value for member in IncidentSeverity}++EXAMPLE_PAYLOAD = {+ "id": "81cd20be-5837-4dd8-a951-2207a025a231",+ "title": "RAM above 60%",+ "eventId": "b4d2a6a9-be50-45ff-863a-b0ee1a77494e",+ "status": "Open",+ "severity": "Warning",+ "intent": "Investigated",+ "attributes": [+ {"name": "Environment", "value": "prod"},+ {"name": "Alert", "value": "RAM > 60%1"},+ ],+}+++class AllQuietIncidentTriggerBlock(Block):+ """Starts a graph whenever All Quiet posts an incident to this webhook.++ Configure an outbound webhook integration in All Quiet pointing at this+ block's webhook URL. The block reads All Quiet's default flattened payload+ (``incidentId``/``incidentTitle``/``incidentProperties``) as well as the+ richer template in ``RECOMMENDED_BODY_TEMPLATE``, and always emits the raw+ body so any custom template stays usable.+ """++ class Input(BlockSchemaInput):+ payload: dict = SchemaField(hidden=True, default_factory=dict)+ signing_secret: str | None = SchemaField(+ title="Signing secret",+ description=(+ "Optional. If All Quiet's outbound webhook has signing enabled, "+ "paste the signing secret here and deliveries with a missing or "+ "bad signature are rejected. Both the All Quiet "+ "(x-aq-signature) and AWS (x-amzn-event-signature) formats are "+ "accepted. Leave empty for unsigned webhooks."+ ),+ default=None,+ secret=True,+ advanced=False,+ )++ class Output(BlockSchemaOutput):+ payload: dict = SchemaField(description="The raw payload All Quiet delivered")+ incident_id: str = SchemaField(description="ID of the incident that fired")+ incident_title: str = SchemaField(description="Title of the incident")+ event_id: str = SchemaField(+ description="ID of the timeline event that triggered this delivery"+ )+ status: Optional[IncidentStatus] = SchemaField(+ description="Incident status, if the payload template includes it"+ )+ severity: Optional[IncidentSeverity] = SchemaField(+ description="Incident severity, if the payload template includes it"+ )+ attributes: dict[str, str] = SchemaField(+ description="Incident attributes flattened to a name/value mapping"+ )++ def __init__(self):+ super().__init__(+ id="9c2e7b41-3d68-4a05-8f1c-6b4d0e9a2f37",+ description="Triggers a graph when All Quiet posts an incident to this webhook",+ categories={BlockCategory.INPUT, BlockCategory.DEVELOPER_TOOLS},+ input_schema=AllQuietIncidentTriggerBlock.Input,+ output_schema=AllQuietIncidentTriggerBlock.Output,+ webhook_config=BlockManualWebhookConfig(+ provider=ProviderName(allquiet.name),+ webhook_type=AllQuietWebhookType.INCIDENT,+ ),+ test_input={"payload": EXAMPLE_PAYLOAD},+ test_output=[+ ("payload", EXAMPLE_PAYLOAD),+ ("incident_id", "81cd20be-5837-4dd8-a951-2207a025a231"),+ ("incident_title", "RAM above 60%"),+ ("event_id", "b4d2a6a9-be50-45ff-863a-b0ee1a77494e"),+ ("status", IncidentStatus.OPEN),+ ("severity", IncidentSeverity.WARNING),+ (+ "attributes",+ {"Environment": "prod", "Alert": "RAM > 60%1"},+ ),+ ],+ )++ async def run(self, input_data: Input, **kwargs) -> BlockOutput:+ payload = input_data.payload+ yield "payload", payload++ # All Quiet's stock template flattens the incident to incidentId /+ # incidentTitle / incidentProperties; a template that forwards the+ # incident itself uses id / title / attributes. Accept both.+ incident_id = _first_str(payload, "incidentId", "id")+ if incident_id:+ yield "incident_id", incident_id++ incident_title = _first_str(payload, "incidentTitle", "title")+ if incident_title:+ yield "incident_title", incident_title++ event_id = _first_str(payload, "eventId")+ if event_id:+ yield "event_id", event_id++ status = _first_str(payload, "status")+ if status in _STATUS_VALUES:+ yield "status", IncidentStatus(status)++ severity = _first_str(payload, "severity")+ if severity in _SEVERITY_VALUES:+ yield "severity", IncidentSeverity(severity)++ yield "attributes", _attributes(payload)+++def _first_str(payload: dict[str, Any], *keys: str) -> str:+ """Return the first of ``keys`` with a non-empty value, as a string."""+ for key in keys:+ value = payload.get(key)+ if value:+ return _unescape(str(value))+ return ""+++def _unescape(value: str) -> str:+ """Undo the HTML escaping Handlebars applies to ``{{ }}`` placeholders.++ All Quiet's stock body template uses the escaping form, so a value like+ ``RAM > 60%`` arrives as ``RAM > 60%``. Unescaping is the correct inverse+ for anything that came through that path: a value containing a literal+ ``>`` would have been double-escaped to ``&gt;`` and round-trips+ cleanly. Templates using the triple-stash form send raw values, where this+ is a no-op unless the value genuinely contains an entity.+ """+ return html.unescape(value)+++def _attributes(payload: dict[str, Any]) -> dict[str, str]:+ """Flatten All Quiet's ``[{name, value}]`` attribute lists to a mapping.++ The body is rendered from a user-editable template, so the value may be any+ JSON shape. Anything that isn't a list of name/value objects is skipped+ rather than raising, so one bad template field can't fail the whole trigger.+ """+ raw = payload.get("attributes") or payload.get("incidentProperties") or []+ try:+ entries = _ATTRIBUTE_LIST.validate_python(raw)+ except ValidationError:+ return {}++ flattened: dict[str, str] = {}+ for entry in entries:+ # Validate entries one at a time so a single malformed item is dropped+ # instead of discarding every attribute alongside it.+ try:+ attribute = _Attribute.model_validate(entry)+ except ValidationError:+ continue+ if attribute.name:+ flattened[_unescape(attribute.name)] = _unescape(attribute.value)+ return flatteneddiff --git a/autogpt_platform/backend/backend/blocks/allquiet/triggers_test.py b/autogpt_platform/backend/backend/blocks/allquiet/triggers_test.pynew file mode 100644index 0000000000..5b348a3443--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/allquiet/triggers_test.py@@ -0,0 +1,226 @@+"""Tests that the trigger block reads both All Quiet webhook payload shapes."""++import html+import json+import re++from backend.blocks.allquiet._types import IncidentSeverity, IncidentStatus+from backend.blocks.allquiet.triggers import (+ EXAMPLE_PAYLOAD,+ RECOMMENDED_BODY_TEMPLATE,+ AllQuietIncidentTriggerBlock,+)++# All Quiet's stock outbound-webhook body template renders this shape.+DEFAULT_TEMPLATE_PAYLOAD = {+ "eventId": "b4d2a6a9-be50-45ff-863a-b0ee1a77494e",+ "incidentId": "81cd20be-5837-4dd8-a951-2207a025a231",+ "incidentTitle": "RAM above 60%",+ "incidentProperties": [+ {"name": "Environment", "value": "prod"},+ {"name": "Alert", "value": "RAM > 60%1"},+ ],+}+++async def _outputs(payload: dict) -> dict:+ block = AllQuietIncidentTriggerBlock()+ collected: dict = {}+ async for name, value in block.run(block.input_schema(payload=payload)):+ collected[name] = value+ return collected+++class TestDefaultTemplate:+ async def test_reads_the_flattened_incident_fields(self):+ out = await _outputs(DEFAULT_TEMPLATE_PAYLOAD)++ assert out["incident_id"] == "81cd20be-5837-4dd8-a951-2207a025a231"+ assert out["incident_title"] == "RAM above 60%"+ assert out["event_id"] == "b4d2a6a9-be50-45ff-863a-b0ee1a77494e"++ async def test_flattens_incident_properties(self):+ out = await _outputs(DEFAULT_TEMPLATE_PAYLOAD)++ assert out["attributes"] == {"Environment": "prod", "Alert": "RAM > 60%1"}++ async def test_omits_status_and_severity_the_template_does_not_carry(self):+ out = await _outputs(DEFAULT_TEMPLATE_PAYLOAD)++ assert "status" not in out+ assert "severity" not in out++ async def test_always_passes_the_raw_payload_through(self):+ out = await _outputs(DEFAULT_TEMPLATE_PAYLOAD)++ assert out["payload"] == DEFAULT_TEMPLATE_PAYLOAD+++class TestRecommendedTemplate:+ async def test_reads_status_and_severity(self):+ out = await _outputs(EXAMPLE_PAYLOAD)++ assert out["status"] == IncidentStatus.OPEN+ assert out["severity"] == IncidentSeverity.WARNING++ async def test_reads_the_unprefixed_id_and_title(self):+ out = await _outputs(EXAMPLE_PAYLOAD)++ assert out["incident_id"] == "81cd20be-5837-4dd8-a951-2207a025a231"+ assert out["incident_title"] == "RAM above 60%"+++class TestUnexpectedPayloads:+ async def test_survives_an_empty_payload(self):+ out = await _outputs({})++ assert out["payload"] == {}+ assert out["attributes"] == {}+ assert "incident_id" not in out++ async def test_ignores_a_status_value_it_does_not_recognise(self):+ # A custom template could send anything; never emit a bogus enum.+ out = await _outputs({"id": "x", "status": "Snoozed", "severity": "Fatal"})++ assert "status" not in out+ assert "severity" not in out+ assert out["incident_id"] == "x"++ async def test_skips_attribute_entries_with_no_name(self):+ out = await _outputs({"attributes": [{"value": "orphan"}, {"name": "ok"}]})++ assert out["attributes"] == {"ok": ""}+++class TestRecommendedTemplateIsValid:+ """The template is copy-paste guidance, so it must render valid JSON."""++ def test_renders_valid_json_for_multiple_attributes(self):+ rendered = _render(+ RECOMMENDED_BODY_TEMPLATE,+ attributes=[+ {"name": "Environment", "value": "prod"},+ {"name": "Alert", "value": "RAM > 60%"},+ ],+ )++ # Values arrive HTML-escaped (the template uses the JSON-safe `{{ }}`+ # form); the block unescapes them on the way in.+ parsed = json.loads(rendered)+ assert parsed["attributes"] == [+ {"name": "Environment", "value": "prod"},+ {"name": "Alert", "value": "RAM > 60%"},+ ]+ assert [html.unescape(a["value"]) for a in parsed["attributes"]] == [+ "prod",+ "RAM > 60%",+ ]++ def test_renders_valid_json_for_one_attribute(self):+ rendered = _render(+ RECOMMENDED_BODY_TEMPLATE, attributes=[{"name": "Env", "value": "prod"}]+ )++ assert json.loads(rendered)["attributes"] == [{"name": "Env", "value": "prod"}]++ def test_renders_valid_json_for_no_attributes(self):+ assert (+ json.loads(_render(RECOMMENDED_BODY_TEMPLATE, attributes=[]))["attributes"]+ == []+ )+++def _render(template: str, *, attributes: list[dict]) -> str:+ """Minimal Handlebars stand-in for the subset the template uses.++ Only `{{#each}}` / `{{#unless @last}}` / `{{field}}` are needed, so this+ avoids adding a Handlebars dependency just to assert the template is valid.+ """+ each = re.search(r"\{\{#each attributes\}\}(.*?)\{\{/each\}\}", template, re.DOTALL)+ assert each, "template no longer contains the attributes loop"++ body = each.group(1)+ rendered_items = []+ for index, attribute in enumerate(attributes):+ item = body+ separator = "" if index == len(attributes) - 1 else ","+ item = re.sub(r"\{\{#unless @last\}\},\{\{/unless\}\}", separator, item)+ # Handlebars HTML-escapes {{ }} values; mirror that here.+ item = item.replace("{{this.name}}", html.escape(attribute["name"], quote=True))+ item = item.replace(+ "{{this.value}}", html.escape(attribute["value"], quote=True)+ )+ rendered_items.append(item.strip())++ out = template[: each.start()] + "".join(rendered_items) + template[each.end() :]+ # Fill the remaining scalar placeholders with something JSON-safe.+ return re.sub(r"\{\{+[^}]+\}\}+", "x", out)+++class TestHtmlEscaping:+ """All Quiet's stock template (and its "test alert" button) HTML-escapes values.++ Handlebars escapes `{{ }}` by default, so `RAM > 60%` arrives as+ `RAM > 60%`. Captured from a real test-alert delivery.+ """++ async def test_unescapes_attribute_values_from_the_test_alert(self):+ out = await _outputs(+ {+ "eventId": "b4d2a6a9-be50-45ff-863a-b0ee1a77494e",+ "incidentId": "81cd20be-5837-4dd8-a951-2207a025a231",+ "incidentTitle": "",+ "incidentProperties": [+ {"name": "Environment", "value": "prod"},+ {"name": "Alert", "value": "RAM > 60%1"},+ ],+ }+ )++ assert out["attributes"] == {+ "Environment": "prod",+ "Alert": "RAM > 60%1",+ }++ async def test_unescapes_the_incident_title(self):+ out = await _outputs({"incidentTitle": "Disk > 90% & climbing"})++ assert out["incident_title"] == "Disk > 90% & climbing"++ async def test_omits_an_empty_title(self):+ # The test alert sends incidentTitle: "" — emitting an empty string+ # would look like a real (blank) title downstream.+ out = await _outputs({"incidentId": "x", "incidentTitle": ""})++ assert "incident_title" not in out++ async def test_round_trips_a_literal_entity(self):+ # A value containing a literal ">" is double-escaped by Handlebars,+ # so unescaping recovers exactly what was typed.+ out = await _outputs({"attributes": [{"name": "n", "value": "&gt;"}]})++ assert out["attributes"]["n"] == ">"++ async def test_unescapes_attribute_names_too(self):+ out = await _outputs({"attributes": [{"name": "A & B", "value": "v"}]})++ assert out["attributes"] == {"A & B": "v"}+++class TestRecommendedTemplateEscapes:+ def test_uses_no_triple_stash(self):+ # Triple-stash emits raw values, so an alert title containing a double+ # quote would terminate the JSON string early and break the body. The+ # escaping form keeps it valid; the block unescapes on the way in.+ assert "{{{" not in RECOMMENDED_BODY_TEMPLATE++ def test_a_value_containing_a_quote_still_renders_valid_json(self):+ rendered = _render(+ RECOMMENDED_BODY_TEMPLATE,+ attributes=[{"name": "Alert", "value": 'unterminated "group"'}],+ )++ # Valid JSON, and the escaped value round-trips through the block.+ parsed = json.loads(rendered)+ assert parsed["attributes"][0]["value"] == "unterminated "group""+ assert html.unescape(parsed["attributes"][0]["value"]) == 'unterminated "group"'diff --git a/autogpt_platform/backend/backend/integrations/webhooks/manager_registry_test.py b/autogpt_platform/backend/backend/integrations/webhooks/manager_registry_test.pynew file mode 100644index 0000000000..b45ffbfd52--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/webhooks/manager_registry_test.py@@ -0,0 +1,126 @@+"""Registry-wide invariants for webhook managers.++`BaseWebhooksManager` declares `validate_payload`, `_register_webhook` and+`_deregister_webhook` abstract. A manager that omits one still imports fine,+still registers against its provider, and still passes the block test harness —+Python only refuses at *instantiation*, and nothing instantiates a webhook+manager until a user actually sets up a trigger. The failure therefore lands on+the user as::++ Can't instantiate abstract class <X>WebhooksManager without an+ implementation for abstract method 'validate_payload'++These tests close that gap by exercising, for every registered provider, the+same call the runtime makes.+"""++import pytest++from backend.blocks import get_blocks+from backend.blocks._base import Block+from backend.integrations import webhooks+from backend.integrations.webhooks import get_webhook_manager, supports_webhooks+from backend.integrations.webhooks._base import BaseWebhooksManager+++def load_webhook_managers():+ """Resolve the loader off the module at call time.++ `AutoRegistry.patch_integrations()` replaces the module attribute, so a+ `from ... import load_webhook_managers` binding taken at import time can+ keep pointing at the unpatched original and miss every SDK-registered+ manager — which would make these checks pass vacuously.+ """+ return webhooks.load_webhook_managers()++[email protected](scope="module", autouse=True)+def _load_sdk_providers():+ """Import every block so SDK-registered webhook managers join the registry.++ Providers built with `ProviderBuilder(...).with_webhook_manager(...)` are+ only added to `load_webhook_managers()` once their block module is imported.+ """+ get_blocks()+++def _webhook_blocks() -> list[type[Block]]:+ return [+ block_cls+ for block_cls in get_blocks().values()+ if block_cls().webhook_config is not None+ ]+++def _registered_providers() -> list:+ """Snapshot the provider keys for parametrization.++ Snapshotted because `get_webhook_manager` calls `load_webhook_managers`+ again, and the SDK's patched loader re-inserts its managers into the same+ cached dict — iterating it live would mutate it mid-iteration.+ """+ get_blocks()+ return list(load_webhook_managers())+++def test_registry_is_not_empty():+ # Guards against the fixture silently failing to import blocks, which would+ # make every other test here vacuously pass.+ assert load_webhook_managers()+++def test_every_registered_manager_implements_all_abstract_methods():+ unimplemented = {+ provider: sorted(manager_cls.__abstractmethods__)+ for provider, manager_cls in load_webhook_managers().items()+ if getattr(manager_cls, "__abstractmethods__", frozenset())+ }++ assert not unimplemented, (+ "These webhook managers are still abstract and will raise TypeError the "+ "first time a user sets up a trigger: "+ f"{unimplemented}"+ )++[email protected]("provider", _registered_providers(), ids=str)+def test_every_registered_manager_can_be_instantiated(provider):+ # Parametrized rather than looped so a failure names the offending provider+ # and keeps its original traceback, instead of being flattened into a dict.+ get_webhook_manager(provider)+++def test_every_registered_manager_subclasses_the_base():+ wrong_base = {+ str(provider): manager_cls.__name__+ for provider, manager_cls in load_webhook_managers().items()+ if not issubclass(manager_cls, BaseWebhooksManager)+ }++ assert (+ not wrong_base+ ), f"Webhook managers not deriving from BaseWebhooksManager: {wrong_base}"+++def _block_name(block_cls: type[Block]) -> str:+ return block_cls().name++[email protected]("block_cls", _webhook_blocks(), ids=_block_name)+def test_webhook_block_has_a_usable_manager(block_cls: type[Block]):+ """A block advertising a webhook must have a manager that actually works.++ This is the end-to-end shape of the bug: the block registers, the provider+ registers, and only `get_webhook_manager()` — reached during trigger setup —+ discovers the manager is unusable.+ """+ block = block_cls()+ webhook_config = block.webhook_config+ assert webhook_config is not None++ provider = webhook_config.provider+ assert supports_webhooks(+ provider+ ), f"{block.name} declares webhook provider {provider!r} with no registered manager"++ get_webhook_manager(provider)diff --git a/autogpt_platform/backend/scripts/generate_block_docs.py b/autogpt_platform/backend/scripts/generate_block_docs.pyindex fa82712594..978b456ee1 100644--- a/autogpt_platform/backend/scripts/generate_block_docs.py+++ b/autogpt_platform/backend/scripts/generate_block_docs.py@@ -229,6 +229,7 @@ def file_path_to_title(file_path: str) -> str:"Pr": "PR","Gmb": "GMB", # Google My Business"Hubspot": "HubSpot",+ "Allquiet": "All Quiet","Linkedin": "LinkedIn","Tiktok": "TikTok","Youtube": "YouTube",diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 00c9e58211..c5ffd77fec 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -484,6 +484,13 @@ Below is a comprehensive list of all available blocks, categorized by their prim| Block Name | Description ||------------|-------------|+| [All Quiet Create Incident](block-integrations/allquiet/incidents.md#all-quiet-create-incident) | Creates an incident in All Quiet and pages the on-call responder |+| [All Quiet Get Incident](block-integrations/allquiet/incident_search.md#all-quiet-get-incident) | Fetches a single All Quiet incident by ID |+| [All Quiet Get On Call](block-integrations/allquiet/on_call.md#all-quiet-get-on-call) | Looks up who is on call in All Quiet, now or at a given time |+| [All Quiet Incident Trigger](block-integrations/allquiet/triggers.md#all-quiet-incident-trigger) | Triggers a graph when All Quiet posts an incident to this webhook |+| [All Quiet List Incidents](block-integrations/allquiet/incident_search.md#all-quiet-list-incidents) | Searches All Quiet incidents by status, severity, team or text |+| [All Quiet List Teams](block-integrations/allquiet/teams.md#all-quiet-list-teams) | Lists All Quiet teams and their IDs |+| [All Quiet Update Incident](block-integrations/allquiet/incidents.md#all-quiet-update-incident) | Investigates, resolves, escalates or comments on an All Quiet incident || [Exa Code Context](block-integrations/exa/code_context.md#exa-code-context) | Search billions of GitHub repos, docs, and Stack Overflow for relevant code examples || [Execute Code](block-integrations/misc.md#execute-code) | Executes code in a sandbox environment with internet access || [Execute Code Step](block-integrations/misc.md#execute-code-step) | Execute code in a previously instantiated sandbox |diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex efcfaa00cf..debb0d15df 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -20,6 +20,11 @@* [Airtable Records](block-integrations/airtable/records.md)* [Airtable Schema](block-integrations/airtable/schema.md)* [Airtable Triggers](block-integrations/airtable/triggers.md)+* [All Quiet Incident Search](block-integrations/allquiet/incident_search.md)+* [All Quiet Incidents](block-integrations/allquiet/incidents.md)+* [All Quiet On Call](block-integrations/allquiet/on_call.md)+* [All Quiet Teams](block-integrations/allquiet/teams.md)+* [All Quiet Triggers](block-integrations/allquiet/triggers.md)* [Apollo Organization](block-integrations/apollo/organization.md)* [Apollo People](block-integrations/apollo/people.md)* [Apollo Person](block-integrations/apollo/person.md)diff --git a/docs/integrations/block-integrations/allquiet/incident_search.md b/docs/integrations/block-integrations/allquiet/incident_search.mdnew file mode 100644index 0000000000..8e138d0f7b--- /dev/null+++ b/docs/integrations/block-integrations/allquiet/incident_search.md@@ -0,0 +1,85 @@+# All Quiet Incident Search+<!-- MANUAL: file_description -->+Blocks that read All Quiet incidents — fetching a single incident by ID, or searching the incident list by status, severity, team, text or time range.+<!-- END MANUAL -->++## All Quiet Get Incident++### What it is+Fetches a single All Quiet incident by ID++### How it works+<!-- MANUAL: how_it_works -->+Fetches one incident by ID and flattens its current status and severity onto the result — All Quiet stores those at the head of the incident's event timeline rather than on the incident itself. `allowed_intents` reports which transitions the incident will currently accept. Turning on `include_markdown` makes a second call for All Quiet's rendered markdown report, which bundles the attributes and full timeline into prose that is well suited to feeding an LLM.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| incident_id | ID of the incident to fetch | str | Yes |+| include_markdown | Also fetch an LLM-friendly markdown report of the incident, including its attributes and full timeline. Costs one extra API call. | bool | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| incident | The incident | Incident |+| status | Current status, when the incident reports one | "Open" \| "Resolved" |+| severity | Current severity, when the incident reports one | "Critical" \| "Warning" \| "Minor" |+| allowed_intents | Transitions this incident currently accepts | List[str] |+| markdown | Markdown report, if include_markdown was set | str |++### Possible use case+<!-- MANUAL: use_case -->+A triage agent receives an incident ID from the trigger block, fetches it with `include_markdown` enabled, and feeds the markdown report — attributes, timeline and all — to an LLM to draft a first-response summary and suggest a likely cause.+<!-- END MANUAL -->++---++## All Quiet List Incidents++### What it is+Searches All Quiet incidents by status, severity, team or text++### How it works+<!-- MANUAL: how_it_works -->+Searches the incident list with All Quiet's server-side filters: status, severity, teams, a free-text title match, an unattended flag, and a created-at range. Results are paginated (`limit`/`offset`) and `has_more` reports whether further pages exist. Alongside the full list the block emits each incident individually, plus a list of bare `incident_ids` that feeds straight into Get Incident or Update Incident.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| statuses | Only return incidents in these statuses. | List["Open" \| "Resolved"] | No |+| severities | Only return incidents at these severities. | List["Critical" \| "Warning" \| "Minor"] | No |+| team_ids | Only return incidents routed to these teams. | List[str] | No |+| search_term | Free-text match against the incident title. | str | No |+| unattended | Set true to return only incidents nobody has picked up. | bool | No |+| limit | Maximum number of incidents to return. | int | No |+| offset | Number of incidents to skip, for paging. | int | No |+| created_from | Only incidents created at or after this ISO-8601 timestamp. | str | No |+| created_until | Only incidents created at or before this ISO-8601 timestamp. | str | No |+| sort_by | Field to sort the results by. | "Created" \| "LastUpdatedAt" \| "LatestInteraction" \| "Urgency" \| "Title" | No |+| ascending | Sort oldest first instead of newest first. | bool | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| incidents | All matching incidents | List[Incident] |+| incident | Each matching incident, emitted one at a time | Incident |+| incident_ids | IDs of the matching incidents | List[str] |+| count | Number of incidents returned | int |+| has_more | Whether more incidents are available beyond this page | bool |++### Possible use case+<!-- MANUAL: use_case -->+A morning-standup agent lists every incident created in the last 24 hours, groups them by severity, and posts a digest — or, filtering on `unattended`, chases anything still open that nobody has picked up.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/allquiet/incidents.md b/docs/integrations/block-integrations/allquiet/incidents.mdnew file mode 100644index 0000000000..fca577f9b5--- /dev/null+++ b/docs/integrations/block-integrations/allquiet/incidents.md@@ -0,0 +1,83 @@+# All Quiet Incidents+<!-- MANUAL: file_description -->+Blocks that create All Quiet incidents and move them through their lifecycle. Use these when an agent needs to raise an alert that reaches a human, or to acknowledge, resolve, escalate or comment on one it already raised.+<!-- END MANUAL -->++## All Quiet Create Incident++### What it is+Creates an incident in All Quiet and pages the on-call responder++### How it works+<!-- MANUAL: how_it_works -->+Posts to All Quiet's `/incident` endpoint with a title, severity and status. All Quiet then applies your routing rules to decide who gets paged — so the block does not pick a responder itself; it hands the incident to the rotation. Optional team IDs override the integration's default routing, and arbitrary key/value attributes ride along for context (host, runbook link, dashboard URL). Note that `on_call_users` is often empty in the response because All Quiet resolves routing asynchronously; read the incident back with Get Incident to see who it landed on.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| title | Short summary of what is wrong. Shown in every alert. | str | Yes |+| severity | How urgent the incident is. | "Critical" \| "Warning" \| "Minor" | No |+| status | Open pages the on-call responder. Resolved records the incident without paging anyone. | "Open" \| "Resolved" | No |+| message | Longer description with context for the responder. | str | No |+| team_ids | Teams to route the incident to. Leave empty to use the integration's default routing. | List[str] | No |+| service_ids | Affected services, used for status pages and uptime. | List[str] | No |+| user_ids | Users to assign directly, in addition to on-call routing. | List[str] | No |+| attributes | Extra key/value context, e.g. host or runbook URL. | Dict[str, str] | No |+| message_is_public | Show the message on a connected public status page. | bool | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| incident | The incident that was created | Incident |+| incident_id | ID of the new incident, for later get/update calls | str |+| on_call_users | Users the incident was routed to. Often empty in the create response because All Quiet resolves routing asynchronously — read the incident back with Get Incident to see the responders. | List[AllQuietUser] |++### Possible use case+<!-- MANUAL: use_case -->+An agent monitoring error rates notices checkout failures spiking. Rather than posting into a chat channel nobody is watching at 3am, it creates a Critical incident routed to the Platform team, attaching the dashboard URL and the failing endpoint as attributes — and All Quiet phones whoever is actually on call.+<!-- END MANUAL -->++---++## All Quiet Update Incident++### What it is+Investigates, resolves, escalates or comments on an All Quiet incident++### How it works+<!-- MANUAL: how_it_works -->+Applies an *intent* to an existing incident — All Quiet's term for a state transition such as Investigated (acknowledge), Resolved, Escalated or Commented. Which intents an incident accepts depends on its current status: an open incident accepts Investigated/Resolved/Escalated, a resolved one accepts Unresolved. The block emits `allowed_intents` after the update so a graph can choose its next move without a second read. The severity can be changed in the same call. Because All Quiet's patch endpoint does not echo the updated incident, the block re-reads it to report the resulting state.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| incident_id | ID of the incident to update | str | Yes |+| intent | The transition to apply. An incident only accepts the intents listed in its allowed_intents — e.g. Investigated/Resolved on an open incident, Unresolved on a resolved one. | "Investigated" \| "Resolved" \| "Unresolved" \| "Escalated" \| "Commented" \| "Snoozed" \| "Archived" | No |+| message | Note recorded on the incident timeline with this change. | str | No |+| severity | Optionally change the severity at the same time. | "Critical" \| "Warning" \| "Minor" | No |+| message_is_public | Show the message on a connected public status page. | bool | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| incident | The incident after the update | Incident |+| allowed_intents | Transitions the incident accepts after this update, so a graph can pick its next intent without re-reading the incident | List[str] |+| status | Status after the update, when the incident reports one | "Open" \| "Resolved" |+| severity | Severity after the update, when the incident reports one | "Critical" \| "Warning" \| "Minor" |++### Possible use case+<!-- MANUAL: use_case -->+After an agent raises an incident and its automated remediation succeeds, it applies the Resolved intent with a message describing what it did, closing the loop so nobody gets woken for an issue that has already fixed itself. If remediation fails instead, it applies Escalated to push the incident to the next tier.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/allquiet/on_call.md b/docs/integrations/block-integrations/allquiet/on_call.mdnew file mode 100644index 0000000000..a4079ec558--- /dev/null+++ b/docs/integrations/block-integrations/allquiet/on_call.md@@ -0,0 +1,43 @@+# All Quiet On Call+<!-- MANUAL: file_description -->+A block for reading All Quiet's on-call rotation: who is responsible right now, or who was (or will be) at any other point in time.+<!-- END MANUAL -->++## All Quiet Get On Call++### What it is+Looks up who is on call in All Quiet, now or at a given time++### How it works+<!-- MANUAL: how_it_works -->+Reads All Quiet's computed rotation rather than a static schedule, so overrides, escalation tiers and rotation handoffs are all reflected. Leaving `timestamp` empty asks who is on call right now; supplying an ISO-8601 timestamp asks who was or will be on call then. A user covering several teams appears once per team in `shifts`, so the block also emits a de-duplicated `users`/`user_ids`/`emails` set to avoid notifying the same person repeatedly. `has_coverage` is false when nobody is on call, which is worth branching on before assuming an alert will reach someone.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| team_ids | Limit to these teams. Leave empty for every team. | List[str] | No |+| user_ids | Limit to these users. Leave empty for every user. | List[str] | No |+| timestamp | ISO-8601 timestamp to evaluate the rotation at. Leave empty for right now. | str | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| shifts | Every matching on-call assignment | List[OnCallShift] |+| shift | Each on-call assignment, emitted one at a time | OnCallShift |+| users | The on-call users, deduplicated across teams | List[AllQuietUser] |+| user_ids | IDs of the on-call users | List[str] |+| emails | Email addresses of the on-call users | List[str] |+| users_without_email | On-call users carrying no email address. These are counted in users/has_coverage but absent from emails, so a graph that notifies by email alone would silently skip them | List[AllQuietUser] |+| has_coverage | False when nobody is on call for the requested teams/time, so a graph can branch to a fallback instead of silently paging no one | bool |++### Possible use case+<!-- MANUAL: use_case -->+Before an agent takes a disruptive automated action such as a production deploy, it checks who is on call and includes their name in the change notice. Wired to `has_coverage`, the same graph can refuse to deploy at all when the rotation has a gap.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/allquiet/teams.md b/docs/integrations/block-integrations/allquiet/teams.mdnew file mode 100644index 0000000000..328f7ed0e0--- /dev/null+++ b/docs/integrations/block-integrations/allquiet/teams.md@@ -0,0 +1,40 @@+# All Quiet Teams+<!-- MANUAL: file_description -->+A block for listing All Quiet teams. Mainly used to resolve the team IDs that the incident and on-call blocks accept as inputs.+<!-- END MANUAL -->++## All Quiet List Teams++### What it is+Lists All Quiet teams and their IDs++### How it works+<!-- MANUAL: how_it_works -->+Lists the teams in your All Quiet organization with their IDs, time zones and labels, optionally filtered by name. Its `team_ids` output is designed to feed the `team_ids` input on Create Incident, List Incidents and Get On-Call, so a graph can target teams by name without hardcoding UUIDs.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| display_name | Filter to teams whose name matches this text. | str | No |+| limit | Maximum number of teams to return. | int | No |+| offset | Number of teams to skip, for paging. | int | No |+| region | The All Quiet deployment your API key belongs to. Use EU if you signed up on allquiet.eu. | "us" \| "eu" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| teams | All matching teams | List[Team] |+| team | Each matching team, emitted one at a time | Team |+| team_ids | IDs of the matching teams, for use as team_ids elsewhere | List[str] |+| has_more | Whether more teams are available beyond this page | bool |++### Possible use case+<!-- MANUAL: use_case -->+A graph that should page whichever team owns a failing service looks the team up by display name, then passes the resulting ID to Create Incident — so renaming or re-creating a team in All Quiet doesn't require editing the agent.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/allquiet/triggers.md b/docs/integrations/block-integrations/allquiet/triggers.mdnew file mode 100644index 0000000000..b220c68edc--- /dev/null+++ b/docs/integrations/block-integrations/allquiet/triggers.md@@ -0,0 +1,40 @@+# All Quiet Triggers+<!-- MANUAL: file_description -->+A webhook trigger that starts a graph when All Quiet posts an incident to it, so agents can react to incidents rather than only create them.+<!-- END MANUAL -->++## All Quiet Incident Trigger++### What it is+Triggers a graph when All Quiet posts an incident to this webhook++### How it works+<!-- MANUAL: how_it_works -->+Runs when All Quiet's outbound webhook posts to this block's URL. Because the request body is whatever Handlebars template you configure in All Quiet, the block does not impose a schema: it always emits the raw `payload`, and additionally reads the well-known keys from both All Quiet's stock flattened template (`incidentId`/`incidentTitle`/`incidentProperties`) and a fuller template that forwards the incident itself. If you enable signing in All Quiet and paste the secret into the block, each delivery is verified as an HMAC-SHA256 of `<timestamp>:<body>` — both the All Quiet (`x-aq-signature`) and AWS (`x-amzn-event-signature`) header formats are accepted — and stale timestamps are rejected to prevent replay. Leave the secret empty and the webhook URL is the only credential.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| signing_secret | Optional. If All Quiet's outbound webhook has signing enabled, paste the signing secret here and deliveries with a missing or bad signature are rejected. Both the All Quiet (x-aq-signature) and AWS (x-amzn-event-signature) formats are accepted. Leave empty for unsigned webhooks. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| payload | The raw payload All Quiet delivered | Dict[str, Any] |+| incident_id | ID of the incident that fired | str |+| incident_title | Title of the incident | str |+| event_id | ID of the timeline event that triggered this delivery | str |+| status | Incident status, if the payload template includes it | "Open" \| "Resolved" |+| severity | Incident severity, if the payload template includes it | "Critical" \| "Warning" \| "Minor" |+| attributes | Incident attributes flattened to a name/value mapping | Dict[str, str] |++### Possible use case+<!-- MANUAL: use_case -->+An incident is raised in All Quiet by a Prometheus alert. The trigger starts a graph that pulls the incident's attributes, queries the relevant logs and dashboards, drafts a probable-cause summary with an LLM, and posts it back as a comment — so the responder opens an incident that already has a first pass of investigation attached.+<!-- END MANUAL -->++---