diff --git a/README.md b/README.md index f5df2cb..9914006 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,19 @@ artifact on the gateway's disk. Filing a record in the ELN is optional and goes only through the central dashboard's ingest ([Print records and ELN ingest](#print-records-and-eln-ingest)); the gateway never writes to the ELN. +## Documentation for agents + +Read the [operating guide](src/bambu_server/docs/AGENT_GUIDE.md) for identity, +A1 agent mode, slicing/submission, claimed-camera decisions, external-spool +mapping, completion and recovery. The [API overview](docs/API_REFERENCE.md) +summarizes the endpoint families. + +The service serves `/agent-docs`, `/agent-docs/api-reference` (generated from +its actual OpenAPI), `/llms.txt`, and the JSON `/docs/agent` guide. All are +credential-free documentation reads without printer I/O. Swagger at `/docs` +is read-only. Dashboard registration belongs on the shared `bambu_gateway` +entry; deploy these routes before enabling the new registry links. + ## Architecture ```text @@ -424,14 +437,36 @@ a *record*, not an action: it marks the job `approved` and sets ### STL slicing With `slicer.enabled`, `POST /submissions` also takes an `.stl` for any printer -listed under `slicer.machine_profiles`, plus a `material` listed under -`slicer.filament_profiles`. The gateway runs the installed Bambu Studio CLI +listed under `slicer.machine_profiles`, plus a configured `material`. Each +printer may name its own machine, process and filament presets; a bare machine +name retains the shared process/filament defaults. An explicit per-printer +filament map replaces those defaults. Presets with a `compatible_printers` +list must include the selected machine, including inherited restrictions. +The gateway runs the installed Bambu Studio CLI headlessly in a scratch directory, forcing two machine facts the stock presets get wrong: the nozzle type the printer reports and the build plate declared in its profile. The resulting `.3mf` is then validated and queued like any other upload, and the job carries `provenance` (source mesh hash, presets, slicer version). Slicing runs inline in the request. +For A1 server-side PLA slicing, add the following alongside existing printer +entries under `slicer.machine_profiles` in the local configuration: + +```yaml +bambu_a1_01: + machine: Bambu Lab A1 0.4 nozzle + process: 0.20mm Standard @BBL A1 + filaments: + PLA: Generic PLA @BBL A1 +``` + +Agents upload multipart fields `file=design.stl`, +`target_machine=bambu_a1_01`, and `material=PLA` to `POST /submissions` +through the authenticated edge with their own API key and `X-Agent-Id`. +A1 agent mode must be on. There is no separate `/slice` endpoint. HTTP 201 +returns a stored submission; inspect its validation and state before approval. +Slicing and submission do not claim, upload to, or start the physical printer. + ### Control plane Off unless `dispatch.enabled` is set. When on, each printer gets STATUS_SPEC diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 07891bf..788d70f 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -6,6 +6,39 @@ The dashboard also publishes the live schema through `/api/equipment/bambu_gateway/documentation/openapi.json` and a read-only Swagger viewer at `/api/equipment/bambu_gateway/documentation/docs`. +The served [agent guide](../src/bambu_server/docs/AGENT_GUIDE.md) is available +at `/agent-docs`; `/agent-docs/api-reference` generates the full method/path, +parameter, request, response and shared-schema reference from the running +app's OpenAPI. `/llms.txt` indexes the documentation, and `/docs/agent` exposes +the service-level JSON guide for SDK discovery as `bambu_gateway`. The +dashboard registers these under the same documentation proxy prefix above. +Swagger is read-only; the documentation proxy cannot execute commands. + +## Endpoint summary + +All paths are relative to the gateway. `{id}` denotes a printer or submission +ID as indicated by the prefix. The generated reference is authoritative for +the routes enabled in a deployment. + +| Purpose | Methods and paths | +|---|---| +| Discovery and health | `GET /`, `/health`, `/status`, `/whoami`, `/printers` | +| Per-printer reads | `GET /printers/{id}/`, `/health`, `/status`, `/profile`, `/queue` | +| Submit and review | `POST /submissions`; `GET /submissions`, `/submissions/{id}`; `POST /submissions/{id}/approve`, `/cancel` | +| Claims (dispatch enabled) | `POST /printers/{id}/control/claim`, `/heartbeat`, `/release` | +| Printer I/O (dispatch enabled) | `POST /printers/{id}/control/snapshot`, `/light`, `/start_print`, `/stop_print` | +| View-only camera (dispatch enabled) | `GET /printers/{id}/camera.jpg` | +| Agent switch | `GET /printers/{id}/agent-mode`; `POST` on that path is admin-only, never agent-operated | +| Completion and pickup | `GET /events`, `/submissions/{id}/objects`, `/submissions/{id}/pickup-targets` | +| Durable records | `GET /submissions/{id}/artifact`, `/result`, `/plate.jpg`; `DELETE /submissions/{id}` for terminal-job housekeeping | +| Optional ELN delivery | `GET` / `POST /submissions/{id}/eln-ingest`; `GET /results/outbox` | +| Optional vision advisory | `POST /printers/{id}/bed-check` (dispatch and vision enabled) | +| Documentation | `GET /docs`, `/openapi.json`, `/agent-docs`, `/agent-docs/api-reference`, `/docs/agent`, `/llms.txt` | + +Agents use the SDK for printer I/O. An occupied or unclear claimed snapshot +means release the claim and stop; never send a start request to test the gate. +Failed or uncertain dispatches require human reconciliation, without retries. + ## Printer inventory `GET /printers` discovers configured printers. For each ID: @@ -26,9 +59,10 @@ chamber camera frame (`image/jpeg`, `Cache-Control: no-store`, capture time in `X-Captured-At`) without a claim. It is the one read that touches the printer: the camera is read at most once per printer every 2 s and the frame is shared by all callers; 503 when the camera does not deliver one. A frame from here is -never plate-check evidence: a camera `start_print` records its own frame under -the claim (a fresh capture when no `snapshot_token` is sent, or a -`/control/snapshot` taken under the claim within 5 minutes). +never plate-check evidence. A person's camera `start_print` records a fresh +frame when no `snapshot_token` is sent, or uses a claimed `/control/snapshot` +no older than 5 minutes. An agent must supply its own claimed snapshot and +visual decision; the agent age limit is normally 120 seconds. | Tray field | Meaning | |---|---| @@ -70,8 +104,8 @@ printer in agent mode — `agent_camera`), and an `ams_mapping` of `{filament_id, ams_id, tray_id}`. Refusals are 412 with a body naming the failed gate; `allowed_actions` on `/status` mirrors them, and `details.claimed_by` names the holder. `GET /submissions/{id}/plate.jpg` returns -the camera frame a start was confirmed against. Without dispatch enabled none -of these paths exist. +the camera frame a start was confirmed against. Without dispatch enabled the +control routes are absent; the stored plate-evidence route remains registered. **Camera snapshot for a plate check.** `POST /printers/{id}/control/snapshot` with the claim token returns `{token, printer_id, captured_at, sha256, diff --git a/printers.example.yaml b/printers.example.yaml index ac83ab3..bed14f7 100644 --- a/printers.example.yaml +++ b/printers.example.yaml @@ -65,11 +65,23 @@ slicer: profiles_dir: /home/you/.local/opt/bambu-studio/squashfs-root/resources/profiles/BBL work_dir: var/slicer timeout_s: 600 + # Defaults for a printer that does not name its own process or filaments. process_profile: "0.20mm Standard @BBL X1C" filament_profiles: # material a submitter names -> filament preset PLA: "Bambu PLA Basic @BBL X1C" - machine_profiles: # printer id -> machine preset; others refuse .stl + # Printer id -> its presets; a printer not listed refuses .stl. A bare string + # is the machine preset alone, with the defaults above. A printer whose + # motion differs from the defaults' (an A1 bed-slinger against X1C presets) + # names its own `process` and `filaments`; its `filaments` replace the + # defaults rather than adding to them. A bundled preset that lists + # `compatible_printers` must list this machine, or slicing is refused. + machine_profiles: bambu_x1c_01: "Bambu Lab X1 Carbon 0.4 nozzle" + # bambu_a1_01: + # machine: "Bambu Lab A1 0.4 nozzle" + # process: "0.20mm Standard @BBL A1" + # filaments: + # PLA: "Bambu PLA Basic @BBL A1" printers: - id: bambu_x1c_01 diff --git a/pyproject.toml b/pyproject.toml index 35fdacf..8c1e90e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -41,7 +41,7 @@ where = ["src"] # The submission page ships with the package so a non-editable install serves # /ui too, not just a checkout-based deploy. [tool.setuptools.package-data] -bambu_server = ["static/*.html"] +bambu_server = ["static/*.html", "docs/*.md"] [tool.pytest.ini_options] asyncio_mode = "auto" diff --git a/src/bambu_server/config.py b/src/bambu_server/config.py index bddc486..e1449db 100644 --- a/src/bambu_server/config.py +++ b/src/bambu_server/config.py @@ -240,6 +240,33 @@ class ResultsSettings(BaseModel): worker_tick_s: float = Field(default=2.0, ge=0.05, le=60) +def _upper_material_keys(value: Any) -> Any: + if isinstance(value, dict): + return {str(key).strip().upper(): preset for key, preset in value.items()} + return value + + +class SlicerPrinterPresets(BaseModel): + """The presets one printer slices with. + + Only ``machine`` is required. ``process`` and ``filaments`` fall back to the + gateway-wide ``process_profile`` and ``filament_profiles`` when omitted; + a printer whose kinematics differ from those defaults (an A1 against X1C + presets) must name its own. A ``filaments`` map *replaces* the defaults + rather than extending them, so a material the printer does not list is + refused instead of being sliced with another machine's preset. + """ + + machine: str = Field(min_length=1) + process: str | None = Field(default=None, min_length=1) + filaments: dict[str, str] | None = None + + @field_validator("filaments", mode="before") + @classmethod + def upper_keys(cls, value: Any) -> Any: + return _upper_material_keys(value) + + class SlicerSettings(BaseModel): """Bambu Studio CLI slicing of an uploaded ``.stl``. @@ -255,25 +282,51 @@ class SlicerSettings(BaseModel): profiles_dir: Path | None = None work_dir: Path = Path("var/slicer") timeout_s: float = Field(default=600.0, ge=30, le=3600) - #: The process preset applied to every slice. One, deliberately: the - #: submitter picks a material, not a print profile. + #: The default process preset, for a printer that does not name its own. + #: One per printer, deliberately: the submitter picks a material, not a + #: print profile. process_profile: str = "0.20mm Standard @BBL X1C" - #: Material name (as the submitter types it, upper-cased) to the filament - #: preset to slice with. A material with no entry cannot be sliced here. + #: Default material name (as the submitter types it, upper-cased) to the + #: filament preset to slice with, for a printer that does not name its own. + #: A material with no entry cannot be sliced here. filament_profiles: dict[str, str] = Field(default_factory=dict) - #: Printer id to the machine preset for it (e.g. "Bambu Lab P1S 0.4 nozzle"). + #: Printer id to its presets. A bare string is the machine preset alone + #: (e.g. "Bambu Lab P1S 0.4 nozzle"), with the defaults above. #: A printer with no entry does not accept ``.stl`` uploads. - machine_profiles: dict[str, str] = Field(default_factory=dict) + machine_profiles: dict[str, SlicerPrinterPresets] = Field(default_factory=dict) #: Ceiling on an uploaded mesh. max_stl_bytes: int = Field(default=100 * 1024 * 1024, ge=1024) @field_validator("filament_profiles", mode="before") @classmethod def upper_keys(cls, value: Any) -> Any: + return _upper_material_keys(value) + + @field_validator("machine_profiles", mode="before") + @classmethod + def accept_bare_machine(cls, value: Any) -> Any: if isinstance(value, dict): - return {str(key).strip().upper(): preset for key, preset in value.items()} + return { + printer_id: {"machine": presets} if isinstance(presets, str) else presets + for printer_id, presets in value.items() + } return value + def presets_for(self, printer_id: str) -> SlicerPrinterPresets | None: + return self.machine_profiles.get(printer_id) + + def process_for(self, printer_id: str) -> str: + presets = self.presets_for(printer_id) + if presets is not None and presets.process is not None: + return presets.process + return self.process_profile + + def filaments_for(self, printer_id: str) -> dict[str, str]: + presets = self.presets_for(printer_id) + if presets is not None and presets.filaments is not None: + return presets.filaments + return self.filament_profiles + class Settings(BaseModel): printers: list[PrinterDefinition] = Field(min_length=1) diff --git a/src/bambu_server/docs/AGENT_GUIDE.md b/src/bambu_server/docs/AGENT_GUIDE.md new file mode 100644 index 0000000..8cb3995 --- /dev/null +++ b/src/bambu_server/docs/AGENT_GUIDE.md @@ -0,0 +1,196 @@ +# Bambu gateway: operating guide for agents + +This gateway monitors multiple Bambu printers and, where enabled, provides +claimed camera snapshots, chamber-light control, print starts and print stops. +Each printer's primary operation is printing a job; the aggregate gateway +has no physical operation of its own. It does not home, jog, heat on demand, +calibrate a robot or move a robot. Monitoring never starts or stops a print. + +[API reference]({{root}}agent-docs/api-reference) · +[OpenAPI]({{root}}openapi.json) · [Read-only Swagger]({{root}}docs) · +[Documentation index]({{root}}llms.txt) + +The binding lab contract is `ac-organic-lab/docs/AGENTIC_LAB_DESIGN.md`, Part I; +the wire contract is `ac-organic-lab/docs/STATUS_SPEC.md`; printer-specific +approvals are in `bambu-server/AGENT_RULES.md`. Documentation is not permission +to execute hardware actions. Agents respect live claims and preconditions and +never bypass a refusal. Registration in the lab plan executor is a separate +approval; these endpoints do not add it. + +**How printer I/O is routed.** `lab-skills` has no Bambu skill yet. Until it +does, the lab rules (`AGENTIC_LAB_DESIGN.md` §1.3, *Bambu A1 agent mode*) +allow exactly one route: the A1 agent-mode workflow below, called directly on +this gateway's HTTP API through the authenticated edge. No other printer may +be driven by an agent, and nothing beyond that workflow is allowed on the A1. +When a Bambu skill lands in `lab-skills`, this exemption ends and the same +steps go through the SDK. + +## Find the printer and establish identity + +Paths below are relative to the gateway. In a signed-in browser, the gateway +is mounted at `/bambu`. The dashboard's `/api/equipment/{id}/documentation/` +surface only reads registered documents; it cannot proxy status or control. +For the dashboard assistant's SDK documentation discovery, request +`bambu_gateway`: the JSON guide describes the whole service, not one printer. + +1. `GET /printers` returns configured IDs and their status paths. +2. Read `/printers/{id}/status`, `/profile` and `/queue`. The gateway's bare + `/status` is an aggregate of monitor connectivity, not permission to print. +3. `GET /whoami` must identify the intended account as verified before approval + or starting. Use an approved automation API key through the authenticated + edge, with `X-Agent-Id` on every agent request. An arbitrary client-supplied + name is an unverified label, not authentication. Never use another person's + session or manufacture edge identity headers. +4. Read `/printers/{id}/agent-mode`. Eligibility is static configuration; + `enabled` is the audited admin switch. Only the approved Bambu A1 workflow + (`bambu_a1_01`) may use agent submission, approval and autonomous plate checks. + H2D and P1S keep their human-in-the-loop rules. An agent cannot flip the + switch, even if its request carries an admin role. + +The edge verifies credentials and supplies identity; the gateway verifies the +edge's shared secret. The shared secret is not an agent credential. Some edge +deployments report an automation account using the legacy `user` role, so an +agent must still declare `X-Agent-Id`. Never infer authorization from that role +alone. Printer credentials, addresses, serials and raw MQTT are never public API +data and must not be included in prompts, submissions or logs. + +## Slice, submit and approve + +Prepare a sliced `.3mf` for the actual printer, nozzle, declared plate and +loaded material. Upload it through `POST /submissions` with `target_machine`; +the endpoint also accepts `.gcode` for inspection. Dispatch requires a sliced +`.3mf`. STL intake is available only when the deployment has enabled slicing +and configured that target's presets; it also requires `material`. Do not +assume that enabled A1 agent mode implies that A1 STL slicing is configured. + +For server-side A1 slicing where configured, send multipart fields `file` +(the STL), `target_machine=bambu_a1_01`, and `material=PLA` to +`POST /submissions`, using your own API key and `X-Agent-Id`. There is no +separate `/slice` route. The request runs Bambu Studio on the server and +returns the validated, stored sliced `.3mf` submission with source hash and +preset provenance. Allow time for slicing; it is synchronous with the upload +request. It does not send any printer command. The server selects the target's +presets, so callers cannot silently use P1S process settings for an A1. + +An agent may instead slice locally with Bambu Studio and submit the result. +Use A1 machine, process and filament presets for an A1; P1S/X1C process settings +are not substitutes. Check the validation verdict returned by submission. +HTTP 201 acknowledges a stored job; its state can still be `rejected`. +The gcode scan is a heuristic, not a proof of safety; review unavailable checks. + +`POST /submissions/{submission_id}/approve` records approval. Agents may approve +only while A1 agent mode is enabled. Approval neither selects a filament tray +nor starts the printer. Submission IDs are 32 lowercase hexadecimal characters. +Use `POST .../cancel` to withdraw a queued/approved job; cancellation is not a +stop command for a running print. + +## Claim, inspect the plate and start once + +1. Acquire `/printers/{id}/control/claim` (see *How printer I/O is routed*) and keep the claim + alive with `heartbeat`. Send its `X-Claim-Token` on every control request. + Never take over another session's claim; release yours on exit. +2. Read the printer's status and `allowed_actions`. These are current device + preconditions, not a complete job-specific authorization. A listed + `start_print` does not mean that the build plate is clear. +3. Take `POST /printers/{id}/control/snapshot` under that claim. Inspect the + returned image itself and retain its token. If an object is present, the + plate is obscured, or the image is unclear, record occupied/unknown, + release the claim and stop. Do not send a start request to test a known + occupied plate. Ask a person to inspect/remove the object, then obtain + fresh evidence before any later attempt. +4. Only after a clear decision, call `/printers/{id}/control/start_print` with the + approved submission, `plate_check_method: agent_camera`, that snapshot + token, an affirmative empty-plate decision, its rationale, and an explicit + mapping for every filament. The snapshot must be from the same printer and + claim, normally no older than 120 seconds (deployment-configurable). +5. Inspect the returned job state. A successful HTTP response can carry a + failed job if running could not be confirmed. Never automatically repeat + a failed, timed-out, disconnected or uncertain dispatch. Preserve the + evidence and ask a person to reconcile the printer first. + +The gateway still requires a reachable, observable, idle, cold printer; a +declared matching build plate; successful artifact revalidation; suitable +loaded material; verified approver/caller where configured; and a live claim. +One dispatch attempt is allowed per job. It archives the camera frame and +SHA-256 with the deciding agent, identity and rationale. + +`GET /printers/{id}/camera.jpg` is view-only: it reads the camera at most once +per printer every two seconds and shares the frame across viewers. It is off +on page load and is never plate-check evidence. H2D camera capture is not +supported by this gateway; its human plate check must be in person. +The optional `/bed-check` compares an existing claimed snapshot with an +operator reference. Its output is advisory and never substitutes for the +agent's own visual decision. + +## External spool and color labels + +An AMS assignment uses the observed `(ams_id, tray_id)` pair. For a +single-filament job on a printer without an AMS, the external spool is +`ams_id: 254`, `tray_id: 0`. Inspect `status.details.external_spool` or +`profile.observed.loaded_trays`; do not guess a tray from MQTT slot numbers. +Map the slicer's actual `filament_id`, not an assumed index. + +Material comes from `tray_type`. A human correction such as **PLA · White** +can appear as `tray_color_name: White`, `tray_color_source: operator_declared`, +while `tray_color` still retains a different printer-reported code. This is +an explicit display-label correction, not a telemetry rewrite or proof of +spool brand/identity. The declaration is matched against slot, material and +reported color and can cease to apply after a spool change. Remaining material +is an estimate or unknown; approval does not prove sufficient quantity. + +## Observe completion, cooling and records + +Use the job record and `/events?after=` for lifecycle changes. +`job.started` is not completion; wait for `job.finished` or a terminal failure. +Event IDs persist across restarts. Save the event cursor; do not turn event +delivery into an automatic command retry. + +For pickup, wait for `job.cooled` or read `/submissions/{id}/pickup-targets`. +Its `ready` requires a finished job, a cooled bed and reported object positions. +Temperature alone does not establish safe robot clearance, part release or +graspability. Objects are in bed millimetres, origin front-left, +X right, ++Y back, Z up. The arm agent owns its calibration and transform; the gateway +never commands the arm. Unknown positions are an empty list, never a guess. + +`/submissions/{id}/artifact` returns the exact stored bytes and SHA-256 ETag. +`/result` returns the durable versioned bundle; `final: false` means the job is +still in progress. The final bundle survives deletion of the submission record. +The start evidence, when available, is at `/submissions/{id}/plate.jpg`. + +ELN delivery is optional and goes through central ingest. Check +`results_ingest_configured` and the outbox state. `local_only` is not proof +of ELN filing; `delivered` and `filing` are not `filed`. Do not configure +credentials or claim that a record was filed merely to complete a workflow. + +## Health, refusals and recovery + +Status/profile/queue/result reads use cached or stored data, without printer +I/O. The view-only camera is the documented exception. An unreachable or stale +printer is `unknown`, not `error`; a reachable failed print reports `error` +with `last_error.code: print_failed`. `activity` separately reports `idle`, +`running` or `unknown`. Readiness does not prove a clear bed. + +| Response | Meaning and response by the agent | +|---|---| +| 401 | Login or claim heartbeat was lost. Stop using that claim. | +| 403 | Identity/admin requirement or agent mode refused the action. Do not impersonate a person or flip the switch. | +| 404 | Unknown job/printer/resource, or a route disabled in this deployment. Inspect OpenAPI. | +| 409 | Claim/job state conflict or ineligible admin toggle. Respect the holder/state. | +| 412 | A dispatch precondition failed; the body names the gate, and may include Retry-After. Do not change parameters to evade it. | +| 423 | Missing, stale or wrong claim token on a hard-enforced control action. | +| 422 | Invalid request or failed slicing; inspect the response. | +| 501 | Unsupported snapshot model, including H2D. | +| 502 / 503 | Camera/upstream failure or a service component unavailable. A failed camera check is not a clear plate. | + +Refusal envelopes can carry gate-specific fields alongside `detail`; FastAPI +request validation uses its standard structured `detail` list. OpenAPI names +the operation's declared responses. A precondition refusal is not a printer +fault and must not be treated as evidence that a physical action occurred. + +Background monitoring reconnects independently of HTTP reads. Gateway shutdown +does not stop the physical printer. A restart loses active claims and can +record an interrupted dispatch as failed/uncertain; it never authorizes replay. +Cooldown event watching does not resume after restart, so poll pickup readiness. +Turning agent mode off blocks subsequent agent submissions, approvals and +starts; it does not stop an already-running print. Operator inspection resolves +ambiguous outcomes; never home or move the bed as a recovery step. diff --git a/src/bambu_server/documentation.py b/src/bambu_server/documentation.py new file mode 100644 index 0000000..7b52026 --- /dev/null +++ b/src/bambu_server/documentation.py @@ -0,0 +1,146 @@ +"""Credential-free documentation, generated without monitor or printer access.""" + +from __future__ import annotations + +import json +from importlib.resources import files +from typing import Any + +from fastapi import FastAPI, Request, Response +from fastapi.responses import PlainTextResponse +from pydantic import BaseModel, ConfigDict + + +class RefusalBody(BaseModel): + """A gateway refusal; additional fields identify the gate that refused it.""" + + model_config = ConfigDict(extra="allow") + detail: str + + +def guide(root: str = "") -> str: + return ( + files("bambu_server") + .joinpath("docs", "AGENT_GUIDE.md") + .read_text(encoding="utf-8") + .replace("{{root}}", root) + ) + + +def operations(schema: dict[str, Any]) -> list[dict[str, Any]]: + return [ + {"method": method.upper(), "path": path, **operation} + for path, item in sorted(schema["paths"].items()) + for method, operation in item.items() + if method in {"get", "post", "put", "patch", "delete", "options", "head"} + ] + + +def api_reference(schema: dict[str, Any], root: str = "../") -> str: + """Render routes and schemas from this app's actual OpenAPI document.""" + lines = [ + "# Bambu gateway API reference", + "", + "Generated from this service's OpenAPI; only registered routes appear.", + "", + f"[Operating guide]({root}agent-docs) · [OpenAPI JSON]({root}openapi.json) · " + f"[Read-only Swagger]({root}docs)", + "", + "Paths are relative to the gateway. Browser clients use the authenticated `/bambu` " + "edge prefix. The dashboard documentation proxy is read-only and cannot execute " + "these operations. lab-skills has no Bambu skill yet; until it does, agents may " + "drive only the A1 agent-mode workflow here, as the operating guide describes.", + "", + "## Endpoints", + "", + "| Method | Path | Summary |", + "|---|---|---|", + ] + entries = operations(schema) + for entry in entries: + summary = entry.get("summary", "").replace("|", "\\|").replace("\n", " ") + lines.append(f"| {entry['method']} | `{entry['path']}` | {summary} |") + for entry in entries: + lines += ["", f"## {entry['method']} {entry['path']}", ""] + if entry.get("description"): + lines += [entry["description"], ""] + # Reproduce the declared operation schema rather than maintaining a + # second copy of parameter, request, response and refusal definitions. + contract = {k: entry[k] for k in ("parameters", "requestBody", "responses") if k in entry} + lines += ["```json", json.dumps(contract, indent=2), "```"] + lines += [ + "", + "## Shared schemas", + "", + "```json", + json.dumps(schema.get("components", {}).get("schemas", {}), indent=2), + "```", + "", + ] + return "\n".join(lines) + + +def register_documentation(app: FastAPI) -> None: + markdown = {200: {"content": {"text/markdown": {}}, "description": "Agent-readable Markdown."}} + headers = {"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"} + + @app.get("/agent-docs/", response_class=Response, include_in_schema=False) + @app.get("/agent-docs", response_class=Response, responses=markdown, tags=["documentation"]) + async def agent_guide(request: Request) -> Response: + """Operating guide: authentication, claims, A1 agent mode, evidence and recovery.""" + root = "../" if request.url.path.endswith("/") else "" + return Response(guide(root), media_type="text/markdown", headers=headers) + + @app.get("/agent-docs/api-reference/", response_class=Response, include_in_schema=False) + @app.get( + "/agent-docs/api-reference", + response_class=Response, + responses=markdown, + tags=["documentation"], + ) + async def generated_reference(request: Request) -> Response: + """Routes, request/response schemas and declared refusals from the running app.""" + root = "../../" if request.url.path.endswith("/") else "../" + return Response( + api_reference(app.openapi(), root), media_type="text/markdown", headers=headers + ) + + @app.get("/llms.txt", response_class=PlainTextResponse, tags=["documentation"]) + async def documentation_index() -> PlainTextResponse: + """Documentation index; links retain direct, edge and dashboard proxy prefixes.""" + return PlainTextResponse( + "# Bambu printer gateway\n\n" + "A multi-printer STATUS_SPEC gateway with optional, claimed print control.\n" + "Documentation does not authorize hardware execution.\n\n" + "## Documentation\n\n" + "- [Agent operating guide](agent-docs)\n" + "- [API reference](agent-docs/api-reference)\n" + "- [OpenAPI](openapi.json)\n" + "- [Read-only Swagger](docs)\n" + "- [Machine-readable gateway guide](docs/agent)\n\n" + "Discover printers using GET /printers on the authenticated gateway; " + "the dashboard documentation proxy does not proxy live status or control.\n", + headers=headers, + ) + + @app.get("/docs/agent", tags=["documentation"]) + async def machine_guide() -> dict[str, Any]: + """Service-level guide for SDK discover_device_guide on bambu_gateway.""" + return { + "documentation_version": "1.0", + "equipment_id": "bambu_gateway", + "equipment_kind": "other", + "scope": "Shared gateway; enumerate printers with GET /printers. " + "Retrieve this guide using the bambu_gateway equipment entry.", + "guide_markdown": guide("../"), + "discovery": { + "guide": "../agent-docs", + "openapi": "../openapi.json", + "api_reference": "../agent-docs/api-reference", + "index": "../llms.txt", + }, + "endpoints": [ + {k: entry.get(k) for k in ("method", "path", "summary")} + for entry in operations(app.openapi()) + ], + } diff --git a/src/bambu_server/main.py b/src/bambu_server/main.py index 1a6c354..e0934d3 100644 --- a/src/bambu_server/main.py +++ b/src/bambu_server/main.py @@ -78,6 +78,7 @@ StopPrintRequest, StopPrintResponse, ) +from .documentation import RefusalBody, register_documentation from .identity import Actor, actor_for, resolve_actor from .models import ( PROTOCOL_VERSION, @@ -356,7 +357,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]: title="AC Bambu Printer Gateway", version=__version__, description=( - "Monitoring-only MQTT gateway for Bambu Lab printers. Each configured " + "MQTT monitoring gateway with optional claimed control for Bambu Lab printers. Each configured " "printer is exposed through the AC lab equipment status spec v1.2. " "Profiles expose typed AMS inventory, color-label provenance, and remaining " "filament estimates. Dispatch can be enabled locally for claimed starts after a " @@ -379,6 +380,7 @@ async def api_docs(request: Request) -> HTMLResponse: return get_swagger_ui_html( openapi_url="../openapi.json" if request.url.path.endswith("/") else "./openapi.json", title="Bambu Gateway API", + swagger_ui_parameters={"supportedSubmitMethods": []}, ) configured_origins = settings.cors_origins if settings else ["http://localhost:8000"] @@ -817,7 +819,7 @@ async def _slice_and_accept( raise HTTPException( status_code=422, detail="material is required to slice an .stl (one of: " - + ", ".join(slicer.materials()) + ")", + + ", ".join(slicer.materials(printer_id)) + ")", ) settings_ = slicer.settings job_dir = settings_.work_dir / uuid.uuid4().hex @@ -1359,6 +1361,7 @@ def get_camera() -> CameraViewer: if settings and settings.agent_workflow.vision_enabled: _register_advisory_bed_check(app, get_monitor, get_dispatcher, workflows) + register_documentation(app) return app @@ -1465,8 +1468,9 @@ def _register_control_routes( """ control_responses = { - 412: {"description": "A precondition is not met; the body names which."}, - 423: {"description": "No live claim token was presented."}, + 403: {"model": RefusalBody, "description": "Verified identity or agent mode required."}, + 412: {"model": RefusalBody, "description": "A precondition is not met; the body names which."}, + 423: {"model": RefusalBody, "description": "No live claim token was presented."}, } @app.post( @@ -1532,7 +1536,11 @@ async def control_release( @app.post( "/printers/{printer_id}/control/snapshot", response_model=SnapshotResponse, - responses={423: control_responses[423], 502: {"description": "Camera unreachable."}}, + responses={ + 423: control_responses[423], + 501: {"model": RefusalBody, "description": "Snapshot unsupported for this printer model."}, + 502: {"model": RefusalBody, "description": "Camera unreachable."}, + }, tags=["control"], ) async def control_snapshot( diff --git a/src/bambu_server/slicer.py b/src/bambu_server/slicer.py index 83f2487..45c3c69 100644 --- a/src/bambu_server/slicer.py +++ b/src/bambu_server/slicer.py @@ -92,39 +92,58 @@ def accepts(self, printer_id: str) -> bool: return self._settings.enabled and printer_id in self._settings.machine_profiles - def materials(self) -> list[str]: - return sorted(self._settings.filament_profiles) + def materials(self, printer_id: str) -> list[str]: + """The materials an ``.stl`` can be sliced in for this printer.""" + + return sorted(self._settings.filaments_for(printer_id)) def resolve_presets(self, request: SliceRequest) -> tuple[Path, Path, Path]: - """Locate the machine, process and filament preset files, or refuse.""" + """Locate the machine, process and filament preset files, or refuse. + + The process and filament presets must be made for the machine preset: + when a bundled preset lists ``compatible_printers``, the machine must be + among them. Bambu Studio's CLI does not enforce this itself, and a + process tuned for one printer's motion slices quietly wrong for another. + """ settings = self._settings if not settings.enabled: raise SlicerUnavailable("slicing is not enabled on this gateway") if settings.profiles_dir is None: raise SlicerUnavailable("the slicer's profiles directory is not configured") - machine_name = settings.machine_profiles.get(request.printer_id) - if machine_name is None: + presets = settings.presets_for(request.printer_id) + if presets is None: raise SlicerUnavailable( f"{request.printer_id} has no slicer machine preset; upload a sliced .3mf instead" ) - filament_name = settings.filament_profiles.get(request.material.strip().upper()) + machine_name = presets.machine + process_name = settings.process_for(request.printer_id) + filament_name = settings.filaments_for(request.printer_id).get( + request.material.strip().upper() + ) if filament_name is None: - offered = ", ".join(self.materials()) or "none" + offered = ", ".join(self.materials(request.printer_id)) or "none" raise SlicerError( - f"no filament preset for {request.material!r}; materials that can be sliced " - f"here: {offered}" + f"no filament preset for {request.material!r} on {request.printer_id}; " + f"materials that can be sliced for it here: {offered}" ) - for name in (machine_name, settings.process_profile, filament_name): + for name in (machine_name, process_name, filament_name): if not _PRESET_NAME_RE.match(name): raise SlicerUnavailable(f"preset name {name!r} contains characters not allowed") root = settings.profiles_dir machine = root / "machine" / f"{machine_name}.json" - process = root / "process" / f"{settings.process_profile}.json" + process = root / "process" / f"{process_name}.json" filament = root / "filament" / f"{filament_name}.json" for path in (machine, process, filament): if not path.is_file(): raise SlicerUnavailable(f"slicer preset not found: {path.name}") + for kind, path in (("process", process), ("filament", filament)): + compatible = _compatible_printers(path) + if compatible and machine_name not in compatible: + raise SlicerUnavailable( + f"{kind} preset {path.stem!r} is not made for {machine_name!r}; " + f"configure a {kind} preset for {request.printer_id}" + ) return machine, process, filament async def slice( @@ -289,6 +308,20 @@ def _flatten_preset( return merged +def _compatible_printers(preset: Path) -> list[str]: + """The machine presets a bundled preset declares itself made for. + + Empty means the preset makes no claim (a user preset, or one that relies on + ``compatible_printers_condition``), and nothing is enforced. + """ + + body = _flatten_preset(preset.parent.parent, preset.parent.name, preset.stem) + listed = body.get("compatible_printers") + if not isinstance(listed, list): + return [] + return [name for name in listed if isinstance(name, str)] + + _VERSION_RE = re.compile(r"BambuStudio Version (\S+)") diff --git a/tests/test_documentation.py b/tests/test_documentation.py new file mode 100644 index 0000000..a253253 --- /dev/null +++ b/tests/test_documentation.py @@ -0,0 +1,91 @@ +"""Documentation is public, packaged, prefix-safe and requires no printer I/O.""" + +from __future__ import annotations + +import re +from urllib.parse import urljoin + +import pytest +from fastapi.testclient import TestClient + +from bambu_server.main import create_app + + +@pytest.mark.parametrize("dispatch", [False, True]) +def test_reference_matches_enabled_schema_without_starting_hardware(settings, dispatch): + settings.dispatch = settings.dispatch.model_copy(update={"enabled": dispatch}) + + def unexpected_backend(*args): + pytest.fail("Documentation constructed a printer backend") + + app = create_app(settings=settings, backend_factory=unexpected_backend) + # No lifespan: documentation must work without a monitor, store or printer. + client = TestClient(app) + schema = client.get("/openapi.json").json() + reference = client.get("/agent-docs/api-reference") + assert reference.status_code == 200 + assert reference.headers["content-type"].startswith("text/markdown") + expected = { + (method.upper(), path) + for path, methods in schema["paths"].items() + for method in methods + if method in {"get", "post", "delete", "put", "patch", "head", "options"} + } + actual = set( + re.findall(r"^## (GET|POST|DELETE|PUT|PATCH|HEAD|OPTIONS) (\S+)$", reference.text, re.M) + ) + assert actual == expected + assert (("POST", "/printers/{printer_id}/control/start_print") in actual) == dispatch + assert ("StartPrintRequest" in reference.text) == dispatch + for secret in ("secret-access-code", "secret-serial", "printer.invalid"): + assert secret not in reference.text + + machine = client.get("/docs/agent").json() + assert machine["equipment_id"] == "bambu_gateway" + assert "agent_camera" in machine["guide_markdown"] + assert {(e["method"], e["path"]) for e in machine["endpoints"]} == expected + assert '"supportedSubmitMethods": []' in client.get("/docs").text + + +@pytest.mark.parametrize("prefix", ["", "/bambu", "/api/equipment/bambu_gateway/documentation"]) +@pytest.mark.parametrize( + "path", + [ + "/llms.txt", + "/agent-docs", + "/agent-docs/", + "/agent-docs/api-reference", + "/agent-docs/api-reference/", + ], +) +def test_document_links_keep_access_prefix(settings, prefix, path): + client = TestClient(create_app(settings=settings)) + response = client.get(path) + assert response.status_code == 200 + assert response.headers["x-content-type-options"] == "nosniff" + assert response.headers["cache-control"] == "no-store" + assert "{{root}}" not in response.text + links = re.findall(r"\]\(([^)]+)\)", response.text) + assert links + for link in links: + resolved = urljoin(f"http://gateway.test{prefix}{path}", link) + assert resolved.startswith(f"http://gateway.test{prefix}/") + local_path = resolved.removeprefix(f"http://gateway.test{prefix}") + assert client.get(local_path).status_code == 200 + + +def test_document_reads_do_not_add_printer_io(client, backend): + before = ( + backend.read_count, + backend.snapshots, + len(backend.uploads), + len(backend.start_commands), + ) + for path in ("/agent-docs", "/agent-docs/api-reference", "/llms.txt", "/docs/agent"): + assert client.get(path).status_code == 200 + assert before == ( + backend.read_count, + backend.snapshots, + len(backend.uploads), + len(backend.start_commands), + ) diff --git a/tests/test_slicer.py b/tests/test_slicer.py index 9f12558..b70f82e 100644 --- a/tests/test_slicer.py +++ b/tests/test_slicer.py @@ -20,7 +20,7 @@ from bambu_server.main import create_app from bambu_server.slicer import BambuStudioSlicer, SliceRequest, SlicerError, SlicerUnavailable -from .conftest import FakeBackend, write_3mf +from .conftest import SAMPLE_GCODE, FakeBackend, write_3mf FAKE_CLI = """#!{python} import json, shutil, sys @@ -178,6 +178,134 @@ async def test_slicing_without_a_declared_plate_is_refused( ) +def _preset(root: Path, kind: str, name: str, compatible: list[str] | None = None) -> None: + body: dict[str, object] = {"name": name} + if compatible is not None: + body["compatible_printers"] = compatible + (root / kind / f"{name}.json").write_text(json.dumps(body)) + + +def test_machine_profiles_accept_a_bare_machine_or_full_presets() -> None: + settings = SlicerSettings.model_validate( + { + "process_profile": "0.20mm Standard @BBL X1C", + "filament_profiles": {"pla": "Bambu PLA Basic @BBL X1C"}, + "machine_profiles": { + "bambu_p1s_01": "Bambu Lab P1S 0.4 nozzle", + "bambu_a1_01": { + "machine": "Bambu Lab A1 0.4 nozzle", + "process": "0.20mm Standard @BBL A1", + "filaments": {"pla": "Bambu PLA Basic @BBL A1"}, + }, + }, + } + ) + assert settings.machine_profiles["bambu_p1s_01"].machine == "Bambu Lab P1S 0.4 nozzle" + assert settings.process_for("bambu_p1s_01") == "0.20mm Standard @BBL X1C" + assert settings.filaments_for("bambu_p1s_01") == {"PLA": "Bambu PLA Basic @BBL X1C"} + assert settings.process_for("bambu_a1_01") == "0.20mm Standard @BBL A1" + assert settings.filaments_for("bambu_a1_01") == {"PLA": "Bambu PLA Basic @BBL A1"} + + +def test_a_printers_own_presets_are_used(slicer_settings: SlicerSettings) -> None: + root = slicer_settings.profiles_dir + assert root is not None + _preset(root, "machine", "Bambu Lab A1 0.4 nozzle") + _preset(root, "process", "0.20mm Standard @BBL A1", ["Bambu Lab A1 0.4 nozzle"]) + _preset(root, "filament", "Bambu PLA Basic @BBL A1", ["Bambu Lab A1 0.4 nozzle"]) + settings = slicer_settings.model_copy( + update={ + "machine_profiles": SlicerSettings.model_validate( + { + "machine_profiles": { + "bambu_test_01": "Bambu Lab Test 0.4 nozzle", + "bambu_a1_01": { + "machine": "Bambu Lab A1 0.4 nozzle", + "process": "0.20mm Standard @BBL A1", + "filaments": {"PLA": "Bambu PLA Basic @BBL A1"}, + }, + } + } + ).machine_profiles + } + ) + slicer = BambuStudioSlicer(settings) + + machine, process, filament = slicer.resolve_presets(_request(printer_id="bambu_a1_01")) + + assert (machine.stem, process.stem, filament.stem) == ( + "Bambu Lab A1 0.4 nozzle", + "0.20mm Standard @BBL A1", + "Bambu PLA Basic @BBL A1", + ) + # The printer without its own presets still slices with the defaults. + _, process, filament = slicer.resolve_presets(_request()) + assert process.stem == "0.20mm Standard @BBL X1C" + assert filament.stem == "Bambu PLA Basic @BBL Test" + + +def test_a_printers_filaments_replace_the_defaults(slicer_settings: SlicerSettings) -> None: + root = slicer_settings.profiles_dir + assert root is not None + _preset(root, "filament", "Bambu PETG Basic @BBL Test") + settings = slicer_settings.model_copy( + update={ + "filament_profiles": { + "PLA": "Bambu PLA Basic @BBL Test", + "PETG": "Bambu PETG Basic @BBL Test", + }, + "machine_profiles": SlicerSettings.model_validate( + { + "machine_profiles": { + "bambu_test_01": { + "machine": "Bambu Lab Test 0.4 nozzle", + "filaments": {"PLA": "Bambu PLA Basic @BBL Test"}, + } + } + } + ).machine_profiles, + } + ) + slicer = BambuStudioSlicer(settings) + + assert slicer.materials("bambu_test_01") == ["PLA"] + with pytest.raises(SlicerError, match="materials that can be sliced for it here: PLA$"): + slicer.resolve_presets(_request(material="PETG")) + + +@pytest.mark.parametrize("kind", ["process", "filament"]) +def test_inherited_machine_restrictions_are_checked( + slicer_settings: SlicerSettings, kind: str, +) -> None: + root = slicer_settings.profiles_dir + assert root is not None + parent = {"process": "fdm_process_test_common", "filament": "fdm_filament_test_pla"}[kind] + _preset(root, kind, parent, ["Bambu Lab X1 Carbon 0.4 nozzle"]) + with pytest.raises(SlicerUnavailable, match=f"{kind} preset .* not made for"): + BambuStudioSlicer(slicer_settings).resolve_presets(_request()) + + +@pytest.mark.parametrize("kind", ["process", "filament"]) +def test_a_preset_made_for_another_machine_is_refused( + slicer_settings: SlicerSettings, kind: str +) -> None: + root = slicer_settings.profiles_dir + assert root is not None + name = { + "process": "0.20mm Standard @BBL X1C", + "filament": "Bambu PLA Basic @BBL Test", + }[kind] + _preset(root, kind, name, ["Bambu Lab X1 Carbon 0.4 nozzle"]) + slicer = BambuStudioSlicer(slicer_settings) + + with pytest.raises(SlicerUnavailable, match=f"{kind} preset .* not made for"): + slicer.resolve_presets(_request()) + + # Listing the machine makes the same preset acceptable. + _preset(root, kind, name, ["Bambu Lab X1 Carbon 0.4 nozzle", "Bambu Lab Test 0.4 nozzle"]) + slicer.resolve_presets(_request()) + + def test_discard_stays_inside_the_work_dir(slicer_settings: SlicerSettings, tmp_path: Path) -> None: with pytest.raises(ValueError): BambuStudioSlicer(slicer_settings).discard(tmp_path) @@ -229,6 +357,63 @@ def test_an_stl_needs_a_material(slicing_client: TestClient) -> None: assert "PLA" in response.json()["detail"] +@pytest.mark.parametrize("agent_mode", [False, True]) +def test_a1_agent_stl_intake_uses_a1_presets_without_printer_commands( + settings: Settings, slicer_settings: SlicerSettings, backend: FakeBackend, + tmp_path: Path, monkeypatch, agent_mode: bool, +) -> None: + monkeypatch.setenv("BAMBU_EDGE_SHARED_SECRET", "test-edge-secret") + payload = settings.model_dump(mode="json") + printer = payload["printers"][0] + printer.update(id="bambu_a1_01", model="A1", agent_mode_eligible=True) + printer["profile"].update(plate="textured_plate", enclosure="open") + payload["dispatch"] = {"enabled": True, "require_verified_identity": True} + slicer_payload = slicer_settings.model_dump(mode="json") + machine = "Bambu Lab A1 0.4 nozzle" + process = "0.20mm Standard @BBL A1" + filament = "Generic PLA @BBL A1" + slicer_payload["machine_profiles"]["bambu_a1_01"] = { + "machine": machine, "process": process, "filaments": {"PLA": filament}, + } + payload["slicer"] = slicer_payload + root = slicer_settings.profiles_dir + _preset(root, "machine", machine) + _preset(root, "process", process, [machine]) + _preset(root, "filament", filament, [machine]) + write_3mf( + tmp_path / "template.3mf", plate_gcode=SAMPLE_GCODE.replace("X1 Carbon", "A1"), + project_settings={"printer_model": "Bambu Lab A1"}, + ) + app = create_app(settings=Settings.model_validate(payload), backend_factory=lambda _d, _c: backend) + with TestClient(app) as client: + if agent_mode: + response = client.post( + "/printers/bambu_a1_01/agent-mode", + headers={"X-Edge-Auth": "test-edge-secret", "X-Auth-User": "admin", "X-Auth-Role": "admin"}, + json={"enabled": True, "reason": "Enable fake-printer slicing test"}, + ) + assert response.status_code == 200 + response = client.post( + "/submissions", + headers={"X-Edge-Auth": "test-edge-secret", "X-Auth-User": "test-agent", "X-Auth-Role": "agent", "X-Agent-Id": "test-agent"}, + files={"file": ("coupon.stl", b"solid coupon\nendsolid\n", "model/stl")}, + data={"target_machine": "bambu_a1_01", "material": "PLA"}, + ) + if agent_mode: + assert response.status_code == 201, response.text + job = response.json() + assert job["state"] == "queued" + assert job["artifact_kind"] == "3mf" + assert job["provenance"]["machine_preset"] == machine + assert job["provenance"]["process_preset"] == process + assert job["provenance"]["filament_preset"] == filament + else: + assert response.status_code == 403, response.text + assert backend.uploads == [] + assert backend.start_commands == [] + assert backend.snapshots == 0 + + def test_stl_is_refused_where_slicing_is_off(client: TestClient) -> None: response = client.post( "/submissions",