Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@ camera snapshot that the plate is empty (`agent_camera`). Every other printer,
and the A1 with the switch off, keeps the human-in-the-loop rules unchanged; see
`AGENT_RULES.md` rule 4. The same day, robot calibration was ruled out of scope:
the gateway reports object positions in bed millimetres and the arm agent owns
the transform. All printer commands go through `bambu_server.dispatch` and
the transform. On 2026-11-05 Yang approved (in a Claude Code session, recorded
in this change) a fifth verb, **`position_bed`, for the Bambu A1 only**: a
Y-only move of the bed to one of two configured positions -- `inspect`, where
the camera sees the whole plate, and `pickup`, where the arm takes parts off --
on an idle printer, under the claim, with a verified caller (an agent also
needs agent mode on) who states `bed_path_clear: true`. No X, no Z, no homing,
no caller-supplied coordinate; never retried. See `AGENT_RULES.md` rule 1. All printer commands go through `bambu_server.dispatch` and
the backend's control methods; nothing else may call `bambulabs_api` command
methods. Adding a verb, relaxing a gate, or letting an agent start a print
without a person anywhere beyond that A1 approval needs a new explicitly
Expand Down
11 changes: 10 additions & 1 deletion AGENT_RULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,16 @@ the Bambu printer gateway.
the stock start gcode's bed-mesh `M500` right after `G29` accepted -- every
other refused command still refused), and
`stop_print`, all behind `dispatch.enabled` and the gates in
`bambu_server.dispatch`. Any other verb, a relaxed gate, or integration with
`bambu_server.dispatch`. **Added 2026-11-05, approved by Yang, Bambu A1
only:** `position_bed`, which moves the bed (Y axis only, absolute `G90` /
`G1 Y.. F..`, nothing else) to a configured `inspect` or `pickup` position
(`bed_positions` on the printer, accepted by config on an A1 only). It needs
the claim, an idle printer in no error state with no job in flight, an
edge-verified caller -- an agent also needs the A1's agent mode on -- and the
caller's statement `bed_path_clear: true` that no robot arm, hand or object
is in the bed's travel or above the plate. The caller names a position,
never a coordinate; a refused or undelivered move is never retried and is
never "fixed" by homing. Any other verb, a relaxed gate, or integration with
`lab-skills` plan execution needs a new, explicitly approved design.
2. Monitoring must never start, pause, resume, stop, heat, home, move, calibrate,
upload to, or otherwise control a printer.
Expand Down
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ a printer.

