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 RMFG manufacturing blocks (#14389)
Nicholas Tindlec48df47288f7
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.defaultindex 2f38586471..79c5f9b4c1 100644--- a/autogpt_platform/backend/.env.default+++ b/autogpt_platform/backend/.env.default@@ -341,6 +341,9 @@ TALLY_API_KEY=ALLQUIET_API_KEY=AUTOMOD_API_KEY=+# RMFG (sheet-metal & tube-laser manufacturing)+RMFG_API_KEY=+## ===== ONBOARDING BRAIN DUMP ===== ### The voice brain-dump onboarding step is gated on the `onboarding-brain-dump`# LaunchDarkly flag and is fail-closed: the endpoints 404 unless it is on.diff --git a/autogpt_platform/backend/backend/blocks/rmfg/__init__.py b/autogpt_platform/backend/backend/blocks/rmfg/__init__.pynew file mode 100644index 0000000000..2e6fa94132--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/__init__.py@@ -0,0 +1,40 @@+from .carts import RMFGCreateCartBlock, RMFGGetCartBlock, RMFGUpdateCartBlock+from .catalog import (+ RMFGListFinishesBlock,+ RMFGListHardwareBlock,+ RMFGListMaterialsBlock,+ RMFGListPowderCoatColorsBlock,+ RMFGListTubeProfilesBlock,+)+from .designs import RMFGAnalyzeDesignBlock, RMFGGetDesignBlock+from .dfm import RMFGCreateDFMReportBlock, RMFGGetDFMReportBlock+from .images import RMFGGetImageBlock+from .orders import RMFGGetOrderBlock, RMFGListOrdersBlock+from .pay_cart import RMFGPayCartBlock+from .quotes import RMFGCreateQuoteBlock, RMFGGetQuoteBlock+from .review_links import RMFGCreateReviewLinkBlock, RMFGGetReviewLinkBlock+from .triggers import RMFGEventTriggerBlock++__all__ = [+ "RMFGAnalyzeDesignBlock",+ "RMFGCreateCartBlock",+ "RMFGCreateDFMReportBlock",+ "RMFGCreateQuoteBlock",+ "RMFGCreateReviewLinkBlock",+ "RMFGEventTriggerBlock",+ "RMFGGetCartBlock",+ "RMFGGetDFMReportBlock",+ "RMFGGetDesignBlock",+ "RMFGGetImageBlock",+ "RMFGGetOrderBlock",+ "RMFGGetQuoteBlock",+ "RMFGGetReviewLinkBlock",+ "RMFGListFinishesBlock",+ "RMFGListHardwareBlock",+ "RMFGListMaterialsBlock",+ "RMFGListOrdersBlock",+ "RMFGListPowderCoatColorsBlock",+ "RMFGListTubeProfilesBlock",+ "RMFGPayCartBlock",+ "RMFGUpdateCartBlock",+]diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_api.py b/autogpt_platform/backend/backend/blocks/rmfg/_api.pynew file mode 100644index 0000000000..cc6531c4d3--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_api.py@@ -0,0 +1,388 @@+"""Async client for the RMFG Manufacturing API.++Responses are validated into the models in ``_models`` and+``_models_commerce`` so blocks never hand raw dicts to downstream nodes.+"""++from io import BytesIO+from typing import Any, Optional+from urllib.parse import quote++from pydantic import TypeAdapter++from backend.sdk import Requests++from ._http import RMFGError, parse_body, poll+from ._models import (+ Design,+ DFMReport,+ Finish,+ HardwareOption,+ Material,+ PowderCoatColor,+ TubeProfile,+)+from ._models_commerce import Cart, Order, Quote, ReviewLink+from ._types import (+ RMFG_API_URL,+ DesignStatus,+ HardwareKind,+ ImageView,+ ManufacturingConfiguration,+ PaymentType,+ Process,+ QuoteItemRequest,+ QuoteStatus,+ RMFGCredentials,+ ShipTo,+)++# How long a create call asks the server to hold the connection while the+# resource finishes, before the client falls back to polling.+SERVER_WAIT_SECONDS = 20+# Listing pages hold up to 500 rows, so this is far beyond any real catalog;+# it only stops a server that keeps answering ``has_more``.+MAX_PAGES = 100++_JSON_LIST = TypeAdapter(list[dict[str, Any]])+++class RMFGClient:+ """Thin wrapper over the RMFG Manufacturing API v1."""++ def __init__(self, credentials: RMFGCredentials):+ self.base_url = f"{RMFG_API_URL}/v1"+ # Sent with each request rather than as ``extra_headers``: the+ # transport drops ``Authorization`` before following a cross-origin+ # redirect but re-applies ``extra_headers`` to the redirected request,+ # which would hand the bearer token to whatever host was named.+ self._auth_header = credentials.auth_header()+ # 429/5xx are retried by ``Requests`` itself with jittered backoff; the+ # attempt cap keeps a stuck endpoint from consuming the whole block+ # timeout before the error surfaces.+ self.requests = Requests(raise_for_status=False, retry_max_attempts=5)++ async def _request(+ self,+ method: str,+ path: str,+ *,+ params: Optional[dict[str, Any]] = None,+ body: Optional[dict[str, Any]] = None,+ files: Optional[list[tuple[str, tuple[str, BytesIO, str]]]] = None,+ idempotency_key: str = "",+ wait: bool = False,+ ) -> dict[str, Any]:+ headers = {"Authorization": self._auth_header, "Accept": "application/json"}+ if idempotency_key:+ headers["Idempotency-Key"] = idempotency_key+ if wait:+ headers["Prefer"] = f"wait={SERVER_WAIT_SECONDS}"+ response = await self.requests.request(+ method,+ f"{self.base_url}{path}",+ headers=headers,+ params={k: v for k, v in (params or {}).items() if v not in (None, "")},+ json=body,+ files=files,+ )+ return parse_body(response)++ async def _list_all(self, path: str, params: Optional[dict] = None) -> list[dict]:+ """Follow ``next_cursor`` until ``has_more`` is false."""+ items: list[dict] = []+ cursor: Optional[str] = None+ seen: set[str] = set()+ for _ in range(MAX_PAGES):+ page = await self._request(+ "GET", path, params={**(params or {}), "cursor": cursor}+ )+ items.extend(_JSON_LIST.validate_python(page.get("data") or []))+ cursor = page.get("next_cursor")+ if not page.get("has_more") or not cursor:+ return items+ if cursor in seen:+ raise RMFGError(+ 200, "pagination_error", f"{path} repeated cursor {cursor}"+ )+ seen.add(cursor)+ raise RMFGError(+ 200, "pagination_error", f"{path} did not end after {MAX_PAGES} pages"+ )++ # --- catalog -----------------------------------------------------------++ async def list_materials(self) -> list[Material]:+ rows = await self._list_all("/materials", {"limit": 500})+ return [Material.model_validate(row) for row in rows]++ async def list_tube_profiles(self) -> list[TubeProfile]:+ rows = await self._list_all("/tube-profiles", {"limit": 500})+ return [TubeProfile.model_validate(row) for row in rows]++ async def list_finishes(self, process: Optional[Process] = None) -> list[Finish]:+ params = {"limit": 500, "process": process.value if process else None}+ rows = await self._list_all("/finishes", params)+ return [Finish.model_validate(row) for row in rows]++ async def list_powder_coat_colors(self) -> list[PowderCoatColor]:+ rows = await self._list_all("/powder-coat-colors", {"limit": 500})+ return [PowderCoatColor.model_validate(row) for row in rows]++ async def list_hardware(self, kind: HardwareKind) -> list[HardwareOption]:+ rows = await self._list_all(f"/hardware/{kind.value}", {"limit": 500})+ return [HardwareOption.model_validate(row) for row in rows]++ # --- designs -----------------------------------------------------------++ async def analyze(+ self, filename: str, content: bytes, idempotency_key: str = ""+ ) -> Design:+ data = await self._request(+ "POST",+ "/analyze",+ files=[("file", (filename, BytesIO(content), "application/step"))],+ idempotency_key=idempotency_key,+ wait=True,+ )+ return Design.model_validate(data)++ async def get_design(self, design_id: str) -> Design:+ return Design.model_validate(+ await self._request("GET", f"/designs/{_id(design_id)}")+ )++ async def wait_for_design(self, design: Design, timeout_seconds: float) -> Design:+ """Poll until analysis leaves ``queued``/``processing``."""+ pending = {DesignStatus.QUEUED, DesignStatus.PROCESSING}+ design = await poll(+ lambda: self.get_design(design.id),+ initial=design,+ is_pending=lambda d: d.status in pending,+ timeout_seconds=timeout_seconds,+ what=f"design {design.id}",+ )+ if design.status == DesignStatus.FAILED:+ reason = design.error.message if design.error else "unknown error"+ raise RMFGError(200, "design_failed", f"Analysis failed: {reason}")+ return design++ async def get_image(+ self,+ design_id: str,+ part_id: str = "",+ dfm_id: str = "",+ view: ImageView = ImageView.ISO,+ width: int = 0,+ ) -> tuple[bytes, str]:+ """Download a rendered picture; returns (bytes, content type).++ Without a part the whole design is drawn. With a DFM report the part+ is drawn with its configured hole operations marked.+ """+ if dfm_id and not part_id:+ raise ValueError("part_id is required when dfm_id is set")+ if dfm_id:+ path = f"/dfm/{_id(dfm_id)}/parts/{_id(part_id)}/image"+ elif part_id:+ path = f"/designs/{_id(design_id)}/parts/{_id(part_id)}/image"+ else:+ path = f"/designs/{_id(design_id)}/image"+ response = await self.requests.request(+ "GET",+ f"{self.base_url}{path}",+ headers={"Authorization": self._auth_header, "Accept": "image/png"},+ params={+ "view": view.value,+ "format": "png",+ **({"width": width} if width else {}),+ },+ )+ if not response.ok:+ parse_body(response)+ return response.content, response.headers.get("content-type", "image/png")++ # --- DFM ---------------------------------------------------------------++ async def create_dfm_report(+ self,+ design_id: str,+ configuration: ManufacturingConfiguration,+ generate_production_files: bool = True,+ idempotency_key: str = "",+ ) -> DFMReport:+ body = {+ "design_id": design_id,+ "configuration": configuration.to_payload(),+ "generate_production_files": generate_production_files,+ }+ data = await self._request(+ "POST", "/dfm", body=body, idempotency_key=idempotency_key+ )+ return DFMReport.model_validate(data)++ async def get_dfm_report(self, dfm_id: str) -> DFMReport:+ return DFMReport.model_validate(+ await self._request("GET", f"/dfm/{_id(dfm_id)}")+ )++ # --- quotes ------------------------------------------------------------++ async def create_quote(+ self,+ items: list[QuoteItemRequest],+ ship_to: Optional[ShipTo] = None,+ idempotency_key: str = "",+ ) -> Quote:+ data = await self._request(+ "POST",+ "/quotes",+ body=_basket(items, ship_to),+ idempotency_key=idempotency_key,+ wait=True,+ )+ return Quote.model_validate(data)++ async def get_quote(self, quote_id: str) -> Quote:+ return Quote.model_validate(+ await self._request("GET", f"/quotes/{_id(quote_id)}")+ )++ async def wait_for_quote(self, quote: Quote, timeout_seconds: float) -> Quote:+ """Poll until pricing and DFM have finished."""+ return await poll(+ lambda: self.get_quote(quote.id),+ initial=quote,+ is_pending=lambda q: q.status == QuoteStatus.PROCESSING,+ timeout_seconds=timeout_seconds,+ what=f"quote {quote.id}",+ )++ # --- carts -------------------------------------------------------------++ async def create_cart(+ self,+ items: list[QuoteItemRequest],+ ship_to: Optional[ShipTo] = None,+ shipping_option_id: str = "",+ client_reference_id: str = "",+ idempotency_key: str = "",+ ) -> Cart:+ body = _basket(items, ship_to)+ if shipping_option_id:+ body["shipping_option_id"] = shipping_option_id+ if client_reference_id:+ body["client_reference_id"] = client_reference_id+ data = await self._request(+ "POST", "/carts", body=body, idempotency_key=idempotency_key+ )+ return Cart.model_validate(data)++ async def get_cart(self, cart_id: str) -> Cart:+ return Cart.model_validate(await self._request("GET", f"/carts/{_id(cart_id)}"))++ async def update_cart(+ self,+ cart_id: str,+ *,+ items: Optional[list[QuoteItemRequest]] = None,+ ship_to: Optional[ShipTo] = None,+ shipping_option_id: str = "",+ idempotency_key: str = "",+ ) -> Cart:+ """Patch an open cart; omitted fields keep their current value.++ ``items=[]`` is a real value that empties the basket; only ``None``+ leaves the current items alone.+ """+ body: dict[str, Any] = {}+ if items is not None:+ body["items"] = [item.to_payload() for item in items]+ if ship_to:+ body["ship_to"] = ship_to.to_payload()+ if shipping_option_id:+ body["shipping_option_id"] = shipping_option_id+ data = await self._request(+ "PATCH",+ f"/carts/{_id(cart_id)}",+ body=body,+ idempotency_key=idempotency_key,+ )+ return Cart.model_validate(data)++ async def pay_cart(+ self,+ cart_id: str,+ payment_type: PaymentType = PaymentType.CARD_ON_FILE,+ payment_method_id: str = "",+ customer_email: str = "",+ customer_phone: str = "",+ idempotency_key: str = "",+ ) -> Cart:+ payment: dict[str, str] = {"type": payment_type.value}+ if payment_type == PaymentType.PAYMENT_METHOD:+ payment["id"] = payment_method_id+ body: dict[str, Any] = {"payment": payment}+ if customer_email:+ body["customer_email"] = customer_email+ if customer_phone:+ body["customer_phone"] = customer_phone+ data = await self._request(+ "POST",+ f"/carts/{_id(cart_id)}/pay",+ body=body,+ idempotency_key=idempotency_key,+ )+ return Cart.model_validate(data)++ # --- orders ------------------------------------------------------------++ async def get_order(self, order_id: str) -> Order:+ return Order.model_validate(+ await self._request("GET", f"/orders/{_id(order_id)}")+ )++ async def list_orders(+ self, limit: int = 20, cursor: str = ""+ ) -> tuple[list[Order], Optional[str]]:+ page = await self._request(+ "GET", "/orders", params={"limit": limit, "cursor": cursor}+ )+ orders = [Order.model_validate(row) for row in page.get("data") or []]+ return orders, page.get("next_cursor") if page.get("has_more") else None++ # --- review links ------------------------------------------------------++ async def create_review_link(+ self,+ design_id: str,+ configuration: ManufacturingConfiguration,+ dfm_id: str = "",+ idempotency_key: str = "",+ ) -> ReviewLink:+ body: dict[str, Any] = {+ "design_id": design_id,+ "configuration": configuration.to_payload(),+ }+ if dfm_id:+ body["dfm_id"] = dfm_id+ data = await self._request(+ "POST", "/review-links", body=body, idempotency_key=idempotency_key+ )+ return ReviewLink.model_validate(data)++ async def get_review_link(self, link_id: str) -> ReviewLink:+ data = await self._request("GET", f"/review-links/{_id(link_id)}")+ return ReviewLink.model_validate(data)+++def _id(value: str) -> str:+ """Escape a resource ID for use as one path segment."""+ return quote(value, safe="")+++def _basket(items: list[QuoteItemRequest], ship_to: Optional[ShipTo]) -> dict:+ body: dict[str, Any] = {"items": [item.to_payload() for item in items]}+ if ship_to:+ body["ship_to"] = ship_to.to_payload()+ return bodydiff --git a/autogpt_platform/backend/backend/blocks/rmfg/_api_test.py b/autogpt_platform/backend/backend/blocks/rmfg/_api_test.pynew file mode 100644index 0000000000..79c90ae02a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_api_test.py@@ -0,0 +1,550 @@+"""Unit tests for the RMFG client's request shaping and error handling."""++import asyncio+from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock++import pytest+from pydantic import SecretStr++from backend.blocks.rmfg import _http+from backend.blocks.rmfg._api import MAX_PAGES, SERVER_WAIT_SECONDS, RMFGClient+from backend.blocks.rmfg._http import POLL_INITIAL_SECONDS, RMFGError, parse_body+from backend.blocks.rmfg._models import Design, Part, ResourceError, absolute_api_url+from backend.blocks.rmfg._testdata import TEST_DESIGN, TEST_PENDING_DESIGN, TEST_SHIP_TO+from backend.blocks.rmfg._types import (+ DesignStatus,+ HardwareKind,+ ImageView,+ ManufacturingConfiguration,+ PaymentType,+ Process,+ QuoteItemRequest,+)+from backend.data.model import APIKeyCredentials+++def _credentials() -> APIKeyCredentials:+ return APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="rmfg",+ 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:+ 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(*responses: _FakeResponse) -> tuple[RMFGClient, AsyncMock]:+ """Build a client whose HTTP layer is swapped for a recording mock."""+ client = RMFGClient(_credentials())+ request = AsyncMock(side_effect=list(responses))+ # Patch the transport itself so the tests cover the client's own request+ # shaping (params, body, headers) without any network access.+ requests: Any = client.requests+ requests.request = request+ return client, request+++def _sent(request: AsyncMock, call: int = 0) -> tuple[str, str, dict[str, Any]]:+ method, url = request.await_args_list[call].args+ return method, url, request.await_args_list[call].kwargs+++def _fake_asyncio(sleep) -> SimpleNamespace:+ """Stand-in for the module's asyncio: a fake sleep, the real wait_for."""+ return SimpleNamespace(+ sleep=sleep, wait_for=asyncio.wait_for, TimeoutError=asyncio.TimeoutError+ )+++class TestAuth:+ async def test_bearer_header_travels_with_each_request(self):+ client, request = _client_with(_FakeResponse(200, {"id": "dsn_1"}))++ await client.get_design("dsn_1")++ _, _, kwargs = _sent(request)+ assert kwargs["headers"]["Authorization"] == "Bearer test-key"+ assert kwargs["headers"]["Accept"] == "application/json"+ # Never on the transport: it re-attaches ``extra_headers`` after a+ # cross-origin redirect has stripped the token from the request.+ assert client.requests.extra_headers is None+ assert client.requests.raise_for_status is False++ async def test_ids_are_escaped_as_single_path_segments(self):+ client, request = _client_with(_FakeResponse(200, {"id": "x"}))++ await client.get_design("dsn/../x?y")++ _, url, _ = _sent(request)+ assert url == "https://api.rmfg.com/v1/designs/dsn%2F..%2Fx%3Fy"+++class TestParseBody:+ def test_returns_object_on_success(self):+ assert parse_body(_FakeResponse(200, {"id": "x"})) == {"id": "x"}++ def test_empty_success_body_is_an_empty_object(self):+ assert parse_body(_FakeResponse(204)) == {}++ def test_error_envelope_is_rendered(self):+ response = _FakeResponse(+ 422,+ {+ "error": {+ "type": "invalid_request_error",+ "code": "validation_error",+ "message": "quantity must be positive",+ "param": "items.0.quantity",+ "request_id": "req_1",+ }+ },+ )+ with pytest.raises(RMFGError) as exc_info:+ parse_body(response)+ assert exc_info.value.status == 422+ assert exc_info.value.code == "validation_error"+ assert "quantity must be positive (field: items.0.quantity)" in str(+ exc_info.value+ )+ assert "req_1" in str(exc_info.value)++ def test_auth_failures_point_at_the_key(self):+ response = _FakeResponse(+ 401, {"error": {"type": "authentication_error", "message": "bad key"}}+ )+ with pytest.raises(RMFGError, match="Check the RMFG API key"):+ parse_body(response)++ def test_non_json_failure_keeps_the_status(self):+ with pytest.raises(RMFGError) as exc_info:+ parse_body(_FakeResponse(502, body="<html>Bad Gateway</html>"))+ assert exc_info.value.status == 502+ assert "Bad Gateway" in str(exc_info.value)++ def test_non_json_success_is_still_an_error(self):+ with pytest.raises(RMFGError, match="not JSON"):+ parse_body(_FakeResponse(200, body="ok"))+++class TestPagination:+ async def test_follows_next_cursor_until_has_more_is_false(self):+ client, request = _client_with(+ _FakeResponse(+ 200, {"data": [{"id": "a"}], "has_more": True, "next_cursor": "c2"}+ ),+ _FakeResponse(200, {"data": [{"id": "b"}], "has_more": False}),+ )++ materials = await client.list_materials()++ assert [m.id for m in materials] == ["a", "b"]+ assert request.await_count == 2+ _, _, first = _sent(request, 0)+ _, _, second = _sent(request, 1)+ assert "cursor" not in first["params"]+ assert second["params"]["cursor"] == "c2"+ assert second["params"]["limit"] == 500++ async def test_a_cursor_that_does_not_advance_is_an_error(self):+ stuck = {"data": [{"id": "a"}], "has_more": True, "next_cursor": "c2"}+ client, request = _client_with(*(_FakeResponse(200, stuck) for _ in range(3)))++ with pytest.raises(RMFGError, match="repeated cursor c2"):+ await client.list_materials()+ assert request.await_count == 2++ async def test_pagination_stops_after_the_page_cap(self):+ pages = (+ _FakeResponse(200, {"data": [], "has_more": True, "next_cursor": f"c{n}"})+ for n in range(MAX_PAGES + 5)+ )+ client, request = _client_with(*pages)++ with pytest.raises(RMFGError, match=f"did not end after {MAX_PAGES} pages"):+ await client.list_materials()+ assert request.await_count == MAX_PAGES++ async def test_finish_process_filter_is_a_query_param(self):+ client, request = _client_with(_FakeResponse(200, {"data": []}))++ await client.list_finishes(Process.TUBE_LASER)++ _, url, kwargs = _sent(request)+ assert url.endswith("/v1/finishes")+ assert kwargs["params"]["process"] == "tube_laser"++ async def test_hardware_kind_selects_the_path(self):+ client, request = _client_with(_FakeResponse(200, {"data": []}))++ await client.list_hardware(HardwareKind.STANDOFFS)++ _, url, _ = _sent(request)+ assert url.endswith("/v1/hardware/standoffs")+++class TestAnalyze:+ async def test_uploads_multipart_with_idempotency_and_wait(self):+ client, request = _client_with(+ _FakeResponse(202, TEST_PENDING_DESIGN.model_dump(mode="json"))+ )++ design = await client.analyze("bracket.step", b"ISO-10303-21;", "key-1")++ assert design.status == DesignStatus.PROCESSING+ method, url, kwargs = _sent(request)+ assert (method, url) == ("POST", "https://api.rmfg.com/v1/analyze")+ assert kwargs["headers"]["Idempotency-Key"] == "key-1"+ assert kwargs["headers"]["Prefer"] == f"wait={SERVER_WAIT_SECONDS}"+ assert kwargs["json"] is None+ field, (filename, handle, content_type) = kwargs["files"][0]+ assert (field, filename, content_type) == (+ "file",+ "bracket.step",+ "application/step",+ )+ assert handle.getvalue() == b"ISO-10303-21;"++ async def test_no_idempotency_header_when_key_is_empty(self):+ client, request = _client_with(+ _FakeResponse(200, TEST_DESIGN.model_dump(mode="json"))+ )++ await client.get_design(TEST_DESIGN.id)++ _, _, kwargs = _sent(request)+ assert "Idempotency-Key" not in kwargs["headers"]+ assert "Prefer" not in kwargs["headers"]+++class TestPolling:+ async def test_returns_immediately_when_already_ready(self):+ client, request = _client_with()++ design = await client.wait_for_design(TEST_DESIGN, timeout_seconds=5)++ assert design is TEST_DESIGN+ assert request.await_count == 0++ async def test_polls_until_ready(self, monkeypatch: pytest.MonkeyPatch):+ sleeps: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleeps.append(seconds)++ monkeypatch.setattr(_http, "asyncio", _fake_asyncio(fake_sleep))+ client, request = _client_with(+ _FakeResponse(200, TEST_PENDING_DESIGN.model_dump(mode="json")),+ _FakeResponse(200, TEST_DESIGN.model_dump(mode="json")),+ )++ design = await client.wait_for_design(TEST_PENDING_DESIGN, timeout_seconds=60)++ assert design.status == DesignStatus.READY+ assert request.await_count == 2+ assert sleeps[0] == POLL_INITIAL_SECONDS+ assert sleeps[1] > sleeps[0], "backoff grows between polls"++ async def test_failed_analysis_raises_with_the_reason(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setattr(_http, "asyncio", _fake_asyncio(AsyncMock()))+ failed = TEST_DESIGN.model_copy(+ update={+ "status": DesignStatus.FAILED,+ "error": ResourceError(code="bad_geometry", message="Not a solid body"),+ }+ )+ client, _ = _client_with(_FakeResponse(200, failed.model_dump(mode="json")))++ with pytest.raises(RMFGError, match="Not a solid body"):+ await client.wait_for_design(TEST_PENDING_DESIGN, timeout_seconds=60)++ async def test_times_out_instead_of_polling_forever(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ # A clock that only the fake sleep advances, scoped to the module so+ # the event loop's own clock is untouched.+ clock = {"now": 0.0}+ sleeps: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleeps.append(seconds)+ clock["now"] += seconds++ monkeypatch.setattr(_http, "asyncio", _fake_asyncio(fake_sleep))+ monkeypatch.setattr(+ _http, "time", SimpleNamespace(monotonic=lambda: clock["now"])+ )+ pending = _FakeResponse(200, TEST_PENDING_DESIGN.model_dump(mode="json"))+ client, request = _client_with(pending, pending, pending, pending)++ with pytest.raises(TimeoutError, match=TEST_PENDING_DESIGN.id):+ await client.wait_for_design(TEST_PENDING_DESIGN, timeout_seconds=10)++ # Backoff 2, 3, 4.5 brings the clock to 9.5 s; the last sleep is+ # capped to the half second left, and nothing is fetched after it.+ assert sleeps == [2.0, 3.0, 4.5, 0.5]+ assert request.await_count == 3++ async def test_a_slow_fetch_is_cut_off_at_the_deadline(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setattr(_http, "POLL_INITIAL_SECONDS", 0.01)++ async def slow_fetch() -> str:+ await asyncio.sleep(5)+ return "ready"++ with pytest.raises(TimeoutError, match="waiting for the thing"):+ await _http.poll(+ slow_fetch,+ initial="pending",+ is_pending=lambda state: state == "pending",+ timeout_seconds=0.1,+ what="the thing",+ )+++class TestBaskets:+ async def test_quote_body_matches_the_documented_shape(self):+ client, request = _client_with(+ _FakeResponse(200, {"id": "qte_1", "status": "processing"})+ )+ configuration = ManufacturingConfiguration.model_validate(+ {"parts": [{"part_id": "prt_1", "material_id": "mat_1"}]}+ )+ item = QuoteItemRequest(+ design_id="dsn_1", quantity=10, configuration=configuration+ )++ await client.create_quote([item], idempotency_key="q-1")++ _, url, kwargs = _sent(request)+ assert url.endswith("/v1/quotes")+ assert kwargs["json"] == {+ "items": [+ {+ "design_id": "dsn_1",+ "quantity": 10,+ "quantity_options": [],+ "configuration": {+ "defaults": {},+ "parts": [+ {+ "part_id": "prt_1",+ "material_id": "mat_1",+ "taps": [],+ "studs": [],+ "nuts": [],+ "standoffs": [],+ "countersinks": [],+ }+ ],+ "assembly_operations": [],+ "accepted_risks": [],+ },+ }+ ]+ }+ assert kwargs["headers"]["Prefer"] == f"wait={SERVER_WAIT_SECONDS}"++ async def test_cart_includes_destination_and_shipping_choice(self):+ client, request = _client_with(_FakeResponse(201, {"id": "crt_1"}))++ await client.create_cart(+ [QuoteItemRequest(design_id="dsn_1")],+ ship_to=TEST_SHIP_TO,+ shipping_option_id="ship_1",+ client_reference_id="po-7",+ )++ _, _, kwargs = _sent(request)+ body = kwargs["json"]+ assert body["ship_to"]["postal_code"] == "78701"+ assert "street2" not in body["ship_to"], "unset optionals are omitted"+ assert body["shipping_option_id"] == "ship_1"+ assert body["client_reference_id"] == "po-7"++ async def test_update_only_sends_what_changed(self):+ client, request = _client_with(_FakeResponse(200, {"id": "crt_1"}))++ await client.update_cart("crt_1", shipping_option_id="ship_2")++ method, url, kwargs = _sent(request)+ assert (method, url) == ("PATCH", "https://api.rmfg.com/v1/carts/crt_1")+ assert kwargs["json"] == {"shipping_option_id": "ship_2"}++ async def test_an_explicit_empty_basket_is_sent(self):+ client, request = _client_with(_FakeResponse(200, {"id": "crt_1"}))++ await client.update_cart("crt_1", items=[])++ _, _, kwargs = _sent(request)+ assert kwargs["json"] == {"items": []}+++class TestPayment:+ async def test_card_on_file_is_the_documented_body(self):+ client, request = _client_with(_FakeResponse(200, {"id": "crt_1"}))++ await client.pay_cart("crt_1", idempotency_key="pay-1")++ method, url, kwargs = _sent(request)+ assert (method, url) == ("POST", "https://api.rmfg.com/v1/carts/crt_1/pay")+ assert kwargs["json"] == {"payment": {"type": "card_on_file"}}+ assert kwargs["headers"]["Idempotency-Key"] == "pay-1"++ async def test_payment_method_carries_its_id_and_contact(self):+ client, request = _client_with(_FakeResponse(200, {"id": "crt_1"}))++ await client.pay_cart(+ "crt_1",+ payment_type=PaymentType.PAYMENT_METHOD,+ payment_method_id="pm_123",+ customer_email="[email protected]",+ )++ _, _, kwargs = _sent(request)+ assert kwargs["json"] == {+ "payment": {"type": "payment_method", "id": "pm_123"},+ "customer_email": "[email protected]",+ }+++class TestOrders:+ async def test_list_returns_cursor_only_when_more_pages_exist(self):+ client, _ = _client_with(+ _FakeResponse(+ 200,+ {"data": [{"id": "ord_1"}], "has_more": True, "next_cursor": "n"},+ )+ )+ orders, cursor = await client.list_orders(limit=1)+ assert [o.id for o in orders] == ["ord_1"]+ assert cursor == "n"++ async def test_last_page_has_no_cursor(self):+ client, _ = _client_with(+ _FakeResponse(200, {"data": [], "has_more": False, "next_cursor": "n"})+ )+ _, cursor = await client.list_orders()+ assert cursor is None+++class TestRelativeUrls:+ def test_api_paths_get_the_origin(self):+ assert absolute_api_url("/v1/designs/d/image") == (+ "https://api.rmfg.com/v1/designs/d/image"+ )++ def test_absolute_and_empty_values_pass_through(self):+ assert absolute_api_url("https://www.rmfg.com/review/x") == (+ "https://www.rmfg.com/review/x"+ )+ assert absolute_api_url(None) is None+ assert absolute_api_url("") == ""++ def test_design_and_part_links_are_absolute_after_validation(self):+ # The live API returns these as bare paths.+ design = Design.model_validate(+ {+ "id": "d",+ "status": "ready",+ "name": "x",+ "image_url": "/v1/designs/d/image",+ "parts": [+ {+ "id": "p",+ "name": "p",+ "suggested_process": "sheet_metal",+ "model_url": "/v1/designs/d/parts/p/model",+ "image_url": "/v1/designs/d/parts/p/image",+ }+ ],+ }+ )+ assert design.image_url == "https://api.rmfg.com/v1/designs/d/image"+ assert design.parts[0].model_url.startswith("https://api.rmfg.com/")+ assert design.parts[0].image_url == (+ "https://api.rmfg.com/v1/designs/d/parts/p/image"+ )++ def test_part_defaults_stay_untouched(self):+ assert Part().image_url is None+++class _BytesResponse(_FakeResponse):+ def __init__(self, status: int, content: bytes, content_type: str):+ super().__init__(status, payload={})+ self.content = content+ self.headers = {"content-type": content_type}+++class TestImages:+ async def test_design_image_request(self):+ client, request = _client_with(_BytesResponse(200, b"PNG", "image/png"))++ content, content_type = await client.get_image("dsn_1")++ assert (content, content_type) == (b"PNG", "image/png")+ method, url, kwargs = _sent(request)+ assert (method, url) == ("GET", "https://api.rmfg.com/v1/designs/dsn_1/image")+ assert kwargs["params"] == {"view": "iso", "format": "png"}+ assert kwargs["headers"] == {+ "Authorization": "Bearer test-key",+ "Accept": "image/png",+ }++ async def test_a_dfm_report_without_a_part_is_rejected(self):+ client, request = _client_with()++ with pytest.raises(ValueError, match="part_id is required"):+ await client.get_image("dsn_1", dfm_id="dfm_1")+ request.assert_not_awaited()++ async def test_part_image_with_view_and_width(self):+ client, request = _client_with(_BytesResponse(200, b"PNG", "image/png"))++ await client.get_image("dsn_1", part_id="prt_1", view=ImageView.FLAT, width=800)++ _, url, kwargs = _sent(request)+ assert url.endswith("/v1/designs/dsn_1/parts/prt_1/image")+ assert kwargs["params"] == {"view": "flat", "format": "png", "width": 800}++ async def test_dfm_part_image_takes_the_dfm_path(self):+ client, request = _client_with(_BytesResponse(200, b"PNG", "image/png"))++ await client.get_image("dsn_1", part_id="prt_1", dfm_id="dfm_1")++ _, url, _ = _sent(request)+ assert url.endswith("/v1/dfm/dfm_1/parts/prt_1/image")++ async def test_image_errors_are_rendered(self):+ client, _ = _client_with(+ _FakeResponse(404, {"error": {"type": "not_found_error", "message": "no"}})+ )+ with pytest.raises(RMFGError, match="no"):+ await client.get_image("dsn_1")diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_config.py b/autogpt_platform/backend/backend/blocks/rmfg/_config.pynew file mode 100644index 0000000000..ed3eb18287--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_config.py@@ -0,0 +1,31 @@+"""Provider registration and shared test credentials for the RMFG blocks."""++from backend.sdk import APIKeyCredentials, ProviderBuilder, SecretStr++from ._webhook import RMFGWebhooksManager++rmfg = (+ ProviderBuilder("rmfg")+ .with_description("Sheet-metal and tube-laser manufacturing quotes and orders")+ .with_api_key("RMFG_API_KEY", "RMFG API Key")+ # Device-code OAuth (RFC 8628) is handled by RMFGDeviceAuthHandler in+ # backend/integrations/oauth/rmfg.py; it yields ordinary oauth2 tokens.+ .with_supported_auth_types("oauth2", "device_code")+ .with_webhook_manager(RMFGWebhooksManager)+ .build()+)++TEST_CREDENTIALS = APIKeyCredentials(+ id="01234567-89ab-cdef-0123-456789abcdef",+ provider="rmfg",+ api_key=SecretStr("mock-rmfg-api-key"),+ title="Mock RMFG API key",+ expires_at=None,+)++TEST_CREDENTIALS_INPUT = {+ "provider": TEST_CREDENTIALS.provider,+ "id": TEST_CREDENTIALS.id,+ "type": TEST_CREDENTIALS.type,+ "title": TEST_CREDENTIALS.title,+}diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_http.py b/autogpt_platform/backend/backend/blocks/rmfg/_http.pynew file mode 100644index 0000000000..2d161ebd9b--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_http.py@@ -0,0 +1,111 @@+"""Transport helpers for the RMFG client: error envelopes and polling."""++import asyncio+import time+from collections.abc import Awaitable, Callable+from typing import Any, Optional, TypeVar++from pydantic import TypeAdapter, ValidationError++from backend.sdk import BaseModel+from backend.util.request import Response++POLL_INITIAL_SECONDS = 2.0+POLL_MAX_SECONDS = 10.0++_JSON_OBJECT = TypeAdapter(dict[str, Any])++T = TypeVar("T")+++class APIError(BaseModel):+ """The ``error`` object of an RMFG error response."""++ type: str = ""+ code: str = ""+ message: str = ""+ param: Optional[str] = None+ request_id: Optional[str] = None+++class ErrorEnvelope(BaseModel):+ error: APIError+++class RMFGError(ValueError):+ """An error envelope returned by the API, rendered for a person."""++ def __init__(self, status: int, code: str, message: str, request_id: str = ""):+ self.status = status+ self.code = code+ self.request_id = request_id+ suffix = f" (request {request_id})" if request_id else ""+ super().__init__(f"RMFG {code or status}: {message}{suffix}")+++def parse_body(response: Response) -> dict[str, Any]:+ """Return the JSON object body, or raise a readable error for a failure."""+ text = response.text()+ try:+ payload = _JSON_OBJECT.validate_python(response.json()) if text else {}+ except (ValueError, ValidationError) as exc:+ if response.ok:+ raise RMFGError(+ response.status, "invalid_response", f"not JSON: {text[:200]}"+ ) from exc+ raise RMFGError(response.status, "http_error", text[:200] or "no body")+ if response.ok:+ return payload+ raise _error_from(response.status, payload)+++def _error_from(status: int, payload: dict[str, Any]) -> RMFGError:+ try:+ error = ErrorEnvelope.model_validate(payload).error+ except ValidationError:+ return RMFGError(status, "http_error", f"HTTP {status}")+ message = error.message or f"HTTP {status}"+ if error.param:+ message = f"{message} (field: {error.param})"+ if status in (401, 403):+ message = f"{message}. Check the RMFG API key and its scopes."+ return RMFGError(status, error.code or error.type, message, error.request_id or "")+++async def poll(+ fetch: Callable[[], Awaitable[T]],+ *,+ initial: T,+ is_pending: Callable[[T], bool],+ timeout_seconds: float,+ what: str,+) -> T:+ """Re-fetch a resource with growing delays until it is no longer pending.++ Every wait, the fetch included, is capped by what is left of+ ``timeout_seconds``, so the call never runs materially past its deadline.+ """+ resource = initial+ deadline = time.monotonic() + timeout_seconds+ delay = POLL_INITIAL_SECONDS+ while is_pending(resource):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise _timeout(timeout_seconds, what)+ await asyncio.sleep(min(delay, remaining))+ delay = min(delay * 1.5, POLL_MAX_SECONDS)+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise _timeout(timeout_seconds, what)+ try:+ resource = await asyncio.wait_for(fetch(), timeout=remaining)+ except asyncio.TimeoutError:+ raise _timeout(timeout_seconds, what) from None+ return resource+++def _timeout(timeout_seconds: float, what: str) -> TimeoutError:+ return TimeoutError(+ f"Timed out after {timeout_seconds:.0f}s waiting for {what}; "+ "fetch it again later with its ID."+ )diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_inputs.py b/autogpt_platform/backend/backend/blocks/rmfg/_inputs.pynew file mode 100644index 0000000000..47b4d8c118--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_inputs.py@@ -0,0 +1,86 @@+"""Input schema shared by the blocks that price or buy a configured design."""++from typing import Annotated++from backend.sdk import BlockSchemaInput, CredentialsMetaInput, Field, SchemaField++from ._config import rmfg+from ._types import ManufacturingConfiguration, QuoteItemRequest+++def credentials_field(required_scopes: set[str] | None = None) -> CredentialsMetaInput:+ return rmfg.credentials_field(+ description=(+ "Connect your RMFG account (approve in the browser) or paste an API "+ "key from rmfg.com/account."+ ),+ required_scopes=required_scopes or set(),+ )+++class RMFGBasketInput(BlockSchemaInput):+ """One configured design plus optional extra items, as quotes and carts take them."""++ credentials: CredentialsMetaInput = credentials_field()+ design_id: str = SchemaField(+ description="Design ID from Analyze Design.", placeholder="dsn_..."+ )+ quantity: int = SchemaField(+ description=(+ "Completed units of the design: exactly the number the customer asked "+ "for (one part means 1). Repeated parts in an assembly are multiplied "+ "by their instance count automatically."+ ),+ default=1,+ ge=1,+ )+ material_id: str = SchemaField(+ description=(+ "Sheet-metal stock for every sheet part, from List Materials. "+ "Required for a price: pick the stocked thickness closest to the "+ "part's detected thickness and mention the difference. Leave empty "+ "only for tube-only designs or when configuration sets it."+ ),+ default="",+ placeholder="mat_...",+ )+ configuration: ManufacturingConfiguration = SchemaField(+ description=(+ "Full manufacturing configuration: per-part material, tube profile, "+ "finish, powder coat, hole operations, welds and accepted risks. "+ "A non-empty material_id above overrides defaults.material_id."+ ),+ default_factory=ManufacturingConfiguration,+ advanced=True,+ )+ quantity_options: list[Annotated[int, Field(ge=1)]] = SchemaField(+ description=(+ "Up to ten other quantities to price alongside quantity, only when the "+ "customer wants a comparison; the main quantity stays as requested."+ ),+ default_factory=list,+ max_length=10,+ advanced=True,+ )+ additional_items: list[QuoteItemRequest] = SchemaField(+ description="Further configured designs to price in the same basket.",+ default_factory=list,+ advanced=True,+ )+ client_reference_id: str = SchemaField(+ description="Your own reference for this item, echoed back on the result.",+ default="",+ advanced=True,+ )+++def build_items(input_data: RMFGBasketInput) -> list[QuoteItemRequest]:+ """Turn the flat block inputs into the API's ``items[]`` basket."""+ item = QuoteItemRequest(+ design_id=input_data.design_id,+ quantity=input_data.quantity,+ configuration=input_data.configuration.with_material(input_data.material_id),+ client_reference_id=input_data.client_reference_id or None,+ quantity_options=input_data.quantity_options,+ )+ return [item, *input_data.additional_items]diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_models.py b/autogpt_platform/backend/backend/blocks/rmfg/_models.pynew file mode 100644index 0000000000..d178c54b35--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_models.py@@ -0,0 +1,311 @@+"""Response models for the RMFG catalog, design analysis and DFM resources.++Every field carries a default so a payload from a newer API version, or one+with fields the platform does not surface, still validates.+"""++from typing import Any, Optional++from pydantic import ConfigDict, field_validator++from backend.sdk import BaseModel, Field++from ._types import (+ RMFG_API_URL,+ DesignStatus,+ ManufacturabilityStatus,+ ManufacturingConfiguration,+ Process,+)+++def absolute_api_url(value: Optional[str]) -> Optional[str]:+ """RMFG returns links to its own resources as paths such as ``/v1/...``.++ Downstream blocks and people need a full URL, so prefix the API origin.+ Website links and other absolute URLs pass through untouched.+ """+ if value and value.startswith("/"):+ return f"{RMFG_API_URL}{value}"+ return value+++class Material(BaseModel):+ """A sheet-metal stock option. Use ``id`` as ``material_id``."""++ id: str = ""+ material: str = ""+ type: str = ""+ thickness_in: float = 0+ thickness_mm: float = 0+ display_thickness: Optional[str] = None+ description: Optional[str] = None+ bendable: bool = False+ weight_g_per_cm2: float = 0+++class TubeProfile(BaseModel):+ """A tube-laser stock profile. Use ``id`` as ``tube_profile_id``."""++ id: str = ""+ material: str = ""+ type: str = ""+ shape: str = ""+ display_name: str = ""+ outer_width_mm: Optional[float] = None+ outer_height_mm: Optional[float] = None+ outer_diameter_mm: Optional[float] = None+ wall_thickness_mm: Optional[float] = None+ default_stock_length_mm: Optional[float] = None+++class Finish(BaseModel):+ """A mechanical finish. Use ``id`` as ``finish_id``."""++ id: str = ""+ name: str = ""+ slug: str = ""+ description: Optional[str] = None+ category: Optional[str] = None+ processes: list[Process] = Field(default_factory=list)+ base_price_cents: int = 0+ price_per_cm2_cents: float = 0+++class PowderCoatColor(BaseModel):+ """A powder-coat color. Use ``id`` as ``powder_coat_color_id``."""++ id: str = ""+ name: str = ""+ slug: str = ""+ hex_color: str = ""+ price_multiplier: float = 1+ available: bool = True+++class HardwareOption(BaseModel):+ """A tap, stud, nut or standoff catalog entry.++ The four families share ``id``/``size`` but differ elsewhere, so the+ remaining catalog fields are passed through as-is.+ """++ model_config = ConfigDict(extra="allow")++ id: str = ""+ size: Optional[str] = None+ hole_diameter_mm: Optional[float] = None+++class Dimensions(BaseModel):+ length_mm: float = 0+ width_mm: float = 0+ height_mm: float = 0+++class Hole(BaseModel):+ """A detected hole or cutout; IDs are stable for the life of the design."""++ id: int = 0+ shape: str = "round"+ diameter_mm: float = 0+ face_id: Optional[int] = None+ nearest_bend_id: Optional[int] = None+ distance_to_nearest_edge_mm: Optional[float] = None+ distance_to_nearest_bend_mm: Optional[float] = None+++class Bend(BaseModel):+ id: int = 0+ angle_degrees: float = 0+ radius_mm: float = 0+ length_mm: float = 0+++class Part(BaseModel):+ """One unique part of a design; ``instance_count`` says how often it occurs."""++ id: str = ""+ name: str = ""+ suggested_process: Process = Process.SHEET_METAL+ instance_count: int = 1+ formed_dimensions: Dimensions = Field(default_factory=Dimensions)+ flat_pattern_dimensions: Optional[Dimensions] = None+ detected_thickness_mm: Optional[float] = None+ bend_count: int = 0+ bends: list[Bend] = Field(default_factory=list)+ hole_count: int = 0+ holes: list[Hole] = Field(default_factory=list)+ surface_area_cm2: Optional[float] = None+ cut_length_mm: Optional[float] = None+ model_url: str = ""+ flat_pattern_model_url: Optional[str] = None+ image_url: Optional[str] = None++ @field_validator("model_url", "flat_pattern_model_url", "image_url")+ @classmethod+ def _absolute(cls, value: Optional[str]) -> Optional[str]:+ return absolute_api_url(value)+++class PartInstance(BaseModel):+ id: str = ""+ part_id: str = ""+ instance_index: int = 0+++class ResourceError(BaseModel):+ code: str = ""+ message: str = ""+++class Design(BaseModel):+ """An analyzed STEP upload. Parts and instances are filled once ``ready``."""++ id: str = ""+ status: DesignStatus = DesignStatus.QUEUED+ name: str = ""+ formed_dimensions: Optional[Dimensions] = None+ parts: list[Part] = Field(default_factory=list)+ part_instances: list[PartInstance] = Field(default_factory=list)+ model_url: Optional[str] = None+ image_url: Optional[str] = None+ review_url: Optional[str] = None+ review_link_id: Optional[str] = None+ created_at: Optional[str] = None+ error: Optional[ResourceError] = None++ @field_validator("model_url", "image_url")+ @classmethod+ def _absolute(cls, value: Optional[str]) -> Optional[str]:+ return absolute_api_url(value)+++class Requirement(BaseModel):+ """A missing selection or decision that keeps a resource from being ready."""++ code: str = ""+ message: str = ""+ part_id: Optional[str] = None+ part_ids: list[str] = Field(default_factory=list)+ field: Optional[str] = None+ allowed_values_url: Optional[str] = None++ @field_validator("allowed_values_url")+ @classmethod+ def _absolute(cls, value: Optional[str]) -> Optional[str]:+ return absolute_api_url(value)+++class DFMIssue(BaseModel):+ code: str = ""+ message: str = ""+ severity: str = "blocking"+ accepted: bool = False+ source: str = ""+ part_id: Optional[str] = None+ hole_id: Optional[int] = None+ bend_id: Optional[int] = None+ operation: Optional[str] = None+ details: dict[str, Any] = Field(default_factory=dict)+++class CapabilityOption(BaseModel):+ id: str = ""+ name: str = ""+ available: bool = True+ unavailable_reason: Optional[str] = None+++class OperationCapability(BaseModel):+ available: bool = False+ unavailable_reason: Optional[str] = None+ options: list[CapabilityOption] = Field(default_factory=list)+++class HoleOperationCapability(BaseModel):+ available: bool = False+ unavailable_reason: Optional[str] = None+ option_ids: list[str] = Field(default_factory=list)+++class HoleCapabilities(BaseModel):+ hole_id: int = 0+ taps: HoleOperationCapability = Field(default_factory=HoleOperationCapability)+ studs: HoleOperationCapability = Field(default_factory=HoleOperationCapability)+ nuts: HoleOperationCapability = Field(default_factory=HoleOperationCapability)+ standoffs: HoleOperationCapability = Field(default_factory=HoleOperationCapability)+ countersinks: HoleOperationCapability = Field(+ default_factory=HoleOperationCapability+ )+++class PartCapabilities(BaseModel):+ """What each configuration field may be set to for one part."""++ taps: OperationCapability = Field(default_factory=OperationCapability)+ studs: OperationCapability = Field(default_factory=OperationCapability)+ nuts: OperationCapability = Field(default_factory=OperationCapability)+ standoffs: OperationCapability = Field(default_factory=OperationCapability)+ countersinks: OperationCapability = Field(default_factory=OperationCapability)+ powder_coat_color_id: OperationCapability = Field(+ default_factory=OperationCapability+ )+ finish_id: OperationCapability = Field(default_factory=OperationCapability)+ holes: list[HoleCapabilities] = Field(default_factory=list)+++class ManufacturingReviewWarning(BaseModel):+ """An advisory for manual preparation; never a checkout requirement."""++ design_id: str = ""+ code: str = ""+ message: str = ""+++class ProductionFilesStatus(BaseModel):+ status: str = "skipped"+ reason: Optional[str] = None+ error: Optional[ResourceError] = None+ review_warning: Optional[ManufacturingReviewWarning] = None+ corrections_applied: bool = False+++class PartDFM(BaseModel):+ part_id: str = ""+ status: ManufacturabilityStatus = ManufacturabilityStatus.READY+ issues: list[DFMIssue] = Field(default_factory=list)+ capabilities: Optional[PartCapabilities] = None+ image_url: Optional[str] = None+ production_warnings: list[str] = Field(default_factory=list)++ @field_validator("image_url")+ @classmethod+ def _absolute(cls, value: Optional[str]) -> Optional[str]:+ return absolute_api_url(value)+++class DFMReport(BaseModel):+ """An immutable manufacturability evaluation of one configuration."""++ id: str = ""+ design_id: str = ""+ status: ManufacturabilityStatus = ManufacturabilityStatus.READY+ review_url: Optional[str] = None+ review_link_id: Optional[str] = None+ configuration: ManufacturingConfiguration = Field(+ default_factory=ManufacturingConfiguration+ )+ parts: list[PartDFM] = Field(default_factory=list)+ requirements: list[Requirement] = Field(default_factory=list)+ assembly_issues: list[DFMIssue] = Field(default_factory=list)+ production_files: ProductionFilesStatus = Field(+ default_factory=ProductionFilesStatus+ )++ @property+ def issues(self) -> list[DFMIssue]:+ """Every finding across parts and the assembly, flattened."""+ return [+ issue for part in self.parts for issue in part.issues+ ] + self.assembly_issuesdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/_models_commerce.py b/autogpt_platform/backend/backend/blocks/rmfg/_models_commerce.pynew file mode 100644index 0000000000..8e8170db0e--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_models_commerce.py@@ -0,0 +1,250 @@+"""Response models for RMFG quotes, carts, orders and review links."""++from typing import Optional++from backend.sdk import BaseModel, Field++from ._models import DFMReport, ManufacturingReviewWarning, Requirement, ResourceError+from ._types import (+ CartStatus,+ ManufacturabilityStatus,+ ManufacturingConfiguration,+ OrderStatus,+ PaymentStatus,+ Process,+ QuoteStatus,+ ShipTo,+)+++class ShippingOption(BaseModel):+ """A carrier service plus production speed. Use ``id`` as ``shipping_option_id``."""++ id: str = ""+ production_speed: str = "standard"+ carrier: str = ""+ service: str = ""+ amount_cents: int = 0+ production_surcharge_cents: int = 0+ planned_ship_date: str = ""+ estimated_delivery_date: str = ""+ delivery_days: int = 0+ delivery_date_guaranteed: bool = False+ requires_freight: bool = False+ rate_source: str = "estimated"+++class ProductionEstimate(BaseModel):+ speed: str = "standard"+ production_days: int = 0+ estimated_ship_date: str = ""+ surcharge_cents: int = 0+++class FulfillmentEstimate(BaseModel):+ production: list[ProductionEstimate] = Field(default_factory=list)+ shipping_status: str = "destination_required"+ shipping_options: list[ShippingOption] = Field(default_factory=list)+ requires_freight: bool = False+ freight_reasons: list[str] = Field(default_factory=list)+++class QuantityOption(BaseModel):+ """Price of the same configuration at another quantity."""++ quantity: int = 0+ unit_amount_cents: int = 0+ amount_cents: int = 0+++class LineItemBreakdown(BaseModel):+ type: str = "base"+ unit_amount_cents: int = 0+ amount_cents: int = 0+++class QuoteLineItem(BaseModel):+ """Pricing for one unique part; quantity is design quantity × instance_count."""++ part_id: str = ""+ process: Process = Process.SHEET_METAL+ quantity: int = 0+ unit_amount_cents: int = 0+ amount_cents: int = 0+ material_id: Optional[str] = None+ tube_profile_id: Optional[str] = None+ breakdown: list[LineItemBreakdown] = Field(default_factory=list)+++class QuotedDesign(BaseModel):+ design_id: str = ""+ quantity: int = 1+ status: ManufacturabilityStatus = ManufacturabilityStatus.READY+ client_reference_id: Optional[str] = None+ unit_amount_cents: Optional[int] = None+ amount_cents: Optional[int] = None+ assembly_operations_amount_cents: int = 0+ quantity_options: list[QuantityOption] = Field(default_factory=list)+ dfm: DFMReport = Field(default_factory=DFMReport)+ requirements: list[Requirement] = Field(default_factory=list)+ line_items: list[QuoteLineItem] = Field(default_factory=list)+++class Quote(BaseModel):+ """An immutable priced evaluation of a basket of designs. Amounts are USD cents."""++ id: str = ""+ status: QuoteStatus = QuoteStatus.PROCESSING+ design_id: Optional[str] = None+ currency: str = "usd"+ amount_subtotal_cents: Optional[int] = None+ amount_shipping_cents: Optional[int] = None+ amount_tax_cents: Optional[int] = None+ amount_total_cents: Optional[int] = None+ items: list[QuotedDesign] = Field(default_factory=list)+ requirements: list[Requirement] = Field(default_factory=list)+ fulfillment: Optional[FulfillmentEstimate] = None+ created_at: str = ""+ expires_at: Optional[str] = None+ error: Optional[ResourceError] = None++ @property+ def shipping_options(self) -> list[ShippingOption]:+ return self.fulfillment.shipping_options if self.fulfillment else []++ @property+ def all_requirements(self) -> list[Requirement]:+ """Quote-level requirements plus every item's, flattened."""+ return self.requirements + [+ requirement for item in self.items for requirement in item.requirements+ ]+++class CartTotals(BaseModel):+ """Every amount checkout charges, in USD cents."""++ amount_subtotal_cents: int = 0+ amount_shipping_cents: Optional[int] = None+ amount_production_surcharge_cents: Optional[int] = None+ amount_tax_cents: Optional[int] = None+ tax_status: str = "destination_required"+ amount_total_cents: int = 0+++class CartPayment(BaseModel):+ cart_id: str = ""+ status: PaymentStatus = PaymentStatus.PROCESSING+ payment_intent_id: Optional[str] = None+ amount_total_cents: int = 0+ order_id: Optional[str] = None+ paid_at: Optional[str] = None+++class CartItem(BaseModel):+ """One configured design as a cart echoes it back.++ The API documents this as the request item shape, but a response model+ must never reject what the server sends, so every field has a default.+ """++ design_id: str = ""+ quantity: int = 1+ configuration: ManufacturingConfiguration = Field(+ default_factory=ManufacturingConfiguration+ )+ client_reference_id: Optional[str] = None+ quantity_options: list[int] = Field(default_factory=list)+++class Cart(BaseModel):+ """A server-side basket that re-quotes on every change.++ ``cart_url`` embeds an unguessable token: anyone holding it can check out.+ """++ id: str = ""+ revision: int = 0+ status: CartStatus = CartStatus.OPEN+ cart_url: str = ""+ items: list[CartItem] = Field(default_factory=list)+ ship_to: Optional[ShipTo] = None+ shipping_option_id: Optional[str] = None+ selected_shipping_option: Optional[ShippingOption] = None+ quote: Quote = Field(default_factory=Quote)+ totals: CartTotals = Field(default_factory=CartTotals)+ manufacturing_warnings: list[ManufacturingReviewWarning] = Field(+ default_factory=list+ )+ order_id: Optional[str] = None+ payment: Optional[CartPayment] = None+ client_reference_id: Optional[str] = None+ created_at: str = ""+ expires_at: Optional[str] = None+++class OrderTracking(BaseModel):+ carrier: Optional[str] = None+ service: Optional[str] = None+ number: Optional[str] = None+ url: Optional[str] = None+ shipped_at: Optional[str] = None+ delivered_at: Optional[str] = None+++class OrderLineItem(BaseModel):+ id: str = ""+ type: str = "part"+ part_id: Optional[str] = None+ design_id: Optional[str] = None+ name: Optional[str] = None+ quantity: int = 0+ unit_amount_cents: int = 0+ amount_cents: int = 0+ material_id: Optional[str] = None+ tube_profile_id: Optional[str] = None+ powder_coat_color_id: Optional[str] = None+ finish_id: Optional[str] = None+ hole_operation_count: int = 0+++class OrderEvent(BaseModel):+ type: str = ""+ at: str = ""+++class Order(BaseModel):+ """A paid manufacturing order and what has happened to it since."""++ id: str = ""+ status: OrderStatus = OrderStatus.RECEIVED+ created_at: str = ""+ cart_id: Optional[str] = None+ quote_id: Optional[str] = None+ amount_subtotal_cents: Optional[int] = None+ amount_discount_cents: Optional[int] = None+ amount_tax_cents: Optional[int] = None+ amount_total_cents: Optional[int] = None+ expedited: bool = False+ production_hold: bool = False+ estimated_ship_date: Optional[str] = None+ delivered_at: Optional[str] = None+ tracking: Optional[OrderTracking] = None+ line_items: list[OrderLineItem] = Field(default_factory=list)+ events: list[OrderEvent] = Field(default_factory=list)+ po_number: Optional[str] = None+++class ReviewLink(BaseModel):+ """A website hand-off where a person can adjust and save a configuration."""++ id: str = ""+ status: str = "open"+ design_id: str = ""+ dfm_id: Optional[str] = None+ review_url: str = ""+ configuration: ManufacturingConfiguration = Field(+ default_factory=ManufacturingConfiguration+ )+ configuration_updated_at: Optional[str] = None+ created_at: str = ""+ expires_at: Optional[str] = Nonediff --git a/autogpt_platform/backend/backend/blocks/rmfg/_testdata.py b/autogpt_platform/backend/backend/blocks/rmfg/_testdata.pynew file mode 100644index 0000000000..f4373a7ebd--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_testdata.py@@ -0,0 +1,268 @@+"""Shared block test fixtures.++Kept in its own module so block files never import test data from each other.+"""++from ._models import (+ Design,+ DFMIssue,+ DFMReport,+ Dimensions,+ Finish,+ HardwareOption,+ Hole,+ Material,+ Part,+ PartDFM,+ PowderCoatColor,+ Requirement,+ TubeProfile,+)+from ._models_commerce import (+ Cart,+ CartPayment,+ CartTotals,+ FulfillmentEstimate,+ Order,+ OrderTracking,+ Quote,+ QuotedDesign,+ QuoteLineItem,+ ReviewLink,+ ShippingOption,+)+from ._types import (+ CartStatus,+ DefaultSelection,+ DesignStatus,+ ManufacturabilityStatus,+ ManufacturingConfiguration,+ OrderStatus,+ PartConfiguration,+ PaymentStatus,+ Process,+ QuoteStatus,+ ShipTo,+)++# "ISO-10303-21;" — the first line of any STEP file, as a data URI.+TEST_STEP_DATA_URI = "data:application/step;base64,SVNPLTEwMzAzLTIxOw=="++# A 1x1 transparent PNG.+TEST_PNG_DATA_URI = (+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ"+ "AAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="+)++TEST_MATERIAL = Material(+ id="mat_5052_0125",+ material="5052 Aluminum",+ type="aluminum",+ thickness_in=0.125,+ thickness_mm=3.175,+ display_thickness='0.125"',+ bendable=True,+ weight_g_per_cm2=0.857,+)++TEST_TUBE_PROFILE = TubeProfile(+ id="tube_sq_25x25x2",+ material="Mild Steel",+ type="steel",+ shape="square",+ display_name='1" square, 0.083" wall',+ outer_width_mm=25.4,+ outer_height_mm=25.4,+ wall_thickness_mm=2.1,+)++TEST_FINISH = Finish(+ id="fin_deburr",+ name="Deburr",+ slug="deburr",+ processes=[Process.SHEET_METAL],+ base_price_cents=0,+)++TEST_POWDER_COAT_COLOR = PowderCoatColor(+ id="pc_ral9005",+ name="Jet Black",+ slug="jet-black",+ hex_color="#0A0A0A",+)++TEST_HARDWARE_OPTION = HardwareOption.model_validate(+ {"id": "tap_m4", "size": "M4", "hole_diameter_mm": 3.3, "thread_standard": "metric"}+)++TEST_PART = Part(+ id="prt_bracket",+ name="bracket",+ suggested_process=Process.SHEET_METAL,+ instance_count=2,+ formed_dimensions=Dimensions(length_mm=120, width_mm=60, height_mm=30),+ detected_thickness_mm=3.0,+ bend_count=1,+ hole_count=2,+ holes=[Hole(id=1, diameter_mm=4.5), Hole(id=2, diameter_mm=4.5)],+ model_url="https://api.rmfg.com/v1/designs/dsn_bracket/parts/prt_bracket/model",+ image_url="https://api.rmfg.com/v1/designs/dsn_bracket/parts/prt_bracket/image",+)++TEST_DESIGN = Design(+ id="dsn_bracket",+ status=DesignStatus.READY,+ name="bracket.step",+ formed_dimensions=Dimensions(length_mm=120, width_mm=60, height_mm=30),+ parts=[TEST_PART],+ review_url="https://www.rmfg.com/review/abc",+ image_url="https://api.rmfg.com/v1/designs/dsn_bracket/image",+ created_at="2026-09-01T12:00:00Z",+)++TEST_PENDING_DESIGN = TEST_DESIGN.model_copy(+ update={"status": DesignStatus.PROCESSING, "parts": []}+)++TEST_CONFIGURATION = ManufacturingConfiguration(+ defaults=DefaultSelection(material_id=TEST_MATERIAL.id),+ parts=[PartConfiguration(part_id=TEST_PART.id)],+)++TEST_DFM_ISSUE = DFMIssue(+ code="hole_too_close_to_bend",+ message="Hole 2 is 2.1 mm from bend 1; 6 mm is recommended.",+ severity="warning",+ source="geometry",+ part_id=TEST_PART.id,+ hole_id=2,+ bend_id=1,+)++TEST_DFM_REPORT = DFMReport(+ id="dfm_001",+ design_id=TEST_DESIGN.id,+ status=ManufacturabilityStatus.READY,+ review_url="https://www.rmfg.com/review/abc?dfm=dfm_001",+ configuration=TEST_CONFIGURATION,+ parts=[PartDFM(part_id=TEST_PART.id, issues=[TEST_DFM_ISSUE])],+)++TEST_REQUIREMENT = Requirement(+ code="material_required",+ message="Select a material for part prt_bracket.",+ part_id=TEST_PART.id,+ field="material_id",+)++TEST_SHIPPING_OPTION = ShippingOption(+ id="ship_ups_ground_std",+ production_speed="standard",+ carrier="UPS",+ service="Ground",+ amount_cents=1850,+ planned_ship_date="2026-09-08",+ estimated_delivery_date="2026-09-11",+ delivery_days=3,+ rate_source="live",+)++TEST_QUOTE = Quote(+ id="qte_001",+ status=QuoteStatus.READY,+ design_id=TEST_DESIGN.id,+ amount_subtotal_cents=24800,+ amount_total_cents=24800,+ items=[+ QuotedDesign(+ design_id=TEST_DESIGN.id,+ quantity=10,+ unit_amount_cents=2480,+ amount_cents=24800,+ dfm=TEST_DFM_REPORT,+ line_items=[+ QuoteLineItem(+ part_id=TEST_PART.id,+ quantity=20,+ unit_amount_cents=1240,+ amount_cents=24800,+ material_id=TEST_MATERIAL.id,+ )+ ],+ )+ ],+ fulfillment=FulfillmentEstimate(+ shipping_status="ready", shipping_options=[TEST_SHIPPING_OPTION]+ ),+ created_at="2026-09-01T12:05:00Z",+)++TEST_PROCESSING_QUOTE = TEST_QUOTE.model_copy(+ update={"status": QuoteStatus.PROCESSING, "items": []}+)++TEST_SHIP_TO = ShipTo(+ name="Ada Lovelace",+ street1="1 Analytical Way",+ city="Austin",+ state="TX",+ postal_code="78701",+)++TEST_CART = Cart(+ id="crt_001",+ revision=1,+ status=CartStatus.OPEN,+ cart_url="https://www.rmfg.com/cart/secret-token",+ ship_to=TEST_SHIP_TO,+ shipping_option_id=TEST_SHIPPING_OPTION.id,+ selected_shipping_option=TEST_SHIPPING_OPTION,+ quote=TEST_QUOTE,+ totals=CartTotals(+ amount_subtotal_cents=24800,+ amount_shipping_cents=1850,+ amount_tax_cents=2199,+ tax_status="calculated",+ amount_total_cents=28849,+ ),+ created_at="2026-09-01T12:06:00Z",+)++TEST_PAID_CART = TEST_CART.model_copy(+ update={+ "status": CartStatus.CHECKED_OUT,+ "order_id": "ord_001",+ "payment": CartPayment(+ cart_id="crt_001",+ status=PaymentStatus.PAID,+ amount_total_cents=28849,+ order_id="ord_001",+ paid_at="2026-09-01T12:10:00Z",+ ),+ }+)++TEST_ORDER = Order(+ id="ord_001",+ status=OrderStatus.SHIPPED,+ created_at="2026-09-01T12:10:00Z",+ cart_id=TEST_CART.id,+ quote_id=TEST_QUOTE.id,+ amount_total_cents=28849,+ estimated_ship_date="2026-09-08",+ tracking=OrderTracking(+ carrier="UPS",+ service="Ground",+ number="1Z999AA10123456784",+ url="https://www.ups.com/track?tracknum=1Z999AA10123456784",+ shipped_at="2026-09-08T16:00:00Z",+ ),+)++TEST_REVIEW_LINK = ReviewLink(+ id="rvl_001",+ design_id=TEST_DESIGN.id,+ review_url="https://www.rmfg.com/review/abc",+ configuration=TEST_CONFIGURATION,+ created_at="2026-09-01T12:07:00Z",+)diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_types.py b/autogpt_platform/backend/backend/blocks/rmfg/_types.pynew file mode 100644index 0000000000..323ff63691--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_types.py@@ -0,0 +1,276 @@+"""Enums and request-side models for the RMFG Manufacturing API (v2026-09-01).++Field names mirror the API so a model's ``model_dump`` is the request body.+Response-side models live in ``_models`` and ``_models_commerce``.+"""++from enum import Enum+from typing import Annotated, Optional++from backend.sdk import APIKeyCredentials, BaseModel, Field, OAuth2Credentials++# An RMFG API key or an OAuth token pair from the device-code connection flow;+# both are sent as a bearer token.+RMFGCredentials = APIKeyCredentials | OAuth2Credentials++# Origin of the RMFG API. Every module joins ``/v1`` itself so the version+# lives at the call sites rather than in two differently-shaped constants.+RMFG_API_URL = "https://api.rmfg.com"+++class Process(str, Enum):+ SHEET_METAL = "sheet_metal"+ TUBE_LASER = "tube_laser"+++class DesignStatus(str, Enum):+ QUEUED = "queued"+ PROCESSING = "processing"+ READY = "ready"+ FAILED = "failed"+++class ManufacturabilityStatus(str, Enum):+ """Outcome of a DFM evaluation. Only ``ready`` can be checked out."""++ REQUIRES_INPUT = "requires_input"+ READY = "ready"+ BLOCKED = "blocked"+++class QuoteStatus(str, Enum):+ PROCESSING = "processing"+ REQUIRES_INPUT = "requires_input"+ READY = "ready"+ BLOCKED = "blocked"+ EXPIRED = "expired"+ FAILED = "failed"+++class CartStatus(str, Enum):+ OPEN = "open"+ CHECKED_OUT = "checked_out"+ EXPIRED = "expired"+++class PaymentStatus(str, Enum):+ PAID = "paid"+ PROCESSING = "processing"+ FAILED = "failed"+ REFUNDED = "refunded"+++class OrderStatus(str, Enum):+ RECEIVED = "received"+ IN_PRODUCTION = "in_production"+ READY_FOR_PICKUP = "ready_for_pickup"+ SHIPPED = "shipped"+ DELIVERED = "delivered"+ CANCELLED = "cancelled"+ REFUNDED = "refunded"+++class HardwareKind(str, Enum):+ """Catalog families under ``/v1/hardware/{kind}``."""++ TAPS = "taps"+ STUDS = "studs"+ NUTS = "nuts"+ STANDOFFS = "standoffs"+++class HoleSide(str, Enum):+ """Sheet face an operation is applied from; ``top`` is the hole's normal."""++ TOP = "top"+ BOTTOM = "bottom"+++class CountersinkAngle(int, Enum):+ DEG_82 = 82+ DEG_90 = 90+++class AcceptedRisk(str, Enum):+ """DFM findings a customer can accept responsibility for."""++ HOLE_TOO_CLOSE_TO_BEND = "hole_too_close_to_bend"+ COUNTERSINK_TOO_CLOSE_TO_BEND = "countersink_too_close_to_bend"+++class WeldMethod(str, Enum):+ AUTO = "auto"+ MIG = "mig"+ TIG = "tig"+++class WeldFinish(str, Enum):+ NONE = "none"+ ROUGH = "rough"+ FINE = "fine"+++class JointAccess(str, Enum):+ OPEN = "open"+ TIGHT = "tight"+ BLIND = "blind"+++class ImageView(str, Enum):+ """Camera angle for rendered design and part pictures."""++ ISO = "iso"+ TOP = "top"+ BOTTOM = "bottom"+ FRONT = "front"+ BACK = "back"+ LEFT = "left"+ RIGHT = "right"+ FLAT = "flat"+++class PaymentType(str, Enum):+ CARD_ON_FILE = "card_on_file"+ PAYMENT_METHOD = "payment_method"+++class TapOperation(BaseModel):+ hole_id: int = Field(description="Hole ID from the analyzed part's holes[]")+ tap_id: str = Field(description="Catalog ID from List Hardware (taps)")+++class StudOperation(BaseModel):+ hole_id: int = Field(description="Hole ID from the analyzed part's holes[]")+ stud_id: str = Field(description="Catalog ID from List Hardware (studs)")+ side: HoleSide = Field(+ default=HoleSide.TOP, description="Sheet face the stud is installed from"+ )+++class NutOperation(BaseModel):+ hole_id: int = Field(description="Hole ID from the analyzed part's holes[]")+ nut_id: str = Field(description="Catalog ID from List Hardware (nuts)")+ side: HoleSide = Field(+ default=HoleSide.TOP, description="Sheet face the nut is installed from"+ )+++class StandoffOperation(BaseModel):+ hole_id: int = Field(description="Hole ID from the analyzed part's holes[]")+ standoff_id: str = Field(description="Catalog ID from List Hardware (standoffs)")+ side: HoleSide = Field(+ default=HoleSide.TOP, description="Sheet face the standoff is installed from"+ )+++class CountersinkOperation(BaseModel):+ hole_id: int = Field(description="Hole ID from the analyzed part's holes[]")+ outer_diameter_mm: float = Field(description="Countersink outer diameter in mm")+ angle: CountersinkAngle = Field(+ default=CountersinkAngle.DEG_82, description="Included angle in degrees"+ )+ side: HoleSide = Field(+ default=HoleSide.TOP, description="Sheet face the countersink is cut into"+ )+++class WeldingOperation(BaseModel):+ """A welded seam. One part instance ID is a seam on that instance; two or more join them."""++ type: str = "weld"+ method: WeldMethod = WeldMethod.AUTO+ weld_length_mm: float = Field(description="Total seam length in mm")+ part_instance_ids: list[str] = Field(+ description="Part instance IDs from the design's part_instances[]"+ )+ weld_finish: WeldFinish = WeldFinish.NONE+ joint_access: JointAccess = JointAccess.OPEN+++class DefaultSelection(BaseModel):+ """Choices applied to every compatible part unless a part overrides them."""++ material_id: Optional[str] = Field(+ default=None, description="Sheet-metal stock; applies to sheet parts only"+ )+ tube_profile_id: Optional[str] = Field(+ default=None, description="Tube stock; applies to tube-laser parts only"+ )+ powder_coat_color_id: Optional[str] = None+ finish_id: Optional[str] = None+++class PartConfiguration(BaseModel):+ """Choices for one unique part; set fields override the defaults for it."""++ part_id: str = Field(description="Part ID from the analyzed design's parts[]")+ material_id: Optional[str] = None+ tube_profile_id: Optional[str] = None+ powder_coat_color_id: Optional[str] = None+ finish_id: Optional[str] = None+ taps: list[TapOperation] = Field(default_factory=list)+ studs: list[StudOperation] = Field(default_factory=list)+ nuts: list[NutOperation] = Field(default_factory=list)+ standoffs: list[StandoffOperation] = Field(default_factory=list)+ countersinks: list[CountersinkOperation] = Field(default_factory=list)+++class ManufacturingConfiguration(BaseModel):+ """Manufacturing intent shared by DFM reports, quotes, carts and review links.++ Precedence is part override, then defaults, then unset. Unset fields are+ omitted from the request, so a missing selection surfaces as a+ ``requires_input`` finding rather than an HTTP error.+ """++ defaults: DefaultSelection = Field(default_factory=DefaultSelection)+ parts: list[PartConfiguration] = Field(default_factory=list)+ assembly_operations: list[WeldingOperation] = Field(default_factory=list)+ accepted_risks: list[AcceptedRisk] = Field(default_factory=list)++ def with_material(self, material_id: str) -> "ManufacturingConfiguration":+ """Return a copy whose default sheet material is ``material_id``."""+ if not material_id:+ return self+ defaults = self.defaults.model_copy(update={"material_id": material_id})+ return self.model_copy(update={"defaults": defaults})++ def to_payload(self) -> dict:+ return self.model_dump(mode="json", exclude_none=True)+++class QuoteItemRequest(BaseModel):+ """One configured design in a quote or cart basket."""++ design_id: str = Field(description="Design ID from Analyze Design")+ quantity: int = Field(default=1, ge=1, description="Completed units of the design")+ configuration: ManufacturingConfiguration = Field(+ default_factory=ManufacturingConfiguration+ )+ client_reference_id: Optional[str] = None+ quantity_options: list[Annotated[int, Field(ge=1)]] = Field(+ default_factory=list,+ max_length=10,+ description="Up to ten other quantities to price alongside quantity",+ )++ def to_payload(self) -> dict:+ payload = self.model_dump(mode="json", exclude_none=True)+ payload["configuration"] = self.configuration.to_payload()+ return payload+++class ShipTo(BaseModel):+ name: str = Field(description="Recipient name")+ company: Optional[str] = None+ street1: str = Field(description="Street address line 1")+ street2: Optional[str] = None+ city: str+ state: str = Field(description="Two-letter state code, e.g. TX")+ postal_code: str+ country: str = Field(default="US", description="Two-letter country code")+ phone: Optional[str] = None+ email: Optional[str] = None++ def to_payload(self) -> dict:+ return self.model_dump(mode="json", exclude_none=True)diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_webhook.py b/autogpt_platform/backend/backend/blocks/rmfg/_webhook.pynew file mode 100644index 0000000000..93bf3d058c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_webhook.py@@ -0,0 +1,248 @@+"""Webhook manager for RMFG lifecycle events.++RMFG registers endpoints through its API and returns a signing secret once,+at creation. Deliveries carry ``X-RMFG-Timestamp`` and+``X-RMFG-Signature: v1=<hex HMAC-SHA256 of "<timestamp>.<raw body>">``.+"""++import hashlib+import hmac+import logging+import time+from datetime import datetime, timezone+from typing import Optional, TypeGuard+from urllib.parse import quote++from fastapi import HTTPException, Request+from pydantic import TypeAdapter, ValidationError+from strenum import StrEnum++from backend.data import integrations+from backend.sdk import (+ APIKeyCredentials,+ BaseWebhooksManager,+ Credentials,+ OAuth2Credentials,+ Requests,+)+from backend.util.request import Response++from ._http import ErrorEnvelope+from ._types import RMFG_API_URL, RMFGCredentials++logger = logging.getLogger(__name__)++RMFG_WEBHOOKS_URL = f"{RMFG_API_URL}/v1/webhook-endpoints"+SIGNATURE_HEADER = "X-RMFG-Signature"+TIMESTAMP_HEADER = "X-RMFG-Timestamp"+# How far a delivery's timestamp may drift before it is treated as a replay.+TIMESTAMP_TOLERANCE_SECONDS = 300+# ``webhook.config`` key holding the secret RMFG returns at endpoint creation.+SIGNING_SECRET_KEY = "signing_secret" # pragma: allowlist secret++# Trigger-block event filter field -> RMFG event type. The platform matches+# deliveries against the filter's field names, so both directions are needed.+EVENT_TYPES: dict[str, str] = {+ "design_ready": "design.ready",+ "design_failed": "design.failed",+ "production_files_ready": "dfm_report.production_files.ready",+ "production_files_failed": "dfm_report.production_files.failed",+ "quote_ready": "quote.ready",+ "quote_failed": "quote.failed",+ "cart_checked_out": "cart.checked_out",+ "order_status_changed": "order.status_changed",+}+FILTER_KEYS: dict[str, str] = {event: key for key, event in EVENT_TYPES.items()}++_JSON_OBJECT = TypeAdapter(dict)+++class RMFGWebhookType(StrEnum):+ ACCOUNT = "account"+++class RMFGWebhooksManager(BaseWebhooksManager):+ WebhookType = RMFGWebhookType++ @classmethod+ async def verify_signature(+ cls, webhook: integrations.WebhookWithRelations, request: Request+ ) -> None:+ secret = webhook.config.get(SIGNING_SECRET_KEY, "")+ if not secret:+ raise HTTPException(+ status_code=500, detail="RMFG signing secret not configured"+ )++ signature_header = request.headers.get(SIGNATURE_HEADER)+ timestamp = request.headers.get(TIMESTAMP_HEADER)+ if not signature_header or not timestamp:+ raise HTTPException(+ status_code=403,+ detail=f"{SIGNATURE_HEADER} or {TIMESTAMP_HEADER} header is missing",+ )+ _reject_stale_timestamp(timestamp)++ body = await request.body()+ expected = hmac.new(+ secret.encode("utf-8"),+ msg=f"{timestamp}.".encode("utf-8") + body,+ digestmod=hashlib.sha256,+ ).hexdigest()+ if not any(+ _signatures_match(expected, sig) for sig in _v1_signatures(signature_header)+ ):+ raise HTTPException(status_code=403, detail="RMFG signature mismatch")++ @classmethod+ async def validate_payload(+ cls,+ webhook: integrations.Webhook,+ request: Request,+ credentials: Credentials | None = None,+ ) -> tuple[dict, str]:+ try:+ payload = _JSON_OBJECT.validate_python(await request.json())+ except (ValueError, ValidationError) as exc:+ raise HTTPException(+ status_code=400, detail="RMFG webhook body must be a JSON object"+ ) from exc+ event_type = str(payload.get("type") or "")+ if not event_type:+ raise HTTPException(+ status_code=400, detail="RMFG event type missing from payload"+ )+ # Report the filter key so the trigger block's event filter matches;+ # an event this integration does not know simply triggers nothing.+ return payload, FILTER_KEYS.get(event_type, event_type)++ async def _register_webhook(+ self,+ credentials: Credentials,+ webhook_type: RMFGWebhookType,+ resource: str,+ events: list[str],+ ingress_url: str,+ secret: str,+ ) -> tuple[str, dict]:+ if not isinstance(credentials, (APIKeyCredentials, OAuth2Credentials)):+ raise ValueError(+ "RMFG webhook registration needs an API key or a connected account"+ )+ unknown = [event for event in events if event not in EVENT_TYPES]+ if unknown:+ raise ValueError(f"Unknown RMFG events: {', '.join(unknown)}")++ response = await Requests(raise_for_status=False).post(+ RMFG_WEBHOOKS_URL,+ headers=_headers(credentials),+ json={+ "url": ingress_url,+ "events": [EVENT_TYPES[event] for event in events],+ "description": "AutoGPT Platform trigger",+ },+ )+ if not response.ok:+ message = _error_message(response)+ if response.status == 403 and isinstance(credentials, OAuth2Credentials):+ # Webhooks are an opt-in permission on RMFG's approval page.+ message += ". Reconnect RMFG and allow the webhooks permission"+ raise ValueError(f"RMFG webhook registration failed: {message}")+ try:+ data = _JSON_OBJECT.validate_python(response.json())+ except (ValueError, ValidationError) as exc:+ raise ValueError(+ "RMFG webhook registration returned an unreadable response"+ ) from exc+ endpoint_id, signing_secret = data.get("id"), data.get("secret")+ # The secret is only returned on creation; without it no delivery+ # could ever be verified, so refuse to keep a half-registered hook.+ # Both must be strings: the secret is keyed into an HMAC on every+ # delivery, and a stored non-string would fail each one with a 403.+ if not _non_empty_str(endpoint_id) or not _non_empty_str(signing_secret):+ raise ValueError(+ "RMFG webhook registration returned no endpoint ID or signing secret"+ )+ return endpoint_id, {SIGNING_SECRET_KEY: signing_secret}++ async def _deregister_webhook(+ self, webhook: integrations.Webhook, credentials: Credentials+ ) -> None:+ if not isinstance(credentials, (APIKeyCredentials, OAuth2Credentials)):+ logger.warning("Cannot deregister RMFG webhook: unsupported credentials")+ return+ if not webhook.provider_webhook_id:+ return+ response = await Requests(raise_for_status=False).delete(+ f"{RMFG_WEBHOOKS_URL}/{quote(webhook.provider_webhook_id, safe='')}",+ headers=_headers(credentials),+ )+ # 404 means the endpoint is already gone, which is the desired state.+ if response.status not in (200, 204, 404):+ logger.warning(+ f"Failed to deregister RMFG webhook {webhook.provider_webhook_id}: "+ f"{_error_message(response)}"+ )+++def _non_empty_str(value: object) -> TypeGuard[str]:+ return isinstance(value, str) and bool(value)+++def _headers(credentials: RMFGCredentials) -> dict[str, str]:+ return {+ "Authorization": credentials.auth_header(),+ "Content-Type": "application/json",+ }+++def _v1_signatures(header: str) -> list[str]:+ """Extract every ``v1=`` value from a comma-separated signature header."""+ found: list[str] = []+ for part in header.split(","):+ key, _, value = part.partition("=")+ if key.strip() == "v1" and value.strip():+ found.append(value.strip())+ return found+++def _signatures_match(expected: str, candidate: str) -> bool:+ """Constant-time compare that treats a non-ASCII candidate as a mismatch."""+ try:+ return hmac.compare_digest(expected, candidate)+ except TypeError:+ return False+++def _reject_stale_timestamp(timestamp: str) -> None:+ sent_at = _parse_timestamp(timestamp)+ if sent_at is None:+ raise HTTPException(status_code=403, detail="Invalid RMFG timestamp")+ if abs(time.time() - sent_at) > TIMESTAMP_TOLERANCE_SECONDS:+ raise HTTPException(+ status_code=403, detail="RMFG webhook timestamp is outside the window"+ )+++def _parse_timestamp(timestamp: str) -> Optional[float]:+ """Accept epoch seconds or an ISO-8601 instant; return epoch seconds."""+ candidate = timestamp.strip()+ try:+ return float(candidate)+ except ValueError:+ pass+ try:+ parsed = datetime.fromisoformat(candidate.replace("Z", "+00:00"))+ except ValueError:+ return None+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.timestamp()+++def _error_message(response: Response) -> str:+ try:+ message = ErrorEnvelope.model_validate(response.json()).error.message+ except (ValueError, ValidationError):+ message = ""+ return message or f"HTTP {response.status}"diff --git a/autogpt_platform/backend/backend/blocks/rmfg/_webhook_test.py b/autogpt_platform/backend/backend/blocks/rmfg/_webhook_test.pynew file mode 100644index 0000000000..d03a9629e0--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/_webhook_test.py@@ -0,0 +1,439 @@+"""Tests for RMFG webhook registration, signature checks and event mapping."""++import hashlib+import hmac+import json+import time+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest+from fastapi import HTTPException, Request+from pydantic import SecretStr++from backend.blocks.rmfg._webhook import (+ EVENT_TYPES,+ SIGNING_SECRET_KEY,+ TIMESTAMP_TOLERANCE_SECONDS,+ RMFGWebhooksManager,+ RMFGWebhookType,+ _parse_timestamp,+)+from backend.data import integrations+from backend.data.model import (+ APIKeyCredentials,+ OAuth2Credentials,+ UserPasswordCredentials,+)+from backend.integrations.providers import ProviderName++SIGNING_SECRET = "whsec_rmfg_test" # pragma: allowlist secret+PAYLOAD = json.dumps(+ {+ "id": "evt_1",+ "type": "order.status_changed",+ "created_at": "2026-09-08T16:00:00Z",+ "data": {"id": "ord_1", "object": "order", "status": "shipped"},+ }+).encode()+++def make_webhook(config: dict | None = None) -> integrations.Webhook:+ return integrations.Webhook(+ id="webhook_123",+ user_id="user_123",+ provider=ProviderName("rmfg"),+ credentials_id="creds_123",+ webhook_type=RMFGWebhookType.ACCOUNT,+ resource="",+ events=["order_status_changed"],+ config={SIGNING_SECRET_KEY: SIGNING_SECRET} if config is None else config,+ secret="platform-secret-not-used-by-rmfg",+ provider_webhook_id="whe_123",+ )+++def make_request(headers: dict[str, str], body: bytes = PAYLOAD) -> Request:+ request = Request(+ {+ "type": "http",+ "method": "POST",+ "path": "/ingress",+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],+ }+ )+ request._body = body+ return request+++def sign(timestamp: str, body: bytes = PAYLOAD, secret: str = SIGNING_SECRET) -> str:+ digest = hmac.new(+ secret.encode(),+ msg=f"{timestamp}.".encode() + body,+ digestmod=hashlib.sha256,+ ).hexdigest()+ return f"v1={digest}"+++def signed_request(timestamp: str | None = None, **overrides: str) -> Request:+ timestamp = timestamp or str(int(time.time()))+ headers = {+ "X-RMFG-Timestamp": timestamp,+ "X-RMFG-Signature": sign(timestamp),+ **overrides,+ }+ return make_request(headers)+++def api_key_credentials() -> APIKeyCredentials:+ return APIKeyCredentials(+ id="creds_123",+ provider="rmfg",+ api_key=SecretStr("rmfg_test_key"),+ title="RMFG API key",+ expires_at=None,+ )+++class _FakeResponse:+ def __init__(self, status: int, payload: Any = None):+ self.status = status+ self._payload = payload++ @property+ def ok(self) -> bool:+ return 200 <= self.status < 300++ def json(self) -> Any:+ if self._payload is None:+ raise ValueError("not JSON")+ return self._payload+++class TestVerifySignature:+ async def test_accepts_a_valid_signature(self):+ await RMFGWebhooksManager.verify_signature(make_webhook(), signed_request())++ async def test_accepts_iso_timestamps(self):+ now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ await RMFGWebhooksManager.verify_signature(+ make_webhook(), signed_request(timestamp=now)+ )++ async def test_accepts_any_v1_entry_in_a_list(self):+ timestamp = str(int(time.time()))+ request = make_request(+ {+ "X-RMFG-Timestamp": timestamp,+ "X-RMFG-Signature": f"v1=deadbeef,{sign(timestamp)}",+ }+ )+ await RMFGWebhooksManager.verify_signature(make_webhook(), request)++ async def test_rejects_a_missing_signature_header(self):+ request = make_request({"X-RMFG-Timestamp": str(int(time.time()))})+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403++ async def test_rejects_a_wrong_secret(self):+ timestamp = str(int(time.time()))+ request = make_request(+ {+ "X-RMFG-Timestamp": timestamp,+ "X-RMFG-Signature": sign(timestamp, secret="someone-else"),+ }+ )+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403+ assert "mismatch" in exc_info.value.detail++ async def test_rejects_a_tampered_body(self):+ timestamp = str(int(time.time()))+ request = make_request(+ {"X-RMFG-Timestamp": timestamp, "X-RMFG-Signature": sign(timestamp)},+ body=PAYLOAD + b" ",+ )+ with pytest.raises(HTTPException):+ await RMFGWebhooksManager.verify_signature(make_webhook(), request)++ async def test_rejects_a_stale_timestamp(self):+ old = str(int(time.time()) - TIMESTAMP_TOLERANCE_SECONDS - 60)+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(+ make_webhook(), signed_request(timestamp=old)+ )+ assert "outside the window" in exc_info.value.detail++ async def test_rejects_an_unparseable_timestamp(self):+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(+ make_webhook(), signed_request(timestamp="yesterday")+ )+ assert exc_info.value.status_code == 403++ async def test_non_ascii_signature_is_a_403_not_a_500(self):+ request = make_request(+ {"X-RMFG-Timestamp": str(int(time.time())), "X-RMFG-Signature": "v1=é"}+ )+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(make_webhook(), request)+ assert exc_info.value.status_code == 403++ async def test_missing_stored_secret_is_a_server_error(self):+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.verify_signature(+ make_webhook(config={}), signed_request()+ )+ assert exc_info.value.status_code == 500+++class TestParseTimestamp:+ def test_epoch_seconds(self):+ assert _parse_timestamp("1700000000") == 1700000000.0++ def test_iso_with_z(self):+ assert _parse_timestamp("1970-01-01T00:00:10Z") == 10.0++ def test_naive_iso_is_treated_as_utc(self):+ assert _parse_timestamp("1970-01-01T00:00:10") == 10.0++ def test_garbage_is_none(self):+ assert _parse_timestamp("soon") is None+++class TestValidatePayload:+ async def test_maps_the_rmfg_type_to_the_filter_key(self):+ payload, event_type = await RMFGWebhooksManager.validate_payload(+ make_webhook(), make_request({}), None+ )+ assert payload["id"] == "evt_1"+ # The trigger block filters on its own field names, so the platform+ # must see the filter key rather than the dotted API type.+ assert event_type == "order_status_changed"++ async def test_unknown_types_pass_through_unmatched(self):+ body = json.dumps({"id": "evt_2", "type": "something.new"}).encode()+ _, event_type = await RMFGWebhooksManager.validate_payload(+ make_webhook(), make_request({}, body=body), None+ )+ assert event_type == "something.new"++ async def test_missing_type_is_a_400(self):+ body = json.dumps({"id": "evt_3"}).encode()+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.validate_payload(+ make_webhook(), make_request({}, body=body), None+ )+ assert exc_info.value.status_code == 400++ async def test_non_object_body_is_a_400(self):+ with pytest.raises(HTTPException) as exc_info:+ await RMFGWebhooksManager.validate_payload(+ make_webhook(), make_request({}, body=b"[1, 2]"), None+ )+ assert exc_info.value.status_code == 400+++class TestEventMapping:+ def test_every_filter_key_is_a_valid_identifier(self):+ # Filter keys become fields on the trigger block's EventsFilter model.+ for key in EVENT_TYPES:+ assert key.isidentifier(), key++ def test_covers_every_documented_event(self):+ assert set(EVENT_TYPES.values()) == {+ "design.ready",+ "design.failed",+ "dfm_report.production_files.ready",+ "dfm_report.production_files.failed",+ "quote.ready",+ "quote.failed",+ "cart.checked_out",+ "order.status_changed",+ }+++class TestRegistration:+ async def test_registers_dotted_events_and_stores_the_secret(self):+ response = _FakeResponse(201, {"id": "whe_1", "secret": "whsec_new"})+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)++ endpoint_id, config = await RMFGWebhooksManager()._register_webhook(+ api_key_credentials(),+ RMFGWebhookType.ACCOUNT,+ "",+ ["order_status_changed", "cart_checked_out"],+ "https://platform.example/ingress",+ "platform-secret",+ )++ post = requests_cls.return_value.post+ url = post.await_args.args[0]+ kwargs = post.await_args.kwargs++ assert endpoint_id == "whe_1"+ assert config == {SIGNING_SECRET_KEY: "whsec_new"}+ assert url == "https://api.rmfg.com/v1/webhook-endpoints"+ assert kwargs["json"]["url"] == "https://platform.example/ingress"+ assert kwargs["json"]["events"] == ["order.status_changed", "cart.checked_out"]+ assert kwargs["headers"]["Authorization"] == "Bearer rmfg_test_key"++ async def test_refuses_unknown_events_before_calling_out(self):+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ with pytest.raises(ValueError, match="Unknown RMFG events: nope"):+ await RMFGWebhooksManager()._register_webhook(+ api_key_credentials(),+ RMFGWebhookType.ACCOUNT,+ "",+ ["nope"],+ "https://platform.example/ingress",+ "s",+ )+ requests_cls.return_value.post.assert_not_called()++ async def test_refuses_a_registration_without_a_secret(self):+ response = _FakeResponse(201, {"id": "whe_1"})+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)+ with pytest.raises(ValueError, match="signing secret"):+ await RMFGWebhooksManager()._register_webhook(+ api_key_credentials(),+ RMFGWebhookType.ACCOUNT,+ "",+ ["design_ready"],+ "https://platform.example/ingress",+ "s",+ )++ @pytest.mark.parametrize(+ "payload, message",+ [+ (["whe_1", "whsec"], "unreadable response"),+ (None, "unreadable response"),+ ({"id": "whe_1", "secret": {"value": "whsec"}}, "signing secret"),+ ({"id": 12, "secret": "whsec"}, "signing secret"),+ ({"id": "whe_1", "secret": ""}, "signing secret"),+ ],+ )+ async def test_refuses_a_malformed_registration_response(self, payload, message):+ # A stored non-string secret would fail the HMAC on every delivery.+ response = _FakeResponse(201, payload)+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)+ with pytest.raises(ValueError, match=message):+ await RMFGWebhooksManager()._register_webhook(+ api_key_credentials(),+ RMFGWebhookType.ACCOUNT,+ "",+ ["design_ready"],+ "https://platform.example/ingress",+ "s",+ )++ async def test_surfaces_the_api_error_message(self):+ response = _FakeResponse(+ 403, {"error": {"type": "permission_error", "message": "scope missing"}}+ )+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)+ with pytest.raises(ValueError, match="scope missing"):+ await RMFGWebhooksManager()._register_webhook(+ api_key_credentials(),+ RMFGWebhookType.ACCOUNT,+ "",+ ["design_ready"],+ "https://platform.example/ingress",+ "s",+ )++ async def test_accepts_a_connected_account(self):+ oauth = OAuth2Credentials(+ id="creds_123",+ provider="rmfg",+ title="RMFG",+ access_token=SecretStr("rmfg_access"),+ scopes=["designs", "webhooks"],+ )+ response = _FakeResponse(201, {"id": "whe_2", "secret": "whsec_oauth"})+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)++ endpoint_id, _ = await RMFGWebhooksManager()._register_webhook(+ oauth, RMFGWebhookType.ACCOUNT, "", ["design_ready"], "https://x", "s"+ )++ kwargs = requests_cls.return_value.post.await_args.kwargs+ assert endpoint_id == "whe_2"+ assert kwargs["headers"]["Authorization"] == "Bearer rmfg_access"++ async def test_forbidden_with_oauth_points_at_the_permission(self):+ oauth = OAuth2Credentials(+ id="creds_123",+ provider="rmfg",+ title="RMFG",+ access_token=SecretStr("rmfg_access"),+ scopes=["designs"],+ )+ response = _FakeResponse(+ 403, {"error": {"type": "permission_error", "message": "scope missing"}}+ )+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.post = AsyncMock(return_value=response)+ with pytest.raises(ValueError, match="allow the webhooks permission"):+ await RMFGWebhooksManager()._register_webhook(+ oauth,+ RMFGWebhookType.ACCOUNT,+ "",+ ["design_ready"],+ "https://x",+ "s",+ )++ async def test_rejects_other_credential_types(self):+ creds = UserPasswordCredentials(+ id="creds_123",+ provider="rmfg",+ title="RMFG",+ username=SecretStr("u"),+ password=SecretStr("p"),+ )+ with pytest.raises(ValueError, match="API key or a connected account"):+ await RMFGWebhooksManager()._register_webhook(+ creds, RMFGWebhookType.ACCOUNT, "", ["design_ready"], "https://x", "s"+ )+++class TestDeregistration:+ async def test_deletes_the_endpoint(self):+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ delete = AsyncMock(return_value=_FakeResponse(204))+ requests_cls.return_value.delete = delete++ await RMFGWebhooksManager()._deregister_webhook(+ make_webhook(), api_key_credentials()+ )++ assert delete.await_args.args[0] == (+ "https://api.rmfg.com/v1/webhook-endpoints/whe_123"+ )++ async def test_an_already_deleted_endpoint_is_fine(self):+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.delete = AsyncMock(+ return_value=_FakeResponse(404, {"error": {"message": "gone"}})+ )+ await RMFGWebhooksManager()._deregister_webhook(+ make_webhook(), api_key_credentials()+ )++ async def test_other_failures_are_logged_not_raised(self):+ with patch("backend.blocks.rmfg._webhook.Requests") as requests_cls:+ requests_cls.return_value.delete = AsyncMock(+ return_value=_FakeResponse(500, {"error": {"message": "boom"}})+ )+ await RMFGWebhooksManager()._deregister_webhook(+ make_webhook(), api_key_credentials()+ )diff --git a/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.py b/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.pynew file mode 100644index 0000000000..2624c4aab1--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.py@@ -0,0 +1,365 @@+"""Block-level tests for behaviour the standard harness can't reach.++The harness exercises one canned input per block. These cover the input+shaping and guard paths it misses.+"""++from types import SimpleNamespace+from typing import Any+from unittest.mock import AsyncMock++import pytest+from pydantic import ValidationError++from backend.blocks.rmfg import carts, images+from backend.blocks.rmfg._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.rmfg._inputs import build_items+from backend.blocks.rmfg._testdata import (+ TEST_CART,+ TEST_CONFIGURATION,+ TEST_DESIGN,+ TEST_PAID_CART,+ TEST_PART,+ TEST_SHIP_TO,+)+from backend.blocks.rmfg._types import (+ CartStatus,+ ManufacturingConfiguration,+ PartConfiguration,+ PaymentType,+ QuoteItemRequest,+ QuoteStatus,+)+from backend.blocks.rmfg.carts import RMFGUpdateCartBlock, is_payable+from backend.blocks.rmfg.designs import RMFGAnalyzeDesignBlock+from backend.blocks.rmfg.images import PNG_SIGNATURE, RMFGGetImageBlock+from backend.blocks.rmfg.pay_cart import RMFGPayCartBlock+from backend.blocks.rmfg.quotes import RMFGCreateQuoteBlock+from backend.blocks.rmfg.triggers import RMFGEventTriggerBlock+from backend.data.execution import ExecutionContext+++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,+ execution_context=ExecutionContext(graph_exec_id="exec-1"),+ node_exec_id="node-exec-1",+ ):+ collected.setdefault(name, value)+ return collected+++class TestBuildItems:+ def test_material_id_becomes_the_default_material(self):+ inputs = RMFGCreateQuoteBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id="dsn_1",+ quantity=3,+ material_id="mat_9",+ )++ [item] = build_items(inputs)++ assert item.design_id == "dsn_1"+ assert item.quantity == 3+ assert item.configuration.defaults.material_id == "mat_9"+ assert item.client_reference_id is None++ def test_material_id_overrides_the_configuration_default(self):+ inputs = RMFGCreateQuoteBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id="dsn_1",+ material_id="mat_new",+ configuration=TEST_CONFIGURATION,+ )++ [item] = build_items(inputs)++ assert item.configuration.defaults.material_id == "mat_new"+ # Per-part choices survive untouched.+ assert item.configuration.parts == TEST_CONFIGURATION.parts+ # The block input itself is not mutated.+ assert TEST_CONFIGURATION.defaults.material_id == "mat_5052_0125"++ def test_empty_material_id_leaves_the_configuration_alone(self):+ configuration = ManufacturingConfiguration(+ parts=[PartConfiguration(part_id="prt_1", tube_profile_id="tube_1")]+ )+ inputs = RMFGCreateQuoteBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id="dsn_1",+ configuration=configuration,+ )++ [item] = build_items(inputs)++ assert item.configuration == configuration++ def test_additional_items_follow_the_primary_one(self):+ extra = QuoteItemRequest(design_id="dsn_2", quantity=5)+ inputs = RMFGCreateQuoteBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id="dsn_1",+ additional_items=[extra],+ client_reference_id="ref-1",+ quantity_options=[1, 25],+ )++ items = build_items(inputs)++ assert [i.design_id for i in items] == ["dsn_1", "dsn_2"]+ assert items[0].client_reference_id == "ref-1"+ assert items[0].quantity_options == [1, 25]+ assert items[1] is extra++ @pytest.mark.parametrize("options", [[0], [5, -1], list(range(1, 12))])+ def test_quantity_options_are_bounded(self, options: list[int]):+ with pytest.raises(ValidationError):+ QuoteItemRequest(design_id="dsn_1", quantity_options=options)+ with pytest.raises(ValidationError):+ RMFGCreateQuoteBlock.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id="dsn_1",+ quantity_options=options,+ )+++class TestQuoteBlock:+ async def test_uses_node_exec_id_as_idempotency_key(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = RMFGCreateQuoteBlock()+ create = AsyncMock(return_value=TEST_CART.quote)+ monkeypatch.setattr(block, "create_quote", create)++ await _run(block, design_id="dsn_1")++ assert create.await_args.args[3] == "node-exec-1"++ async def test_explicit_idempotency_key_wins(self, monkeypatch: pytest.MonkeyPatch):+ block = RMFGCreateQuoteBlock()+ create = AsyncMock(return_value=TEST_CART.quote)+ monkeypatch.setattr(block, "create_quote", create)++ await _run(block, design_id="dsn_1", idempotency_key="bracket-quote-001")++ assert create.await_args.args[3] == "bracket-quote-001"++ async def test_reports_requirements_from_items(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ from backend.blocks.rmfg._models import Requirement++ quote = TEST_CART.quote.model_copy(+ deep=True, update={"status": QuoteStatus.REQUIRES_INPUT}+ )+ quote.items[0].requirements = [+ Requirement(code="material_required", message="Pick a material")+ ]+ block = RMFGCreateQuoteBlock()+ monkeypatch.setattr(block, "create_quote", AsyncMock(return_value=quote))++ out = await _run(block, design_id="dsn_1")++ assert out["is_ready"] is False+ assert [r.code for r in out["requirements"]] == ["material_required"]+++class TestCartPayability:+ def test_ready_open_cart_with_address_and_shipping_is_payable(self):+ assert is_payable(TEST_CART) is True++ def test_missing_shipping_option_is_not_payable(self):+ cart = TEST_CART.model_copy(update={"shipping_option_id": None})+ assert is_payable(cart) is False++ def test_missing_address_is_not_payable(self):+ cart = TEST_CART.model_copy(update={"ship_to": None})+ assert is_payable(cart) is False++ def test_unready_quote_is_not_payable(self):+ quote = TEST_CART.quote.model_copy(update={"status": QuoteStatus.BLOCKED})+ assert is_payable(TEST_CART.model_copy(update={"quote": quote})) is False++ def test_checked_out_cart_is_not_payable_again(self):+ assert TEST_PAID_CART.status == CartStatus.CHECKED_OUT+ assert is_payable(TEST_PAID_CART) is False+++class TestUpdateCartBlock:+ async def test_refuses_an_empty_update(self, monkeypatch: pytest.MonkeyPatch):+ block = RMFGUpdateCartBlock()+ update = AsyncMock(return_value=TEST_CART)+ monkeypatch.setattr(block, "update_cart", update)++ with pytest.raises(ValueError, match="Nothing to update"):+ await _run(block, cart_id="crt_1")+ update.assert_not_awaited()++ async def test_address_alone_is_a_valid_update(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = RMFGUpdateCartBlock()+ monkeypatch.setattr(block, "update_cart", AsyncMock(return_value=TEST_CART))++ out = await _run(block, cart_id="crt_1", ship_to=TEST_SHIP_TO.model_dump())++ assert out["cart_id"] == TEST_CART.id+ assert out["is_payable"] is True++ async def test_unset_items_do_not_empty_the_basket(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ # The input's empty default must reach the client as "not set";+ # an empty list there is an instruction to clear the cart.+ update = AsyncMock(return_value=TEST_CART)+ monkeypatch.setattr(+ carts, "RMFGClient", lambda _: SimpleNamespace(update_cart=update)+ )++ await _run(RMFGUpdateCartBlock(), cart_id="crt_1", shipping_option_id="s")++ assert update.await_args.kwargs["items"] is None+++class TestPayCartBlock:+ def test_is_a_sensitive_action(self):+ assert RMFGPayCartBlock().is_sensitive_action is True++ async def test_uses_node_exec_id_as_idempotency_key(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ # The double-charge protection rests on this default.+ block = RMFGPayCartBlock()+ pay = AsyncMock(return_value=TEST_PAID_CART)+ monkeypatch.setattr(block, "pay_cart", pay)++ await _run(block, cart_id="crt_1")++ assert pay.await_args.args[2] == "node-exec-1"++ async def test_explicit_idempotency_key_wins(self, monkeypatch: pytest.MonkeyPatch):+ block = RMFGPayCartBlock()+ pay = AsyncMock(return_value=TEST_PAID_CART)+ monkeypatch.setattr(block, "pay_cart", pay)++ await _run(block, cart_id="crt_1", idempotency_key="pay-bracket-001")++ assert pay.await_args.args[2] == "pay-bracket-001"++ async def test_payment_method_requires_an_id(self, monkeypatch: pytest.MonkeyPatch):+ block = RMFGPayCartBlock()+ pay = AsyncMock(return_value=TEST_PAID_CART)+ monkeypatch.setattr(block, "pay_cart", pay)++ with pytest.raises(ValueError, match="payment_method_id"):+ await _run(block, cart_id="crt_1", payment_type=PaymentType.PAYMENT_METHOD)+ pay.assert_not_awaited()++ async def test_processing_payment_is_reported_not_hidden(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ # A 202 leaves the cart open with no payment object yet; the graph must+ # see "processing" so it re-checks the cart rather than paying again.+ block = RMFGPayCartBlock()+ monkeypatch.setattr(block, "pay_cart", AsyncMock(return_value=TEST_CART))++ out = await _run(block, cart_id="crt_1")++ assert out["payment_status"].value == "processing"+ assert out["checked_out"] is False+ assert "order_id" not in out+++class TestAnalyzeDesignBlock:+ async def test_step_extension_is_added_when_missing(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = RMFGAnalyzeDesignBlock()+ monkeypatch.setattr(+ block, "read_step_file", AsyncMock(return_value=("upload", b"ISO"))+ )+ analyze = AsyncMock(return_value=TEST_DESIGN)+ monkeypatch.setattr(block, "analyze", analyze)++ await _run(block, file="data:application/step;base64,SVNP")++ assert analyze.await_args.args[1] == "upload.step"++ async def test_file_name_override_and_stp_are_kept(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ block = RMFGAnalyzeDesignBlock()+ monkeypatch.setattr(+ block, "read_step_file", AsyncMock(return_value=("x.step", b"ISO"))+ )+ analyze = AsyncMock(return_value=TEST_DESIGN)+ monkeypatch.setattr(block, "analyze", analyze)++ await _run(+ block, file="data:application/step;base64,SVNP", file_name="Bracket.STP"+ )++ assert analyze.await_args.args[1] == "Bracket.STP"+++class TestGetImageBlock:+ def _client(self, monkeypatch: pytest.MonkeyPatch, content: bytes, kind: str):+ get_image = AsyncMock(return_value=(content, kind))+ monkeypatch.setattr(+ images, "RMFGClient", lambda _: SimpleNamespace(get_image=get_image)+ )++ async def test_png_bytes_become_a_png_data_uri(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ self._client(monkeypatch, PNG_SIGNATURE + b"...", "image/png; charset=binary")+ block = RMFGGetImageBlock()++ image = await block.fetch_image(+ TEST_CREDENTIALS,+ block.input_schema(+ credentials=TEST_CREDENTIALS_INPUT,+ design_id=TEST_DESIGN.id,+ part_id=TEST_PART.id,+ ),+ )++ assert image.startswith("data:image/png;base64,iVBORw0KGgo")++ @pytest.mark.parametrize(+ "content, kind",+ [+ (b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/svg+xml"),+ (b"<html><script>alert(1)</script></html>", "text/html"),+ (b"<html>oops</html>", "image/png"),+ ],+ )+ async def test_anything_but_png_bytes_is_refused(+ self, monkeypatch: pytest.MonkeyPatch, content: bytes, kind: str+ ):+ # A stored SVG or HTML page would execute in the viewer's browser.+ self._client(monkeypatch, content, kind)+ block = RMFGGetImageBlock()++ with pytest.raises(ValueError, match="instead of a PNG"):+ await block.fetch_image(+ TEST_CREDENTIALS,+ block.input_schema(+ credentials=TEST_CREDENTIALS_INPUT, design_id=TEST_DESIGN.id+ ),+ )+++class TestEventTrigger:+ async def test_malformed_data_does_not_fail_the_trigger(self):+ block = RMFGEventTriggerBlock()+ payload = {"id": "evt_1", "type": "design.ready", "data": "not-an-object"}++ out = await _run(block, payload=payload)++ assert out["event"] == "design.ready"+ assert out["resource_id"] == ""+ assert out["status_url"] == ""diff --git a/autogpt_platform/backend/backend/blocks/rmfg/carts.py b/autogpt_platform/backend/backend/blocks/rmfg/carts.pynew file mode 100644index 0000000000..9403cd9df3--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/carts.py@@ -0,0 +1,304 @@+"""Blocks that build and update an RMFG cart.++A cart re-quotes on every change and carries a website link a person can pay+from. Paying through the API lives in ``pay_cart``.+"""++from typing import Optional++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import RMFGBasketInput, build_items, credentials_field+from ._models import ManufacturingReviewWarning, Requirement+from ._models_commerce import Cart, CartTotals, ShippingOption+from ._testdata import TEST_CART, TEST_MATERIAL, TEST_SHIP_TO, TEST_SHIPPING_OPTION+from ._types import CartStatus, QuoteItemRequest, QuoteStatus, RMFGCredentials, ShipTo++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGCartOutput(BlockSchemaOutput):+ cart: Cart = SchemaField(description="The full cart, including its latest quote")+ cart_id: str = SchemaField(description="Cart ID")+ cart_url: str = SchemaField(+ description="Website checkout link; anyone holding it can pay, keep it private"+ )+ status: CartStatus = SchemaField(description="open, checked_out or expired")+ quote_status: QuoteStatus = SchemaField(+ description="Status of the cart's latest quote; only ready carts can be paid"+ )+ is_payable: bool = SchemaField(+ description="True when the cart is open, quoted ready, and has an address and shipping option"+ )+ totals: CartTotals = SchemaField(description="Subtotal, shipping, tax and total")+ amount_total_cents: int = SchemaField(+ description="What checkout will charge, in USD cents"+ )+ shipping_options: list[ShippingOption] = SchemaField(+ description="Delivery choices once ship_to is set; pass an id to Update Cart"+ )+ requirements: list[Requirement] = SchemaField(+ description="Selections or decisions still needed before ordering"+ )+ manufacturing_warnings: list[ManufacturingReviewWarning] = SchemaField(+ description="Advisories from automatic file preparation; they do not block ordering"+ )+ order_id: Optional[str] = SchemaField(+ description="Order ID; only emitted once the cart has been paid",+ default=None,+ )+ error: str = SchemaField(description="Error message if the request failed")+++def is_payable(cart: Cart) -> bool:+ return (+ cart.status == CartStatus.OPEN+ and cart.quote.status == QuoteStatus.READY+ and cart.ship_to is not None+ and bool(cart.shipping_option_id)+ )+++async def emit_cart(cart: Cart) -> BlockOutput:+ yield "cart", cart+ yield "cart_id", cart.id+ yield "cart_url", cart.cart_url+ yield "status", cart.status+ yield "quote_status", cart.quote.status+ yield "is_payable", is_payable(cart)+ yield "totals", cart.totals+ yield "amount_total_cents", cart.totals.amount_total_cents+ yield "shipping_options", cart.quote.shipping_options+ yield "requirements", cart.quote.all_requirements+ yield "manufacturing_warnings", cart.manufacturing_warnings+ if cart.order_id:+ yield "order_id", cart.order_id+++CART_TEST_OUTPUT = [+ ("cart", TEST_CART),+ ("cart_id", TEST_CART.id),+ ("cart_url", TEST_CART.cart_url),+ ("status", CartStatus.OPEN),+ ("quote_status", QuoteStatus.READY),+ ("is_payable", True),+ ("totals", TEST_CART.totals),+ ("amount_total_cents", 28849),+ ("shipping_options", [TEST_SHIPPING_OPTION]),+ ("requirements", []),+ ("manufacturing_warnings", []),+]+++class RMFGCreateCartBlock(Block):+ """Create a priced cart and a checkout link for a configured design."""++ class Input(RMFGBasketInput):+ ship_to: Optional[ShipTo] = SchemaField(+ description="Delivery address. Needed for shipping options, tax and API payment.",+ default=None,+ advanced=False,+ )+ shipping_option_id: str = SchemaField(+ description=(+ "A shipping_options[].id from a quote or cart with the same "+ "address. Can be chosen later with Update Cart."+ ),+ default="",+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description="Stable key for identical retries; defaults to the node execution ID.",+ default="",+ advanced=True,+ )++ class Output(RMFGCartOutput):+ pass++ def __init__(self):+ super().__init__(+ id="4302f685-7fab-4396-abbb-f7421f2ad511",+ description=(+ "Creates an RMFG cart with a website checkout link for one or more "+ "configured designs, priced live with shipping and tax once an "+ "address is set. A cart is not an order; the person pays on the link "+ "or Pay Cart charges the saved card after approval"+ ),+ categories=CATEGORIES,+ input_schema=RMFGCreateCartBlock.Input,+ output_schema=RMFGCreateCartBlock.Output,+ test_input={+ "design_id": TEST_CART.quote.design_id,+ "quantity": 10,+ "material_id": TEST_MATERIAL.id,+ "ship_to": TEST_SHIP_TO.model_dump(),+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=CART_TEST_OUTPUT,+ test_mock={"create_cart": lambda *args, **kwargs: TEST_CART},+ )++ @staticmethod+ async def create_cart(+ credentials: RMFGCredentials,+ items: list[QuoteItemRequest],+ ship_to: Optional[ShipTo],+ shipping_option_id: str,+ client_reference_id: str,+ idempotency_key: str,+ ) -> Cart:+ return await RMFGClient(credentials).create_cart(+ items,+ ship_to,+ shipping_option_id,+ client_reference_id,+ idempotency_key,+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ cart = await self.create_cart(+ credentials,+ build_items(input_data),+ input_data.ship_to,+ input_data.shipping_option_id,+ input_data.client_reference_id,+ input_data.idempotency_key or node_exec_id,+ )+ async for output in emit_cart(cart):+ yield output+++class RMFGGetCartBlock(Block):+ """Re-read a cart, e.g. after a person edited it on the website."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ cart_id: str = SchemaField(description="Cart ID from Create Cart")++ class Output(RMFGCartOutput):+ pass++ def __init__(self):+ super().__init__(+ id="c1104739-f8dc-4d7f-a99a-4bb418102287",+ description="Fetches an RMFG cart and its latest quote by ID",+ categories=CATEGORIES,+ input_schema=RMFGGetCartBlock.Input,+ output_schema=RMFGGetCartBlock.Output,+ test_input={"cart_id": TEST_CART.id, "credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=CART_TEST_OUTPUT,+ test_mock={"get_cart": lambda *args, **kwargs: TEST_CART},+ )++ @staticmethod+ async def get_cart(credentials: RMFGCredentials, cart_id: str) -> Cart:+ return await RMFGClient(credentials).get_cart(cart_id)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ cart = await self.get_cart(credentials, input_data.cart_id)+ async for output in emit_cart(cart):+ yield output+++class RMFGUpdateCartBlock(Block):+ """Set the address or shipping option on an open cart; it re-quotes."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ cart_id: str = SchemaField(description="Cart ID from Create Cart")+ ship_to: Optional[ShipTo] = SchemaField(+ description="New delivery address; leave empty to keep the current one.",+ default=None,+ advanced=False,+ )+ shipping_option_id: str = SchemaField(+ description="A shipping_options[].id to select; empty keeps the current one.",+ default="",+ advanced=False,+ )+ items: list[QuoteItemRequest] = SchemaField(+ description="Replacement basket; empty keeps the current items.",+ default_factory=list,+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description="Stable key for identical retries; defaults to the node execution ID.",+ default="",+ advanced=True,+ )++ class Output(RMFGCartOutput):+ pass++ def __init__(self):+ super().__init__(+ id="7ecccdcf-9879-433e-8325-7ccc6b3b4870",+ description="Updates an open RMFG cart's address, shipping option or items",+ categories=CATEGORIES,+ input_schema=RMFGUpdateCartBlock.Input,+ output_schema=RMFGUpdateCartBlock.Output,+ test_input={+ "cart_id": TEST_CART.id,+ "shipping_option_id": TEST_SHIPPING_OPTION.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=CART_TEST_OUTPUT,+ test_mock={"update_cart": lambda *args, **kwargs: TEST_CART},+ )++ @staticmethod+ async def update_cart(+ credentials: RMFGCredentials, input_data: Input, idempotency_key: str+ ) -> Cart:+ return await RMFGClient(credentials).update_cart(+ input_data.cart_id,+ # An empty list here means "not set"; the client treats [] as a+ # request to empty the basket.+ items=input_data.items or None,+ ship_to=input_data.ship_to,+ shipping_option_id=input_data.shipping_option_id,+ idempotency_key=idempotency_key,+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ if not (+ input_data.ship_to or input_data.shipping_option_id or input_data.items+ ):+ raise ValueError(+ "Nothing to update: set ship_to, shipping_option_id or items."+ )+ cart = await self.update_cart(+ credentials, input_data, input_data.idempotency_key or node_exec_id+ )+ async for output in emit_cart(cart):+ yield outputdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/catalog.py b/autogpt_platform/backend/backend/blocks/rmfg/catalog.pynew file mode 100644index 0000000000..e1b4f3b810--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/catalog.py@@ -0,0 +1,276 @@+"""Blocks that read the RMFG catalogs: stock, finishes, colors and hardware."""++from typing import Optional++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models import Finish, HardwareOption, Material, PowderCoatColor, TubeProfile+from ._testdata import (+ TEST_FINISH,+ TEST_HARDWARE_OPTION,+ TEST_MATERIAL,+ TEST_POWDER_COAT_COLOR,+ TEST_TUBE_PROFILE,+)+from ._types import HardwareKind, Process, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGListMaterialsBlock(Block):+ """List sheet-metal stock. Use a returned ``id`` as ``material_id``."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()++ class Output(BlockSchemaOutput):+ materials: list[Material] = SchemaField(+ description="Every sheet-metal material, across all pages"+ )+ material: Material = SchemaField(description="One material at a time")+ material_ids: list[str] = SchemaField(description="IDs in the same order")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="bd3afa7d-607e-4b0e-bd24-201c54fa0ad4",+ description=(+ "Lists the sheet-metal stock RMFG can cut and bend, with thickness in "+ "mm and inches. Choose the entry closest to a part's detected "+ "thickness and pass its id as material_id to quote"+ ),+ categories=CATEGORIES,+ input_schema=RMFGListMaterialsBlock.Input,+ output_schema=RMFGListMaterialsBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("materials", [TEST_MATERIAL]),+ ("material", TEST_MATERIAL),+ ("material_ids", [TEST_MATERIAL.id]),+ ],+ test_mock={"list_materials": lambda *args, **kwargs: [TEST_MATERIAL]},+ )++ @staticmethod+ async def list_materials(credentials: RMFGCredentials) -> list[Material]:+ return await RMFGClient(credentials).list_materials()++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ materials = await self.list_materials(credentials)+ yield "materials", materials+ for material in materials:+ yield "material", material+ yield "material_ids", [material.id for material in materials]+++class RMFGListTubeProfilesBlock(Block):+ """List tube-laser stock. Use a returned ``id`` as ``tube_profile_id``."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()++ class Output(BlockSchemaOutput):+ tube_profiles: list[TubeProfile] = SchemaField(+ description="Every tube profile, across all pages"+ )+ tube_profile: TubeProfile = SchemaField(description="One profile at a time")+ tube_profile_ids: list[str] = SchemaField(description="IDs in the same order")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="48356027-25ee-4711-ae2e-5204e5a5f717",+ description="Lists the tube stock profiles RMFG can laser-cut",+ categories=CATEGORIES,+ input_schema=RMFGListTubeProfilesBlock.Input,+ output_schema=RMFGListTubeProfilesBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("tube_profiles", [TEST_TUBE_PROFILE]),+ ("tube_profile", TEST_TUBE_PROFILE),+ ("tube_profile_ids", [TEST_TUBE_PROFILE.id]),+ ],+ test_mock={+ "list_tube_profiles": lambda *args, **kwargs: [TEST_TUBE_PROFILE]+ },+ )++ @staticmethod+ async def list_tube_profiles(credentials: RMFGCredentials) -> list[TubeProfile]:+ return await RMFGClient(credentials).list_tube_profiles()++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ profiles = await self.list_tube_profiles(credentials)+ yield "tube_profiles", profiles+ for profile in profiles:+ yield "tube_profile", profile+ yield "tube_profile_ids", [profile.id for profile in profiles]+++class RMFGListFinishesBlock(Block):+ """List mechanical finishes. Use a returned ``id`` as ``finish_id``."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ process: Optional[Process] = SchemaField(+ description="Only finishes that apply to this process; empty for all.",+ default=None,+ advanced=False,+ )++ class Output(BlockSchemaOutput):+ finishes: list[Finish] = SchemaField(description="Matching finishes")+ finish: Finish = SchemaField(description="One finish at a time")+ finish_ids: list[str] = SchemaField(description="IDs in the same order")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="87dbab6f-26ac-4371-9aef-51ad30bc0584",+ description="Lists the finishes RMFG can apply to sheet or tube parts",+ categories=CATEGORIES,+ input_schema=RMFGListFinishesBlock.Input,+ output_schema=RMFGListFinishesBlock.Output,+ test_input={+ "process": Process.SHEET_METAL.value,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("finishes", [TEST_FINISH]),+ ("finish", TEST_FINISH),+ ("finish_ids", [TEST_FINISH.id]),+ ],+ test_mock={"list_finishes": lambda *args, **kwargs: [TEST_FINISH]},+ )++ @staticmethod+ async def list_finishes(+ credentials: RMFGCredentials, process: Optional[Process]+ ) -> list[Finish]:+ return await RMFGClient(credentials).list_finishes(process)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ finishes = await self.list_finishes(credentials, input_data.process)+ yield "finishes", finishes+ for finish in finishes:+ yield "finish", finish+ yield "finish_ids", [finish.id for finish in finishes]+++class RMFGListPowderCoatColorsBlock(Block):+ """List powder-coat colors. Use a returned ``id`` as ``powder_coat_color_id``."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()++ class Output(BlockSchemaOutput):+ colors: list[PowderCoatColor] = SchemaField(description="Every color")+ color: PowderCoatColor = SchemaField(description="One color at a time")+ color_ids: list[str] = SchemaField(description="IDs in the same order")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="e0eea253-ccdc-4ee8-bb16-68e444dad6fc",+ description="Lists the powder-coat colors RMFG offers",+ categories=CATEGORIES,+ input_schema=RMFGListPowderCoatColorsBlock.Input,+ output_schema=RMFGListPowderCoatColorsBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("colors", [TEST_POWDER_COAT_COLOR]),+ ("color", TEST_POWDER_COAT_COLOR),+ ("color_ids", [TEST_POWDER_COAT_COLOR.id]),+ ],+ test_mock={"list_colors": lambda *args, **kwargs: [TEST_POWDER_COAT_COLOR]},+ )++ @staticmethod+ async def list_colors(credentials: RMFGCredentials) -> list[PowderCoatColor]:+ return await RMFGClient(credentials).list_powder_coat_colors()++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ colors = await self.list_colors(credentials)+ yield "colors", colors+ for color in colors:+ yield "color", color+ yield "color_ids", [color.id for color in colors]+++class RMFGListHardwareBlock(Block):+ """List taps, studs, nuts or standoffs for hole operations."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ kind: HardwareKind = SchemaField(+ description=(+ "Which catalog to read. Reference an entry's id as tap_id, "+ "stud_id, nut_id or standoff_id in a part configuration."+ ),+ default=HardwareKind.TAPS,+ advanced=False,+ )++ class Output(BlockSchemaOutput):+ options: list[HardwareOption] = SchemaField(description="Catalog entries")+ option: HardwareOption = SchemaField(description="One entry at a time")+ option_ids: list[str] = SchemaField(description="IDs in the same order")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="6496ec49-0a6d-4b74-9d2f-573bb09e735d",+ description="Lists the taps, studs, nuts or standoffs RMFG can install",+ categories=CATEGORIES,+ input_schema=RMFGListHardwareBlock.Input,+ output_schema=RMFGListHardwareBlock.Output,+ test_input={+ "kind": HardwareKind.TAPS.value,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("options", [TEST_HARDWARE_OPTION]),+ ("option", TEST_HARDWARE_OPTION),+ ("option_ids", [TEST_HARDWARE_OPTION.id]),+ ],+ test_mock={"list_hardware": lambda *args, **kwargs: [TEST_HARDWARE_OPTION]},+ )++ @staticmethod+ async def list_hardware(+ credentials: RMFGCredentials, kind: HardwareKind+ ) -> list[HardwareOption]:+ return await RMFGClient(credentials).list_hardware(kind)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ options = await self.list_hardware(credentials, input_data.kind)+ yield "options", options+ for option in options:+ yield "option", option+ yield "option_ids", [option.id for option in options]diff --git a/autogpt_platform/backend/backend/blocks/rmfg/designs.py b/autogpt_platform/backend/backend/blocks/rmfg/designs.pynew file mode 100644index 0000000000..9cb7f62ccf--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/designs.py@@ -0,0 +1,267 @@+"""Blocks that upload a STEP file for analysis and read the resulting design."""++from pathlib import Path+from typing import Optional++from backend.data.execution import ExecutionContext+from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ MediaFileType,+ SchemaField,+ store_media_file,+)+from backend.util.file import get_exec_file_path++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models import Design, Part+from ._testdata import TEST_DESIGN, TEST_PART, TEST_STEP_DATA_URI+from ._types import DesignStatus, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGDesignOutput(BlockSchemaOutput):+ design: Design = SchemaField(description="The design resource")+ design_id: str = SchemaField(description="ID to pass to DFM, quote and cart")+ status: DesignStatus = SchemaField(+ description="queued, processing, ready or failed"+ )+ parts: list[Part] = SchemaField(+ description="Every unique part with its instance count, once ready"+ )+ part: Part = SchemaField(description="One part at a time")+ part_ids: list[str] = SchemaField(description="Part IDs in the same order")+ review_url: Optional[str] = SchemaField(+ description=(+ "Website page where a person can inspect and configure the design; "+ "emitted once RMFG has assigned one"+ ),+ default=None,+ )+ image_url: Optional[str] = SchemaField(+ description="Rendered picture of the whole design; emitted once analysis is ready",+ default=None,+ )+ error: str = SchemaField(description="Error message if the request failed")+++async def emit_design(design: Design) -> BlockOutput:+ yield "design", design+ yield "design_id", design.id+ yield "status", design.status+ yield "parts", design.parts+ for part in design.parts:+ yield "part", part+ yield "part_ids", [part.id for part in design.parts]+ if design.review_url:+ yield "review_url", design.review_url+ if design.image_url:+ yield "image_url", design.image_url+++class RMFGAnalyzeDesignBlock(Block):+ """Upload a STEP file; RMFG splits it into parts and detects bends and holes."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ file: MediaFileType = SchemaField(+ description="STEP or STP file to analyze (URL, data URI or workspace file)"+ )+ file_name: str = SchemaField(+ description="Name to record for the upload; defaults to the file's own.",+ default="",+ advanced=True,+ )+ wait_for_ready: bool = SchemaField(+ description="Poll until analysis finishes instead of returning at once.",+ default=True,+ advanced=True,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for analysis when wait_for_ready is on.",+ default=300,+ ge=5,+ le=1500,+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description=(+ "Stable key so a retried upload returns the same design. "+ "Defaults to this node execution's ID."+ ),+ default="",+ advanced=True,+ )++ class Output(RMFGDesignOutput):+ pass++ def __init__(self):+ super().__init__(+ id="bcbee3ee-4ff4-485b-afa8-a57856ab12b6",+ description=(+ "Uploads a STEP file to RMFG, a manufacturer that makes and ships real "+ "sheet-metal and tube-laser parts, and returns its analyzed parts: the "+ "first step before a live quote, cart or order. Works on a URL, an "+ "attached workspace file or a data URI"+ ),+ categories=CATEGORIES,+ input_schema=RMFGAnalyzeDesignBlock.Input,+ output_schema=RMFGAnalyzeDesignBlock.Output,+ test_input={+ "file": TEST_STEP_DATA_URI,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("design", TEST_DESIGN),+ ("design_id", TEST_DESIGN.id),+ ("status", DesignStatus.READY),+ ("parts", [TEST_PART]),+ ("part", TEST_PART),+ ("part_ids", [TEST_PART.id]),+ ("review_url", TEST_DESIGN.review_url),+ ("image_url", TEST_DESIGN.image_url),+ ],+ test_mock={+ "read_step_file": lambda *args, **kwargs: ("bracket.step", b"ISO"),+ "analyze": lambda *args, **kwargs: TEST_DESIGN,+ },+ )++ @staticmethod+ async def read_step_file(+ file: MediaFileType, execution_context: ExecutionContext+ ) -> tuple[str, bytes]:+ """Materialise the input file locally and return (name, bytes)."""+ local_path = await store_media_file(+ file=file,+ execution_context=execution_context,+ return_format="for_local_processing",+ )+ if not execution_context.graph_exec_id:+ raise ValueError("execution_context.graph_exec_id is required")+ path = Path(get_exec_file_path(execution_context.graph_exec_id, local_path))+ return path.name, path.read_bytes()++ @staticmethod+ async def analyze(+ credentials: RMFGCredentials,+ file_name: str,+ content: bytes,+ idempotency_key: str,+ wait_for_ready: bool,+ timeout_seconds: int,+ ) -> Design:+ client = RMFGClient(credentials)+ design = await client.analyze(file_name, content, idempotency_key)+ if not wait_for_ready:+ return design+ return await client.wait_for_design(design, timeout_seconds)++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ execution_context: ExecutionContext,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ file_name, content = await self.read_step_file(+ input_data.file, execution_context+ )+ if input_data.file_name:+ file_name = input_data.file_name+ if not file_name.lower().endswith((".step", ".stp")):+ file_name = f"{file_name}.step"+ design = await self.analyze(+ credentials,+ file_name,+ content,+ input_data.idempotency_key or node_exec_id,+ input_data.wait_for_ready,+ input_data.timeout_seconds,+ )+ async for output in emit_design(design):+ yield output+++class RMFGGetDesignBlock(Block):+ """Read a design by ID, optionally waiting for analysis to finish."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ design_id: str = SchemaField(description="Design ID from Analyze Design")+ wait_for_ready: bool = SchemaField(+ description="Poll until analysis finishes instead of returning at once.",+ default=False,+ advanced=True,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for analysis when wait_for_ready is on.",+ default=300,+ ge=5,+ le=1500,+ advanced=True,+ )++ class Output(RMFGDesignOutput):+ pass++ def __init__(self):+ super().__init__(+ id="8918fea0-ca1b-4df0-bcec-dfc66c66536e",+ description="Fetches an RMFG design and its analyzed parts by ID",+ categories=CATEGORIES,+ input_schema=RMFGGetDesignBlock.Input,+ output_schema=RMFGGetDesignBlock.Output,+ test_input={+ "design_id": TEST_DESIGN.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("design", TEST_DESIGN),+ ("design_id", TEST_DESIGN.id),+ ("status", DesignStatus.READY),+ ("parts", [TEST_PART]),+ ("part", TEST_PART),+ ("part_ids", [TEST_PART.id]),+ ("review_url", TEST_DESIGN.review_url),+ ("image_url", TEST_DESIGN.image_url),+ ],+ test_mock={"get_design": lambda *args, **kwargs: TEST_DESIGN},+ )++ @staticmethod+ async def get_design(+ credentials: RMFGCredentials,+ design_id: str,+ wait_for_ready: bool,+ timeout_seconds: int,+ ) -> Design:+ client = RMFGClient(credentials)+ design = await client.get_design(design_id)+ if not wait_for_ready:+ return design+ return await client.wait_for_design(design, timeout_seconds)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ design = await self.get_design(+ credentials,+ input_data.design_id,+ input_data.wait_for_ready,+ input_data.timeout_seconds,+ )+ async for output in emit_design(design):+ yield outputdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/dfm.py b/autogpt_platform/backend/backend/blocks/rmfg/dfm.pynew file mode 100644index 0000000000..a6636247b4--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/dfm.py@@ -0,0 +1,217 @@+"""Blocks that evaluate manufacturability (DFM) for a configured design."""++from typing import Optional++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models import DFMIssue, DFMReport, PartDFM, Requirement+from ._testdata import TEST_CONFIGURATION, TEST_DFM_ISSUE, TEST_DFM_REPORT+from ._types import ManufacturabilityStatus, ManufacturingConfiguration, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGDFMOutput(BlockSchemaOutput):+ report: DFMReport = SchemaField(description="The full DFM report")+ dfm_id: str = SchemaField(description="Report ID, for review links and re-reads")+ status: ManufacturabilityStatus = SchemaField(+ description="ready, requires_input (a selection is missing) or blocked"+ )+ is_ready: bool = SchemaField(description="True when nothing prevents ordering")+ configuration: ManufacturingConfiguration = SchemaField(+ description="The configuration that was evaluated; feed it to a quote"+ )+ issues: list[DFMIssue] = SchemaField(+ description="Every finding across all parts and the assembly"+ )+ issue: DFMIssue = SchemaField(description="One finding at a time")+ requirements: list[Requirement] = SchemaField(+ description="Selections still needed before the design can be quoted"+ )+ parts: list[PartDFM] = SchemaField(+ description="Per-part status, findings, capabilities and images"+ )+ review_url: Optional[str] = SchemaField(+ description=(+ "Website page showing this exact configuration for a person to "+ "adjust; emitted when RMFG provides one"+ ),+ default=None,+ )+ error: str = SchemaField(description="Error message if the request failed")+++async def emit_report(report: DFMReport) -> BlockOutput:+ yield "report", report+ yield "dfm_id", report.id+ yield "status", report.status+ yield "is_ready", report.status == ManufacturabilityStatus.READY+ yield "configuration", report.configuration+ issues = report.issues+ yield "issues", issues+ for issue in issues:+ yield "issue", issue+ yield "requirements", report.requirements+ yield "parts", report.parts+ if report.review_url:+ yield "review_url", report.review_url+++class RMFGCreateDFMReportBlock(Block):+ """Check whether a configuration can be made, and learn what each part allows."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ design_id: str = SchemaField(description="Design ID from Analyze Design")+ material_id: str = SchemaField(+ description=(+ "Sheet-metal stock for every sheet part, from List Materials. "+ "Leave empty for tube-only designs or when configuration sets it."+ ),+ default="",+ )+ configuration: ManufacturingConfiguration = SchemaField(+ description=(+ "Per-part material, tube profile, finish, powder coat, hole "+ "operations, welds and accepted risks. A non-empty material_id "+ "above overrides defaults.material_id."+ ),+ default_factory=ManufacturingConfiguration,+ advanced=True,+ )+ generate_production_files: bool = SchemaField(+ description="Also prepare laser DXF and corrected STEP files.",+ default=True,+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description="Stable key for identical retries; defaults to the node execution ID.",+ default="",+ advanced=True,+ )++ class Output(RMFGDFMOutput):+ pass++ def __init__(self):+ super().__init__(+ id="0d755311-d01c-4cd9-a1cc-196a78590a18",+ description=(+ "Runs an RMFG manufacturability (DFM) check on a configured design. A "+ "blocked finding such as a hole close to a bend can be accepted with "+ "accepted_risks once the customer agrees; requires_input means a "+ "material or profile is still missing"+ ),+ categories=CATEGORIES,+ input_schema=RMFGCreateDFMReportBlock.Input,+ output_schema=RMFGCreateDFMReportBlock.Output,+ test_input={+ "design_id": TEST_DFM_REPORT.design_id,+ "material_id": "mat_5052_0125",+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("report", TEST_DFM_REPORT),+ ("dfm_id", TEST_DFM_REPORT.id),+ ("status", ManufacturabilityStatus.READY),+ ("is_ready", True),+ ("configuration", TEST_CONFIGURATION),+ ("issues", [TEST_DFM_ISSUE]),+ ("issue", TEST_DFM_ISSUE),+ ("requirements", []),+ ("parts", TEST_DFM_REPORT.parts),+ ("review_url", TEST_DFM_REPORT.review_url),+ ],+ test_mock={"create_report": lambda *args, **kwargs: TEST_DFM_REPORT},+ )++ @staticmethod+ async def create_report(+ credentials: RMFGCredentials,+ design_id: str,+ configuration: ManufacturingConfiguration,+ generate_production_files: bool,+ idempotency_key: str,+ ) -> DFMReport:+ return await RMFGClient(credentials).create_dfm_report(+ design_id, configuration, generate_production_files, idempotency_key+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ report = await self.create_report(+ credentials,+ input_data.design_id,+ input_data.configuration.with_material(input_data.material_id),+ input_data.generate_production_files,+ input_data.idempotency_key or node_exec_id,+ )+ async for output in emit_report(report):+ yield output+++class RMFGGetDFMReportBlock(Block):+ """Re-read a DFM report, e.g. to check whether production files are ready."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ dfm_id: str = SchemaField(description="Report ID from Create DFM Report")++ class Output(RMFGDFMOutput):+ pass++ def __init__(self):+ super().__init__(+ id="c36c49da-605f-4f1a-9da0-6f0a2cf9abfd",+ description="Fetches an RMFG DFM report by ID",+ categories=CATEGORIES,+ input_schema=RMFGGetDFMReportBlock.Input,+ output_schema=RMFGGetDFMReportBlock.Output,+ test_input={+ "dfm_id": TEST_DFM_REPORT.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("report", TEST_DFM_REPORT),+ ("dfm_id", TEST_DFM_REPORT.id),+ ("status", ManufacturabilityStatus.READY),+ ("is_ready", True),+ ("configuration", TEST_CONFIGURATION),+ ("issues", [TEST_DFM_ISSUE]),+ ("issue", TEST_DFM_ISSUE),+ ("requirements", []),+ ("parts", TEST_DFM_REPORT.parts),+ ("review_url", TEST_DFM_REPORT.review_url),+ ],+ test_mock={"get_report": lambda *args, **kwargs: TEST_DFM_REPORT},+ )++ @staticmethod+ async def get_report(credentials: RMFGCredentials, dfm_id: str) -> DFMReport:+ return await RMFGClient(credentials).get_dfm_report(dfm_id)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ report = await self.get_report(credentials, input_data.dfm_id)+ async for output in emit_report(report):+ yield outputdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/images.py b/autogpt_platform/backend/backend/blocks/rmfg/images.pynew file mode 100644index 0000000000..3f2e702fed--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/images.py@@ -0,0 +1,136 @@+"""Block that fetches RMFG's rendered pictures of a design or part.++The API's image links need the account's credentials, so a bare URL is of no+use to a downstream block or a person; this block downloads the picture and+hands it on as a platform media file.+"""++import base64++from backend.data.execution import ExecutionContext+from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ MediaFileType,+ SchemaField,+ store_media_file,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._testdata import TEST_DESIGN, TEST_PART, TEST_PNG_DATA_URI+from ._types import ImageView, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.MULTIMEDIA}++PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+++class RMFGGetImageBlock(Block):+ """Render a design, one of its parts, or a DFM report's configured part."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ design_id: str = SchemaField(description="Design ID from Analyze Design")+ part_id: str = SchemaField(+ description=(+ "Draw only this part, with every hole and bend labelled by ID. "+ "Empty draws the whole design."+ ),+ default="",+ )+ dfm_id: str = SchemaField(+ description=(+ "With part_id, draw the part as configured in this DFM report, "+ "taps, studs, nuts and countersinks marked."+ ),+ default="",+ advanced=True,+ )+ view: ImageView = SchemaField(+ description="Camera angle; flat shows a sheet part's flat pattern.",+ default=ImageView.ISO,+ advanced=False,+ )+ width: int = SchemaField(+ description="Image width in pixels; 0 uses RMFG's default.",+ default=0,+ ge=0,+ le=4096,+ advanced=True,+ )++ class Output(BlockSchemaOutput):+ image: MediaFileType = SchemaField(description="The rendered PNG")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="1c1f8d0e-3e57-4c4a-9b7a-2f6a0f4d9e21",+ description="Downloads RMFG's rendered picture of a design or part, with holes and bends labelled",+ categories=CATEGORIES,+ input_schema=RMFGGetImageBlock.Input,+ output_schema=RMFGGetImageBlock.Output,+ test_input={+ "design_id": TEST_DESIGN.id,+ "part_id": TEST_PART.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("image", lambda value: value.startswith(("workspace://", "data:")))+ ],+ test_mock={+ "fetch_image": lambda *args, **kwargs: TEST_PNG_DATA_URI,+ "save_image": lambda *args, **kwargs: TEST_PNG_DATA_URI,+ },+ )++ @staticmethod+ async def fetch_image(+ credentials: RMFGCredentials, input_data: Input+ ) -> MediaFileType:+ """Download the picture and return it as a PNG data URI."""+ content, content_type = await RMFGClient(credentials).get_image(+ input_data.design_id,+ input_data.part_id,+ input_data.dfm_id,+ input_data.view,+ input_data.width,+ )+ # The block always asks for PNG. Anything else, such as the SVG the+ # API can also render or an HTML error page, must not be stored as a+ # media file, so the bytes are checked rather than the header trusted.+ if not content.startswith(PNG_SIGNATURE):+ raise ValueError(+ f"RMFG returned {content_type or 'an unknown type'} instead of a PNG"+ )+ return MediaFileType(+ f"data:image/png;base64,{base64.b64encode(content).decode('ascii')}"+ )++ @staticmethod+ async def save_image(+ image: MediaFileType, execution_context: ExecutionContext+ ) -> MediaFileType:+ return await store_media_file(+ file=image,+ execution_context=execution_context,+ return_format="for_block_output",+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ execution_context: ExecutionContext,+ **kwargs,+ ) -> BlockOutput:+ image = await self.fetch_image(credentials, input_data)+ yield "image", await self.save_image(image, execution_context)diff --git a/autogpt_platform/backend/backend/blocks/rmfg/orders.py b/autogpt_platform/backend/backend/blocks/rmfg/orders.pynew file mode 100644index 0000000000..6a3f724b8b--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/orders.py@@ -0,0 +1,161 @@+"""Blocks that track paid RMFG orders."""++from typing import Optional++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models_commerce import Order, OrderTracking+from ._testdata import TEST_ORDER+from ._types import OrderStatus, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGGetOrderBlock(Block):+ """Read an order's status and tracking."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ order_id: str = SchemaField(+ description="Order ID from Pay Cart or an order.status_changed event"+ )++ class Output(BlockSchemaOutput):+ order: Order = SchemaField(description="The full order")+ order_id: str = SchemaField(description="Order ID")+ status: OrderStatus = SchemaField(+ description="received, in_production, ready_for_pickup, shipped, delivered, cancelled or refunded"+ )+ tracking: Optional[OrderTracking] = SchemaField(+ description="Carrier, number and link once shipped"+ )+ tracking_url: Optional[str] = SchemaField(+ default=None, description="Carrier tracking link, once shipped"+ )+ tracking_number: Optional[str] = SchemaField(+ description="Carrier tracking number, once shipped", default=None+ )+ estimated_ship_date: Optional[str] = SchemaField(+ description="Planned ship date, when known", default=None+ )+ amount_total_cents: int = SchemaField(description="Amount charged, USD cents")+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="281a1730-e414-4773-8a20-7c3472cc267d",+ description="Fetches an RMFG order's status and shipment tracking",+ categories=CATEGORIES,+ input_schema=RMFGGetOrderBlock.Input,+ output_schema=RMFGGetOrderBlock.Output,+ test_input={+ "order_id": TEST_ORDER.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("order", TEST_ORDER),+ ("order_id", TEST_ORDER.id),+ ("status", OrderStatus.SHIPPED),+ ("tracking", TEST_ORDER.tracking),+ (+ "tracking_url",+ "https://www.ups.com/track?tracknum=1Z999AA10123456784",+ ),+ ("tracking_number", "1Z999AA10123456784"),+ ("estimated_ship_date", "2026-09-08"),+ ("amount_total_cents", 28849),+ ],+ test_mock={"get_order": lambda *args, **kwargs: TEST_ORDER},+ )++ @staticmethod+ async def get_order(credentials: RMFGCredentials, order_id: str) -> Order:+ return await RMFGClient(credentials).get_order(order_id)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ order = await self.get_order(credentials, input_data.order_id)+ yield "order", order+ yield "order_id", order.id+ yield "status", order.status+ yield "tracking", order.tracking+ if order.tracking and order.tracking.url:+ yield "tracking_url", order.tracking.url+ if order.tracking and order.tracking.number:+ yield "tracking_number", order.tracking.number+ if order.estimated_ship_date:+ yield "estimated_ship_date", order.estimated_ship_date+ yield "amount_total_cents", order.amount_total_cents or 0+++class RMFGListOrdersBlock(Block):+ """Page through the account's orders, newest first."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ limit: int = SchemaField(+ description="Orders per page.", default=20, ge=1, le=100+ )+ cursor: str = SchemaField(+ description="next_cursor from a previous page; empty for the first page.",+ default="",+ advanced=True,+ )++ class Output(BlockSchemaOutput):+ orders: list[Order] = SchemaField(description="This page of orders")+ order: Order = SchemaField(description="One order at a time")+ order_ids: list[str] = SchemaField(description="IDs in the same order")+ next_cursor: str = SchemaField(+ description="Pass back as cursor to fetch the next page; empty on the last page"+ )+ error: str = SchemaField(description="Error message if the request failed")++ def __init__(self):+ super().__init__(+ id="4dd0f5c1-aaa6-4c20-b942-613aea6528c9",+ description="Lists the RMFG account's manufacturing orders",+ categories=CATEGORIES,+ input_schema=RMFGListOrdersBlock.Input,+ output_schema=RMFGListOrdersBlock.Output,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("orders", [TEST_ORDER]),+ ("order", TEST_ORDER),+ ("order_ids", [TEST_ORDER.id]),+ ("next_cursor", ""),+ ],+ test_mock={"list_orders": lambda *args, **kwargs: ([TEST_ORDER], None)},+ )++ @staticmethod+ async def list_orders(+ credentials: RMFGCredentials, limit: int, cursor: str+ ) -> tuple[list[Order], Optional[str]]:+ return await RMFGClient(credentials).list_orders(limit, cursor)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ orders, next_cursor = await self.list_orders(+ credentials, input_data.limit, input_data.cursor+ )+ yield "orders", orders+ for order in orders:+ yield "order", order+ yield "order_ids", [order.id for order in orders]+ yield "next_cursor", next_cursor or ""diff --git a/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.py b/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.pynew file mode 100644index 0000000000..11a7ff743c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.py@@ -0,0 +1,135 @@+"""Block that pays an RMFG cart through the API.++Paying charges the account's saved card and places a real production order,+so this is a sensitive action that the platform asks a person to approve.+"""++from backend.sdk import (+ Block,+ BlockOutput,+ BlockSchemaInput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models_commerce import Cart+from ._testdata import TEST_CART, TEST_PAID_CART, TEST_SHIPPING_OPTION+from ._types import CartStatus, PaymentStatus, PaymentType, QuoteStatus, RMFGCredentials+from .carts import CATEGORIES, RMFGCartOutput, emit_cart+++class RMFGPayCartBlock(Block):+ """Charge the account's saved card for a ready cart and place the order."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field({"payments"})+ cart_id: str = SchemaField(+ description=(+ "Open cart whose quote is ready and which has a ship_to and "+ "shipping option. Its totals.amount_total_cents will be charged."+ )+ )+ payment_type: PaymentType = SchemaField(+ description=(+ "card_on_file charges the card saved on the RMFG account page; "+ "payment_method charges a Stripe PaymentMethod you manage."+ ),+ default=PaymentType.CARD_ON_FILE,+ advanced=True,+ )+ payment_method_id: str = SchemaField(+ description="Stripe PaymentMethod id (pm_...) when payment_type is payment_method.",+ default="",+ advanced=True,+ )+ customer_email: str = SchemaField(+ description="Receipt and order emails; defaults to the account email.",+ default="",+ advanced=True,+ )+ customer_phone: str = SchemaField(+ description="Contact number for the order.", default="", advanced=True+ )+ idempotency_key: str = SchemaField(+ description=(+ "Stable key so a retry never charges twice; defaults to the "+ "node execution ID. Use a new key only for a different purchase."+ ),+ default="",+ advanced=True,+ )++ class Output(RMFGCartOutput):+ payment_status: PaymentStatus = SchemaField(+ description="paid, processing (check the cart again later), failed or refunded"+ )+ checked_out: bool = SchemaField(description="True once the order exists")++ def __init__(self):+ super().__init__(+ id="4a72f115-17a1-4843-899f-fdbeb480903e",+ description="Pays an RMFG cart with the saved card and places a real production order",+ categories=CATEGORIES,+ input_schema=RMFGPayCartBlock.Input,+ output_schema=RMFGPayCartBlock.Output,+ is_sensitive_action=True,+ test_input={"cart_id": TEST_CART.id, "credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("cart", TEST_PAID_CART),+ ("cart_id", TEST_PAID_CART.id),+ ("cart_url", TEST_PAID_CART.cart_url),+ ("status", CartStatus.CHECKED_OUT),+ ("quote_status", QuoteStatus.READY),+ ("is_payable", False),+ ("totals", TEST_PAID_CART.totals),+ ("amount_total_cents", 28849),+ ("shipping_options", [TEST_SHIPPING_OPTION]),+ ("requirements", []),+ ("manufacturing_warnings", []),+ ("order_id", "ord_001"),+ ("payment_status", PaymentStatus.PAID),+ ("checked_out", True),+ ],+ test_mock={"pay_cart": lambda *args, **kwargs: TEST_PAID_CART},+ )++ @staticmethod+ async def pay_cart(+ credentials: RMFGCredentials, input_data: Input, idempotency_key: str+ ) -> Cart:+ return await RMFGClient(credentials).pay_cart(+ input_data.cart_id,+ payment_type=input_data.payment_type,+ payment_method_id=input_data.payment_method_id,+ customer_email=input_data.customer_email,+ customer_phone=input_data.customer_phone,+ idempotency_key=idempotency_key,+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ if (+ input_data.payment_type == PaymentType.PAYMENT_METHOD+ and not input_data.payment_method_id+ ):+ raise ValueError("payment_method_id is required for payment_method")+ cart = await self.pay_cart(+ credentials, input_data, input_data.idempotency_key or node_exec_id+ )+ async for output in emit_cart(cart):+ yield output+ payment_status = (+ cart.payment.status if cart.payment else PaymentStatus.PROCESSING+ )+ yield "payment_status", payment_status+ yield "checked_out", cart.status == CartStatus.CHECKED_OUTdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/quotes.py b/autogpt_platform/backend/backend/blocks/rmfg/quotes.pynew file mode 100644index 0000000000..a5d0a4c91e--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/quotes.py@@ -0,0 +1,253 @@+"""Blocks that price a configured design."""++from typing import Optional++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import RMFGBasketInput, build_items, credentials_field+from ._models import DFMIssue, Requirement+from ._models_commerce import QuantityOption, Quote, QuotedDesign, ShippingOption+from ._testdata import TEST_DFM_ISSUE, TEST_MATERIAL, TEST_QUOTE, TEST_SHIPPING_OPTION+from ._types import QuoteItemRequest, QuoteStatus, RMFGCredentials, ShipTo++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGQuoteOutput(BlockSchemaOutput):+ quote: Quote = SchemaField(description="The full quote")+ quote_id: str = SchemaField(description="Quote ID")+ status: QuoteStatus = SchemaField(+ description="processing, requires_input, ready, blocked, expired or failed"+ )+ is_ready: bool = SchemaField(description="True when the quote can be ordered")+ amount_total_cents: int = SchemaField(+ description="Total in USD cents (shipping and tax excluded until a cart)"+ )+ amount_subtotal_cents: int = SchemaField(description="Sum of items in USD cents")+ unit_amount_cents: int = SchemaField(+ description="Price per completed unit of the first design, in USD cents"+ )+ items: list[QuotedDesign] = SchemaField(+ description="Per-design pricing, line items and DFM findings"+ )+ quantity_options: list[QuantityOption] = SchemaField(+ description="Prices at the other quantities requested, for the first design"+ )+ shipping_options: list[ShippingOption] = SchemaField(+ description="Delivery choices when ship_to was given; pick an id for the cart"+ )+ requirements: list[Requirement] = SchemaField(+ description="Selections or decisions still needed before ordering"+ )+ dfm_issues: list[DFMIssue] = SchemaField(+ description="Manufacturability findings across every design"+ )+ error: str = SchemaField(description="Error message if the request failed")+++async def emit_quote(quote: Quote) -> BlockOutput:+ yield "quote", quote+ yield "quote_id", quote.id+ yield "status", quote.status+ yield "is_ready", quote.status == QuoteStatus.READY+ yield "amount_total_cents", quote.amount_total_cents or 0+ yield "amount_subtotal_cents", quote.amount_subtotal_cents or 0+ first = quote.items[0] if quote.items else None+ yield "unit_amount_cents", (first.unit_amount_cents or 0) if first else 0+ yield "items", quote.items+ yield "quantity_options", first.quantity_options if first else []+ yield "shipping_options", quote.shipping_options+ yield "requirements", quote.all_requirements+ yield "dfm_issues", [issue for item in quote.items for issue in item.dfm.issues]+++class RMFGCreateQuoteBlock(Block):+ """Price one or more configured designs. Quoting also runs DFM."""++ class Input(RMFGBasketInput):+ ship_to: Optional[ShipTo] = SchemaField(+ description="Destination, to include delivery options in the quote.",+ default=None,+ advanced=True,+ )+ wait_for_ready: bool = SchemaField(+ description="Poll until pricing finishes instead of returning at once.",+ default=True,+ advanced=True,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for pricing when wait_for_ready is on.",+ default=300,+ ge=5,+ le=1500,+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description="Stable key for identical retries; defaults to the node execution ID.",+ default="",+ advanced=True,+ )++ class Output(RMFGQuoteOutput):+ pass++ def __init__(self):+ super().__init__(+ id="916c21ad-f85e-4a08-be83-3a9bffb83404",+ description=(+ "Gets a live price from RMFG, a manufacturer that laser-cuts, bends and "+ "ships real sheet-metal and tube parts, plus manufacturability findings. "+ "Quote with the stocked material closest to the part's detected "+ "thickness and report any mismatch; quote exactly the quantity the "+ "customer asked for, and every unique part of a project at its "+ "required quantity; a requires_input result means a "+ "selection is missing, blocked means a finding must be resolved or "+ "accepted"+ ),+ categories=CATEGORIES,+ input_schema=RMFGCreateQuoteBlock.Input,+ output_schema=RMFGCreateQuoteBlock.Output,+ test_input={+ "design_id": TEST_QUOTE.design_id,+ "quantity": 10,+ "material_id": TEST_MATERIAL.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("quote", TEST_QUOTE),+ ("quote_id", TEST_QUOTE.id),+ ("status", QuoteStatus.READY),+ ("is_ready", True),+ ("amount_total_cents", 24800),+ ("amount_subtotal_cents", 24800),+ ("unit_amount_cents", 2480),+ ("items", TEST_QUOTE.items),+ ("quantity_options", []),+ ("shipping_options", [TEST_SHIPPING_OPTION]),+ ("requirements", []),+ ("dfm_issues", [TEST_DFM_ISSUE]),+ ],+ test_mock={"create_quote": lambda *args, **kwargs: TEST_QUOTE},+ )++ @staticmethod+ async def create_quote(+ credentials: RMFGCredentials,+ items: list[QuoteItemRequest],+ ship_to: Optional[ShipTo],+ idempotency_key: str,+ wait_for_ready: bool,+ timeout_seconds: int,+ ) -> Quote:+ client = RMFGClient(credentials)+ quote = await client.create_quote(items, ship_to, idempotency_key)+ if not wait_for_ready:+ return quote+ return await client.wait_for_quote(quote, timeout_seconds)++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ quote = await self.create_quote(+ credentials,+ build_items(input_data),+ input_data.ship_to,+ input_data.idempotency_key or node_exec_id,+ input_data.wait_for_ready,+ input_data.timeout_seconds,+ )+ async for output in emit_quote(quote):+ yield output+++class RMFGGetQuoteBlock(Block):+ """Re-read a quote, e.g. one that was still processing."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ quote_id: str = SchemaField(description="Quote ID from Create Quote")+ wait_for_ready: bool = SchemaField(+ description="Poll until pricing finishes instead of returning at once.",+ default=False,+ advanced=True,+ )+ timeout_seconds: int = SchemaField(+ description="How long to wait for pricing when wait_for_ready is on.",+ default=300,+ ge=5,+ le=1500,+ advanced=True,+ )++ class Output(RMFGQuoteOutput):+ pass++ def __init__(self):+ super().__init__(+ id="3e9bb152-0505-4a4e-91a8-a30f0cc3dbfb",+ description="Fetches an RMFG quote by ID",+ categories=CATEGORIES,+ input_schema=RMFGGetQuoteBlock.Input,+ output_schema=RMFGGetQuoteBlock.Output,+ test_input={+ "quote_id": TEST_QUOTE.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("quote", TEST_QUOTE),+ ("quote_id", TEST_QUOTE.id),+ ("status", QuoteStatus.READY),+ ("is_ready", True),+ ("amount_total_cents", 24800),+ ("amount_subtotal_cents", 24800),+ ("unit_amount_cents", 2480),+ ("items", TEST_QUOTE.items),+ ("quantity_options", []),+ ("shipping_options", [TEST_SHIPPING_OPTION]),+ ("requirements", []),+ ("dfm_issues", [TEST_DFM_ISSUE]),+ ],+ test_mock={"get_quote": lambda *args, **kwargs: TEST_QUOTE},+ )++ @staticmethod+ async def get_quote(+ credentials: RMFGCredentials,+ quote_id: str,+ wait_for_ready: bool,+ timeout_seconds: int,+ ) -> Quote:+ client = RMFGClient(credentials)+ quote = await client.get_quote(quote_id)+ if not wait_for_ready:+ return quote+ return await client.wait_for_quote(quote, timeout_seconds)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ quote = await self.get_quote(+ credentials,+ input_data.quote_id,+ input_data.wait_for_ready,+ input_data.timeout_seconds,+ )+ async for output in emit_quote(quote):+ yield outputdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/review_links.py b/autogpt_platform/backend/backend/blocks/rmfg/review_links.pynew file mode 100644index 0000000000..68e6cfb667--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/review_links.py@@ -0,0 +1,163 @@+"""Blocks that hand a design to a person on rmfg.com and read back their choices."""++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ CredentialsMetaInput,+ SchemaField,+)++from ._api import RMFGClient+from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from ._inputs import credentials_field+from ._models_commerce import ReviewLink+from ._testdata import TEST_CONFIGURATION, TEST_REVIEW_LINK+from ._types import ManufacturingConfiguration, RMFGCredentials++CATEGORIES = {BlockCategory.HARDWARE, BlockCategory.DATA}+++class RMFGReviewLinkOutput(BlockSchemaOutput):+ review_link: ReviewLink = SchemaField(description="The review link resource")+ link_id: str = SchemaField(description="Link ID, to read the saved result back")+ review_url: str = SchemaField(+ description="Website page for a person to inspect and configure the design; keep private"+ )+ configuration: ManufacturingConfiguration = SchemaField(+ description="The configuration on the link, including any saved changes"+ )+ configuration_updated_at: str = SchemaField(+ description="When a person last saved changes; empty until they do"+ )+ status: str = SchemaField(description="open or expired")+ error: str = SchemaField(description="Error message if the request failed")+++async def emit_link(link: ReviewLink) -> BlockOutput:+ yield "review_link", link+ yield "link_id", link.id+ yield "review_url", link.review_url+ yield "configuration", link.configuration+ yield "configuration_updated_at", link.configuration_updated_at or ""+ yield "status", link.status+++LINK_TEST_OUTPUT = [+ ("review_link", TEST_REVIEW_LINK),+ ("link_id", TEST_REVIEW_LINK.id),+ ("review_url", TEST_REVIEW_LINK.review_url),+ ("configuration", TEST_CONFIGURATION),+ ("configuration_updated_at", ""),+ ("status", "open"),+]+++class RMFGCreateReviewLinkBlock(Block):+ """Mint a website link where a person can adjust a configuration and save it."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ design_id: str = SchemaField(description="Design ID from Analyze Design")+ configuration: ManufacturingConfiguration = SchemaField(+ description="Starting configuration shown on the page; may be empty.",+ default_factory=ManufacturingConfiguration,+ advanced=False,+ )+ dfm_id: str = SchemaField(+ description="Attach a DFM report so the page opens that report's exact configuration.",+ default="",+ advanced=True,+ )+ idempotency_key: str = SchemaField(+ description="Stable key for identical retries; defaults to the node execution ID.",+ default="",+ advanced=True,+ )++ class Output(RMFGReviewLinkOutput):+ pass++ def __init__(self):+ super().__init__(+ id="9409dd93-3ce2-4fef-b14d-b70b1ecf6b17",+ description="Creates an RMFG review link so a person can inspect and adjust a design",+ categories=CATEGORIES,+ input_schema=RMFGCreateReviewLinkBlock.Input,+ output_schema=RMFGCreateReviewLinkBlock.Output,+ test_input={+ "design_id": TEST_REVIEW_LINK.design_id,+ "configuration": TEST_CONFIGURATION.model_dump(),+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=LINK_TEST_OUTPUT,+ test_mock={"create_link": lambda *args, **kwargs: TEST_REVIEW_LINK},+ )++ @staticmethod+ async def create_link(+ credentials: RMFGCredentials, input_data: Input, idempotency_key: str+ ) -> ReviewLink:+ return await RMFGClient(credentials).create_review_link(+ input_data.design_id,+ input_data.configuration,+ input_data.dfm_id,+ idempotency_key,+ )++ async def run(+ self,+ input_data: Input,+ *,+ credentials: RMFGCredentials,+ node_exec_id: str = "",+ **kwargs,+ ) -> BlockOutput:+ link = await self.create_link(+ credentials, input_data, input_data.idempotency_key or node_exec_id+ )+ async for output in emit_link(link):+ yield output+++class RMFGGetReviewLinkBlock(Block):+ """Read a review link back, including the configuration a person saved."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field()+ link_id: str = SchemaField(+ description="Link ID from Create Review Link, or a design's review_link_id"+ )++ class Output(RMFGReviewLinkOutput):+ pass++ def __init__(self):+ super().__init__(+ id="d82a0bed-6e69-48ae-b391-3eb84842069e",+ description="Fetches an RMFG review link and the configuration a person saved on it",+ categories=CATEGORIES,+ input_schema=RMFGGetReviewLinkBlock.Input,+ output_schema=RMFGGetReviewLinkBlock.Output,+ test_input={+ "link_id": TEST_REVIEW_LINK.id,+ "credentials": TEST_CREDENTIALS_INPUT,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=LINK_TEST_OUTPUT,+ test_mock={"get_link": lambda *args, **kwargs: TEST_REVIEW_LINK},+ )++ @staticmethod+ async def get_link(credentials: RMFGCredentials, link_id: str) -> ReviewLink:+ return await RMFGClient(credentials).get_review_link(link_id)++ async def run(+ self, input_data: Input, *, credentials: RMFGCredentials, **kwargs+ ) -> BlockOutput:+ link = await self.get_link(credentials, input_data.link_id)+ async for output in emit_link(link):+ yield outputdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/triggers.py b/autogpt_platform/backend/backend/blocks/rmfg/triggers.pynew file mode 100644index 0000000000..4d85f49ae3--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/rmfg/triggers.py@@ -0,0 +1,139 @@+"""Trigger block fired by RMFG lifecycle events.++Dropping this block on a graph registers a webhook endpoint with RMFG through+its API; removing it deletes the endpoint again. Deliveries are verified+against the signing secret RMFG returned at registration.+"""++from typing import Any++from pydantic import BaseModel, TypeAdapter, ValidationError++from backend.sdk import (+ Block,+ BlockCategory,+ BlockOutput,+ BlockSchemaInput,+ BlockSchemaOutput,+ BlockWebhookConfig,+ CredentialsMetaInput,+ ProviderName,+ SchemaField,+)++from ._config import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT, rmfg+from ._inputs import credentials_field+from ._webhook import RMFGWebhookType++_JSON_OBJECT = TypeAdapter(dict[str, Any])++EXAMPLE_PAYLOAD = {+ "id": "evt_01J9RMFG0000000000000001",+ "type": "order.status_changed",+ "created_at": "2026-09-08T16:00:00Z",+ "data": {+ "id": "ord_001",+ "object": "order",+ "status": "shipped",+ "status_url": "https://api.rmfg.com/v1/orders/ord_001",+ },+}+++class RMFGEventTriggerBlock(Block):+ """Start a graph when a design, quote, cart or order changes at RMFG."""++ class Input(BlockSchemaInput):+ credentials: CredentialsMetaInput = credentials_field({"webhooks"})++ class EventsFilter(BaseModel):+ """Lifecycle events RMFG can deliver. Names mirror the API's event types."""++ design_ready: bool = False+ design_failed: bool = False+ production_files_ready: bool = False+ production_files_failed: bool = False+ quote_ready: bool = False+ quote_failed: bool = False+ cart_checked_out: bool = False+ order_status_changed: bool = True++ events: EventsFilter = SchemaField(+ title="Events",+ description="Which RMFG events start this graph",+ default_factory=EventsFilter,+ )+ payload: dict = SchemaField(hidden=True, default_factory=dict)++ class Output(BlockSchemaOutput):+ payload: dict = SchemaField(description="The raw event RMFG delivered")+ event: str = SchemaField(+ description="RMFG event type, e.g. order.status_changed"+ )+ event_id: str = SchemaField(description="Unique ID of this event")+ resource_id: str = SchemaField(+ description="ID of the design, DFM report, quote, cart or order concerned"+ )+ resource_type: str = SchemaField(+ description="design, dfm_report, quote, cart or order"+ )+ status: str = SchemaField(+ description="The resource's new status, when the event carries one"+ )+ status_url: str = SchemaField(+ description="API URL of the resource, for fetching its full state"+ )+ created_at: str = SchemaField(description="When RMFG emitted the event")++ def __init__(self):+ super().__init__(+ id="62db5c4c-186e-43d3-8078-886b2c29848a",+ description="Triggers when an RMFG design, quote, cart or order changes",+ categories={BlockCategory.INPUT, BlockCategory.HARDWARE},+ input_schema=RMFGEventTriggerBlock.Input,+ output_schema=RMFGEventTriggerBlock.Output,+ webhook_config=BlockWebhookConfig(+ provider=ProviderName(rmfg.name),+ webhook_type=RMFGWebhookType.ACCOUNT,+ resource_format="",+ event_filter_input="events",+ event_format="{event}",+ ),+ test_input={+ "events": {"order_status_changed": True},+ "credentials": TEST_CREDENTIALS_INPUT,+ "payload": EXAMPLE_PAYLOAD,+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[+ ("payload", EXAMPLE_PAYLOAD),+ ("event", "order.status_changed"),+ ("event_id", "evt_01J9RMFG0000000000000001"),+ ("resource_id", "ord_001"),+ ("resource_type", "order"),+ ("status", "shipped"),+ ("status_url", "https://api.rmfg.com/v1/orders/ord_001"),+ ("created_at", "2026-09-08T16:00:00Z"),+ ],+ )++ async def run(self, input_data: Input, **kwargs) -> BlockOutput:+ payload = input_data.payload+ yield "payload", payload+ yield "event", str(payload.get("type") or "")+ yield "event_id", str(payload.get("id") or "")++ data = _event_data(payload)+ yield "resource_id", str(data.get("id") or "")+ yield "resource_type", str(data.get("object") or "")+ yield "status", str(data.get("status") or "")+ yield "status_url", str(data.get("status_url") or "")+ yield "created_at", str(payload.get("created_at") or "")+++def _event_data(payload: dict[str, Any]) -> dict[str, Any]:+ """The event's ``data`` object, or empty when the body has another shape."""+ try:+ return _JSON_OBJECT.validate_python(payload.get("data") or {})+ except ValidationError:+ return {}diff --git a/autogpt_platform/backend/backend/integrations/oauth/__init__.py b/autogpt_platform/backend/backend/integrations/oauth/__init__.pyindex 323ea17624..1133e09f1a 100644--- a/autogpt_platform/backend/backend/integrations/oauth/__init__.py+++ b/autogpt_platform/backend/backend/integrations/oauth/__init__.py@@ -12,6 +12,7 @@ from .github import GitHubOAuthHandlerfrom .google import GoogleOAuthHandlerfrom .notion import NotionOAuthHandlerfrom .reddit import RedditOAuthHandler+from .rmfg import RMFGDeviceAuthHandlerfrom .stripe_link import StripeLinkDeviceAuthHandlerfrom .twitter import TwitterOAuthHandler@@ -234,6 +235,7 @@ CREDENTIALS_BY_PROVIDER: dict[str, SDKAwareCredentials] = SDKAwareCredentialsDic# ------------------------------------------------------------------ #_ORIGINAL_DEVICE_HANDLERS: list[type[BaseDeviceAuthHandler]] = [CodexDeviceAuthHandler,+ RMFGDeviceAuthHandler,StripeLinkDeviceAuthHandler,]diff --git a/autogpt_platform/backend/backend/integrations/oauth/rmfg.py b/autogpt_platform/backend/backend/integrations/oauth/rmfg.pynew file mode 100644index 0000000000..72d0a1934e--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/oauth/rmfg.py@@ -0,0 +1,199 @@+"""+RMFG — OAuth 2.0 Device Code Grant handler (RFC 8628).++RMFG issues no client secret: the public client id ``rmfg-agent`` starts a+device authorization, the person approves it at rmfg.com/connect, and the+token endpoint returns an access token plus a *rotating* refresh token.+Access tokens last up to 15 minutes; a connection lasts 30 days.+"""++import logging+import time+from typing import Any, ClassVar++import httpx+from pydantic import SecretStr++from backend.data.model import OAuth2Credentials+from backend.integrations.oauth.device_base import (+ BaseDeviceAuthHandler,+ DeviceAuthInitiation,+ DeviceAuthPollResult,+)+from backend.integrations.providers import ProviderName++logger = logging.getLogger(__name__)++RMFG_API_URL = "https://api.rmfg.com"+RMFG_OAUTH_URL = f"{RMFG_API_URL}/v1/oauth"+# Every call here is awaited inline by an API handler or the credentials+# manager, so a stalled upstream must not hold a worker indefinitely.+RMFG_HTTP_TIMEOUT = 15.0+RMFG_CLIENT_ID = "rmfg-agent"+DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"+FORM_HEADERS = {"Content-Type": "application/x-www-form-urlencoded"}++# Granted to every connection; nearly every RMFG block needs them.+BASE_SCOPES = ["designs", "dfm", "quotes", "carts", "orders"]+# Shown as opt-in choices on RMFG's approval page: ``webhooks`` for the+# trigger block, ``payments`` for Pay Cart. A person can decline either while+# the connection still succeeds, so the granted set is read from the token.+OPTIONAL_SCOPES = ["webhooks", "payments"]+++class RMFGDeviceAuthHandler(BaseDeviceAuthHandler):+ """Device code handler for RMFG."""++ PROVIDER_NAME: ClassVar[ProviderName | str] = ProviderName.RMFG+ DEFAULT_SCOPES: ClassVar[list[str]] = BASE_SCOPES + OPTIONAL_SCOPES+ # RMFG treats reuse of a consumed refresh token as compromise and revokes+ # the whole connection, so refreshes must be serialized.+ ROTATES_REFRESH_TOKEN: ClassVar[bool] = True++ async def initiate_device_auth(self, scopes: list[str]) -> DeviceAuthInitiation:+ requested = self.handle_default_scopes(scopes)+ # A block that needs one optional permission asks for just that scope.+ # The base set has to ride along, or the resulting token could not+ # even read the design the block is acting on.+ effective = BASE_SCOPES + [s for s in requested if s not in BASE_SCOPES]++ async with httpx.AsyncClient(timeout=RMFG_HTTP_TIMEOUT) as client:+ response = await client.post(+ f"{RMFG_OAUTH_URL}/device/code",+ data={"client_id": RMFG_CLIENT_ID, "scope": " ".join(effective)},+ headers=FORM_HEADERS,+ )+ response.raise_for_status()+ data = response.json()++ return DeviceAuthInitiation(+ device_code=data["device_code"],+ user_code=data["user_code"],+ verification_url=data["verification_uri"],+ verification_url_complete=data.get("verification_uri_complete"),+ expires_in=data["expires_in"],+ interval=data.get("interval", 5),+ )++ async def poll_for_tokens(self, device_code: str) -> DeviceAuthPollResult:+ async with httpx.AsyncClient(timeout=RMFG_HTTP_TIMEOUT) as client:+ response = await client.post(+ f"{RMFG_OAUTH_URL}/token",+ data={+ "grant_type": DEVICE_CODE_GRANT,+ "client_id": RMFG_CLIENT_ID,+ "device_code": device_code,+ },+ headers=FORM_HEADERS,+ )++ if response.status_code == 200:+ data = response.json()+ credentials = OAuth2Credentials(+ provider=self.PROVIDER_NAME,+ access_token=SecretStr(data["access_token"]),+ refresh_token=SecretStr(data["refresh_token"]),+ access_token_expires_at=int(time.time()) + int(data["expires_in"]),+ # Record what was granted, not what was asked for: the person+ # may have left "Also allow paid orders" unchecked.+ scopes=str(data.get("scope") or "").split(),+ title="RMFG",+ # Lets a re-connect of the same account update the existing+ # credential instead of stacking a second one.+ username=await self._fetch_username(data["access_token"]),+ )+ return DeviceAuthPollResult(status="approved", credentials=credentials)++ # RFC 8628 reports every waiting and terminal state as HTTP 400.+ if response.status_code == 400:+ error_code = response.json().get("error", "")+ if error_code == "authorization_pending":+ return DeviceAuthPollResult(status="pending")+ if error_code == "slow_down":+ # RMFG asks for the interval plus five seconds.+ return DeviceAuthPollResult(status="slow_down", next_poll_interval=10)+ if error_code == "expired_token":+ return DeviceAuthPollResult(status="expired")+ if error_code == "access_denied":+ return DeviceAuthPollResult(status="denied")++ raise RuntimeError(+ f"Unexpected response from RMFG auth: "+ f"{response.status_code} {response.text[:200]}"+ )++ async def _fetch_username(self, access_token: str) -> str | None:+ """Best-effort account email, used only to de-duplicate credentials.++ The grant is already complete here; a failure must not turn an+ approved authorization into a lost credential.+ """+ try:+ async with httpx.AsyncClient(timeout=RMFG_HTTP_TIMEOUT) as client:+ response = await client.get(+ f"{RMFG_API_URL}/v1/account",+ headers={"Authorization": f"Bearer {access_token}"},+ )+ if response.status_code != 200:+ return None+ email = response.json().get("email")+ return str(email) if email else None+ except Exception as exc:+ logger.warning(f"Could not read RMFG account for credential title: {exc}")+ return None++ async def _refresh_tokens(+ self, credentials: OAuth2Credentials+ ) -> OAuth2Credentials:+ if not credentials.refresh_token:+ raise RuntimeError("No refresh token available")++ async with httpx.AsyncClient(timeout=RMFG_HTTP_TIMEOUT) as client:+ response = await client.post(+ f"{RMFG_OAUTH_URL}/token",+ data={+ "grant_type": "refresh_token",+ "client_id": RMFG_CLIENT_ID,+ "refresh_token": credentials.refresh_token.get_secret_value(),+ },+ headers=FORM_HEADERS,+ )+ response.raise_for_status()+ data: dict[str, Any] = response.json()++ access_token, replacement = data.get("access_token"), data.get("refresh_token")+ if not isinstance(access_token, str) or not access_token:+ raise RuntimeError("RMFG token refresh returned no access token")+ # RMFG rotates the refresh token on every refresh and revokes the+ # connection if a consumed one is replayed. Keeping the old token+ # would make the next refresh kill the connection, so a response+ # without a replacement is a failed refresh, and nothing is changed.+ if not isinstance(replacement, str) or not replacement:+ raise RuntimeError(+ "RMFG token refresh returned no replacement refresh token"+ )+ credentials.access_token = SecretStr(access_token)+ credentials.refresh_token = SecretStr(replacement)+ if data.get("expires_in") is not None:+ credentials.access_token_expires_at = int(time.time()) + int(+ data["expires_in"]+ )+ if data.get("scope"):+ credentials.scopes = str(data["scope"]).split()+ return credentials++ async def revoke_tokens(self, credentials: OAuth2Credentials) -> bool:+ if not credentials.refresh_token:+ return False++ async with httpx.AsyncClient(timeout=RMFG_HTTP_TIMEOUT) as client:+ response = await client.post(+ f"{RMFG_OAUTH_URL}/revoke",+ data={+ "client_id": RMFG_CLIENT_ID,+ "token": credentials.refresh_token.get_secret_value(),+ },+ headers=FORM_HEADERS,+ )++ return response.status_code == 200diff --git a/autogpt_platform/backend/backend/integrations/oauth/rmfg_test.py b/autogpt_platform/backend/backend/integrations/oauth/rmfg_test.pynew file mode 100644index 0000000000..a4d64f4aad--- /dev/null+++ b/autogpt_platform/backend/backend/integrations/oauth/rmfg_test.py@@ -0,0 +1,262 @@+"""Tests for the RMFG device-code handler.++RFC 8628 signals `pending`, `slow_down`, `expired_token` and `access_denied`+all as HTTP 400, so misreading the body turns a normal wait into a failure.+The scope handling matters too: a block that needs one opt-in permission+must not end up with a token that lacks the base permissions.+"""++import time+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from pydantic import SecretStr++from backend.data.model import OAuth2Credentials+from backend.integrations.oauth.rmfg import (+ BASE_SCOPES,+ RMFG_CLIENT_ID,+ RMFGDeviceAuthHandler,+)+++def _response(status_code: int, payload: dict, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.json = MagicMock(return_value=payload)+ response.text = text+ response.raise_for_status = MagicMock()+ return response+++def mock_http(+ post: tuple[int, dict] | None = None, get: tuple[int, dict] | None = None+):+ """Patch the module's httpx client with canned POST and GET responses."""+ client = MagicMock()+ if post:+ client.post = AsyncMock(return_value=_response(*post))+ if get:+ client.get = AsyncMock(return_value=_response(*get))+ ctx = MagicMock()+ ctx.__aenter__ = AsyncMock(return_value=client)+ ctx.__aexit__ = AsyncMock(return_value=False)+ return (+ patch("backend.integrations.oauth.rmfg.httpx.AsyncClient", return_value=ctx),+ client,+ )+++def credentials(refresh_token: str | None = "old-refresh") -> OAuth2Credentials:+ return OAuth2Credentials(+ provider="rmfg",+ access_token=SecretStr("old-access"),+ refresh_token=SecretStr(refresh_token) if refresh_token else None,+ access_token_expires_at=int(time.time()) + 60,+ scopes=BASE_SCOPES,+ title="RMFG",+ )+++DEVICE_PAYLOAD = {+ "device_code": "dev_abc",+ "user_code": "ZULF-5PT3",+ "verification_uri": "https://www.rmfg.com/connect",+ "verification_uri_complete": "https://www.rmfg.com/connect?user_code=ZULF-5PT3",+ "expires_in": 600,+ "interval": 5,+}+++class TestInitiate:+ async def test_maps_the_device_code_response(self):+ patcher, client = mock_http(post=(200, DEVICE_PAYLOAD))+ with patcher:+ result = await RMFGDeviceAuthHandler().initiate_device_auth([])++ assert result.device_code == "dev_abc"+ assert result.user_code == "ZULF-5PT3"+ assert result.verification_url == "https://www.rmfg.com/connect"+ assert result.verification_url_complete is not None+ assert (result.expires_in, result.interval) == (600, 5)++ sent = client.post.call_args.kwargs["data"]+ assert sent["client_id"] == RMFG_CLIENT_ID+ # Nothing requested: ask for everything, including the opt-in scopes+ # RMFG shows as checkboxes on its approval page.+ assert sent["scope"] == "designs dfm quotes carts orders webhooks payments"++ async def test_base_scopes_ride_along_with_a_narrow_request(self):+ # The Pay Cart block requires only `payments`; the frontend forwards+ # exactly that. Without the base set the token could not read a cart.+ patcher, client = mock_http(post=(200, DEVICE_PAYLOAD))+ with patcher:+ await RMFGDeviceAuthHandler().initiate_device_auth(["payments"])++ sent = client.post.call_args.kwargs["data"]+ assert sent["scope"] == "designs dfm quotes carts orders payments"++ async def test_interval_defaults_when_absent(self):+ payload = {k: v for k, v in DEVICE_PAYLOAD.items() if k != "interval"}+ patcher, _ = mock_http(post=(200, payload))+ with patcher:+ result = await RMFGDeviceAuthHandler().initiate_device_auth([])+ assert result.interval == 5+++class TestPoll:+ async def test_approved_records_granted_scopes_and_account(self):+ patcher, client = mock_http(+ post=(+ 200,+ {+ "access_token": "acc",+ "refresh_token": "ref",+ "expires_in": 900,+ # The person left "Also allow paid orders" unchecked.+ "scope": "designs dfm quotes carts orders webhooks",+ },+ ),+ get=(200, {"email": "[email protected]", "auth_method": "api_key"}),+ )+ with patcher:+ result = await RMFGDeviceAuthHandler().poll_for_tokens("dev_abc")++ assert result.status == "approved"+ assert result.credentials is not None+ creds = result.credentials+ assert creds.access_token.get_secret_value() == "acc"+ assert creds.refresh_token is not None+ assert creds.refresh_token.get_secret_value() == "ref"+ assert creds.scopes == [+ "designs",+ "dfm",+ "quotes",+ "carts",+ "orders",+ "webhooks",+ ]+ assert "payments" not in creds.scopes+ assert creds.username == "[email protected]"+ assert creds.access_token_expires_at is not None+ assert creds.access_token_expires_at > int(time.time()) + 800++ sent = client.post.call_args.kwargs["data"]+ assert sent["grant_type"] == "urn:ietf:params:oauth:grant-type:device_code"+ assert sent["device_code"] == "dev_abc"++ async def test_account_lookup_failure_does_not_lose_the_grant(self):+ patcher, _ = mock_http(+ post=(+ 200,+ {"access_token": "acc", "refresh_token": "ref", "expires_in": 900},+ ),+ get=(500, {}),+ )+ with patcher:+ result = await RMFGDeviceAuthHandler().poll_for_tokens("dev_abc")+ assert result.status == "approved"+ assert result.credentials is not None+ assert result.credentials.username is None++ @pytest.mark.parametrize(+ "error, status",+ [+ ("authorization_pending", "pending"),+ ("slow_down", "slow_down"),+ ("expired_token", "expired"),+ ("access_denied", "denied"),+ ],+ )+ async def test_maps_rfc8628_400_states(self, error: str, status: str):+ patcher, _ = mock_http(post=(400, {"error": error}))+ with patcher:+ result = await RMFGDeviceAuthHandler().poll_for_tokens("dev_abc")+ assert result.status == status+ assert result.credentials is None++ async def test_slow_down_lengthens_the_interval(self):+ patcher, _ = mock_http(post=(400, {"error": "slow_down"}))+ with patcher:+ result = await RMFGDeviceAuthHandler().poll_for_tokens("dev_abc")+ assert result.next_poll_interval == 10++ async def test_unexpected_status_raises(self):+ patcher, _ = mock_http(post=(503, {}, "down"))+ with patcher:+ with pytest.raises(RuntimeError, match="503"):+ await RMFGDeviceAuthHandler().poll_for_tokens("dev_abc")+++class TestRefresh:+ async def test_rotates_the_refresh_token(self):+ patcher, client = mock_http(+ post=(+ 200,+ {+ "access_token": "new-access",+ "refresh_token": "new-refresh",+ "expires_in": 900,+ },+ )+ )+ with patcher:+ updated = await RMFGDeviceAuthHandler().refresh_tokens(credentials())++ assert updated.access_token.get_secret_value() == "new-access"+ assert updated.refresh_token is not None+ assert updated.refresh_token.get_secret_value() == "new-refresh"+ assert updated.access_token_expires_at is not None+ assert updated.access_token_expires_at > int(time.time()) + 800+ sent = client.post.call_args.kwargs["data"]+ assert sent["grant_type"] == "refresh_token"+ assert sent["refresh_token"] == "old-refresh"+ assert sent["client_id"] == RMFG_CLIENT_ID++ async def test_a_missing_replacement_refresh_token_is_a_failed_refresh(self):+ # The old token has been consumed; saving it would make the next+ # refresh look like a replay and get the connection revoked.+ patcher, _ = mock_http(post=(200, {"access_token": "new-access"}))+ creds = credentials()+ with patcher, pytest.raises(RuntimeError, match="replacement refresh token"):+ await RMFGDeviceAuthHandler().refresh_tokens(creds)+ assert creds.access_token.get_secret_value() == "old-access"+ assert creds.refresh_token is not None+ assert creds.refresh_token.get_secret_value() == "old-refresh"++ async def test_a_missing_access_token_is_a_failed_refresh(self):+ patcher, _ = mock_http(post=(200, {"refresh_token": "new-refresh"}))+ with patcher, pytest.raises(RuntimeError, match="no access token"):+ await RMFGDeviceAuthHandler().refresh_tokens(credentials())++ async def test_requires_a_refresh_token(self):+ with pytest.raises(RuntimeError, match="No refresh token"):+ await RMFGDeviceAuthHandler().refresh_tokens(+ credentials(refresh_token=None)+ )++ async def test_refuses_other_providers(self):+ other = credentials()+ other.provider = "slant3d"+ with pytest.raises(ValueError, match="cannot refresh"):+ await RMFGDeviceAuthHandler().refresh_tokens(other)++ def test_is_marked_as_rotating(self):+ # The credentials manager serializes refreshes only for handlers that+ # say so; RMFG revokes the connection on refresh-token replay.+ assert RMFGDeviceAuthHandler.ROTATES_REFRESH_TOKEN is True+++class TestRevoke:+ async def test_revokes_the_refresh_token(self):+ patcher, client = mock_http(post=(200, {}))+ with patcher:+ assert await RMFGDeviceAuthHandler().revoke_tokens(credentials()) is True+ sent = client.post.call_args.kwargs["data"]+ assert sent["token"] == "old-refresh"++ async def test_nothing_to_revoke(self):+ assert (+ await RMFGDeviceAuthHandler().revoke_tokens(credentials(refresh_token=None))+ is False+ )diff --git a/autogpt_platform/backend/backend/integrations/providers.py b/autogpt_platform/backend/backend/integrations/providers.pyindex bd9f701f88..8e0a9f2808 100644--- a/autogpt_platform/backend/backend/integrations/providers.py+++ b/autogpt_platform/backend/backend/integrations/providers.py@@ -45,6 +45,7 @@ class ProviderName(str, Enum):REDDIT = "reddit"REPLICATE = "replicate"REVID = "revid"+ RMFG = "rmfg"SCREENSHOTONE = "screenshotone"SLACK = "slack"SLANT3D = "slant3d"diff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 88a6867595..9615d8acd4 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -181,6 +181,25 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [JSON Encoder](block-integrations/data.md#json-encoder) | Encodes any value or data structure into a JSON string || [Keyword Suggestion Extractor](block-integrations/dataforseo/keyword_suggestions.md#keyword-suggestion-extractor) | Extract individual fields from a KeywordSuggestion object || [Persist Information](block-integrations/data.md#persist-information) | Persists a key-value pair for use across multiple runs of an agent |+| [RMFG Analyze Design](block-integrations/rmfg/designs.md#rmfg-analyze-design) | Uploads a STEP file to RMFG, a manufacturer that makes and ships real sheet-metal and tube-laser parts, and returns its analyzed parts: the first step before a live quote, cart or order |+| [RMFG Create Cart](block-integrations/rmfg/carts.md#rmfg-create-cart) | Creates an RMFG cart with a website checkout link for one or more configured designs, priced live with shipping and tax once an address is set |+| [RMFG Create DFM Report](block-integrations/rmfg/dfm.md#rmfg-create-dfm-report) | Runs an RMFG manufacturability (DFM) check on a configured design |+| [RMFG Create Quote](block-integrations/rmfg/quotes.md#rmfg-create-quote) | Gets a live price from RMFG, a manufacturer that laser-cuts, bends and ships real sheet-metal and tube parts, plus manufacturability findings |+| [RMFG Create Review Link](block-integrations/rmfg/review_links.md#rmfg-create-review-link) | Creates an RMFG review link so a person can inspect and adjust a design |+| [RMFG Get Cart](block-integrations/rmfg/carts.md#rmfg-get-cart) | Fetches an RMFG cart and its latest quote by ID |+| [RMFG Get DFM Report](block-integrations/rmfg/dfm.md#rmfg-get-dfm-report) | Fetches an RMFG DFM report by ID |+| [RMFG Get Design](block-integrations/rmfg/designs.md#rmfg-get-design) | Fetches an RMFG design and its analyzed parts by ID |+| [RMFG Get Order](block-integrations/rmfg/orders.md#rmfg-get-order) | Fetches an RMFG order's status and shipment tracking |+| [RMFG Get Quote](block-integrations/rmfg/quotes.md#rmfg-get-quote) | Fetches an RMFG quote by ID |+| [RMFG Get Review Link](block-integrations/rmfg/review_links.md#rmfg-get-review-link) | Fetches an RMFG review link and the configuration a person saved on it |+| [RMFG List Finishes](block-integrations/rmfg/catalog.md#rmfg-list-finishes) | Lists the finishes RMFG can apply to sheet or tube parts |+| [RMFG List Hardware](block-integrations/rmfg/catalog.md#rmfg-list-hardware) | Lists the taps, studs, nuts or standoffs RMFG can install |+| [RMFG List Materials](block-integrations/rmfg/catalog.md#rmfg-list-materials) | Lists the sheet-metal stock RMFG can cut and bend, with thickness in mm and inches |+| [RMFG List Orders](block-integrations/rmfg/orders.md#rmfg-list-orders) | Lists the RMFG account's manufacturing orders |+| [RMFG List Powder Coat Colors](block-integrations/rmfg/catalog.md#rmfg-list-powder-coat-colors) | Lists the powder-coat colors RMFG offers |+| [RMFG List Tube Profiles](block-integrations/rmfg/catalog.md#rmfg-list-tube-profiles) | Lists the tube stock profiles RMFG can laser-cut |+| [RMFG Pay Cart](block-integrations/rmfg/pay_cart.md#rmfg-pay-cart) | Pays an RMFG cart with the saved card and places a real production order |+| [RMFG Update Cart](block-integrations/rmfg/carts.md#rmfg-update-cart) | Updates an open RMFG cart's address, shipping option or items || [Read Spreadsheet](block-integrations/data.md#read-spreadsheet) | Reads CSV and Excel files and outputs the data as a list of dictionaries and individual rows || [Related Keyword Extractor](block-integrations/dataforseo/related_keywords.md#related-keyword-extractor) | Extract individual fields from a RelatedKeyword object || [Retrieve Information](block-integrations/data.md#retrieve-information) | Reads back a key-value pair previously saved by PersistInformationBlock |@@ -688,3 +707,5 @@ Below is a comprehensive list of all available blocks, categorized by their prim| Block Name | Description ||------------|-------------|| [Compass AI Trigger](block-integrations/compass/triggers.md#compass-ai-trigger) | This block will output the contents of the compass transcription |+| [RMFG Event Trigger](block-integrations/rmfg/triggers.md#rmfg-event-trigger) | Triggers when an RMFG design, quote, cart or order changes |+| [RMFG Get Image](block-integrations/rmfg/images.md#rmfg-get-image) | Downloads RMFG's rendered picture of a design or part, with holes and bends labelled |diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex 379dcde5ad..23a4198556 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -115,6 +115,16 @@* [Nvidia Deepfake](block-integrations/nvidia/deepfake.md)* [Replicate Flux Advanced](block-integrations/replicate/flux_advanced.md)* [Replicate Replicate Block](block-integrations/replicate/replicate_block.md)+* [Rmfg Carts](block-integrations/rmfg/carts.md)+* [Rmfg Catalog](block-integrations/rmfg/catalog.md)+* [Rmfg Designs](block-integrations/rmfg/designs.md)+* [Rmfg Dfm](block-integrations/rmfg/dfm.md)+* [Rmfg Images](block-integrations/rmfg/images.md)+* [Rmfg Orders](block-integrations/rmfg/orders.md)+* [Rmfg Pay Cart](block-integrations/rmfg/pay_cart.md)+* [Rmfg Quotes](block-integrations/rmfg/quotes.md)+* [Rmfg Review Links](block-integrations/rmfg/review_links.md)+* [Rmfg Triggers](block-integrations/rmfg/triggers.md)* [Search](block-integrations/search.md)* [Slack Blocks](block-integrations/slack/blocks.md)* [Slant3D Filament](block-integrations/slant3d/filament.md)diff --git a/docs/integrations/block-integrations/rmfg/carts.md b/docs/integrations/block-integrations/rmfg/carts.mdnew file mode 100644index 0000000000..3a4325af19--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/carts.md@@ -0,0 +1,158 @@+# Rmfg Carts+<!-- MANUAL: file_description -->+Blocks that build and update an RMFG cart. A cart is a quoted basket with a website link a person can pay from; setting an address and shipping option completes its totals, after which Pay Cart can charge the saved card. Creating a cart does not place an order.+<!-- END MANUAL -->++## RMFG Create Cart++### What it is+Creates an RMFG cart with a website checkout link for one or more configured designs, priced live with shipping and tax once an address is set. A cart is not an order; the person pays on the link or Pay Cart charges the saved card after approval++### How it works+<!-- MANUAL: how_it_works -->+Posts the same basket shape as Create Quote to `/v1/carts`, optionally with `ship_to` and a `shipping_option_id`, under an `Idempotency-Key`; `quantity` and `quantity_options` are validated as for quotes. RMFG quotes the cart immediately and returns `cart_url`, an unguessable checkout link, plus `totals` with subtotal, shipping and tax (once the address is known) and the amount that will be charged. `is_payable` is true only when the cart is open, its quote is `ready`, and both address and shipping option are set.++A `shipping_option_id` that does not belong to the given address is rejected by RMFG and surfaced as `RMFG <code>: <message>`; a missing material shows up as `quote_status` `requires_input` with `requirements` rather than as an error. `order_id` is emitted only after the cart has been paid. The cart URL grants access to anyone holding it, so treat it as a secret.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design. | str | Yes |+| quantity | Completed units of the design: exactly the number the customer asked for (one part means 1). Repeated parts in an assembly are multiplied by their instance count automatically. | int | No |+| material_id | Sheet-metal stock for every sheet part, from List Materials. Required for a price: pick the stocked thickness closest to the part's detected thickness and mention the difference. Leave empty only for tube-only designs or when configuration sets it. | str | No |+| configuration | Full manufacturing configuration: per-part material, tube profile, finish, powder coat, hole operations, welds and accepted risks. A non-empty material_id above overrides defaults.material_id. | ManufacturingConfiguration | No |+| quantity_options | Up to ten other quantities to price alongside quantity, only when the customer wants a comparison; the main quantity stays as requested. | List[int] | No |+| additional_items | Further configured designs to price in the same basket. | List[QuoteItemRequest] | No |+| client_reference_id | Your own reference for this item, echoed back on the result. | str | No |+| ship_to | Delivery address. Needed for shipping options, tax and API payment. | ShipTo | No |+| shipping_option_id | A shipping_options[].id from a quote or cart with the same address. Can be chosen later with Update Cart. | str | No |+| idempotency_key | Stable key for identical retries; defaults to the node execution ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| cart | The full cart, including its latest quote | Cart |+| cart_id | Cart ID | str |+| cart_url | Website checkout link; anyone holding it can pay, keep it private | str |+| status | open, checked_out or expired | "open" \| "checked_out" \| "expired" |+| quote_status | Status of the cart's latest quote; only ready carts can be paid | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_payable | True when the cart is open, quoted ready, and has an address and shipping option | bool |+| totals | Subtotal, shipping, tax and total | CartTotals |+| amount_total_cents | What checkout will charge, in USD cents | int |+| shipping_options | Delivery choices once ship_to is set; pass an id to Update Cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| manufacturing_warnings | Advisories from automatic file preparation; they do not block ordering | List[ManufacturingReviewWarning] |+| order_id | Order ID; only emitted once the cart has been paid | str |++### Possible use case+<!-- MANUAL: use_case -->+**Website Checkout Hand-Off**: Create a cart with the customer's address and send them `cart_url` to pick delivery, sign in and pay.++**Agent Ordering Prep**: Build a cart with address and shipping option so Pay Cart can charge the saved card after approval.++**Tax-Inclusive Total**: Show a customer the final total including shipping and tax before they commit.+<!-- END MANUAL -->++---++## RMFG Get Cart++### What it is+Fetches an RMFG cart and its latest quote by ID++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/carts/{id}`, including re-quoted totals, the current `status` (`open`, `checked_out` or `expired`) and the `order_id` once paid. Use it after a person edits the cart on the website, or to check the outcome of a payment that returned `processing`.++An unknown ID is reported as `RMFG not_found_error: <message>`. `order_id` is only emitted for a paid cart, so a graph can branch on its presence, and `is_payable` is recomputed on every read.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| cart_id | Cart ID from Create Cart | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| cart | The full cart, including its latest quote | Cart |+| cart_id | Cart ID | str |+| cart_url | Website checkout link; anyone holding it can pay, keep it private | str |+| status | open, checked_out or expired | "open" \| "checked_out" \| "expired" |+| quote_status | Status of the cart's latest quote; only ready carts can be paid | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_payable | True when the cart is open, quoted ready, and has an address and shipping option | bool |+| totals | Subtotal, shipping, tax and total | CartTotals |+| amount_total_cents | What checkout will charge, in USD cents | int |+| shipping_options | Delivery choices once ship_to is set; pass an id to Update Cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| manufacturing_warnings | Advisories from automatic file preparation; they do not block ordering | List[ManufacturingReviewWarning] |+| order_id | Order ID; only emitted once the cart has been paid | str |++### Possible use case+<!-- MANUAL: use_case -->+**Payment Settlement**: Poll a cart after a `processing` payment until it is `checked_out`, then pass `order_id` to Get Order.++**Customer Edits**: Re-read a cart the customer changed on rmfg.com before quoting the final total back to them.++**Expiry Guard**: Check a cart is still `open` before asking for approval to pay it.+<!-- END MANUAL -->++---++## RMFG Update Cart++### What it is+Updates an open RMFG cart's address, shipping option or items++### How it works+<!-- MANUAL: how_it_works -->+Patches `/v1/carts/{id}` with whichever of `ship_to`, `shipping_option_id` or `items` you set; omitted fields keep their current values, and an empty `items` list keeps the current basket rather than emptying it. The cart re-quotes on every change, so read the returned totals and `quote_status` before paying.++The block refuses to run with nothing to change (`Nothing to update: set ship_to, shipping_option_id or items`). RMFG rejects updates to a `checked_out` or `expired` cart and shipping options that do not match the address; both are surfaced as `RMFG <code>: <message>`.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| cart_id | Cart ID from Create Cart | str | Yes |+| ship_to | New delivery address; leave empty to keep the current one. | ShipTo | No |+| shipping_option_id | A shipping_options[].id to select; empty keeps the current one. | str | No |+| items | Replacement basket; empty keeps the current items. | List[QuoteItemRequest] | No |+| idempotency_key | Stable key for identical retries; defaults to the node execution ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| cart | The full cart, including its latest quote | Cart |+| cart_id | Cart ID | str |+| cart_url | Website checkout link; anyone holding it can pay, keep it private | str |+| status | open, checked_out or expired | "open" \| "checked_out" \| "expired" |+| quote_status | Status of the cart's latest quote; only ready carts can be paid | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_payable | True when the cart is open, quoted ready, and has an address and shipping option | bool |+| totals | Subtotal, shipping, tax and total | CartTotals |+| amount_total_cents | What checkout will charge, in USD cents | int |+| shipping_options | Delivery choices once ship_to is set; pass an id to Update Cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| manufacturing_warnings | Advisories from automatic file preparation; they do not block ordering | List[ManufacturingReviewWarning] |+| order_id | Order ID; only emitted once the cart has been paid | str |++### Possible use case+<!-- MANUAL: use_case -->+**Shipping Selection**: Let the customer pick from `shipping_options`, then select it so tax and total are final.++**Address Correction**: Replace a mistyped delivery address and re-read the re-quoted totals.++**Quantity Change**: Replace `items` with the same design at a new quantity after the customer changes their order.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/catalog.md b/docs/integrations/block-integrations/rmfg/catalog.mdnew file mode 100644index 0000000000..8d5e721cfc--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/catalog.md@@ -0,0 +1,176 @@+# Rmfg Catalog+<!-- MANUAL: file_description -->+Blocks that read RMFG's catalogs of sheet-metal stock, tube profiles, finishes, powder-coat colors and hardware. Every other RMFG block takes catalog IDs rather than names, so a quoting graph usually starts here. All RMFG blocks accept either an API key from rmfg.com/account or a connected account: choose Connect, open the approval link RMFG shows, and confirm the code.+<!-- END MANUAL -->++## RMFG List Finishes++### What it is+Lists the finishes RMFG can apply to sheet or tube parts++### How it works+<!-- MANUAL: how_it_works -->+Reads `/v1/finishes` in pages of 500, following `next_cursor` until `has_more` is false; the optional `process` filter (`sheet_metal` or `tube_laser`) is sent as a query parameter. The block emits the full list, each finish on `finish` one at a time, and `finish_ids` for wiring into a configuration; an empty catalog gives an empty list and no per-item output.++A non-2xx answer from RMFG is raised as `RMFG <code>: <message>` on the `error` output, with 401/403 pointing at the key and its scopes. A cursor that repeats, or a listing that runs past 100 pages, raises a `pagination_error` instead of looping forever. The list says what exists; whether a finish fits a specific part comes from a DFM report's `capabilities`.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| process | Only finishes that apply to this process; empty for all. | "sheet_metal" \| "tube_laser" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| finishes | Matching finishes | List[Finish] |+| finish | One finish at a time | Finish |+| finish_ids | IDs in the same order | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Deburred Bracket Quote**: List sheet-metal finishes, pick the entry named Deburr, and pass its id as `finish_id` in the quote configuration.++**Finish Menu for Customers**: Show a customer the finishes available for their process before they choose one.++**Configuration Validation**: Check that a `finish_id` saved in an old graph still exists before re-quoting with it.+<!-- END MANUAL -->++---++## RMFG List Hardware++### What it is+Lists the taps, studs, nuts or standoffs RMFG can install++### How it works+<!-- MANUAL: how_it_works -->+Reads one of the four `/v1/hardware/{kind}` catalogs (`taps`, `studs`, `nuts` or `standoffs`) with pagination. Each family has its own fields (thread pitch, PEM part number, minimum sheet thickness), which pass through untouched on `option`; the id becomes `tap_id`, `stud_id`, `nut_id` or `standoff_id` on a hole operation in a part configuration.++`kind` is an enum, so an unknown family is rejected before any request is made. API errors and pagination faults are surfaced as on the other catalog blocks, and a family with no entries yields an empty `options` list.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| kind | Which catalog to read. Reference an entry's id as tap_id, stud_id, nut_id or standoff_id in a part configuration. | "taps" \| "studs" \| "nuts" \| "standoffs" | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| options | Catalog entries | List[Dict[str, Any]] |+| option | One entry at a time | Dict[str, Any] |+| option_ids | IDs in the same order | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Tapped Holes**: Find the M4 tap entry and use its id in the `taps` array of a part configuration.++**PEM Hardware Lookup**: Look up a self-clinching nut by part number before adding it to a hole.++**Sheet Thickness Check**: Read each stud's minimum sheet thickness and skip options the chosen material is too thin for.+<!-- END MANUAL -->++---++## RMFG List Materials++### What it is+Lists the sheet-metal stock RMFG can cut and bend, with thickness in mm and inches. Choose the entry closest to a part's detected thickness and pass its id as material_id to quote++### How it works+<!-- MANUAL: how_it_works -->+Reads `/v1/materials` across all pages. Each material is a specific alloy at a stock thickness, given in both inches and millimetres, with a `bendable` flag; use the id as `material_id` on quotes, carts and DFM reports. Tube parts use tube profiles instead.++The block takes no inputs beyond credentials, so the only failures are API-side: an invalid or under-scoped key is reported as `RMFG <code>: <message>. Check the RMFG API key and its scopes`, and any other non-2xx answer as `RMFG <code>: <message>`. Rows are validated into a model whose fields all have defaults, so extra fields from a newer API version pass through instead of failing the block.+<!-- END MANUAL -->++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| materials | Every sheet-metal material, across all pages | List[Material] |+| material | One material at a time | Material |+| material_ids | IDs in the same order | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Closest Stock Thickness**: Pick the material whose `thickness_mm` is nearest a part's `detected_thickness_mm` and report the difference.++**Alloy Request Matching**: Turn "5052 aluminum, about an eighth inch" into the catalog id with `thickness_in` near 0.125.++**Bendable Stock Only**: Filter to `bendable` materials when the part has bends.+<!-- END MANUAL -->++---++## RMFG List Powder Coat Colors++### What it is+Lists the powder-coat colors RMFG offers++### How it works+<!-- MANUAL: how_it_works -->+Reads `/v1/powder-coat-colors` with pagination. Each color has a hex value for previews, an `available` flag and a price multiplier; use the id as `powder_coat_color_id` in a configuration. The DFM report decides whether a given part can be coated.++Colors with `available` false are still listed, so check the flag before offering one. API errors and pagination faults are surfaced as on the other catalog blocks.+<!-- END MANUAL -->++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| colors | Every color | List[PowderCoatColor] |+| color | One color at a time | PowderCoatColor |+| color_ids | IDs in the same order | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Color by Name**: Match a customer's requested color to a catalog entry and quote the part coated in it.++**Swatch Preview**: Show hex swatches of every available color in a storefront.++**Price Impact**: Compare price multipliers to explain why a metallic color costs more.+<!-- END MANUAL -->++---++## RMFG List Tube Profiles++### What it is+Lists the tube stock profiles RMFG can laser-cut++### How it works+<!-- MANUAL: how_it_works -->+Reads `/v1/tube-profiles` across all pages. A profile is a material plus a cross-section (square, rectangular or round) with outer dimensions and wall thickness in millimetres; use the id as `tube_profile_id` for parts whose `suggested_process` is `tube_laser`.++Round profiles carry `outer_diameter_mm` and leave width and height empty, so read `shape` first. API errors and pagination faults are surfaced as on the other catalog blocks.+<!-- END MANUAL -->++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| tube_profiles | Every tube profile, across all pages | List[TubeProfile] |+| tube_profile | One profile at a time | TubeProfile |+| tube_profile_ids | IDs in the same order | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Matching Tube Stock**: Choose the profile matching a detected cross-section and configure the tube part with it.++**Wall Thickness Options**: Offer the customer the available wall thicknesses for a 25 mm square tube.++**Stock Length Planning**: Read `default_stock_length_mm` to explain how long a part can be cut.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/designs.md b/docs/integrations/block-integrations/rmfg/designs.mdnew file mode 100644index 0000000000..22efcc2882--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/designs.md@@ -0,0 +1,96 @@+# Rmfg Designs+<!-- MANUAL: file_description -->+Blocks that upload a STEP file to RMFG for analysis and read the resulting design. Analysis is the first step of every quote: it splits an assembly into unique parts and detects bends, holes and the suggested manufacturing process.+<!-- END MANUAL -->++## RMFG Analyze Design++### What it is+Uploads a STEP file to RMFG, a manufacturer that makes and ships real sheet-metal and tube-laser parts, and returns its analyzed parts: the first step before a live quote, cart or order. Works on a URL, an attached workspace file or a data URI++### How it works+<!-- MANUAL: how_it_works -->+Reads the input file through the platform's media pipeline (a URL, data URI or workspace file), appends `.step` to the recorded name unless it already ends in `.step` or `.stp`, and uploads it as multipart form data to `/v1/analyze` with an `Idempotency-Key` (defaulting to the node execution ID), so a retried run returns the same design instead of a duplicate. The request asks RMFG to hold the connection for up to 20 seconds; with `wait_for_ready` on, the block then polls with growing delays, capped by `timeout_seconds`, until the design is `ready` or `failed`.++A `failed` analysis (for example a file that is not a solid body) raises `RMFG design_failed: Analysis failed: <reason>`; running out of time raises `Timed out after Ns waiting for design <id>; fetch it again later with its ID`, and any HTTP error is reported as `RMFG <code>: <message>`. `review_url` and `image_url` are only emitted once RMFG has assigned them, and `part` is emitted once per unique part, so a design that is still queued has no parts yet.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| file | STEP or STP file to analyze (URL, data URI or workspace file) | str (file) | Yes |+| file_name | Name to record for the upload; defaults to the file's own. | str | No |+| wait_for_ready | Poll until analysis finishes instead of returning at once. | bool | No |+| timeout_seconds | How long to wait for analysis when wait_for_ready is on. | int | No |+| idempotency_key | Stable key so a retried upload returns the same design. Defaults to this node execution's ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| design | The design resource | Design |+| design_id | ID to pass to DFM, quote and cart | str |+| status | queued, processing, ready or failed | "queued" \| "processing" \| "ready" \| "failed" |+| parts | Every unique part with its instance count, once ready | List[Part] |+| part | One part at a time | Part |+| part_ids | Part IDs in the same order | List[str] |+| review_url | Website page where a person can inspect and configure the design; emitted once RMFG has assigned one | str |+| image_url | Rendered picture of the whole design; emitted once analysis is ready | str |++### Possible use case+<!-- MANUAL: use_case -->+**Customer STEP Upload**: Analyze an emailed STEP file and show the customer each unique part and its instance count before quoting.++**Assembly Breakdown**: Split an assembly into unique parts so every one can be configured and priced.++**Fire and Forget**: Upload with `wait_for_ready` off and let a `design.ready` webhook continue the graph.+<!-- END MANUAL -->++---++## RMFG Get Design++### What it is+Fetches an RMFG design and its analyzed parts by ID++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/designs/{id}` and emits the same outputs as Analyze Design. With `wait_for_ready` on it polls until analysis leaves `queued`/`processing`, bounded by `timeout_seconds`, which is useful after an upload with waiting off or a run that timed out.++An unknown ID is reported as `RMFG not_found_error: <message>`. A design whose analysis failed raises `RMFG design_failed` with the reason when waiting, or is returned with `status` `failed` when not. `review_url` and `image_url` are emitted only when present.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design | str | Yes |+| wait_for_ready | Poll until analysis finishes instead of returning at once. | bool | No |+| timeout_seconds | How long to wait for analysis when wait_for_ready is on. | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| design | The design resource | Design |+| design_id | ID to pass to DFM, quote and cart | str |+| status | queued, processing, ready or failed | "queued" \| "processing" \| "ready" \| "failed" |+| parts | Every unique part with its instance count, once ready | List[Part] |+| part | One part at a time | Part |+| part_ids | Part IDs in the same order | List[str] |+| review_url | Website page where a person can inspect and configure the design; emitted once RMFG has assigned one | str |+| image_url | Rendered picture of the whole design; emitted once analysis is ready | str |++### Possible use case+<!-- MANUAL: use_case -->+**Webhook Continuation**: Load the parts after a `design.ready` event using the event's `resource_id`.++**Resume After Timeout**: Re-read a large design that Analyze Design gave up waiting for.++**Part ID Lookup**: Re-fetch a design's `part_ids` before building a per-part configuration.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/dfm.md b/docs/integrations/block-integrations/rmfg/dfm.mdnew file mode 100644index 0000000000..0caf47d4d3--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/dfm.md@@ -0,0 +1,98 @@+# Rmfg Dfm+<!-- MANUAL: file_description -->+Blocks that check manufacturability (design for manufacturing) of a configured design. A DFM report says whether the configuration is ready, needs input or is blocked, and reports what each part and hole can take.+<!-- END MANUAL -->++## RMFG Create DFM Report++### What it is+Runs an RMFG manufacturability (DFM) check on a configured design. A blocked finding such as a hole close to a bend can be accepted with accepted_risks once the customer agrees; requires_input means a material or profile is still missing++### How it works+<!-- MANUAL: how_it_works -->+Posts the design ID and a manufacturing configuration to `/v1/dfm` with an `Idempotency-Key`. Precedence is per-part override, then `defaults`; the `material_id` input is a shortcut that sets `defaults.material_id`. RMFG answers with a status per part and overall: `ready`, `requires_input` (a selection is missing, listed in `requirements`) or `blocked` (the geometry or configuration cannot be made). Neither of the latter is an error; they are results for the graph to act on. Findings carry a severity, and warning-level ones such as a hole near a bend can be accepted by listing their code in `accepted_risks`. Each part's `capabilities` list which finishes, colors and hardware fit that part and each of its holes.++Unknown design, material or hardware IDs are rejected by RMFG and surfaced as `RMFG <code>: <message> (field: <path>)`. By default production files (laser DXF, corrected STEP) are also prepared; their status arrives on the report and can be re-read with Get DFM Report. Reports are immutable, so a changed configuration means a new report. `review_url` is emitted only when RMFG provides one.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design | str | Yes |+| material_id | Sheet-metal stock for every sheet part, from List Materials. Leave empty for tube-only designs or when configuration sets it. | str | No |+| configuration | Per-part material, tube profile, finish, powder coat, hole operations, welds and accepted risks. A non-empty material_id above overrides defaults.material_id. | ManufacturingConfiguration | No |+| generate_production_files | Also prepare laser DXF and corrected STEP files. | bool | No |+| idempotency_key | Stable key for identical retries; defaults to the node execution ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| report | The full DFM report | DFMReport |+| dfm_id | Report ID, for review links and re-reads | str |+| status | ready, requires_input (a selection is missing) or blocked | "requires_input" \| "ready" \| "blocked" |+| is_ready | True when nothing prevents ordering | bool |+| configuration | The configuration that was evaluated; feed it to a quote | ManufacturingConfiguration |+| issues | Every finding across all parts and the assembly | List[DFMIssue] |+| issue | One finding at a time | DFMIssue |+| requirements | Selections still needed before the design can be quoted | List[Requirement] |+| parts | Per-part status, findings, capabilities and images | List[PartDFM] |+| review_url | Website page showing this exact configuration for a person to adjust; emitted when RMFG provides one | str |++### Possible use case+<!-- MANUAL: use_case -->+**Resolving requires_input**: Read the `material_required` requirement and each part's capabilities, pick a compatible material, and re-run.++**Accepting a Known Risk**: After the customer approves a hole-near-bend warning, re-run with its code in `accepted_risks`.++**Production File Prep**: Generate laser DXF and corrected STEP files for a configuration that is already priced.+<!-- END MANUAL -->++---++## RMFG Get DFM Report++### What it is+Fetches an RMFG DFM report by ID++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/dfm/{id}` and emits the same outputs as Create DFM Report. Findings never change, but the `production_files` status does, so re-reading tells you when DXF and STEP files are ready or whether preparation failed with a manual-review warning.++An unknown or foreign report ID is reported as `RMFG not_found_error: <message>`. `issue` is emitted once per finding, so a clean report yields none, and `review_url` only when present.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| dfm_id | Report ID from Create DFM Report | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| report | The full DFM report | DFMReport |+| dfm_id | Report ID, for review links and re-reads | str |+| status | ready, requires_input (a selection is missing) or blocked | "requires_input" \| "ready" \| "blocked" |+| is_ready | True when nothing prevents ordering | bool |+| configuration | The configuration that was evaluated; feed it to a quote | ManufacturingConfiguration |+| issues | Every finding across all parts and the assembly | List[DFMIssue] |+| issue | One finding at a time | DFMIssue |+| requirements | Selections still needed before the design can be quoted | List[Requirement] |+| parts | Per-part status, findings, capabilities and images | List[PartDFM] |+| review_url | Website page showing this exact configuration for a person to adjust; emitted when RMFG provides one | str |++### Possible use case+<!-- MANUAL: use_case -->+**Production Files Ready**: After a `dfm_report.production_files.ready` event, read the report and forward the file links to the shop floor.++**Audit Trail**: Re-read the report a quote was based on to show the customer exactly what was checked.++**Failed Preparation**: Detect a `production_files` failure and route the design to a person for review.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/images.md b/docs/integrations/block-integrations/rmfg/images.mdnew file mode 100644index 0000000000..c60fe59bf3--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/images.md@@ -0,0 +1,44 @@+# Rmfg Images+<!-- MANUAL: file_description -->+Block that downloads RMFG's rendered pictures. The API's image links need the account's credentials, so a bare URL is useless downstream; this block fetches the PNG and hands it on as a platform media file.+<!-- END MANUAL -->++## RMFG Get Image++### What it is+Downloads RMFG's rendered picture of a design or part, with holes and bends labelled++### How it works+<!-- MANUAL: how_it_works -->+Requests `/v1/designs/{id}/image`, `/v1/designs/{id}/parts/{part_id}/image`, or `/v1/dfm/{id}/parts/{part_id}/image` with the chosen `view` (iso, top, bottom, front, back, left, right, or flat for a sheet part's flat pattern) and optional `width` (0 uses RMFG's default, up to 4096). Setting `dfm_id` without `part_id` is rejected before any request, since a DFM picture is always of one part. Part pictures label every hole and bend by ID, which is how an agent decides which `hole_id` to tap or countersink; DFM part pictures additionally mark the configured operations.++The block always asks for PNG and checks the bytes it gets back: anything else (the SVG the API can also render, or an HTML error page) is refused with `RMFG returned <type> instead of a PNG` rather than stored as a media file. Unknown IDs and other HTTP errors are reported as `RMFG <code>: <message>`. The PNG goes through the platform's media pipeline, so the output is a workspace file in CoPilot and a data URI in graphs.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design | str | Yes |+| part_id | Draw only this part, with every hole and bend labelled by ID. Empty draws the whole design. | str | No |+| dfm_id | With part_id, draw the part as configured in this DFM report, taps, studs, nuts and countersinks marked. | str | No |+| view | Camera angle; flat shows a sheet part's flat pattern. | "iso" \| "top" \| "bottom" \| "front" \| "back" \| "left" \| "right" \| "flat" | No |+| width | Image width in pixels; 0 uses RMFG's default. | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| image | The rendered PNG | str (file) |++### Possible use case+<!-- MANUAL: use_case -->+**Hole Selection**: Show the customer the flat view of a part with labelled holes before asking which to tap.++**Quote Attachment**: Attach an iso render of the whole design to the quote email.++**Configuration Proof**: Send the DFM part picture so the customer can see where the hardware will go.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/orders.md b/docs/integrations/block-integrations/rmfg/orders.mdnew file mode 100644index 0000000000..783c8df9fe--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/orders.md@@ -0,0 +1,87 @@+# Rmfg Orders+<!-- MANUAL: file_description -->+Blocks that track paid RMFG orders through production and shipping.+<!-- END MANUAL -->++## RMFG Get Order++### What it is+Fetches an RMFG order's status and shipment tracking++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/orders/{id}`: the status (`received`, `in_production`, `ready_for_pickup`, `shipped`, `delivered`, `cancelled` or `refunded`), estimated ship date, line items, a status history, and carrier tracking once shipped.++An unknown ID is reported as `RMFG not_found_error: <message>`. `tracking_url`, `tracking_number` and `estimated_ship_date` are emitted only when RMFG has them, so a graph can branch on their presence; `amount_total_cents` is `0` until the order carries a total.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| order_id | Order ID from Pay Cart or an order.status_changed event | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| order | The full order | Order |+| order_id | Order ID | str |+| status | received, in_production, ready_for_pickup, shipped, delivered, cancelled or refunded | "received" \| "in_production" \| "ready_for_pickup" \| "shipped" \| "delivered" \| "cancelled" \| "refunded" |+| tracking | Carrier, number and link once shipped | OrderTracking |+| tracking_url | Carrier tracking link, once shipped | str |+| tracking_number | Carrier tracking number, once shipped | str |+| estimated_ship_date | Planned ship date, when known | str |+| amount_total_cents | Amount charged, USD cents | int |++### Possible use case+<!-- MANUAL: use_case -->+**Shipping Notification**: When an `order.status_changed` event arrives, load the order and message the customer with the tracking link.++**Delivery Confirmation**: Check for `delivered` status before closing a support ticket.++**Cancellation Handling**: Detect `cancelled` or `refunded` orders and update the internal record.+<!-- END MANUAL -->++---++## RMFG List Orders++### What it is+Lists the RMFG account's manufacturing orders++### How it works+<!-- MANUAL: how_it_works -->+Reads one page of `/v1/orders`, newest first, with `limit` between 1 and 100, and returns `next_cursor` when there are more. Feed the cursor back in to page; an empty `next_cursor` means the last page.++An invalid cursor is rejected by RMFG and surfaced as `RMFG <code>: <message>`. An account with no orders yields an empty `orders` list, no `order` items and an empty cursor.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| limit | Orders per page. | int | No |+| cursor | next_cursor from a previous page; empty for the first page. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| orders | This page of orders | List[Order] |+| order | One order at a time | Order |+| order_ids | IDs in the same order | List[str] |+| next_cursor | Pass back as cursor to fetch the next page; empty on the last page | str |++### Possible use case+<!-- MANUAL: use_case -->+**Weekly Production Report**: Page through all orders and summarise what is in production versus shipped.++**Open Order Dashboard**: List recent orders and filter to those not yet `delivered`.++**Reconciliation**: Match order totals against the accounting system's records.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/pay_cart.md b/docs/integrations/block-integrations/rmfg/pay_cart.mdnew file mode 100644index 0000000000..e3de86f532--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/pay_cart.md@@ -0,0 +1,58 @@+# Rmfg Pay Cart+<!-- MANUAL: file_description -->+Block that pays an RMFG cart through the API. This charges a real card and starts production, so the platform marks it as a sensitive action that a person approves before it runs.+<!-- END MANUAL -->++## RMFG Pay Cart++### What it is+Pays an RMFG cart with the saved card and places a real production order++### How it works+<!-- MANUAL: how_it_works -->+Posts to `/v1/carts/{id}/pay` with `card_on_file`, which uses the card saved on the RMFG account page, or with `payment_method` and a Stripe PaymentMethod id you manage; the block refuses `payment_method` without a `payment_method_id` before any request is made. A connected RMFG account must have been approved with "Also allow paid orders" (the `payments` permission); an API key pays whenever the account has a saved card. RMFG only accepts an open cart whose quote is `ready` with a `ship_to` and `shipping_option_id`; anything else, a missing card, or a declined charge is reported as `RMFG <code>: <message>` on `error` and nothing is charged.++The charge is the cart's `totals.amount_total_cents`. A stable `Idempotency-Key` (defaulting to the node execution ID) makes retries safe: repeating a paid cart returns the existing payment rather than charging twice. A 202 means the outcome is not yet known, so `payment_status` is `processing` and `checked_out` is false; re-read the cart instead of paying again. On success the cart becomes `checked_out` and `order_id` points at the new order. The platform marks this block as a sensitive action, so a person approves each run.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| cart_id | Open cart whose quote is ready and which has a ship_to and shipping option. Its totals.amount_total_cents will be charged. | str | Yes |+| payment_type | card_on_file charges the card saved on the RMFG account page; payment_method charges a Stripe PaymentMethod you manage. | "card_on_file" \| "payment_method" | No |+| payment_method_id | Stripe PaymentMethod id (pm_...) when payment_type is payment_method. | str | No |+| customer_email | Receipt and order emails; defaults to the account email. | str | No |+| customer_phone | Contact number for the order. | str | No |+| idempotency_key | Stable key so a retry never charges twice; defaults to the node execution ID. Use a new key only for a different purchase. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| cart | The full cart, including its latest quote | Cart |+| cart_id | Cart ID | str |+| cart_url | Website checkout link; anyone holding it can pay, keep it private | str |+| status | open, checked_out or expired | "open" \| "checked_out" \| "expired" |+| quote_status | Status of the cart's latest quote; only ready carts can be paid | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_payable | True when the cart is open, quoted ready, and has an address and shipping option | bool |+| totals | Subtotal, shipping, tax and total | CartTotals |+| amount_total_cents | What checkout will charge, in USD cents | int |+| shipping_options | Delivery choices once ship_to is set; pass an id to Update Cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| manufacturing_warnings | Advisories from automatic file preparation; they do not block ordering | List[ManufacturingReviewWarning] |+| order_id | Order ID; only emitted once the cart has been paid | str |+| payment_status | paid, processing (check the cart again later), failed or refunded | "paid" \| "processing" \| "failed" \| "refunded" |+| checked_out | True once the order exists | bool |++### Possible use case+<!-- MANUAL: use_case -->+**Approved Agent Order**: After the customer confirms the total, pay the cart and hand `order_id` to Get Order for tracking.++**Automated Reorder**: Re-order a standard part from a saved configuration with the account's card on file.++**Managed Payment Method**: Pay with a specific Stripe PaymentMethod when the business keeps its own cards.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/quotes.md b/docs/integrations/block-integrations/rmfg/quotes.mdnew file mode 100644index 0000000000..c205f215a8--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/quotes.md@@ -0,0 +1,110 @@+# Rmfg Quotes+<!-- MANUAL: file_description -->+Blocks that price a configured design. Quoting runs DFM as well, so one call returns both price and manufacturability. A quote is immutable and never includes tax or a shipping selection; carts add those.+<!-- END MANUAL -->++## RMFG Create Quote++### What it is+Gets a live price from RMFG, a manufacturer that laser-cuts, bends and ships real sheet-metal and tube parts, plus manufacturability findings. Quote with the stocked material closest to the part's detected thickness and report any mismatch; quote exactly the quantity the customer asked for, and every unique part of a project at its required quantity; a requires_input result means a selection is missing, blocked means a finding must be resolved or accepted++### How it works+<!-- MANUAL: how_it_works -->+Builds an `items[]` basket from the inputs (one design with a quantity and configuration, plus any `additional_items`) and posts it to `/v1/quotes` with an `Idempotency-Key`. The `material_id` shortcut becomes `defaults.material_id`. `quantity` is completed designs and must be at least 1, and `quantity_options` takes at most ten entries, each at least 1; both are checked before any request is sent. RMFG holds the connection briefly and the block then polls until pricing leaves `processing`, bounded by `timeout_seconds`. Amounts are integer USD cents, reported as `0` until priced; with `ship_to` set the quote also lists `shipping_options` a cart can select.++`requires_input` and `blocked` are statuses, not errors: `requirements` says what is missing and `dfm_issues` what blocks manufacture, so the graph can fix the configuration and quote again. A quote RMFG marks `failed` comes back with that status and its error object on `quote`; HTTP errors are reported as `RMFG <code>: <message>` and an exhausted wait as `Timed out after Ns waiting for quote <id>`.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design. | str | Yes |+| quantity | Completed units of the design: exactly the number the customer asked for (one part means 1). Repeated parts in an assembly are multiplied by their instance count automatically. | int | No |+| material_id | Sheet-metal stock for every sheet part, from List Materials. Required for a price: pick the stocked thickness closest to the part's detected thickness and mention the difference. Leave empty only for tube-only designs or when configuration sets it. | str | No |+| configuration | Full manufacturing configuration: per-part material, tube profile, finish, powder coat, hole operations, welds and accepted risks. A non-empty material_id above overrides defaults.material_id. | ManufacturingConfiguration | No |+| quantity_options | Up to ten other quantities to price alongside quantity, only when the customer wants a comparison; the main quantity stays as requested. | List[int] | No |+| additional_items | Further configured designs to price in the same basket. | List[QuoteItemRequest] | No |+| client_reference_id | Your own reference for this item, echoed back on the result. | str | No |+| ship_to | Destination, to include delivery options in the quote. | ShipTo | No |+| wait_for_ready | Poll until pricing finishes instead of returning at once. | bool | No |+| timeout_seconds | How long to wait for pricing when wait_for_ready is on. | int | No |+| idempotency_key | Stable key for identical retries; defaults to the node execution ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| quote | The full quote | Quote |+| quote_id | Quote ID | str |+| status | processing, requires_input, ready, blocked, expired or failed | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_ready | True when the quote can be ordered | bool |+| amount_total_cents | Total in USD cents (shipping and tax excluded until a cart) | int |+| amount_subtotal_cents | Sum of items in USD cents | int |+| unit_amount_cents | Price per completed unit of the first design, in USD cents | int |+| items | Per-design pricing, line items and DFM findings | List[QuotedDesign] |+| quantity_options | Prices at the other quantities requested, for the first design | List[QuantityOption] |+| shipping_options | Delivery choices when ship_to was given; pick an id for the cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| dfm_issues | Manufacturability findings across every design | List[DFMIssue] |++### Possible use case+<!-- MANUAL: use_case -->+**Quantity Comparison**: Quote 10 units with `quantity_options` [1, 25] and report the unit price at each quantity.++**Multi-Part Project**: Price every unique part of an assembly in one basket, each at its required quantity.++**Delivery Estimate**: Include `ship_to` to get shipping options and lead times alongside the price.+<!-- END MANUAL -->++---++## RMFG Get Quote++### What it is+Fetches an RMFG quote by ID++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/quotes/{id}` and, with `wait_for_ready` on, polls until the quote is no longer `processing`, bounded by `timeout_seconds`. Outputs match Create Quote.++An unknown ID is reported as `RMFG not_found_error: <message>`; a quote past its `expires_at` returns status `expired` and should be re-created rather than ordered. Amount outputs are `0` while the quote is still processing.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| quote_id | Quote ID from Create Quote | str | Yes |+| wait_for_ready | Poll until pricing finishes instead of returning at once. | bool | No |+| timeout_seconds | How long to wait for pricing when wait_for_ready is on. | int | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| quote | The full quote | Quote |+| quote_id | Quote ID | str |+| status | processing, requires_input, ready, blocked, expired or failed | "processing" \| "requires_input" \| "ready" \| "blocked" \| "expired" \| "failed" |+| is_ready | True when the quote can be ordered | bool |+| amount_total_cents | Total in USD cents (shipping and tax excluded until a cart) | int |+| amount_subtotal_cents | Sum of items in USD cents | int |+| unit_amount_cents | Price per completed unit of the first design, in USD cents | int |+| items | Per-design pricing, line items and DFM findings | List[QuotedDesign] |+| quantity_options | Prices at the other quantities requested, for the first design | List[QuantityOption] |+| shipping_options | Delivery choices when ship_to was given; pick an id for the cart | List[ShippingOption] |+| requirements | Selections or decisions still needed before ordering | List[Requirement] |+| dfm_issues | Manufacturability findings across every design | List[DFMIssue] |++### Possible use case+<!-- MANUAL: use_case -->+**Resume a Long Quote**: Read a large assembly quote by ID after an earlier run timed out.++**Webhook Follow-Up**: Load the finished quote when a `quote.ready` event arrives.++**Expiry Check**: Confirm a saved quote is still `ready` before turning it into a cart.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/review_links.md b/docs/integrations/block-integrations/rmfg/review_links.mdnew file mode 100644index 0000000000..e59d8c2446--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/review_links.md@@ -0,0 +1,89 @@+# Rmfg Review Links+<!-- MANUAL: file_description -->+Blocks for handing a design to a person on rmfg.com. A review link opens the 3D configurator with a starting configuration; whatever the person saves can be read back and used for quoting.+<!-- END MANUAL -->++## RMFG Create Review Link++### What it is+Creates an RMFG review link so a person can inspect and adjust a design++### How it works+<!-- MANUAL: how_it_works -->+Posts a design ID and configuration to `/v1/review-links` with an `Idempotency-Key`; optionally attach a `dfm_id` so the page opens with that report's exact configuration. The returned `review_url` is a private hand-off link: the viewer can change material, finish and hole operations and save. Every design also carries a default `review_url`.++An unknown design or DFM report, or a configuration that references invalid IDs, is rejected by RMFG and reported as `RMFG <code>: <message> (field: <path>)`. Links carry an `expires_at`, and `configuration_updated_at` is empty until a person saves.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| design_id | Design ID from Analyze Design | str | Yes |+| configuration | Starting configuration shown on the page; may be empty. | ManufacturingConfiguration | No |+| dfm_id | Attach a DFM report so the page opens that report's exact configuration. | str | No |+| idempotency_key | Stable key for identical retries; defaults to the node execution ID. | str | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| review_link | The review link resource | ReviewLink |+| link_id | Link ID, to read the saved result back | str |+| review_url | Website page for a person to inspect and configure the design; keep private | str |+| configuration | The configuration on the link, including any saved changes | ManufacturingConfiguration |+| configuration_updated_at | When a person last saved changes; empty until they do | str |+| status | open or expired | str |++### Possible use case+<!-- MANUAL: use_case -->+**Complex Configuration**: Hand an assembly with many holes to the customer to configure themselves instead of guessing.++**Approval Before Ordering**: Let a customer inspect and adjust the exact configuration before the agent quotes it.++**Engineer Sign-Off**: Send a DFM report's configuration to an engineer for review on rmfg.com.+<!-- END MANUAL -->++---++## RMFG Get Review Link++### What it is+Fetches an RMFG review link and the configuration a person saved on it++### How it works+<!-- MANUAL: how_it_works -->+Fetches `/v1/review-links/{id}`. `configuration_updated_at` is set once a person has saved changes, and `configuration` then holds their choices, ready to pass into Create Quote or Create Cart; before that it is empty and `configuration` is the starting configuration.++An unknown ID is reported as `RMFG not_found_error: <message>`; a link past `expires_at` returns status `expired`, and a new link must be created for further edits.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| link_id | Link ID from Create Review Link, or a design's review_link_id | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the request failed | str |+| review_link | The review link resource | ReviewLink |+| link_id | Link ID, to read the saved result back | str |+| review_url | Website page for a person to inspect and configure the design; keep private | str |+| configuration | The configuration on the link, including any saved changes | ManufacturingConfiguration |+| configuration_updated_at | When a person last saved changes; empty until they do | str |+| status | open or expired | str |++### Possible use case+<!-- MANUAL: use_case -->+**Customer Done Signal**: When the customer replies "done", read the link and quote the saved configuration.++**Scheduled Check**: Poll the link daily and continue once `configuration_updated_at` is set.++**Change Summary**: Compare the saved configuration with the original and tell the customer what changed.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/rmfg/triggers.md b/docs/integrations/block-integrations/rmfg/triggers.mdnew file mode 100644index 0000000000..24944b6064--- /dev/null+++ b/docs/integrations/block-integrations/rmfg/triggers.md@@ -0,0 +1,47 @@+# Rmfg Triggers+<!-- MANUAL: file_description -->+Trigger block that starts a graph on RMFG lifecycle events. Adding it to a graph registers a webhook endpoint with RMFG through the API; removing it deletes the endpoint again.+<!-- END MANUAL -->++## RMFG Event Trigger++### What it is+Triggers when an RMFG design, quote, cart or order changes++### How it works+<!-- MANUAL: how_it_works -->+Select which events to subscribe to; the platform registers an endpoint at `/v1/webhook-endpoints` for exactly those events and stores the signing secret RMFG returns once, at creation. A connected RMFG account needs the `webhooks` permission from the approval page; an API key registers directly. Registration fails with a clear message when an event is unknown, when RMFG refuses (a 403 on a connected account says to reconnect and allow the webhooks permission), or when the response lacks an endpoint ID or a string signing secret, so no half-registered hook is ever kept. Removing the block deletes the endpoint again; an already-deleted endpoint is fine.++Each delivery is verified before it reaches the graph: `X-RMFG-Signature` must carry a `v1=` HMAC-SHA256 of `<X-RMFG-Timestamp>.<raw body>` under the stored secret, and a timestamp that is missing, unparseable or more than 300 seconds off is rejected with 403. A body that is not a JSON object or lacks `type` is rejected with 400, and an event type the block does not know triggers nothing. The event body is `{id, type, created_at, data}`; the block emits the type plus the data object's id, object, status and `status_url` (as empty strings when absent), so the next block can fetch the full resource with Get Design, Get DFM Report, Get Quote, Get Cart or Get Order.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| events | Which RMFG events start this graph | Events | No |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| payload | The raw event RMFG delivered | Dict[str, Any] |+| event | RMFG event type, e.g. order.status_changed | str |+| event_id | Unique ID of this event | str |+| resource_id | ID of the design, DFM report, quote, cart or order concerned | str |+| resource_type | design, dfm_report, quote, cart or order | str |+| status | The resource's new status, when the event carries one | str |+| status_url | API URL of the resource, for fetching its full state | str |+| created_at | When RMFG emitted the event | str |++### Possible use case+<!-- MANUAL: use_case -->+**Fulfilment Feed**: Subscribe to `cart.checked_out` and `order.status_changed`, fetch the order, and post it to the fulfilment channel.++**Async Analysis**: Upload with waiting off and continue the graph when `design.ready` fires.++**Failure Alerts**: Route `design.failed` and `quote.failed` events to a person with the resource ID.+<!-- END MANUAL -->++---