By default the service is **monitoring-only** and exposes no control endpoints.
A deployment that sets `dispatch.enabled` gets a narrow control plane: claims
plus four verbs (camera snapshot, chamber light, start an approved job, stop),
plus five verbs (camera snapshot, chamber light, start an approved job, stop,
and — on the Bambu A1 only — moving the bed to a named position),
behind the gates described in [Control plane](#control-plane). A person
confirms the plate is empty before every start, except on a printer whose
**agent mode** an admin has switched on — approved 2026-11-02 for the Bambu A1
Expand Down Expand Up @@ -489,7 +490,7 @@ 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
v1.1 claims and four verbs under `/printers/{id}/control/`:
v1.1 claims and five verbs under `/printers/{id}/control/`:

| Route | What it does |
|---|---|
Expand All @@ -498,6 +499,17 @@ v1.1 claims and four verbs under `/printers/{id}/control/`:
| `light` | Switch the chamber light (`{"on": true}`), e.g. before a snapshot. No motion, no heat. |
| `start_print` | Upload an approved job's `.3mf` and start it. |
| `stop_print` | Stop the job in flight. |
| `position_bed` | Bambu A1 only (approved 2026-11-05): move the bed to `inspect` (camera sees the whole plate) or `pickup` (where the arm takes parts). |

`position_bed` takes `{"position": "inspect" | "pickup", "bed_path_clear": true}`
and moves the bed to the Y configured under the printer's `bed_positions`
(`inspect_y_mm`, `pickup_y_mm`; keep `pickup_y_mm` equal to the slicer's
`end_bed_y_mm`). It sends exactly `G90` / `G1 Y<y> F<feed>` -- no X, no Z, no
homing -- and is refused (412) unless the printer is idle, error-free and not
running a gateway job; it needs an edge-verified caller, and an agent also needs
agent mode on. Each move emits a `bed.moved` event. The printer does not report
bed position, so confirm it with a snapshot; a refused or undelivered move
(502) is never retried. Config accepts `bed_positions` on an A1 only.

`start_print` is refused (412, a body naming the failed gate) unless the printer
is observable, idle, not in a failed state and cold (`safe_bed_c`,
Expand Down
7 changes: 5 additions & 2 deletions docs/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ the routes enabled in a deployment.
| 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` |
| Printer I/O (dispatch enabled) | `POST /printers/{id}/control/snapshot`, `/light`, `/start_print`, `/stop_print`, `/position_bed` (A1 only) |
| 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` |
Expand Down Expand Up @@ -101,7 +101,10 @@ not establish a filament-to-slot mapping or sufficient remaining quantity.

Per printer, under `/printers/{id}/control/`: `claim`, `heartbeat`, `release`
(STATUS_SPEC §5), then `snapshot`, `light` (`{"on": true|false}`),
`start_print`, `stop_print`, each requiring
`start_print`, `stop_print` and, on the Bambu A1 only, `position_bed`
(`{"position": "inspect"|"pickup", "bed_path_clear": true}`: a Y-only move to a
configured position on an idle printer; verified caller, agent mode for an
agent; emits `bed.moved`; never retried), each requiring
`X-Claim-Token` (423 without it). `start_print` takes the approved
`submission_id`, `plate_confirmed_empty: true`, `plate_check_method`
(`printer_camera` with a `snapshot_token`, `in_person`, or — for an agent on a
Expand Down
6 changes: 6 additions & 0 deletions printers.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,12 @@ printers:
# (POST /printers/bambu_a1_01/agent-mode). The switch itself starts off.
# Accepted on a Bambu A1 only; any other model fails config validation.
agent_mode_eligible: true
# Named bed positions for POST /control/position_bed (approved 2026-11-05,
# A1 only): `inspect` where the camera sees the whole plate, `pickup` where
# the arm takes parts off (keep equal to the slicer's end_bed_y_mm).
# bed_positions:
# inspect_y_mm: 128
# pickup_y_mm: 250
profile:
enclosure: open
nozzle_diameter_mm: 0.4
Expand Down
1 change: 1 addition & 0 deletions src/bambu_server/agent_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"job.cancelled",
"job.cooled",
"gateway.restarted",
"bed.moved",
]

#: Terminal job state to the event announcing it.
Expand Down
22 changes: 22 additions & 0 deletions src/bambu_server/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,8 @@ def stop_print(self) -> None: ...

def set_chamber_light(self, on: bool) -> None: ...

def move_bed_y(self, y_mm: float, feed_mm_min: int) -> None: ...

def current_job_file(self) -> str | None: ...

def snapshot(self, timeout_s: float = 10.0) -> bytes: ...
Expand Down Expand Up @@ -335,6 +337,26 @@ def set_chamber_light(self, on: bool) -> None:
}
)

def move_bed_y(self, y_mm: float, feed_mm_min: int) -> None:
"""Move the Y axis only (on a bed-slinger, the bed), in absolute mode.

Exactly two gcode lines, built here from numbers: no X, no Z, no
homing, no heat, no extrusion. Approved 2026-11-05 for the A1's
``position_bed`` verb; :mod:`bambu_server.dispatch` gates every call.
"""

if not (0 <= y_mm <= 256) or not (300 <= feed_mm_min <= 6000):
raise PrinterCommandError("bed move out of range")
self._publish(
{
"print": {
"command": "gcode_line",
"param": f"G90\nG1 Y{y_mm:.1f} F{int(feed_mm_min)}\n",
"sequence_id": "10000002",
}
}
)

def current_job_file(self) -> str | None:
"""The file the printer says it is printing, from the cached telemetry."""

Expand Down
32 changes: 32 additions & 0 deletions src/bambu_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@ def validate_bed(cls, value: tuple[float, float] | None) -> tuple[float, float]
BedPlate = Literal["cool_plate", "eng_plate", "hot_plate", "textured_plate", "supertack_plate"]


class BedPositions(BaseModel):
"""Named Y positions the ``position_bed`` verb may park a bed-slinger at.

Approved by Yang on 2026-11-05 for the Bambu A1 only. The caller names a
position, never a coordinate: ``inspect`` is where the camera sees the
whole plate (for the plate check), ``pickup`` where the robot arm takes
parts off (keep it equal to the slicer's ``end_bed_y_mm``).
"""

inspect_y_mm: float = Field(ge=0, le=256)
pickup_y_mm: float = Field(ge=0, le=256)
#: Feed rate of the move, mm/min. 3000 (50 mm/s) is gentler than the
#: A1's own end-gcode park move (3600).
feed_mm_min: int = Field(default=3000, ge=300, le=6000)

def y_for(self, position: str) -> float:
return self.inspect_y_mm if position == "inspect" else self.pickup_y_mm


class PrinterDefinition(BaseModel):
id: str = Field(pattern=r"^[a-z][a-z0-9_]*$")
name: str = Field(min_length=1, max_length=120)
Expand All @@ -120,6 +139,9 @@ class PrinterDefinition(BaseModel):
#: Whether an admin may switch agent mode on for this printer at runtime.
#: Approved 2026-11-02 for the Bambu A1 only; refused on any other model.
agent_mode_eligible: bool = False
#: Named bed positions for ``position_bed`` (approved 2026-11-05 for the
#: Bambu A1 only). Absent means the verb is refused on this printer.
bed_positions: BedPositions | None = None

@field_validator("id", "name", "model", "env_prefix", mode="before")
@classmethod
Expand All @@ -134,6 +156,16 @@ def agent_mode_only_on_a1(self) -> PrinterDefinition:
raise ValueError(
f"agent_mode_eligible is approved for Bambu A1 printers only, not {self.model!r}"
)
if self.bed_positions is not None and not model_is_agent_mode_capable(self.model):
raise ValueError(
f"bed_positions (position_bed) is approved for Bambu A1 printers only, "
f"not {self.model!r}"
)
bed = self.profile.bed_size_mm
if self.bed_positions is not None and bed is not None:
for name in ("inspect_y_mm", "pickup_y_mm"):
if getattr(self.bed_positions, name) > bed[1]:
raise ValueError(f"bed_positions.{name} is beyond the {bed[1]:g} mm bed")
return self


Expand Down
149 changes: 149 additions & 0 deletions src/bambu_server/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
step that ends without the printer settling the question is ``failed`` with
the uncertainty written down. Nothing here retries.

``position_bed`` (approved by Yang on 2026-11-05, Bambu A1 only) moves the bed
between two configured Y positions -- ``inspect`` so the camera sees the whole
plate, ``pickup`` for the robot arm -- on an idle printer, under the claim, with
the caller's affirmative statement that nothing is in the bed's path. It is a
Y-only move: no X, no Z, no homing.

Refusals never touch ``last_error`` (STATUS_SPEC §6.3).
"""

Expand Down Expand Up @@ -114,6 +120,32 @@ class LightResponse(BaseModel):
note: str = "command delivered; the printer's light_state in /status confirms it"


BedPosition = Literal["inspect", "pickup"]


class PositionBedRequest(BaseModel):
position: BedPosition
#: Must be literally true: the caller states that no robot arm, hand or
#: object is in the bed's travel or standing above the plate.
bed_path_clear: Literal[True]
moved_by: str | None = Field(default=None, min_length=1, max_length=120)
reason: str | None = Field(default=None, max_length=500)


class PositionBedResponse(BaseModel):
printer_id: str
position: BedPosition
y_mm: float
requested_at: datetime
moved_by: str
moved_by_verified: bool
agent_id: str | None = None
note: str = (
"command delivered; the printer does not report bed position, so confirm "
"it with a camera snapshot before relying on it"
)


class StopPrintResponse(BaseModel):
printer_id: str
stop_requested_at: datetime
Expand Down Expand Up @@ -215,12 +247,59 @@ def light_blockers(self, monitor: PrinterMonitor) -> list[dict[str, object]]:
]
return []

def position_bed_blockers(
self, monitor: PrinterMonitor, *, busy_with_dispatch: bool
) -> list[dict[str, object]]:
"""Only an idle, error-free printer with configured positions moves its bed."""

if monitor.definition.bed_positions is None:
return [
{
"detail": "position_bed is not configured for this printer "
"(approved for the Bambu A1 only)",
"bed_positions": None,
}
]
status = monitor.status()
if status.activity == "unknown":
return [
{
"detail": "printer state is not determinable (telemetry missing or stale)",
"activity": "unknown",
"retry_after_s": 10,
}
]
blockers: list[dict[str, object]] = []
if status.activity != "idle":
blockers.append(
{"detail": "the bed only moves on an idle printer", "activity": status.activity}
)
if status.equipment_status == "error":
blockers.append(
{
"detail": "the printer reports an error; clear it on the printer first",
"equipment_status": "error",
}
)
if busy_with_dispatch:
blockers.append(
{
"detail": "the gateway is tracking a job on this printer",
"gateway_job_in_flight": True,
}
)
return blockers

def allowed_actions(self, monitor: PrinterMonitor, *, busy_with_dispatch: bool) -> list[str]:
if not self.settings.enabled:
return []
actions = ["snapshot"]
if not self.light_blockers(monitor):
actions.append("light")
if monitor.definition.bed_positions is not None and not self.position_bed_blockers(
monitor, busy_with_dispatch=busy_with_dispatch
):
actions.append("position_bed")
if not self.start_print_blockers(monitor, busy_with_dispatch=busy_with_dispatch):
actions.append("start_print")
if not self.stop_print_blockers(monitor):
Expand Down Expand Up @@ -709,6 +788,76 @@ async def light(
raise ControlRefusal(502, {"detail": f"light command not delivered: {exc}"}) from exc
return LightResponse(printer_id=printer_id, on=request.on, requested_at=datetime.now(UTC))

# -- position_bed --------------------------------------------------------

async def position_bed(
self,
printer_id: str,
request: PositionBedRequest,
*,
actor: Actor,
agent: AgentCaller,
claim_token: str | None,
) -> PositionBedResponse:
"""Move the bed to a named position. Never retried; never homes."""

control = self._control(printer_id)
self.require_claim(printer_id, claim_token)
monitor = self._monitors[printer_id]
positions = monitor.definition.bed_positions
if positions is None:
raise ControlRefusal(
412, self.gate.position_bed_blockers(monitor, busy_with_dispatch=False)[0]
)
who, verified = self._identity(actor, request.moved_by)
if self.settings.require_verified_identity and not verified:
raise ControlRefusal(
403, {"detail": "moving the bed requires an edge-verified identity"}
)
if agent.is_agent:
if self._agent_mode is None:
raise ControlRefusal(
403, {"detail": "agent bed moves are not available", "agent_mode": "not_eligible"}
)
try:
self._agent_mode.require(printer_id, "bed move")
except AgentModeRefusal as exc:
raise ControlRefusal(exc.status, exc.body) from exc
if control.lock.locked():
raise ControlRefusal(
412, {"detail": "another control step is in progress on this printer"}
)
async with control.lock:
blockers = self.gate.position_bed_blockers(
monitor, busy_with_dispatch=self.busy(printer_id)
)
if blockers:
raise ControlRefusal(412, {**blockers[0], "blockers": blockers})
y_mm = positions.y_for(request.position)
try:
await asyncio.to_thread(
self._backends[printer_id].move_bed_y, y_mm, positions.feed_mm_min
)
except PrinterCommandError as exc:
raise ControlRefusal(
502, {"detail": f"bed move not delivered: {exc}; check the printer, do not retry"}
) from exc
logger.info(
"Bed on %s moved to %s (Y%.1f) by %s%s%s",
printer_id, request.position, y_mm, who,
" (verified identity)" if verified else "",
f" as agent {agent.agent_id}" if agent.is_agent else "",
)
return PositionBedResponse(
printer_id=printer_id,
position=request.position,
y_mm=y_mm,
requested_at=datetime.now(UTC),
moved_by=who,
moved_by_verified=verified,
agent_id=agent.agent_id if agent.is_agent else None,
)

# -- helpers -----------------------------------------------------------

def _identity(self, actor: Actor, supplied: str | None) -> tuple[str, bool]:
Expand Down
9 changes: 9 additions & 0 deletions src/bambu_server/docs/AGENT_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,15 @@ stop command for a running print.
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.
On the A1 the previous print leaves the bed parked forward for pickup,
where the camera cannot see the front of the plate. Before the snapshot,
move it into view: `POST /printers/bambu_a1_01/control/position_bed` with
`{"position": "inspect", "bed_path_clear": true}`. Send
`bed_path_clear: true` only after confirming the robot arm is parked clear
of the bed's travel and nothing stands above the plate. If the move is
refused or returns 502, stop and ask a person; never retry it. For pickup,
`{"position": "pickup", ...}` returns the bed to where the arm expects it
(`bed_park_y_mm` on `pickup-targets`).
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,
Expand Down
Loading
Loading