# @printhive/api reference

Feature-by-feature reference for the `@printhive/api` client. Start with the
[quickstart](https://www.npmjs.com/package/@printhive/api) for install, API keys,
and a first print. This file ships in the package as
`node_modules/@printhive/api/docs/reference.md`.

## Embed filament management in React

`@printhive/react` puts PrintHive's filament manager inside a React app, with one import path for each feature. Its [README on npm](https://www.npmjs.com/package/@printhive/react) covers install, peer dependencies, the provider, the server handler, and styles. It lists this SDK, `^0.9.0`, as a peer dependency. Your server handler uses the SDK with your API key, and the browser uses its response guards.

For a direct integration, `client.printers.materialSlots.layout(printerId)` reads the same public view of a printer's nozzles, sources, and slots. `@printhive/api/validation` exports response guards for the layout, catalog search, assignment, clearing, and RFID receipts, so a browser can check a response without constructing an API-key client.

## Search

The client exposes `client.search.printers({ query })` and
`client.search.filaments({ query })`. Both use the same contracts as
`client.printers.search` and `client.filaments.search`.

## Create a print job

Use an API key with `control` to create and `read` to poll.

```ts
import { PrintHive } from "@printhive/api";

const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const request = await hive.printJobs.create({
  file: "/srv/designs/project.3mf",
  filename: "project.3mf",
  plate: 2,
  filaments: [{ sourceSlot: 0, material: "PETG", color: "#FF0000" }],
  printer_id: "00000000-0000-4000-8000-000000000001",
  idempotencyKey: "storefront:print-1234",
});
const created = await hive.printJobs.waitUntilCreated(request.requestId);
console.log(created.createdJobIds);
```

`printJobs.create` sends multipart to `/v1/print-jobs/create` for a file path or `Uint8Array` plus `filename`. `plate` and typed `filaments` are required; `targetSlot` is optional. Other inputs include `printer_id`, `name`, `externalId`, `release`, `acceptEngineSettingUpdates`, `allowUnqualifiedConversion`, `on_filament_mismatch`, and existing `print_options`. This method reads file paths into memory, copies byte inputs, and can retry the multipart body safely. It returns the server's `202` request fields plus `idempotencyKey`. Persist your own key before calling when retries must survive process restarts. Changed metadata or bytes with the same key conflict.

For an existing artifact, `printJobs.create({ name, model_file_id, ... })` sends JSON and returns the existing `201` response with `job` and eligibility fields plus `idempotencyKey`. The client generates an idempotency key once per call if omitted.

For a library project file, call `printJobs.openSource(modelFileId)` until its status is `ready`, then `printJobs.createFromSource({ source_version_id, plate, filaments, idempotencyKey, ... })`. The caller must retain and reuse `idempotencyKey` after a timeout or lost response. It sends JSON, takes the same optional fields as the multipart create, and returns the `202` request fields plus `idempotencyKey`. Many calls can name one source, one for each plate and printer. A source that is still `reading` is accepted. A source of another organization answers 404, a failed source answers 422 `source_inspection_failed`, and a body that also names `model_file_id` answers 400 `conflicting_source`. Repeating a key with the same body returns the same request, and a changed body conflicts.

Use `quantity` to repeat the selected plate in a source-version or multipart
create. It defaults to 1. A value above the server limit of 200 returns 422
`quantity_limit_exceeded`. Each copy is a separate job that shares the prepared
artifacts. Read `createdJobIds` after creation for all IDs in creation order.
The legacy `job` and `createdJobId` fields refer to the first job.

`printJobs.getCreateRequest(requestId)` reads the current receipt. `waitUntilCreated(requestId, { intervalMs?, timeoutMs?, signal? })` polls while `preparing`, defaults to a 120-second total deadline, and returns when `created`, including a retained receipt with `job: null` after the job was deleted. `PrintJobCreateStoppedError.request` exposes a `held`, `failed`, or `cancelled` receipt, including its required actions or failure reasons. It does not authorize a held request automatically.

### Release or cancel a creation request

`printJobs.releaseCreateRequest(requestId, signal?)` requires `control` and returns
`PrintJobCreateRequestRelease`, `{ authorized: boolean }`, after authorizing a
manual request. It does not approve other preparation holds or wait for job creation.
Poll with `getCreateRequest` or `waitUntilCreated` afterward.

`printJobs.cancelCreateRequest(requestId, signal?)` also requires `control`.
Its `PrintJobCreateRequestCancellation` result is a union keyed by `code`:

| HTTP | `code`                | Result                                                                       |
| ---- | --------------------- | ---------------------------------------------------------------------------- |
| 202  | `cancelled`           | `{ cancelled: true, status: "cancelled", code: "cancelled" }`.               |
| 200  | `already_terminal`    | Unchanged failed receipt with `status: "failed"`.                            |
| 200  | `already_cancelled`   | Unchanged cancelled receipt with `status: "cancelled"`.                      |
| 409  | `job_already_created` | Throws `PrintHiveApiError`; `body.jobId` can be null if the job was deleted. |

Narrow successful results by `code`:

```ts
const result = await hive.printJobs.cancelCreateRequest(request.requestId);
switch (result.code) {
  case "cancelled":
    console.log(result.cancelled);
    break;
  case "already_terminal":
    console.log(result.status, result.error);
    break;
  case "already_cancelled":
    console.log(result.status, result.requestId);
    break;
}
```

Both methods send an empty POST and do not automatically retry. They preserve
`PrintHiveApiError` status, code, and body. Release returns `409`
`manual_release_not_available` when another hold remains or release is unavailable.
Cancellation returns `409` `job_already_created` after admission; use the job API
to cancel an existing job. Missing or foreign requests return `404` `not_found`.
Missing authentication returns `401`; insufficient scope returns `403`.

Cancellation returns `503` `creation_unavailable` when it cannot confirm the
outcome, including a lost response after commit. Retry the same cancellation
explicitly. If the first cancellation committed, the retry returns `200`
`already_cancelled`. A `202` confirms request cancellation, not that a printer
or an external slicing process stopped.

All current partner upload and Slice job routes already have SDK methods:
`partnerSources.upload`, `partnerSources.get`, `models.findByExternalId`,
`models.listSourceFiles`, `sliceJobs.create`, `sliceJobs.get`, `sliceJobs.waitUntilSettled`,
and `sliceJobs.downloadInfo`. They send `POST /v1/slice-jobs`,
`GET /v1/slice-jobs/{sliceJobId}`, and its plate download.
Their contracts come from the same generated OpenAPI
types. Partner routes use `production:upload` or `production:read`, independently
of the general print-job `control` and `read` scopes.
`printJobs.listCreateRequests({ status?, since?, batch?, limit?, cursor? })` reads one page of the organization's create requests, newest first, as `{ requests, nextCursor }`. `status` takes an array of `preparing`, `held`, `created`, `failed`, and `cancelled`. `since` is an ISO 8601 timestamp with an offset and keeps requests created at or after it. `batch: "none"` keeps only requests that have no batch. `limit` is 1 to 100 and defaults to 50, and a bad value answers 400. Pass `nextCursor` as `cursor` for the next page, with the same `status`, `since` and `batch`, until it is `null`. Requests that share a creation time neither repeat nor go missing. A walk is not a snapshot: a request that arrives above your cursor is not in the walk, so read the first page again to see it. A key with the `read` scope can list.

## Source preparation opt-ins

Both options are top-level booleans. They grant independent permissions and can be enabled together. Each option has its own default rules below.

| Option                       | Permission                                                       |
| ---------------------------- | ---------------------------------------------------------------- |
| `allowUnqualifiedConversion` | Accept missing qualification for a supported printer conversion. |
| `acceptEngineSettingUpdates` | Accept eligible stock engine-setting changes.                    |

Conversion consent does not approve customised engine-setting changes. Engine-setting consent does not permit an unqualified conversion.

### Unqualified conversions

Unqualified conversion requires an explicit `printer_id`. Automatic target selection continues to use native or qualified targets.

`allowUnqualifiedConversion` is accepted on JSON and multipart creates. Multipart has no schema default. Omit the field to inherit the organization setting captured at submission; an explicit `true` or `false` overrides it. An unset organization setting means off. Multipart encodes a supplied value as the JSON literal `true` or `false`. The JSON schema retains `default: false` for compatibility, but the flag has no effect on JSON creates, which use an existing artifact without re-slicing.

Source and target printer brands must match. This path supports Bambu Lab source projects and Bambu Lab target printers using the Bambu Studio engine family. For source preparation, `true` permits unqualified Bambu conversions with the same 0.4 mm nozzle and unchanged PLA or PETG on Textured PEI. HiveSlice uses the target machine, its default process, and a compatible Generic filament profile from the selected engine bundle. Missing profiles, a different engine family, physical setup mismatches, incomplete or duplicate mappings, and output validation failures still hold. Every source G-code setting is replaced by the target stock value, or an empty string when the selected bundle has no template. Dropped instructions appear under `custom_instructions_replaced`. Authored process settings remain. Native material changes keep their qualification rules. The source printable area and height must fit inside the target bed, and all prime-tower positions must lie inside it. Output print features, including arcs and prime towers, must stay inside the target XY area and Z height. Explicit coordinate moves are bounded outside the initial machine-start region ending at `MACHINE_START_GCODE_END` and the machine-end region beginning at `MACHINE_END_GCODE_START`. Machine start/end markers must occur exactly once, in order, and the end marker must directly follow its Custom tag. Other `FEATURE: Custom` sections hold. XYZ coordinate resets, `M206` and `M290` coordinate shifts, and untracked G commands outside the exempt regions also hold. P2S alone permits the parameterless stock commands `G150.3` for Smooth timelapse and `G39` for wrapping detection. Adding parameters still holds. Exponent coordinates hold to preserve position tracking. Selected-plate type 0 (color change), type 3 (template), and type 4 (custom) entries with non-empty `extra` hold with `conversion_layer_instructions_unsupported`. Type 3 also holds when the source template contains G-code. Unknown types always hold, including empty entries. Types 1 (pause) and 2 (tool change) may stay because the engine does not emit their `extra`; pauses use stock `machine_pause_gcode`. Loaded-filament admission still applies.

The resulting `printer_conversion_unqualified` and, for PLA, `material_not_qualified` warnings appear in prepared-plate lineage, the create-request `warnings`, and the job's `print_options.preparation_warnings`. These warnings acknowledge missing qualification evidence, not a successful print. Engine-setting review is independent of this opt-in.

An organization admin can set the default through `PUT /v1/organizations/{organizationId}/settings` with `{"settings":[{"category":"print_job_creation","key":"allowUnqualifiedConversion","value":true}]}`. Only a stored boolean `true` enables it. Multipart submission snapshots the default in its stored intent. Retries retain that snapshot even after the org default changes. The preparation captures the effective value in its immutable target. Changing the default does not release an existing held preparation. Cancel and resubmit with a new identity when consent changes.

### Engine-setting updates

`acceptEngineSettingUpdates` has OpenAPI `default: false` for JSON and multipart creates. For source preparation, `true` accepts engine changes only to settings absent from the source's `different_settings_to_system` customisation list and backed by nonempty `inherits_group` entries for their presets. Missing diff metadata, a missing diff entry, or missing or empty preset inheritance makes the setting customised and it holds. An empty diff entry counts as stock only with inheritance evidence. Empty source setting values do not exempt customised settings. Accepted changes appear in the prepared plate's `lineage.acceptedEngineSettingChanges`.

An engine review hold includes `changes`, `sourceRelease`, and `engineRelease`, alongside the existing `detail`. Each change has `key`, `sourceValue`, `engineValue`, and `slots`. Array values identify changed slots using one-based source slot numbers. Scalar settings have an empty `slots` array. A setting removed by the engine has `engineValue: null`.

Call `printJobs.approveReview(requestId, { changes, sourceRelease, engineRelease })` with the reported values to re-slice. This requires `control` scope. It returns `{ approved: true }` with HTTP 202. Repeating the same approval returns 202 while that submitted review still covers the current pending or ready slice, without starting another slice. This includes Cloud Slice retries that change the slice ID while retaining the plate's approval. A stale or mismatched review returns HTTP 409 `review_conflict`. Approval accepts those changes for those releases, including customised settings. The create-time stock opt-in continues to accept eligible stock changes after approval. Other changes hold again. Poll the receipt again after approval.

A request held for `inspection_review_required` with reason `material_usage_unresolved` takes `printJobs.approveReview(requestId, { inspection: { plateVersion } })`, with the `plateVersion` that its hold reports. This includes a Smart Queue request with no printer, where one approval covers every held target configuration. A request held for both sends the engine fields and `inspection` in one body. `PrintJobReviewApproval` types the body, and `EngineSettingReviewApproval` stays the engine fields alone. Each hold in a request's `requiredActions` lists `allowedActions` (`approve`, `amend` and `cancel`), from facts the database reports with the rules that approval and amendment enforce, so read it instead of deriving it from the hold code. It lists `approve` only when approving now would succeed. A plate that changed since you read it returns HTTP 409 `review_conflict`. Read the request again. An inspection approval records its approver, so a principal that is neither an API key nor a signed-in user gets HTTP 403 `approval_actor_required`.

A hold that the request's own input causes lists `amend`, and its `resolvedBy` names the fields that clear it: `materialMappings` for slot and material holds, `printerId` for a physical setup mismatch or an unqualified conversion on a request that names its printer, and `sourceVersionId` for a file that Hive cannot interpret or slice, or for a conversion that the project does not list. A `printerId` is qualified when Hive plans again, so a printer that is still unqualified holds the request again. Call `printJobs.amendCreateRequest(requestId, { plateVersion, materialMappings })` with the `plateVersion` that the hold reports and at least one of those fields. `materialMappings` takes the filaments that a create takes. `PrintJobCreateRequestAmendment` types the body. This requires `control` scope and returns `{ amended: true }` with HTTP 202. Each field replaces that field of the request, and Hive plans the request again under the same `requestId`, so poll it as a new request. Repeating the latest amendment returns 202 and plans nothing while the request prepares. A stale `plateVersion`, or a request that is not held, returns HTTP 409 `review_conflict`. A Smart Queue request refuses `printerId` with HTTP 422 `printer_not_amendable`, a source version that is still being inspected returns HTTP 409 `source_not_inspected`, and a source version whose inspection lists no plate of the request's number returns HTTP 422 `plate_not_found` and changes nothing.

For `release: "manual"` requests held by an engine review or another preparation reason, `/release` now returns HTTP 409 `manual_release_not_available` instead of 202. It keeps the holds and does not authorize manual release. Resolve the preparation holds first, then call `/release` when the only hold is `manual_release_required`.

Use the HTTP release and cancel operations when needed.

## List organization print jobs

This source capability is unreleased. `printJobs.list()` reads
`GET /v1/print-jobs` with an organization `read` key or authenticated session.
Host credentials and source-only production keys are refused. The result includes
jobs created by other clients, unassigned work, and assigned work whose printer
is offline, not ready, or under maintenance.

```ts
const page = await client.printJobs.list({
  statuses: ["QUEUED", "PAUSED"],
  printerIds: [printerId],
  limit: 50,
});
const next = page.nextCursor
  ? await client.printJobs.list({
      statuses: ["QUEUED", "PAUSED"],
      printerIds: [printerId],
      cursor: page.nextCursor,
    })
  : null;
```

Omit `statuses` for queued jobs and `printerIds` to include unassigned jobs.
Pages contain at most 100 jobs, with a default of 50. Ordering follows global
queue rank, printer queue rank, creation time, then the unique job ID; null ranks
sort last. Repeat the same filters with the returned cursor. Changing the page
size is allowed. A cursor for another organization or different filters returns
400 `invalid_cursor`.

This is a live queue view, not a snapshot. If jobs move or change state between
pages, their positions can change; refresh the first page for the latest queue.
Job IDs and ranks are safe JSON integers, and timestamps retain database
microseconds. An invalid stored projection returns 503 rather than silently
rounding identifiers or ranks. No private storage paths, signed URLs, print
options, or claim secrets are returned.

Accepted or preparing source requests remain separate from admitted Print Jobs;
read them with `printJobs.listCreateRequests()`. A listed job or printer assignment
does not establish current physical work or permission to Stop.

## Send a group of source requests

`printJobs.send(input, signal?)` calls `POST /v1/print-jobs/sends` with a
`control` scope API key. One send atomically creates between 1 and 32 print
requests for one existing source version. Every request must name the same
`source_version_id`. A send that mixes source versions returns `400 mixed_sources` and makes
nothing. Larger inputs fail locally with `TypeError`, as do inputs the server
would refuse: a blank batch name or request key after trimming, a
`submissionId` over 120 UTF-16 code units, or a `batchId`, `supersedes` entry,
or `modelFileId` that is not a UUID. Request bodies are checked by the server. The
SDK never splits a group into multiple sends.

A send accepts up to 200 copies across its requests. An omitted `quantity`
counts as one copy. A send batch has the same 200-copy budget across the
sends that join it. Replacing a request reuses its slots, and a retry keeps
the slots of the original request. An excessive total returns 422
`send_copies_limit_exceeded` with `limit.max` and `requested`, typed by
`PrintJobSendCopiesLimitExceeded`. A later release raises this limit.

Persist the complete input before the first call. Keep `submissionId`, every
request `key`, and every nested body unchanged when recovering after a timeout,
a lost response, or a process restart.

```ts
import type { PrintJobSendInput } from "@printhive/api";

const savedInput: PrintJobSendInput = {
  submissionId: "order-482-send-1",
  batch: { name: "Order 482" },
  requests: [
    {
      key: "order-482-plate-2",
      body: {
        source_version_id: sourceVersionId,
        externalId: "order-482-plate-2",
        plate: 2,
        quantity: 3,
        release: "manual",
        filaments,
      },
    },
  ],
};
// Save savedInput to your durable store before this call.
const send = await hive.printJobs.send(savedInput);
// After an uncertain answer, load that same input and call send again.
const recovered = await hive.printJobs.send(savedInput);
```

This request creates three independent jobs for the same plate.
They do not repack objects on one bed. Source requests with `release: "manual"`
remain unreleased until explicitly released through the create-request workflow.
Artifact JSON creation with `model_file_id` uses automatic release and cannot
replace this manual preparation workflow.

The SDK snapshots JSON before sending and reuses those bytes for transport
retries. Recovery across separate calls still requires your persisted input.
The server uses the body's `submissionId` and fingerprint of `batch` and
`requests` to identify a replay. The SDK also sends the URL-encoded JSON string of `submissionId` as the
transport's `idempotency-key` header. That header adds no server guarantee.
The same accepted body returns the original send with `replayed: true`.
A changed body under that identity returns `409 idempotency_conflict`, whose
`PrintHiveApiError.body.accepted` identifies the send that stands. A request
`key` or `externalId` that collides with an existing request also returns
`409 idempotency_conflict`, but with no `accepted`: no send stands under this
`submissionId`, so change the colliding key, and its matching
`body.externalId` when you set one, rather than replaying. A key that differs
from its `body.externalId` is refused with `422 key_mismatch` in `refused`:
when you supply `body.externalId`, it must equal the key after trimming.
Refusals retain their per-request details in `PrintHiveApiError.body.refused`.

`batch` can name a new batch, join an existing `batchId` with optional
`supersedes`, or request `{ unbatched: true }` for exactly one request.
Returned requests can have a different order. To correlate them, include
`body.externalId` equal to the request `key`, as in the example. If omitted,
the returned request's `externalId` is null.

`printJobs.listSends({ sourceVersionId }, signal?)` calls
`GET /v1/print-jobs/sends` with `read` scope and returns `{ batches }`.
It lists at most 20 batches for that source version, ordered by each batch's
first send of that source version, newest first, then by batch ID descending.
It is not a complete submission history or a lookup by `submissionId`.
Use the original saved body to recover an uncertain send. Unbatched requests
and requests created before sends existed remain available through
`printJobs.listCreateRequests`.

## Observe created jobs

`printJobs.get(jobId, signal?)` reads `GET /v1/print-jobs/{id}` and returns the inner job snapshot. It requires a positive safe-integer ID. After a create receipt reaches `created` with a non-null job, read that job separately to observe its current status and `print_options.filament_waiting_reasons`. A created job may still wait for materials or printer readiness. Keep polling the live job rather than treating its creation receipt as a current material assessment. A deleted or inaccessible job returns the API's error; the retained create receipt does not recreate it.

The job, and the `job` in a create receipt read with `getCreateRequest`, carry `load_actions`. They are recomputed on every read from the assigned printer's current filament state by the same planner as `printJobs.plan`, and list `load` and `swap` actions only. An empty list means nothing to load, including an unassigned or finished job. A queue-routed job gains actions once the queue assigns it. `null` means the actions could not be computed this time, so read again. It never means "all loaded". A later read can return different actions when the printer state changes.

The local 0.3.2 build includes the live job read and the merged #4945 waiting-reason types. It is not an npm release. Reasons list only unmet filaments; the optional `cause` remains advisory because a material-type mismatch can still report `color_distance`.

## Send a printer command

```ts
const receipt = await hive.printers.commands.send({
  printerId,
  command: "pause",
  idempotencyKey: "pause-job-42",
});
```

`printers.commands.send(input, signal?)` calls `POST /v1/printers/{id}/commands`.
Use an organization API key. Host credentials are refused. The request body
contains `command` and its `params` when applicable. A `dangerous` key also
satisfies `control`.

| Command               | Scope       | Parameters                                                                                                                                                                                                                                                                                                                                                                          |
| --------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ams_control`         | `dangerous` | `param` is `resume`, `reset`, `pause`, `done`, or `abort`. A managed Print Job or pending bound Stop blocks the command.                                                                                                                                                                                                                                                            |
| `amsCalibrate`        | `dangerous` | `amsId` is 0–31 for standard units or 128–135 for AMS HT.                                                                                                                                                                                                                                                                                                                           |
| `amsUserSettings`     | `control`   | Use `amsId: -1` for all units. Send the three boolean flags `startupReadOption`, `trayReadOption`, and `calibrateRemainFlag` together. A managed Print Job or pending bound Stop blocks the command.                                                                                                                                                                                |
| `autoLevel`           | `dangerous` | None. The printer firmware must support `G29`.                                                                                                                                                                                                                                                                                                                                      |
| `axisControl`         | `dangerous` | `axis` is `X`, `Y`, `Z`, or `E`. `distance` is a signed whole number from −10 to 10 mm, excluding zero. Optional `unit` is 1. Optional `speed` is a whole number from 1 to 3000 mm/min. See the family limits below.                                                                                                                                                                |
| `gcode`               | `dangerous` | `gcodes` holds 1–8 instructions in order. Each element has 1–256 printable ASCII characters and contains a single line.                                                                                                                                                                                                                                                             |
| `homeAxes`            | `dangerous` | `axes` holds 1–3 entries from `X`, `Y`, and `Z`. For Bambu, use `goHome`.                                                                                                                                                                                                                                                                                                           |
| `manualExtrude`       | `dangerous` | H2C accepts `extruderIndex: 0`, `direction` of `extrude` or `retract`, and `lengthMm` from 1 to 200 whole millimetres.                                                                                                                                                                                                                                                              |
| `setNozzleTempNew`    | `dangerous` | Use `extruderIndex` 0 or 1 and a whole-number `targetTemp`. The range is 0–350 °C on H2C, H2D, and H2D Pro and 0–300 °C on X2D.                                                                                                                                                                                                                                                     |
| `snapmakerNamedFan`   | `dangerous` | Snapmaker accepts a configured fan `name` and `speed` from 0 to 100 percent. A name starts with an ASCII letter or underscore and contains up to 64 letters, digits, or underscores.                                                                                                                                                                                                |
| `refreshPrinterState` | `control`   | None. Read printer state to see the update.                                                                                                                                                                                                                                                                                                                                         |
| `stopBuzzer`          | `control`   | None.                                                                                                                                                                                                                                                                                                                                                                               |
| `updateLight`         | `control`   | `isOn` (boolean) or `mode` (`on` or `off`). Optional `light` is `chamber_light` (default) or `work_light`.                                                                                                                                                                                                                                                                          |
| `amsSelectTray`       | `dangerous` | `trayId` and `confirm: true`. Use 0–255 or an AMS HT address (512, 516, 520, 524, 528, 532, 536, 540), as a number or digit string. The printer must allow filament motion.                                                                                                                                                                                                         |
| `amsFilamentDrying`   | `dangerous` | `amsId` (0–3 for AMS 2 Pro or 128–135 for AMS HT). To start, send `confirm: true`, `temp` (0–100 °C), and `durationHours` (1–72 hours), both whole numbers. Start accepts optional `mode` (1 or `on`), `filament`, `rotateTray` (defaults to true), and `coolingTemp` (whole degrees from 0 to 100 °C, defaults to 0). To stop, send only `amsId` and `mode` (0, `off`, or `stop`). |
| `cleanPrintError`     | `dangerous` | None. Uses the latest reported error.                                                                                                                                                                                                                                                                                                                                               |
| `goHome`              | `dangerous` | None.                                                                                                                                                                                                                                                                                                                                                                               |
| `loadFilament`        | `dangerous` | Optional `source: { amsId, slotId }` or numeric `trayId` (0–254, defaults to 254 on Bambu). Optional `oldTemp` and `newTemp` default to 250 °C. Optional `extruder` is 0–1 on Bambu and 0–3 on Snapmaker.                                                                                                                                                                           |
| `pause`               | `dangerous` | None.                                                                                                                                                                                                                                                                                                                                                                               |
| `resume`              | `dangerous` | Optional `cleanPrintError` defaults to true.                                                                                                                                                                                                                                                                                                                                        |
| `stop`                | `dangerous` | None. Stops an unmanaged print. For an active managed Bambu print, use [`printJobs.stop(jobId, { receiptId, startAttemptId })`](#cancel-queued-work-and-stop-an-active-attempt). For other printer families, use the printer controls in PrintHive.                                                                                                                                 |
| `unloadFilament`      | `dangerous` | Optional `amsId`, `oldTemp` and `newTemp` (default 250 °C), and `extruder` (0–1 on Bambu and 0–3 on Snapmaker).                                                                                                                                                                                                                                                                     |
| `updateFan`           | `dangerous` | `fan` accepts `1` (`part_cooling` or `part`), `2` (`auxiliary` or `aux`), or `3` (`chamber`). `speed` is a whole number from 0 to 100 percent.                                                                                                                                                                                                                                      |
| `updateSpeed`         | `dangerous` | `speed` is 1 (silent), 2 (standard), 3 (sport), or 4 (ludicrous), as a number or string.                                                                                                                                                                                                                                                                                            |
| `updateTemp`          | `dangerous` | `part` is `bed` or `nozzle`. `temperature` is a whole number from 0 to 300 °C. On Snapmaker, Klipper, and OctoPrint, `nozzle` accepts an optional zero-based `extruder` (0–3) for a configured tool.                                                                                                                                                                                |

For filament load and unload, the AMS ID is 0–31 for a standard unit, 128–135
for AMS HT, or 254/255 for an external holder. Standard units use slots 0–3.
AMS HT and external holders use slot 0. Temperatures must be finite numbers.

- Bambu accepts the AMS commands. Support on the device depends on the model, firmware, and installed AMS units.
- Bambu, Klipper, OctoPrint, and Snapmaker support raw G-code. Use the dedicated controls for Snapmaker tool pickup and park operations.
- Bambu and OctoPrint expose `autoLevel`. Klipper, OctoPrint, and Snapmaker expose `homeAxes`.
- Bambu jogs X, Y, or Z in steps of ±1 or ±10 mm using Studio's model-specific direction. Legacy jogs use 3000 mm/min for X and Y and 900 mm/min for Z. Omit `speed` for Bambu jogs and OctoPrint extrusion jogs.
- Raw G-code, jogging, both homing commands, auto leveling, manual extrusion, and AMS calibration require an idle printer. Hive Link reads fresh device status before sending the command. Busy, unknown, or stale status returns `409 printer_busy`. A Bambu filament change also counts as busy.
- API-key MCP calls to `gcode_send` use the same admission and audit as REST. The MCP result includes a command attempt receipt. The public limit is eight lines, and Snapmaker tool commands are refused.
- Snapmaker load and unload accept only `extruder`. Omitting it lets Hive Link select the tool.
- Klipper, OctoPrint, and Snapmaker accept only the part-cooling fan target.
- Flashforge, Creality Print, and Elegoo SDCP expose a single light using `chamber_light`.
- PrusaLink supports pause, resume, and raw stop.
- For non-Bambu resume, omit `cleanPrintError` or set it to `false`.

### Bambu calibration and air purification

Every command below requires a `dangerous` key. The OpenAPI command variants
list the individual fields.

| Command                      | Parameters                                                                                                                                                                                                                 |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `calibration`                | `routines` lists one or more of `xcamCali`, `bedLeveling`, `vibration`, `motorNoise`, `nozzleCali`, `bedCali`, and `clumpPosCali`. Available routines depend on the model and firmware.                                    |
| `paCalibration`              | `mode: 0`, nozzle diameter, and filament entries with the tray address, nozzle, temperatures, and maximum volumetric speed. Requires firmware that advertises the direct pressure-advance calibration command.             |
| `flowRateCalibration`        | First filament's tray ID, nozzle diameter, and filament entries with tray addresses, temperatures, maximum volumetric speed, and flow ratios. Requires firmware that advertises the direct flow-ratio calibration command. |
| `extrusionCalibrationSet`    | Nozzle diameter and entries with filament identity, a name, and K/N coefficients. For a new unassigned profile, use `tray_id: -1`, `ams_id: 0`, and `slot_id: 0`, and omit `cali_idx`.                                     |
| `extrusionCalibrationSelect` | Tray address, calibration index, filament ID, nozzle diameter, and optional physical nozzle address.                                                                                                                       |
| `extrusionCalibrationDelete` | Extruder and nozzle identifiers, filament ID, calibration index, nozzle diameter, and optional physical nozzle address.                                                                                                    |
| `airPurification`            | Send `enabled: false` to stop the air filter on a supported H2 model. Requests to enable it return `409 command_unsupported`.                                                                                              |

Nozzle diameters are 0.2, 0.4, 0.6, or 0.8 mm. Bed and nozzle temperatures
are whole degrees Celsius. For calibration, the nozzle limit is 320 °C on X1E, 350 °C on H2C, H2D, H2D Pro, H2S and H3C, and 300 °C on other models. The bed limit depends on the model and is at most 120 °C. Volumetric speed is
greater than 0 and at most 200 mm³/s. Flow ratios and K values are greater than
0 and less than 2. N is 0 for manual profiles or 0.6–2 for automatic profiles.

Hive Link checks fresh idle status before calibration starts or profile writes.
When a calibration request binds a tray to an extruder, the tray must feed that
extruder. On dual-extruder printers, external holder 255 feeds extruder 0 and
holder 254 feeds extruder 1. For AMS trays, the API resolves the reported
binding using the AMS type and the printer's filament switch or rack topology.
Direct-connected rack holders feed extruder 0. Profile selection associates a
saved calibration with the tray. If the request specifies `nozzle_pos`, the tray
must feed that nozzle.

Setting, selecting, or deleting calibration profiles returns
`409 command_unsupported` on the H3C and other printers with a nozzle rack.
Refs [nozzle rack support (#6295)](https://github.com/PrintHive/hive/issues/6295).

If the printer reports laser mode, bed leveling and vibration return
`409 fdm_mode_required`. Switch the printer to FDM mode and submit a new
request. Older Hive Link versions that lack the guarded calibration commands or
the public air filter stop return `409 command_unsupported` with upgrade
instructions.

Use `printers.materialSlots.assign` for filament metadata sync. Get access
codes on the device. Start managed prints through the Print Job API, delete
printer files through the file route, and use `stop` for raw task abort or
cancel. The direct command endpoint omits `xyzAbsoluteMode` and
`vortek_filament_settings`.

The optional `idempotencyKey` sets the `Idempotency-Key` header. It must contain
1 to 200 characters after trimming. The idempotency key is unique within the
organization. Use the original API key, printer, command, and parameters to replay the
attempt. The API compares normalized device parameters. Another API key gets 409 even if it sends the same command. A request
without the header creates a new attempt.

The SDK requires a printer UUID before it sends a request. The API records the
attempt before dispatch. An HTTP 200 receipt contains
`{ command, status: "accepted", requestId, attemptId }` after Hive Link
acknowledges the command. The receipt retains the request ID that created the
attempt. The SDK checks that `attemptId` is a UUID. If you replay while the attempt is in flight, the response can change
from 502 to 200 when the attempt settles. Read the printer's state to observe the
result.

Pause and resume use the device's current state. On Bambu printers, resume
attempts to clear a standing error before asking the device to resume.
The clear is best effort. Bambu refuses `cleanPrintError: false`.
Raw Stop checks a snapshot of managed ownership. For an active managed
Bambu Print Job, use [bound Stop](#cancel-queued-work-and-stop-an-active-attempt).
Clear error uses the print error reported when the attempt was created.

| HTTP status  | Reason                         | Meaning                                                                                                                                         |
| ------------ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| 400          | `invalid_request`              | The printer ID, command body, or idempotency key is invalid.                                                                                    |
| 401          | `authentication_required`      | The request lacks valid credentials.                                                                                                            |
| 403          | `insufficient_scope`           | The API key lacks the scope required by the command.                                                                                            |
| 403          | `host_principal_forbidden`     | The key represents a Host.                                                                                                                      |
| 403          | `organization_forbidden`       | The key cannot make this request for the organization.                                                                                          |
| 404          | `printer_not_found`            | The authenticated organization has no printer with this ID.                                                                                     |
| 409          | `printer_unavailable`          | The printer has no available Hive Link connection.                                                                                              |
| 409          | `unsafe_printer_state`         | The current state blocks AMS tray selection.                                                                                                    |
| 409          | `managed_print_active`         | A managed Print Job owns the printer or has a pending bound Stop.                                                                               |
| 409          | `printer_busy`                 | The command requires an idle printer. The printer is busy, has managed work, or Hive Link cannot verify fresh idle status.                      |
| 409          | `fdm_mode_required`            | The printer must be in FDM mode to run bed leveling or vibration calibration.                                                                   |
| 409          | `command_unsupported`          | The adapter cannot honor the command or its parameters, or Hive Link needs an update.                                                           |
| 409          | `no_print_error`               | The printer had no reported error to clear.                                                                                                     |
| 409          | `command_failed`               | Hive Link confirmed a refusal or an unsupported command. For example, Snapmaker load can be refused before motion if its feeder inlet is empty. |
| 409          | `command_expired`              | The attempt expired before dispatch.                                                                                                            |
| 409          | `idempotency_key_reused`       | The key already names a different request or belongs to another actor in the organization.                                                      |
| 502          | `command_unconfirmed`          | The outcome is unknown, for example after a transport failure or an unrecognized reply.                                                         |
| 503          | `command_dispatch_unavailable` | The API could not reach an available command relay to dispatch.                                                                                 |
| Other errors | `unexpected_error`             | The API could not handle the request.                                                                                                           |

A `PrintHiveApiError` carries `error`, `message`, `reason`, and `requestId`.
The API records `managed_print_active` and unsupported printer capabilities
as refusals before dispatch. If an older Hive Link refuses a relayed idle-only
command or a nozzle setpoint above 300 °C, the API records the refusal
after relay and returns `409 command_unsupported` with upgrade instructions.
Hive Link can also refuse an idle-only command with `printer_busy` before
sending it to the device. For a pending Bambu Stop, read the [existing Stop receipt](#cancel-queued-work-and-stop-an-active-attempt).
Failures tied to an attempt include its `attemptId`, including a 502 after a
lost acknowledgement or an unrecorded result. The SDK sends each request once.
A `prepared` attempt expires to `refused` after 45 seconds. Recovery marks a
`dispatched` attempt `indeterminate` after 5 minutes without a recorded outcome
and does not resend it. The 15-minute readiness fence starts at the recovery
deadline, so a recovered dispatch can block readiness for 20 minutes from dispatch.
If the API records `indeterminate` earlier after losing the acknowledgement,
the fence starts at that write. [#6232](https://github.com/PrintHive/hive/issues/6232)
tracks the end-to-end command deadline gap.

To retrieve the outcome after a timeout, use the original API and idempotency
keys. A new idempotency key requests a new command, so check the printer state first.

### Commands with separate routes or internal use

- `getAccessCode` returns a printer's LAN credential.
- `printDeviceFile` bypasses Start Print. Use Start Print for managed work.
- Use printer tasks to delete files and the filament routes to update slot metadata or refresh RFID.
- Use `stop` for an unmanaged print in place of `taskAbort` or `taskCancel`.
- `xyzAbsoluteMode` is an internal mode change. Use `axisControl` for jogging.
- `vortek_filament_settings` requires a qualified Hive Link dispatch implementation.

## Read live printer progress

`printers.watch()` gives the latest state of each printer of the key's organization: connectivity, Print Status, stage, progress with current and total layers, remaining minutes and an estimated end, the file Hive Link sends, temperatures, and filament slots with their material, color, profile, and tag. It reads the `printer.telemetry.sampled` Farm Event from Pulse's `/partner` Socket.IO namespace.

The key needs `events:read`, `events:read:*`, or `events:read:printer`. Pulse refuses Host keys, Host-bound keys, keys with a `production:*` scope, and keys with the legacy `*` scope, even with an events grant. One address gets 20 connection attempts in 10 seconds. Keep the key on your server.

```ts
import { PrintHive, isPrinterTelemetryStale } from "@printhive/api";

const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const watch = hive.printers.watch();
for await (const update of watch) {
  if (update.type !== "printer") continue;
  const { printer } = update;
  const { percent, currentLayer, totalLayers, remainingMinutes } =
    printer.progress;
  console.log(
    printer.printerName,
    printer.stage.phase,
    `${percent ?? "?"}%`,
    `layer ${currentLayer ?? "?"}/${totalLayers ?? "?"}`,
    `${remainingMinutes ?? "?"} min left`,
    isPrinterTelemetryStale(printer) ? "stale" : "fresh"
  );
}
```

The first updates come from the snapshot, the latest stored sample of each printer that reported in the last day, in parts of up to 50 printers. Live samples follow, at least every 60 seconds for an online printer and about every 10 seconds while a Bambu printer prints. The watch drops a sample whose `revision` is older than the one it holds, so a reconnect never moves a printer backwards. `isPrinterTelemetryStale` reports a sample older than 90 seconds, or a printer that is offline. `watch.get(printerId)` and `watch.all()` read the latest state at any time. Pass `printerIds` to watch some printers only. An `invalid` item names a sample that failed this client's schema, and the printer keeps its last state. Update the client when you see one.

`events.subscribe({ kinds, scopes, since, snapshot, signal })` is the stream underneath. It yields `snapshot`, `event`, `connection`, `reset`, and `invalid` items. `event.event` is a Farm Event typed by `kind`. Name `printer.telemetry.sampled` to receive telemetry, because a pattern such as `printer.*` leaves it out. Durable kinds such as `job.started` and `job.completed` need `events:read` or `events:read:job`. A large snapshot arrives as several `snapshot` items. Save `subscription.cursor` after you handle a durable event, and now and then, and pass it as `since` when your process starts again. The stream then resumes after that point, and the client drops a repeated event. Pulse sends checkpoints as the stream passes events that your selector skips, so the cursor moves past them too, and a resume reads little of the log.

```ts
const live = hive.events.subscribe({
  kinds: ["job.*", "printer.telemetry.sampled"],
  since: await loadCursor(),
});
for await (const item of live) {
  if (item.type === "event" && item.event.kind === "job.completed") {
    await markPrinted(item.event.payload.jobId);
    await saveCursor(live.cursor);
  }
}
```

The client reconnects with backoff after a network failure, a Pulse restart, or a stream that closed itself, and resumes durable events after its cursor. A slow reader pauses the socket and resumes from its cursor when it catches up, so durable events are never dropped. A `reset` item means the server's log is behind your cursor. Reconcile by REST, then read on. An `invalid` item names a message that failed the stream's schema, and the stream continues. When the key loses an events grant, Pulse closes the stream with `credential_changed`, and the client subscribes again. A refused key, a revoked key, or a selector that the key no longer covers ends the loop with `PrintHiveLiveError`, whose `code` is `unauthorized`, `forbidden`, `credential_revoked`, `selector_denied`, `organization_not_allowed`, `invalid_payload`, or `stream_unavailable`.

The client connects to `https://pulse.printhiv3d.com`. With a custom `baseUrl`, pass `liveUrl` too. Pulse serves the stream only while `FARM_EVENTS_FANOUT_ENABLED` is on. Production has had it on since 2026-11-14 15:37 UTC. A Pulse that runs with it off, such as a local one, fails the connection with `stream_unavailable`.

Effect users can import `@printhive/api/effect`, which needs `effect` 4 and ships as ESM only. `liveEvents(hive, options)` and `watchedPrinters(hive, options)` return a `Stream` whose scope closes the socket.

```ts
import { Effect, Stream } from "effect";
import { watchedPrinters } from "@printhive/api/effect";

await Effect.runPromise(
  watchedPrinters(hive).pipe(Stream.runForEach((update) => Effect.log(update)))
);
```

## Plan printers and trays before you submit

`printJobs.plan` ranks the printers that could take a plate and names the exact tray for each missing filament. It needs the plate's effective filament requirements, the same facts `printJobs.create` takes. It slices nothing, creates no job and sends nothing to a printer, so a retry is safe. An API key with `read` is enough.

Suggestions describe material routing. They do not check connectivity, readiness, maintenance or current work, and do not reserve a printer. Check that the printer is available before changing its spools.

```ts
const plan = await hive.printJobs.plan({
  filaments: [
    { sourceSlot: 0, material: "PLA", color: "#000000" },
    { sourceSlot: 1, material: "PLA", color: "#FF0000" },
  ],
  printer_ids: ["00000000-0000-4000-8000-000000000001"],
});
for (const suggestion of plan.suggestions) {
  console.log(suggestion.rank, suggestion.printer.name);
  for (const action of suggestion.load_actions) console.log(action.text);
}
```

Omit `printer_id` and `printer_ids` to evaluate the organization's printers, up to 100 in name order. Name up to 25 printers with `printer_ids`, or one with `printer_id`. A named printer your key cannot see returns `404`, the same as one that does not exist.

Suggestions rank by fewest `load` and `swap` actions, then by Smart Queue match score, then by name. `load_actions` lists only what is still missing, in source slot order. A filament a saved assignment already satisfies is counted in `already_loaded_count` and has no entry. `ineligible` lists printers where some filament has no bay, with a `reason` of `no_filament_bays`, `no_eligible_bay` or `no_free_bay` and the `source_slots` affected. A printer in `ineligible` never appears in `suggestions`. `truncated` is true when the request evaluated or listed fewer printers than exist. The response caps at 10 suggestions and 25 ineligible printers.

Send `material` exactly as the plate needs it. The planner does not alias or normalize it beyond trimming and upper-casing, so `PLA-S` stays `PLA-S`. Add `nozzle` (`0` left, `1` right) on a filament, `nozzle_diameters` and `filament_source` when the slice binds them, so the plan matches the job it becomes.

Each action carries `actionId`, `sourceSlot`, `kind` (`load`, `swap` or `already_loaded`), `filament`, `bay` and `text`. `bay.ams_id` and `bay.slot_id` use the same addresses as `targetSlot`, and a toolhead has neither. The `actionId` stays the same for one printer, source slot, bay, material and colour, whatever the `kind`. Pass `printer_id` to `printJobs.create` to pick a suggestion, or omit it to leave the job to the Smart Queue.

Catalog identity stays on each action's `filament`: `filamentId`, `brand`, `name`, `colorName`, effective `material` and `colorHex`. Colors use uppercase `#RRGGBB`, or `#RRGGBBAA` when alpha is not FF. Required and current load-action colors both preserve transparency. Named colors produce instructions such as `BAMBU LAB Jade White PLA into AMS 1 SLOT 2`; legacy requirements retain material-and-hex text. A different catalog id changes the action id. For pre-submit planning, supply resolved identity alongside `material` and `color`. Resolving a catalog id alone is supported by `printJobs.create`, not `printJobs.plan`.

## Upload a Printie design

```ts
import { PrintHive } from "@printhive/api";

const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const source = await hive.partnerSources.upload({
  file: "/srv/designs/project.3mf",
  filename: "project.3mf",
  externalId: "printie:design-1234",
  idempotencyKey: "printie:design-1234:revision-1",
});
const settled = await hive.partnerSources.waitUntilSettled(
  source.sourceVersionId,
  {
    intervalMs: 1000,
    timeoutMs: 120_000,
  }
);
if (settled.status === "ready") {
  console.log(settled.inspection);
} else {
  console.error(settled.error.code, settled.error.limit);
}
```

The key needs `production:upload` and `production:read` scopes. The organization must have partner source intake enabled. `ready` means inspection completed; it does not authorize printing or establish printer compatibility.

## Receive webhooks

`hive.webhooks` manages the HTTPS endpoints that receive job, printer, and library events. Reads (`list`, `get`, `attempts`) need `read` or `webhooks:read`. Writes (`create`, `update`, `delete`, `test`) need `webhooks:write` exactly: a `control` or Host key is refused with 403. An organization holds up to 20 endpoints.

| Method                                                                         | Request                          | Result                                                                                        |
| ------------------------------------------------------------------------------ | -------------------------------- | --------------------------------------------------------------------------------------------- |
| `list(signal?)`                                                                | `GET /v1/webhooks`               | `Webhook[]`, without secrets                                                                  |
| `get(id, signal?)`                                                             | `GET /v1/webhooks/{id}`          | `Webhook`                                                                                     |
| `create({ name, url, event_types, enabled? }, signal?)`                        | `POST /v1/webhooks`              | `CreatedWebhook`, with `signing_secret` once                                                  |
| `update(id, { name?, url?, event_types?, enabled?, rotate_secret? }, signal?)` | `PATCH /v1/webhooks/{id}`        | `UpdatedWebhook`, with a new `signing_secret` once after `rotate_secret: true`                |
| `delete(id, signal?)`                                                          | `DELETE /v1/webhooks/{id}`       | `{ deleted: true }`                                                                           |
| `attempts(id, signal?)`                                                        | `GET /v1/webhooks/{id}/attempts` | The latest 100 `WebhookAttempt`s, newest first, each with its event type and `event_data`     |
| `test(id, signal?)`                                                            | `POST /v1/webhooks/{id}/test`    | `{ event_id, queued: true }`. One `webhook.test` event is queued, at most once a minute (429) |

`url` must be HTTPS with a public DNS name. IP literals, credentials, and fragments answer 400, and the worker refuses private and special-use addresses and never follows a redirect. `event_types` takes one or more of the types below, each once. `update` with `enabled: true` clears the failure count of an endpoint that Print Hive disabled after ten failed attempts in a row. The client refuses an unknown type or field with `TypeError` before it sends. It never retries `create`, `test`, `delete`, or an `update` with `rotate_secret: true`, because a repeat could create a second endpoint, queue a second test, answer 404 for an endpoint that the first attempt removed, or replace a secret that you just stored.

**Types.** Each Farm Event type carries the Farm Event of the same name. A name is permanent: Print Hive adds types and fields, so ignore a type or a field you do not know.

| Type                                             | Fires when                                                  | `data` fields                                                                                                                                          |
| ------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `job.created`                                    | A Print Job is created                                      | `jobId`, `printerId` (null until chosen), `jobName`, `modelFileId`, `batchId`, `source`                                                                |
| `job.assigned`                                   | A printer claims the job                                    | `jobId`, `printerId`, `jobName`, `modelFileId`, `batchId`, `claimGeneration`                                                                           |
| `job.started`                                    | The printer starts the print                                | `jobId`, `printerId`, `jobName`, `status`, `previousStatus`, `claimGeneration`                                                                         |
| `job.paused` / `job.resumed`                     | The print pauses, or continues                              | the `job.started` fields, and `errorCode` and `errorMessage` on `job.paused`                                                                           |
| `job.recovered`                                  | The printer reports a print again after it was marked ended | `jobId`, `printerId`, `jobName`, `status`, `previousStatus`. It undoes an earlier `job.failed`                                                         |
| `job.completed` / `job.failed` / `job.cancelled` | The print ends                                              | `jobId`, `printerId`, `jobName`, `status`, `previousStatus`, `printCompletedAt`, `claimGeneration`, and `errorCode` and `errorMessage` on `job.failed` |
| `printer.ready`                                  | A printer is marked ready and holds no completed-job lock   | `printerId`, `releasedJobId`, `readySource`, `readyUpdatedSource`                                                                                      |
| `printer.online` / `printer.offline`             | A printer's connection changes                              | `printerId`, `printerName`, `observedAt`, and `lastSeenAt` on `printer.offline`                                                                        |
| `model.created` / `model_file.uploaded`          | A Model is created, or a `.3mf` is registered               | library fields, see the served API description                                                                                                         |

`printer.online` and `printer.offline` fire once for each change and never while a printer stays in one state, so repeated reports of one state send nothing. A printer whose connection was never known is not offline. `printer.offline` comes from a Host that reports the printer, and from a Host that stops answering: Print Hive marks its printers offline when the 90-second lease expires and a 30-second sweep finds it, so that event can arrive up to about two minutes late. `observedAt` is when Print Hive recorded the change.

**Delivery.** Each POST is `{ id, type, occurred_at, org_id, data }` with `X-Hive-Event-Id` and `X-Hive-Signature: t=<unix seconds>,v1=<hex>`. For a job or printer type, `id` is the Farm Event's id and `data` is its `payload`, the same object that `events.subscribe` yields in `event.event.payload`. Delivery is at least once and unordered: skip an `id` you have handled, and order by `occurred_at`. A non-2xx answer or a timeout retries with backoff for 24 hours, then dead-letters. Ten failed attempts in a row disable the endpoint and notify the organization. Print Hive stores an event only for an endpoint that subscribes to its type at that moment, so subscribing later sends no earlier event. To catch up after an outage, read `GET /v1/organizations/{orgId}/events?since=<cursor>` with `events:read`. Its items carry the same ids. Name `printer.online` and `printer.offline` in `kinds` there, because it leaves them out otherwise.

**Verify the signature.** `verifyWebhookSignature({ rawBody, signatureHeader, secret, toleranceSeconds? })` resolves to `true` only when the header's HMAC-SHA256 over `<timestamp>.<rawBody>` under `secret` matches and the timestamp is within `toleranceSeconds` (300 by default) of now. It compares every byte and resolves to `false` for a missing, malformed, old, future, or wrong signature. It throws `RangeError` for a negative or non-finite tolerance. `rawBody` is the request body as it arrived: a string, `Uint8Array`, or `ArrayBuffer`. A parsed and re-serialized body has other bytes and never verifies. It uses Web Crypto, so it runs in Node 20 or later, Bun, Deno, and edge runtimes. Each retry carries a fresh timestamp and signature, and rotating a secret ends the old one for later attempts.

```ts
import {
  PrintHive,
  verifyWebhookSignature,
  type WebhookEvent,
} from "@printhive/api";

const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const endpoint = await hive.webhooks.create({
  name: "Fulfilment",
  url: "https://hooks.example.com/printhive",
  event_types: ["job.completed", "job.failed", "printer.offline"],
});
await saveSecret(endpoint.signing_secret); // returned once

export async function receive(request: Request): Promise<Response> {
  const rawBody = await request.arrayBuffer();
  const verified = await verifyWebhookSignature({
    rawBody,
    signatureHeader: request.headers.get("x-hive-signature"),
    secret: await loadSecret(),
  });
  if (!verified) return new Response(null, { status: 400 });
  const event = JSON.parse(new TextDecoder().decode(rawBody)) as WebhookEvent;
  if (await alreadyHandled(event.id))
    return new Response(null, { status: 204 });
  if (event.type === "job.completed") await markPrinted(event.data.jobId);
  if (event.type === "printer.offline") await markOffline(event.data.printerId);
  await remember(event.id);
  return new Response(null, { status: 204 });
}
```

## Client options and resources

`new PrintHive({ apiKey, baseUrl?, liveUrl?, fetch?, timeoutMs?, maxRetries? })` defaults to `https://api.printhiv3d.com`, the live stream at `https://pulse.printhiv3d.com`, global `fetch`, 30 seconds per request attempt, and two retries. `baseUrl` can include a reverse-proxy path prefix. Redirects fail to prevent credentials moving to another origin. Missing, blank, or invalid header values for `apiKey` throw `TypeError` during construction.

`partnerSources.upload` accepts a filesystem path, Buffer, Uint8Array, or `ReadableStream<Uint8Array>`. Streams require an explicit byte `size`. Every upload sends `Content-Length` and a raw `model/3mf` body. Byte inputs are copied and path inputs are read into memory before sending. Upload returns the source fields plus `idempotencyKey`. When omitted, the client generates that key once per call. Persist a caller-supplied key before the first call when retries must survive process restarts. Use a new key when the bytes or binding change. An optional `modelId` binds to an existing model.

`partnerSources.get(sourceId)` returns one typed source. `partnerSources.waitUntilSettled(sourceId, { intervalMs?, timeoutMs?, signal? })` resolves on `ready` or `failed`. Its default total polling deadline is 120 seconds; cancellation stops active reads and delays.

`models.findByExternalId(externalId)` returns the bound model and latest source. `models.listSourceFiles(modelId)` is an async iterator over sources across cursor pages.

```ts
const model = await hive.models.findByExternalId("printie:design-1234");
for await (const source of hive.models.listSourceFiles(model.modelId)) {
  console.log(source.sourceVersionId, source.status);
}
```

## Create a Slice job

A Slice job requires `production:upload` for creation and `production:read` for reads and downloads, plus the organization's preparation feature flag.

```ts
const sliceJob = await hive.sliceJobs.create({
  idempotencyKey: "printie:order-1234",
  items: [
    {
      sourceVersionId: source.sourceVersionId,
      plates: [2],
      quantity: 3,
      materialMappings: [{ sourceSlot: 1, material: "PETG", color: "#1F6FEB" }],
      target: { printerId: "<qualified printer UUID>" },
    },
  ],
});
const outcome = await hive.sliceJobs.waitUntilSettled(sliceJob.sliceJobId, {
  timeoutMs: 120_000,
  intervalMs: 1000,
});
for (const item of outcome.items) {
  for (const plate of item.preparedPlates) {
    if (plate.status === "ready") {
      const info = await hive.sliceJobs.downloadInfo(
        outcome.sliceJobId,
        plate.plateId
      );
      // info contains url, expiresAt, filename, bytes and sha256.
      // Fetch the signed URL without sending the Hive API key.
    }
  }
}
```

Creation accepts at most 20 items. Generated request validation rejects larger arrays locally with `TypeError` before sending HTTP. The API continues to return `422 request_too_large` with limit metadata for oversized raw HTTP requests.

Each item names either `sourceVersionId` or `externalId`. Creation returns the Slice job plus the supplied or generated `idempotencyKey`, just like upload. Persist a caller-supplied key before sending when recovery must survive process restarts. A replay returns the original Slice job identity. Request JSON is snapshotted before sending and stays unchanged across retries.

`sliceJobs.get(id, signal?)` returns the full Slice job. `waitUntilSettled` resolves on `ready`, `held`, or `failed`. Holds and failures remain in the returned items and plates. Its total deadline aborts active reads, retry delays, and poll delays. A timeout leaves the creation outcome intact; resume reads using the Slice job ID instead of creating replacement work. `downloadInfo(id, plateId, signal?)` retains all signed-download metadata without fetching the artifact.

`materialMappings[].sourceSlot` is one-based. To keep a slot's file material, map its `type` from `inspection.materialSlots[]`, such as `PLA`. Do not map `material`, which joins the vendor and the type, such as `Bambu Lab PLA`: Hive reads it as a material change and holds every used slot with `material_change_requires_qualification`. A source inspected before `type` existed omits it. A `material_change_requires_qualification` hold's `releaseActions` list what releases it: `restore_project_material` (amend `materialMappings` back to the project's material) and `submit_source_with_material_preset` (save the project with the requested material's preset and submit the new source version). Ambiguous palettes require explicit source-version or SHA-bound bindings; color order alone cannot establish source slots. Pin `sourceVersionId` after validating a binding. `target.printerId` names the exact qualified target. A Slice job creates no print job and never authorizes printer motion.

`hive.sliceJobs.create`, `get`, `waitUntilSettled`, and `downloadInfo` send their calls to `POST /v1/slice-jobs`, `GET /v1/slice-jobs/{sliceJobId}`, and `GET /v1/slice-jobs/{sliceJobId}/plates/{plateId}/download`. `create` throws a `TypeError` with the message `Invalid Slice job input` for an invalid input. `create`, `get`, and `waitUntilSettled` reject a response without `sliceJobId`. The API must serve the Slice job paths, which production does.

**Deprecated names.** `hive.preparations` is deprecated. It is the same object as `hive.sliceJobs`, so it takes the same inputs and returns the same results, and its public types stay the preparation types. The HTTP paths `POST /v1/partner-production/preparations`, `GET /v1/partner-production/preparations/{preparationId}`, and `GET /v1/partner-production/preparations/{preparationId}/plates/{plateId}/download` are also deprecated. Their successors are the Slice job paths above. The old paths keep their statuses and bodies, answer with `Deprecation` and `Link` headers, and carry no removal date.

The types `SliceJob`, `SliceJobCreateOptions`, and `SettledSliceJob` derive from the Slice job paths. Public preparation types, including `PartnerPreparationItemInput`, `PartnerMaterialMapping`, `PartnerPreparedPlate`, `PartnerPreparationDownload`, and `PartnerPreparationTargetReason`, derive from the current API export.

## Engine-forced setting warnings

For native Bambu Studio project slicing, Hive accepts the CLI's forced
`filament_prime_volume` of `45` only when every output slot is `45` and the
normalized slot count is unchanged. Scalar strings count as one slot, following
the preserved-settings comparison rule, and warnings contain normalized arrays.
The source 3MF's `Application` metadata must start with `BambuStudio-`, and the
runtime release must be `02.08.02.60` or `02.08.04.57`. Missing Application metadata
or an unverified release retains the hold, even if the output equals the default.
Native commands load no external filament profiles and keep CLI checks enabled.
Qualified paths that load filaments retain the hold.
Other changes to this setting or other preserved keys still hold.

Plate `lineage.warnings` and the create-request view's `warnings` include
`{ code: "engine_forced_setting", key: "filament_prime_volume", source: ["30", "30"], engine: ["45", "45"] }`.
This exception runs before engine-setting review. It requires no approval action,
adds no `acceptedEngineSettingChanges` review, and does not hold the plate or request.
`PrintJobCreateRequest` and `PartnerPreparedPlate` expose the warning through
the generated SDK types. `printJobs.getCreateRequest` and `waitUntilCreated`
return it alongside other warnings.

Bambu Studio applies the same guard, `is_bbl_3mf && !no_check && load_filament_count == 0`,
and writes `45.f` into every existing vector element in both
[02.08.02.60](https://github.com/bambulab/BambuStudio/blob/v02.08.02.60/src/BambuStudio.cpp#L6886-L6894)
and [02.08.04.57](https://github.com/bambulab/BambuStudio/blob/v02.08.04.57/src/BambuStudio.cpp#L6976-L6984).

## Unused-slot instruction warnings

As a temporary policy tracked in #5118,
Completed project lineage can include these advisory warnings in `warnings`:

- `output_identity_unverified` means the slicer produced an output, and Hive
  could not verify its correspondence with the source parts. `reason`
  explains the gap. `entity` identifies the affected source part keys as
  `objectId:partId`, or describes the project parts when no keys are available.
- `part_codes_unavailable` means Hive sliced the validated original after
  stamping or storage failed, processing timed out, or an older processor
  recorded no stamp. The corresponding reasons include `stamping_failed`,
  `storage_failed`, `processing_timeout`, and `stamp_not_recorded`.
  Library slice requests report this warning in `quality.findings`.
- Older completed lineage can contain `object_skipped`, with the affected
  source instance in `entity` and an explanation in `reason`.

If the engine reports a skipped instance or produces fewer objects than
requested, the plate has a `project_review_required` hold with
`output_objects_missing` at the start of its `detail`. The detail describes
the missing objects. The held plate has no downloadable artifact. An intact
count with unverified identify IDs can still produce a warning.

`engine_unused_slot_setting` reports `filament_start_gcode` and `filament_end_gcode` differences
only on slots unused by the selected plate. HiveSlice includes painted slots in
its usage computation and rejects output G-code selecting an unused tool.
Used-slot and uncertain changes still require review.

The warning contains key names and one-based slot indexes only, without G-code:
`{ code: "engine_unused_slot_setting", keys: ["filament_end_gcode"], slots: [2, 4] }`.
It appears in plate `lineage.warnings` and create-request `warnings` through
`PartnerPreparedPlate` and `PrintJobCreateRequest`. It adds no approval action.
Deploy compatible API and Slicing readers before activating an emitting runtime.

## Handle failures and retries

`PrintHiveApiError` exposes HTTP `status`, the response's `error` as `code`, optional `limit` with `name`, `max`, and `observed`, `retryAfterMs`, and `requestId`. For `target_not_qualified`, `reasons` exposes validated, typed printer qualification reasons. Its optional `body` exposes the validated error envelope, preserving additional fields as JSON values for callers to narrow. Invalid envelopes leave `body` undefined. Error messages omit response bodies and credentials. `PrintHiveNetworkError.reason` distinguishes `network`, `timeout`, and `aborted` failures.

The API can answer `411 content_length_required`, `413 upload_too_large`, `429 upload_capacity_reached`, `409 external_id_conflict`, or `409 idempotency_conflict`. Inspection failures resolve through the source's `failed` status and include their own error and optional restriction limit.

Only 429, 503, and network failures retry. Permanent `preparation_disabled` never retries, including HTTP 503. GET requests are idempotent, and so is `printJobs.plan`, which only reads. Slice job JSON and upload retries retain their idempotency key and require replayable bytes or a path. One-shot streams never retry. Timeouts and caller aborts never retry. Retries use exponential backoff with jitter and wait at least `Retry-After`, supporting both seconds and HTTP dates. If `Retry-After` exceeds 60 seconds, the client throws the API error with `retryAfterMs` so the caller can schedule the retry. It never retries before that delay. `maxRetries: 0` disables retries. Request timeouts apply per attempt; polling also has a total deadline.

## Read organization printers

Use an organization API key with the `read` scope or higher. Keys with any
`production:*` scope cannot call these routes, including mixed-scope keys.

```ts
const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const page = await hive.printers.list({ limit: 50 });
const first = page.printers[0];
if (first) {
  const printer = await hive.printers.get(first.id);
}
```

`printers.list` returns `PrinterPage` and `printers.get` returns `Printer`. Both types come from the OpenAPI schema, so `page.printers[0].id` is a `string` under `strict`.

List returns `{ printers, nextCursor }`. Pass `nextCursor` as `cursor` until
it is null. Detail returns 404 for missing or foreign-organization printers.
Each printer includes model, connection, status, and `readyMarked`, the stored
readiness flag. It does not guarantee an empty bed or authorize dispatch.
`loadedFilament` uses Smart Queue's material source. Each slot includes
`address: { ams_id, slot_id }`, material, color, and a `state` of `loaded`,
`empty`, or `unknown`. AMS IDs and tray IDs are zero based; external spools
use `{ams_id:255,slot_id:0}` on a single-nozzle printer, even when its legacy
`vt_tray` report carries id 254. Dual-nozzle printers retain both external
addresses, `{ams_id:254,slot_id:0}` and `{ams_id:255,slot_id:0}`. AMS HT position
512 uses `{ams_id:128,slot_id:0}`. Directory reads return stored observations
and never contact a printer.

Mapping previews label position 512 as `AMS HT-A · Slot 1` and group it under
`AMS HT-A`. Only positions 254 and 255 appear in the external-spool group.

`readiness.ready` reports the stored ready flag. `readiness.bedClear` reports
the flag only when its source is `bed_occupancy_verified`; otherwise it is null.

## Pause printer pickup

`printers.pausePickup(printerId)` needs an organization API key with `control`.
It pauses pickup when no job holds the printer lock, no tracked job is printing
or paused, and no device-file start is in progress. A successful call returns a
`PrinterPickupPause` and blocks job pickup and web device-file starts until
`printers.attestOperatorReady` succeeds.

A retained job lock or active tracked print returns 409 `printer_busy`.
A job can retain the lock with `ERROR` after a start confirmation timeout.
The error's `body` has the `PrinterPickupBusy` shape. Its `holdingJob` gives the
blocking job's numeric `id` and stored `status`. Hive omits `holdingJob` if the
lock points outside the key's organization.

A device-file start returns 409 `printer_busy` with `holding.kind` set to
`device_file`. The `holding.expires_at` field gives the reservation deadline.
Fresh printer activity can settle the reservation sooner.

## Sync your filament catalog

Use a Control API key to sync each partner record. Repeating an external id
updates the same organization-owned material, including concurrent retries.
The external id namespace belongs to the organization, so coordinate ids across
integrations. Reads require Read scope. Hive trims surrounding whitespace from `externalId`
and `sku` on writes and list filters; neither field can be blank.

```ts
const filament = await hive.filamentCatalog.upsert({
  externalId: "printie-pla-blue",
  brand: "Printie",
  material: "PLA",
  colorName: "Blue",
  colorHex: "#0000FF",
  sku: "PLA-BLUE",
  replacementFilamentId: null,
});
console.log(filament.id, filament.sku);
const page = await hive.filamentCatalog.list({ sku: "PLA-BLUE", limit: 100 });
const saved = await hive.filamentCatalog.get(filament.id);
```

`POST /v1/filament-catalog` accepts the fields above and returns 200 with the
material row. `hex` is an alias for `colorHex`; both must agree when supplied.
`replacementFilamentId` is retained as partner metadata, not resolved as a Hive id.

### Choose the filament profile of a color

A catalog color slices with a stock filament profile. Name it with
`bambuFilamentId`, the Bambu filament ID such as `GFG02`, or omit the field and
Hive takes the stock default for the material type: `PLA` takes `GFA00`, `PETG`
takes `GFG00`, `PLA Matte` takes `GFA01`, and `TPU` takes `GFU99`. A job that
matches the color with `exact_material` then slices that slot with the profile of
the filament loaded on the printer. Without the link, the slot keeps the 3MF's
profile.

Hive stores the link on every upsert, so an upsert that omits `bambuFilamentId`
selects the default again, even for a color that had an ID. The link changes how
a plate slices and how the color assigns to a printer only for an organization
with the `hiveslice_loaded_filament_profiles` flag, which stays off until the
runtime is qualified. Until then the color assigns as one with no link. A color
you saved before the link existed has none until you upsert it again. An ID that
is not a stock profile answers 400.

```ts
const choices = await hive.filamentProfiles.compatible({
  material: "PETG",
  printerId,
});
const color = await hive.filamentCatalog.upsert({
  externalId: "printie-petg-blue",
  brand: "Printie",
  material: "PETG",
  colorName: "Blue",
  colorHex: "#0000FF",
  sku: "PETG-BLUE",
  bambuFilamentId: "GFG02",
});
console.log(color.bambuFilamentId);
```

`filamentProfiles.compatible({ material, printerId })` reads
`GET /v1/filament-profiles/compatible` with the `read` scope. It lists, ordered by
`bambuFilamentId`, each stock profile that accepts the material type and that the
printer's model and nozzle take, with the printer's own `settingId` and
`isDefault` for the profile an upsert would take. The list is one page and holds
at most one entry for each of the 90 stock profiles. It is empty when no profile
fits. A printer from another organization answers 404 `printer_not_found`, and one
with no known model or nozzle diameter answers 409 `printer_target_unknown`.

The ID must be one the list can return, and its formulation must accept
`material`; the formulation's label and its slicer types count, so `PETG` and
`PETG HF` both accept `GFG02`. The color's `bambuFilamentId` is `null` when no stock
profile exists for its material type, which none of the types the stock catalog
names lacks, and when you omitted it and the stock profile has no usable row in
the database yet. Hive logs the last
case and saves the color without a link, so a missing row never stops a catalog
write.

Check `bambuFilamentId` in the response. An API that predates this field drops
it from the request and answers 200 with no profile.

A color that is already assigned to a printer slot keeps the old assignment, so
changing its `bambuFilamentId` makes the slot's evidence disagree. A job names no
loaded filament for that slot, and slices with the 3MF's profile, until you assign
the slot again with `printers.materialSlots.assign`.

An upsert states the profile again every time. The request alone decides the
link, so repeating a call writes the same row, and an upsert that omits
`bambuFilamentId` selects the default even for a color you gave an ID before.
Changing `material` selects again from the new type. Colors created before this
field keep no link until you upsert them again.
`GET /v1/filament-catalog` filters by exact `externalId` and `sku`, with `limit`
(1–200, default 100) and `offset` (default 0). Results are ordered by Hive id.
It returns `{ materials, total }`. `GET /v1/filament-catalog/:id` returns one row.
All operations enforce organization ownership. Returned rows include `id`, `sku`,
`material_type`, `color`, and partner metadata.

Errors include 400 `invalid_catalog_input`, 400 `conflicting_color_hex`,
400 `unknown_filament_profile` for a `bambuFilamentId` the stock catalog does not
name, 400 `filament_profile_material_mismatch` for one whose formulation does not
accept `material`, 403 `API_KEY_SCOPE_REQUIRED`,
404 `catalog_filament_not_found`, 409 `catalog_conflict` for uniqueness conflicts,
500 `catalog_store_failed`, and 503 `filament_profile_unavailable` when a profile you
named has no usable row in the database yet. Retry the 503 after the next release.
Invalid bodies return the API validation error.
Pass the returned `id` as `filaments[].filamentId` in JSON or multipart print-job
creation. A slot can contain only `{ sourceSlot, filamentId }`, plus optional
`targetSlot` and `match` fields. Hive derives material and color from the catalog row. Catalog read and upsert
responses expose canonical primary `color`, ordered `colors`, and nullable
`colorName`, using the color rules below.
Explicit `material` and `color` must agree with the row. Material comparisons
ignore finish and case; fibre fillers and polymer grade are matched. Colors accept
a leading `#` and either case.

For a catalog row whose `material_type` is `PLA` and whose metadata declares carbon
fibre, `{ filamentId, material: "PLA" }` returns `422 filament_catalog_conflict`.
Send the composed type (`material: "PLA-CF"`), or omit `material` when passing
`filamentId` and let the catalog resolve it. Exact matching still checks that
composition against the plate's sliced type.

Each filament can set `match`. Omit it to keep the existing type and color
proximity rules, even when the request supplies `filamentId`.

| `match`                                             | Required identity                      | Qualification                                                                                                                                                                |
| --------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{ kind: "exact_material", alternates?: string[] }` | `filamentId`                           | The loaded assignment's `materials.id` equals the requested ID or a listed alternate. On each printer, the requested ID is preferred, then loaded alternates in array order. |
| `{ kind: "type_color" }`                            | `filamentId` or `material` and `color` | Material type and the existing organization color proximity threshold.                                                                                                       |
| `{ kind: "type_only" }`                             | `filamentId` or `material`             | Material type with any color. `color` can be omitted and does not constrain matching.                                                                                        |

```ts
await hive.printJobs.create({
  model_file_id: fileId,
  filaments: [
    {
      sourceSlot: 0,
      filamentId: matteRedId,
      match: { kind: "exact_material", alternates: [basicRedId, matteBlueId] },
    },
  ],
});
```

Alternates are capped at eight and de-duplicated in caller order. The primary cannot appear in its own list (`422 primary_in_alternates`). Every alternate must have the same polymer grade and fibre fillers as the primary (`422 alternate_material_mismatch`). PLA Silk, PLA+, PLA Basic, and PLA Matte all compare as PLA. Exact choices that conflict with the plate's polymer grade and fibre fillers return `422 filament_catalog_conflict` at creation or PATCH. Every ID must resolve under the same catalog
ownership, global enablement, and usable identity rules as `filamentId`.
Unknown or inaccessible alternates return `422 catalog_filament_not_found` with
the source slot. Invalid shapes return 400. JSON creation returns `{ error: "Bad Request", message: "Invalid filaments" }` after domain validation; Fastify schema rejections use the same `error`/`message` envelope with validation-specific text and an optional `requestId`. Source/upload reservation errors use `error: "invalid_filaments"`.
A create that names a Bambu printer returns HTTP 422 with
`error: "printer_material_incompatible"` when the pinned profiles rule out
the model or its temperature limits for the selected plate. Read
`materialCapability` for the zero-based `sourceSlot`, `printerModel`, engine
`bundle`, `code`, and `evidence`. For a source or upload create, a refusal
detected after slicing is available on the failed request in `error.body`.

Queued-job edits that submit `constraints.typed_filaments` repeat creation's catalog validation, plate coverage, and conflicting-option checks. Resending a stored row does not treat its snapshotted color as an assertion against today's catalog; type-and-color policies retain their requested color. Typed requirements cannot be combined with Make, raw AMS mappings, or legacy `required_materials` or `acceptable_materials`. Unrelated option edits preserve the stored policy. `POST /batch-jobs` rejects raw typed policies, including per-printer options; use the top-level `filaments` field on print-job creation.

Type-and-color and any-color rows accept PLA Silk, PLA Silk+, PLA+Silk, PLA+, PLA Basic, PLA Matte, PLA Matte+, and PLA SnapSpeed for PLA. HTPLA, HT-PLA, and HT PLA are one grade. NYLON maps to generic PA; generic PA does not satisfy PA6 or PA12. Finish is not matched; fibre fillers and polymer grade are. PLA, PLA-CF, and PLA-GF are distinct, as are PA6, PA12, and PA-CF. A Shore hardness such as 95A grades a TPU or TPE, and a grade that only one side names is no difference: TPU 95A HF matches TPU, while TPU 85A and TPU 95A are distinct. This applies to exact rows too. Hive also reads the grade of the filament profile the plate was sliced with, such as 95A in `Bambu TPU 95A HF @BBL P1S`. Creation refuses an exact product or alternate whose stated grade differs, and Smart Queue never selects or claims a loaded spool whose stated grade differs. A plate profile, product, or spool that states no grade accepts any.

Invented composites such as PLA-CF-GF are rejected with 422: `invalid_catalog_filament` for invalid catalog identities, or `invalid_preparation_mappings` for raw material requests and preparation mappings. Exact rows compare approved product IDs, with the same composition checks against the sliced plate and reported tray type. Catalog-only fibre evidence is retained in typed requirements, slicing mappings, and dispatch mappings. Existing material names are preserved when they already carry the fibre. An unassigned spool whose tag cannot establish the exact product uses conditional assignment guidance; type and color alone do not establish product identity.

Exact matching never falls back to type, color, or a slicer profile. New requests that name a merge tombstone are rejected with a replacement hint. The catalog merge workflow rewrites existing job references to the replacement. Stored alternate lists are de-duplicated on read and exclude their primary identity after those rewrites.
The policy persists in `print_options.constraints.typed_filaments` and is
rechecked before claim. Waiting reasons include `match`, `message`, and `messageKind`. A `requirement` message
is a label such as `Bambu PLA Matte Red (or 2 alternates)` or `PLA, any color`;
clients put it inside load or slot-conflict guidance. An `instruction` message is
specific guidance to display directly. Clients must not infer this distinction
from English wording.

Smart Queue source preparation tries another representative after a permanent
filament refusal and skips a configuration only when all its representatives
refuse. Other configurations still prepare. A named printer retains its refusal;
a lookup outage stays retryable.

Source and upload creation use these modes through typed filaments. For exact
and any-color rows, preparation resolves a loaded assignment on the selected
preparation printer and slices with its identity color: the slot's custom color, then the catalog color. Live tray color never replaces that selected color. A live material-type contradiction blocks the exact slot and asks for reassignment or reload. A color-only contradiction keeps the identity match and is recorded in `print_options.filament_warnings`. For a missing route, `on_filament_mismatch: "wait"` keeps the requested or
catalog color for the initial slice and lets admission record a filament wait.
A colorless wildcard uses neutral RGB `#808080` until a loaded match is available.
An assigned request with `"reject"` fails with `422 filament_requirements_unsatisfied`.
An unassigned request leaves material selection to Smart Queue, so a missing spool
on the preparation printer does not reject it. An unreadable selected color returns
`422 filament_color_unavailable`. Type-and-color rows keep the
requested color for slicing. HiveSlice receives RGB; the stored requirement
retains alpha. Later claim rechecks can choose another allowed alternate. They
update the dispatch target color and do not reslice an existing artifact.
Existing `model_file_id` jobs also keep their already sliced artifact; their
mapping records requested `sourceColor` and actual `targetColor`.

The separate Slice job contract at `POST /v1/slice-jobs` accepts
`materialMappings` with material and RGB color only. It does not accept these
matching policies. Use `printJobs.create` or `printJobs.createFromSource` for the
typed filament contract.

Create also accepts global filament IDs. Global filaments are platform-managed
`materials` rows with no organization owner. Search reports their
`organization_id` as `"global"`. The organization's `materials.global_filaments_enabled`
setting must be enabled. The setting defaults to enabled when absent, as in the
web material picker and Smart Queue. Organization-owned rows qualify when any of
these fields is present:

- `sku`: a non-empty, trimmed product code. Any SKU format is accepted, including an Amazon ASIN.
- `asin` or `metadata.asin`: a non-empty, trimmed Amazon ASIN string. The web form, MCP, and imports write the `asin` column.
- `import_source_product_id`: a value starting with `partner-catalog:`. Its suffix is the
  partner's own database key (`externalId`) used for catalog sync. This external ID is
  required only when both SKU and ASIN are missing.

A contradiction returns 422 `filament_catalog_conflict` with the `sourceSlot` in
`filaments[]`. An unknown or foreign catalog ID, merge tombstone, unidentified
organization row, or disabled global ID returns 422 `catalog_filament_not_found`.
Rows without a material of at most 100 characters or a usable hex color return
422 `invalid_catalog_filament`.

The shared `MaterialColor` reader returns `{ colors, primary, name, multicolor }`.
It accepts `metadata.colors` as an array, a hex string, or a JSON-array string.
Valid metadata hex entries take precedence, even when the column disagrees.
Missing, empty, or wholly unusable metadata falls back to the column hex. Blank
strings are ignored. Free-text column values remain `name`, never a hex color.
Printer filament assignment responses use MaterialHex: uppercase `#RRGGBB`, or
`#RRGGBBAA` only when alpha is not FF. A stored `#abcdef` is returned as
`slots[].color: "#ABCDEF"`. Explicit assignment hex colors use the same format.
Consumers should normalize hex values before comparing colors.

Color names use non-hex column text, then `metadata.colorName`. Material updates
and catalog upserts preserve non-FF alpha.

Colors preserve order and remove duplicates. Short RGB and RGBA hex expand, and
bare hex gains `#`. Output is uppercase `#RRGGBB` for opaque colors or
`#RRGGBBAA` for non-FF alpha. Transparent `#00000000` is usable and distinct
from opaque black `#000000`.

Multi-color rows are admitted. `catalogMatchingPrimaryColor` uses the first color
for matching, like Bambu's representative `tray_color`. Bambu reports RGBA:
missing alpha means FF, and matching requires equal alpha before measuring RGB
color distance. A clear `00000000` tray matches transparent material, never
opaque `000000FF`. Type-only matching remains an explicit separate strategy.
This normalization happens while reading. It does not migrate stored rows.

Direct Slice job and Cloud Slice material mappings accept only
six-digit `#RRGGBB`; direct RGBA mappings return HTTP 400. In contrast,
`POST /v1/print-jobs/create` accepts RGBA filament requirements and retains their
alpha for admission and matching. When that route prepares a source project,
it projects requirements to six-digit RGB for HiveSlice: `#00000000` becomes
`#000000`, and `#12345680` becomes `#123456`. This projection applies only to
slicing mappings, not the stored job requirement.
Projected source-preparation mappings are validated before a preparation is
created: material labels must fit 32 characters, and zero-based source slots
must fit 0..63. A create request accepted with broader upstream requirements
terminates as `failed` with `422 invalid_preparation_mappings` if the projection
cannot satisfy that contract. It does not remain in a preparation retry loop. Source inspection retains RGBA
observations but does not suggest an RGB-only binding for them. Load-prompt tag
colors retain their existing RGB projection because prompt storage accepts only
six digits. Preserving transparency in prompts needs a separate schema change.
An empty reported tray type means no loaded spool, even when `tray_color` is
`00000000`; a present clear material keeps that transparent color.

For an accessible merge tombstone, the slot error includes `merged_into`, the
replacement material ID. A setting read error returns 503 `catalog_store_failed`;
only a missing setting defaults to enabled.

Stored requirements, waiting reasons, and load-step requirements retain
`filamentId`, `brand`, `name`, `colorName`, `material`, and `colorHex`. Catalog identity is a snapshot. Multipart retries reuse the first saved snapshot even if the catalog changes. The persisted `match` selects exact identity, type and color, or type with any color. Omitted modes keep type-and-color proximity. Any-color waiting reasons store `color: null` and name "any color"; exact reasons name the product and alternate count. Catalog diameter is outside the snapshot and does not add a filament-diameter constraint.

Catalog validation errors in JSON or multipart creation do not reserve a new
idempotency key or `externalId`. For JSON requests that include `filamentId`,
the same applies to every other validation error that Hive returns
before it accepts the request. Correct the request, or add the missing catalog
entry, and retry with the same identity. Existing created or failed receipts
replay before a new catalog lookup. Once Hive accepts the request, changes to
its submitted fields or uploaded bytes return 409. Requests without `filamentId`
keep their existing receipt behavior.
Filament search returns catalog IDs and `acceptedByCreate`. A result with
`acceptedByCreate: true` satisfies the current catalog admission checks for
print-job filament requirements. Other create admission checks still apply.

## Search printers and filaments

Both methods require an organization API key with the `read` tier or higher.
The API derives organization ownership from the authenticated key.

The existing `GET /v1/search` and `GET /v1/materials/command-search` routes
also require the `read` tier or higher for API keys. Empty-scope API keys now
receive 403 on those routes. JWT authentication keeps its existing membership
checks.

```ts
const printerPage = await hive.printers.search({ query: "Boo P1S", limit: 10 });
const filamentPage = await hive.filaments.search({
  query: "black PETG",
  limit: 20,
});
const redFilaments = await hive.filaments.search({ query: "bambu red" });
```

| Method                                                  | Return type                   | API route                        |
| ------------------------------------------------------- | ----------------------------- | -------------------------------- |
| `printers.search({ query, limit?, offset?, signal? })`  | `Promise<PrinterSearchPage>`  | `GET /v1/printers/search?q=...`  |
| `filaments.search({ query, limit?, offset?, signal? })` | `Promise<FilamentSearchPage>` | `GET /v1/filaments/search?q=...` |

`SearchOptions` contains the string `query`, optional integer `limit` and
`offset`, and an optional `AbortSignal`. Both methods return one page and use
the client's normal GET retry policy. Invalid response shapes throw `TypeError`.
Missing authentication returns 401. Insufficient API-key scope returns 403.
Fractional or out-of-range pagination returns 400. `limit` accepts 1–50, with
default 20. `offset` accepts 0–10,000, with default 0.

`PrinterSearchPage` contains `printers`, `total`, and `query`. Each
`PrinterSearchResult` includes `id`, name, model, serial, status, location,
`score`, and `match`. The API reads organization-scoped stored observations
and uses the same shared candidate builder and ranking code as the web
palette. Queries contain 1–256 characters. Ranking happens before pagination.
Each request reads every organization printer in batches of up to 1,000 before
ranking and pagination. These reads have no per-organization cache. Large
fleets and frequent queries therefore increase database read work. The SDK
does not debounce or cache requests.

No printer search index is involved, and no printer is contacted. Printer `id`
is the identity for explicit printer placement. Search does not guarantee
readiness; `printers.get(id)` returns stored printer details.

`FilamentSearchPage` contains `filaments`, `total`, `hasMore`, `matchMode`, and
`originalQuery`. Each `FilamentSearchResult` includes `id`, `filamentId`, name,
brand, material type, canonical primary `color`, ordered `colors`, nullable
`colorName`, diameter, category, organization, and optional SKU.
`filamentId` equals the catalog material row's `id`. It is not an inventory item
ID. `acceptedByCreate` reports whether the row satisfies the same catalog
admission operation used by creation, including the organization's global-filament
setting, ownership, material, and normalized color checks. It does not promise that a print job
passes file, plate, target, or dispatch admission.

Filament search reuses the web Material Command Search picker, including its
ranked database query and the organization's global-filament setting. It can
return organization filaments and enabled global catalog filaments. Global
rows have `organization_id: "global"`. In SDK 0.4.1, eligible global rows have
`acceptedByCreate: true` and their IDs can be used in `filaments[].filamentId` on
`POST /v1/print-jobs/create`. When globals are disabled, search excludes those
rows and creation rejects their IDs with `catalog_filament_not_found`.

Organization-owned rows need a non-empty SKU, ASIN in the column or metadata, or partner external ID
as described above. Merge tombstones and rows without a usable material or hex
color have `acceptedByCreate: false`. Multi-color and transparent rows are valid.
Search does not otherwise filter out ineligible catalog rows.
An admission-setting read error returns 503; only a missing setting defaults to
enabled.

Queries contain at most 100 characters. An empty query browses the catalog.
Set the next offset to the previous offset plus the returned filament count
while `hasMore` is true. When no strict filament match exists, the picker
returns a broader catalog page with `matchMode: "broadened"` and retains the
sanitized `originalQuery`. Callers can display that distinction and ask users
to choose a filament. Neither search method selects a result or creates a job.

## Reorder queued jobs

`printJobs.reorder({ scope, printerId?, orderedJobIds }, signal?)` calls
`POST /v1/print-jobs/reorder` with the `control` scope and returns
`{ success: true }`. Use `scope: "printer"` with a printer UUID or
`scope: "global"` for unassigned jobs.

Send a nonempty list of unique job IDs. The listed jobs move to the front in
the order given. Unlisted jobs keep their relative order after them. Send one
ID to move one job to the front. Every listed job must be queued in the
selected queue.

Malformed input returns 400. Duplicate IDs return 400 with the HTTP reason
`duplicate_job_ids`. A job outside the organization or an unknown ID returns 404 `job_not_found`. A job that left the queue or changed queues returns
409 `job_not_queued` or `job_queue_changed`. The SDK does not retry the request.

## Change a print job's assignment

`printJobs.assign(jobId, { printerId, expectedPrinterId?, autoAssign? }, signal?)`
calls `PATCH /v1/print-jobs/{id}/assign` with the `control` scope. It returns
the job's `id`, `printer_id`, `queue_rank`, `global_queue_rank`, and
`status`. Assigning a queued job to a printer appends it to that printer's
queue, even when the job is already assigned there.

Send `printerId: null` to unassign the job. Omit `autoAssign` or set it to
`true` to release the job to the Smart Queue. Set it to `false` to leave the job
queued without automatic assignment. To guard the change against a concurrent
reassignment, send the current printer ID as `expectedPrinterId`. Send
`expectedPrinterId: null` to require that the job is still unassigned.

A job that is no longer queued returns 409 `job_not_queued`. A different
current assignment returns 409 `job_assignment_changed`. The SDK does not
retry the request.

## Start a queued print job

`printJobs.start(jobId, { expectedPrinterId?, organizationId? }, signal?)` calls
`POST /v1/print-jobs/{id}/start` and needs the `control` scope. It returns
`StartedPrintJob`: `{ id, printer_id, queue_rank, global_queue_rank, status,
dispatch: "requested" }`.

A resolved call means Print Hive accepted the request, not that printing began.
Print Hive sends no command to the printer. It checks that dispatch is safe now,
moves the job to the front of its printer's queue, and leaves the job `QUEUED`.
The printer's Hive Link host claims it on its next poll, which makes it
`IN_PROGRESS`. Read the job with `printJobs.get(jobId)` to follow it.

A started print uses printer time and filament. Ask the person who owns the job
before you call `start`. Pass `expectedPrinterId` with the printer you checked,
so a job that was reassigned fails with `job_assignment_changed` and starts
nothing.

Every call checks the job and the printer again. A failed check throws
`PrintHiveApiError`. A 404 or 409 means dispatch was refused. A 500 `dispatch_failed`
has an unknown outcome, because the dispatch may have committed before the
answer was lost, so read the job with `printJobs.get` before you act again. Its `status` is 404, 409, or 500, its
`code` is the response's `error` (`Not Found`, `Conflict`, or
`Internal Server Error`), and `body.reason` names the check. The
`PrintJobStartFailureReason` type lists every reason:

| Status | `reason`                                                                                                                     | Meaning                                                                                                  |
| ------ | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| 404    | `job_not_found`, `printer_not_found`                                                                                         | The job is not in the organization, or its assigned printer is missing.                                  |
| 409    | `job_not_queued`, `job_unassigned`, `job_assignment_changed`                                                                 | The job is not `QUEUED`, has no printer, or is assigned to a printer other than the expected.            |
| 409    | `printer_offline`, `printer_not_ready`, `printer_in_maintenance`, `printer_locked`, `printer_busy`, `material_route_changed` | The printer cannot take the job now, or no longer holds the materials the job's route chose.             |
| 409    | `model_file_unavailable`, `model_file_deleted`, `model_file_not_ready`, `model_unavailable`, `model_deleted`                 | The job's model file is missing, deleted, or still processing. Retry `model_file_not_ready`.             |
| 409    | `batch_scheduling_held`, `batch_scheduling_scope_conflict`, `h3c_rack_dispatch_unqualified`                                  | An operator holds the job's batch, or start is on hold for this printer model.                           |
| 500    | `model_file_check_failed`, `dispatch_failed`                                                                                 | The file check failed (nothing changed), or dispatch failed with an unknown outcome: read the job first. |

The client never retries `start`, including after a 429, a 503, or a lost
response, because repeating it is the caller's decision.

```ts
import { PrintHiveApiError } from "@printhive/api";

// approvedPrinterId: the printer the person approved before create.
if (!approvedPrinterId) throw new Error("No printer was approved for this job");
try {
  const started = await hive.printJobs.start(job.id, {
    expectedPrinterId: approvedPrinterId,
  });
  console.log(started.dispatch, started.status); // "requested" "QUEUED"
} catch (error) {
  if (error instanceof PrintHiveApiError && error.status === 409) {
    console.log(error.body?.reason, error.body?.message);
  } else {
    throw error;
  }
}
```

## Recover a managed Bambu print

Call `printJobs.getRecoveryContext(jobId)` to get the active `startAttemptId`
and the reported `hmsFault`, if any. Use its `allowedActions` to choose a command. The fault ID represents the print attempt,
firmware job ID, and decimal error code. The API omits device credentials.
Hive Link checks the task and fault against a fresh printer report before sending.

- With a `control` key, call `printJobs.recover(jobId, { action: "hmsIgnore", startAttemptId, faultId })`
  to ignore the reported fault. Use `"hmsResume"` when the fault has been resolved.
- With a `dangerous` key, call `printJobs.hmsStop(jobId, { receiptId, startAttemptId, hmsFaultId })`
  to Stop for the reported fault. Use the returned receipt ID with `getStop`
  to observe completion. After a timeout, read the receipt before sending again.

If `pendingStopReceiptId` is present, read that receipt with `printJobs.getStop`
for the latest confirmation status. Recovery returns 409 `stop_unresolved`
while a legacy Stop for the same claim is unresolved. It returns 409
`stop_pending` for an acknowledged Stop awaiting proof the print ended, or
until 30 seconds after an unresolved HMS Stop's publish cutoff. A refusal before
sending clears that dispatch's fence immediately. If Stop returns 409
`recovery_action_busy`, wait for the in-flight action to settle and read the job
state again.
Refresh context on 409 `recovery_fault_changed`, `recovery_attempt_conflict`,
or `recovery_action_expired`. The last code means the action expired before
Hive Link sent it. Older Hive Link versions return
`recovery_host_upgrade_required`. A 200 from `recover` confirms firmware acknowledgement. A 409
`recovery_device_refused` means the firmware explicitly rejected the command.
After a 502, read job and printer state before deciding whether to send another action.

## Cancel queued work and stop an active attempt

`cancelQueued(jobId)` sends no printer command. It also accepts RETRYING work
without an open reserved, acknowledged, ambiguous, or active confirmed attempt.
RETRYING with an unresolved Start Print attempt returns `stop_not_ready` and
`canCancelWithoutStop: false`; wait for that attempt to resolve. A concurrent claim returns a typed conflict;
read the state again before choosing the next operation. Cancellation records
history once, sets completion time, and clears retry scheduling and handoff.
COMPLETED, FAILED, and ERROR return HTTP 409 `print_job_terminal` with
`reason: "job_already_ended"` and the actual `jobStatus`. CANCELLED replay stays
successful. A claim before confirmation returns `stop_not_ready`; a confirmed
active attempt returns `queued_cancel_conflict`. QUEUED work with a confirmed
attempt in its current claim generation and no completion time returns the same
`queued_cancel_conflict` and cannot use no-command cancellation. Its message is
"The job is no longer eligible for no-command cancellation. Use Stop instead."
`PrintJobControlError.error` includes the literal `queued_cancel_conflict` code.

```ts
const state = await client.printJobs.getControlState(jobId);
if (state.canCancelWithoutStop) {
  await client.printJobs.cancelQueued(jobId);
} else if (state.stopAvailability === "unsupported") {
  console.log(state.reason, state.printerFamily, state.message);
} else if (state.stopAvailability === "not_ready") {
  console.log("Start Print is not confirmed. Read the state again shortly.");
} else if (state.stopAvailability === "ready" && state.startAttemptId) {
  // Persist this ID before sending the request.
  const receiptId = crypto.randomUUID();
  const input = { receiptId, startAttemptId: state.startAttemptId };
  const receipt = await client.printJobs.stop(jobId, input);
  const current = await client.printJobs.getStop(jobId, receipt.id);
  console.log(current.confirmation);
}
```

Stop requires the literal `dangerous` scope. Queued cancellation accepts `control`
or `dangerous`, so one Dangerous key can perform both operations. Unbound legacy
`*` keys are accepted for both. A `host` scope or
any `apiKeyHostId` principal returns 403 even with those scopes or `*`;
`production:*` grants neither operation. Human JWTs require verified organization
membership. The SDK preserves the 403 error and capability message.
State and receipt reads require Read scope. An IN_PROGRESS job without a
confirmed attempt returns `stop_not_ready`, so wait and read its state again.
Non-Bambu Stop returns HTTP 409 `stop_unsupported` immediately with
`reason: "printer_family_unsupported"`, `printerFamily`, and a human `message`.
Do not poll an unsupported printer waiting for bound Stop to become possible.
Unsupported receipts expose the same reason, family, and message with
`confirmation: "unsupported"`. Queued work can still use no-command cancellation.
A new Stop on COMPLETED, CANCELLED, FAILED, or ERROR returns HTTP 409 `stop_job_terminal`
with `reason: "job_already_ended"`, terminal `jobStatus`, and a human `message`.
The SDK exports `PrintJobControlError` for these bodies. Stop, receipt reads, and
control-state reads document 404, 409, and 503 responses in the generated spec.
Both mutations document 403. Replaying a matching existing receipt and attempt
after the job becomes terminal returns that receipt without another abort.

`command_outcome` is `acknowledged`, `unknown`, `rejected`, or `not_delivered`.
Regular job Stop works with existing Hive Link versions. HMS Stop requires an
updated Hive Link and returns `not_delivered` if the Host reaches its publish
cutoff before it can send the command.
An ACK is not confirmation. `abort_acknowledged` stays true across re-sends for
the same attempt. The API reconciles pending receipts in the background;
`getStop` reserves a shared observation slot and skips the printer read while
that slot is in the future. Read-only observations have an eight-second budget.
The API also confirms after the Host closes CANCELLED in the same claim
generation on the same printer, whether the abort reply was acknowledged or unknown.
A FAILED or ERROR closure stays pending during up to three final
observations. Failed reads can retry after the cooldown; fresh same-task
non-running evidence confirms Stop and records
CANCELLED. Host automatic retry returns `stop_requested` for that generation,
including after an unconfirmed outcome. Explicit operator retry remains separate.
After the active attempt's 60-second budget or exhaustion of final observations,
`unconfirmed` stops automatic polling until
an explicit re-send. An observation already in flight can still confirm Stop
after the deadline when it freshly shows the same task ended. Stale, retained,
and foreign-attempt reports cannot confirm.
`already_ended` preserves a naturally completed or previously ended job's status.
It is distinct from confirming a requested Stop. A RETRYING attempt reported as
`already_ended` can then use no-command cancellation. Readiness stays false until
bed clearance. Receipt reads remain available after the job becomes terminal.

After `not_delivered`, repeat `stop` with the same persisted input when the Host
is available or upgraded. After `unconfirmed` or rejection, an explicit repeat
can retry the same task-bound command while the job still owns that attempt.
A duplicate while dispatch is pending observes only. If another caller already
reserved the attempt's receipt, persist the canonical returned `id` for reads.
Changing the attempt returns HTTP 409 instead of stopping its successor.

Both `stop` and `getStop` have a minimum 45-second client timeout per attempt, above the server's
30-second Pulse budget. A larger configured timeout remains in effect, and an
AbortSignal can end the wait earlier. Timeout, abort, or lost connection does not
prove non-delivery. Recover with `getStop(jobId, persistedReceiptId)` or repeat
`stop` with the original input. Preserve that input across retries. Explicit
DB-only `force` recovery remains separate.

These methods replace Printago's `sendStop:false` and `sendStop:true` branches.
`cancelCreateRequest` still cancels pre-admission preparation. Mock tests prove
command construction and state contracts, not real firmware. No npm publication
occurs until the owner approves it.

## Assign, clear, and inspect Printer material slots

Use an organization API key with `control` scope for these writes. A `read` key
can inspect slot state. These methods do not change operator bed-clear readiness.
A Printer material slot is a physical filament position on a printer. A Filament
assignment is the material that Hive records for that slot.

```ts
const result = await client.printers.materialSlots.assign(printerId, {
  slots: [
    { position: 0, materialId: exactMaterialId },
    { position: 255, materialId: exactMaterialId },
  ],
  syncPolicy: "automatic",
});

for (const slot of result.slots) {
  console.log(slot.record, slot.printerSync, slot.observation);
}

await client.printers.materialSlots.clearAssignments(printerId, [0]);
await client.printers.materialSlots.refreshRfid(printerId, 0);
const snapshot = await client.printers.materialSlots.list(printerId);
console.log(snapshot.freshness, snapshot.slots);
const slot = await client.printers.materialSlots.get(printerId, 0);
const saved = await client.printers.materialSlots.getAssignment(printerId, 0);
```

| Method                                                           | Request                                                         |
| ---------------------------------------------------------------- | --------------------------------------------------------------- |
| `materialSlots.layout(printerId, signal?)`                       | `GET /v1/printers/{id}/material-slots/layout`                   |
| `materialSlots.list(printerId, { positions? }?, signal?)`        | `GET /v1/printers/{id}/material-slots`                          |
| `materialSlots.get(printerId, position, signal?)`                | `GET /v1/printers/{id}/material-slots/{position}`               |
| `materialSlots.getAssignment(printerId, position, signal?)`      | `GET /v1/printers/{id}/material-slots/{position}/assignment`    |
| `materialSlots.assign(printerId, input, signal?)`                | `POST /v1/printers/{id}/material-slots/assign`                  |
| `materialSlots.clearAssignments(printerId, positions, options?)` | `POST /v1/printers/{id}/material-slots/clear-assignments`       |
| `materialSlots.refreshRfid(printerId, position, signal?)`        | `POST /v1/printers/{id}/material-slots/{position}/refresh-rfid` |

The result types are `AssignFilamentsResult`, `ClearFilamentAssignmentsResult`,
`RefreshMaterialSlotRfidResult`, `MaterialSlotList`, and `MaterialSlot`.
`layout` returns `PrinterMaterialLayout`, including nozzle and source topology,
the hotend rack, and per-slot operation availability.
`getAssignment` returns the saved Filament assignment without asking the printer,
so its `observation` is `{ status: "unavailable", reason: "observation_not_requested" }`.

**Deprecated names.** `client.printers.filaments` is deprecated. Its `assign`,
`clear`, `refreshRfid`, `get`, and `getAll` take the inputs and return the values
of `materialSlots.assign`, `clearAssignments`, `refreshRfid`, `get`, and `list`, and
send every call to the `/material-slots` paths. The type names `FilamentAssignment`,
`FilamentClear`, `FilamentRfidRefresh`, `FilamentSlotState`, `FilamentSlotsState`,
and `ReadFilamentSlotsInput` are deprecated aliases of the types above. Deploy the
API before you release this version, because an API that predates the
`/material-slots` paths answers them with 404. The HTTP paths under
`/v1/printers/{id}/filaments` are also deprecated. They keep their statuses and
bodies, answer with `Deprecation` and `Link` headers, and carry no removal date.
The successors are `filaments/state` to `material-slots`, `filaments/{position}/state`
to `material-slots/{position}`, `filaments/{position}/assignment` to
`material-slots/{position}/assignment`, `filaments/assign` to `material-slots/assign`,
`filaments/clear` to `material-slots/clear-assignments`, and
`filaments/{position}/refresh-rfid` to `material-slots/{position}/refresh-rfid`.
`POST .../filaments/clear-captured` has no path of its own. Its successor is
`clearAssignments` with `expectedVersion`. The `Link` header names the successor
path without the query string.

`materialId` identifies the exact Hive catalog material. Firmware filament family
and setting IDs identify profiles and appear separately in `expected` and
`observation.reported`.

Slot-operation response colors use MaterialHex: uppercase `#RRGGBB`, or `#RRGGBBAA`
only for non-FF alpha. Hex request colors accept RGB or RGBA with an optional
`#` and are normalized before storage. Printer commands and `tray_color` use
uppercase `RRGGBBAA` without a leading `#`. Normalize both formats before comparing.

| Field                                                                         | Format                                |
| ----------------------------------------------------------------------------- | ------------------------------------- |
| Assignment `slots[].color`                                                    | MaterialHex, or null when unavailable |
| `expected.color`, `observation.reported.color`, slot-state `assignment.color` | MaterialHex, or null when unavailable |
| Directory `loadedFilament[].color` and `colorHex`                             | Existing directory format, unchanged  |

Existing directory and stored-row color formats are outside this contract change.
Each assignment reports persistence, delivery, and observation separately.
`record: "saved"` means Hive stored the Filament assignment. `database` repeats
`record` and is deprecated, as is `databaseError`, which is diagnostic text that
can change. `printerSync.status: "sent"`
means dispatch was acknowledged. Only `observation.status: "observed"` means a
fresh request-bound post-barrier report matched type and full RGBA color.
This describes the printer's fresh report. It does not prove that firmware
accepted a particular write.
Family and setting IDs must match when the printer reports them; omitted IDs
do not manufacture a mismatch. Mismatches, stale reports, and unavailable observations do not confirm a
write. Older APIs may omit the additive observation fields. An offline printer
can save an assignment without receiving a command. `syncPolicy: "save-only"`
also avoids dispatch.

Post-assignment observation requires the Hive Link release with request-bound
live reads. A released Host that rejects `requestBound` returns
`observation: { status: "unavailable", reason: "host_upgrade_required" }`.
Hive preserves saved/sent receipts and does not retry with an unbound read.

Host credentials cannot access filament endpoints, even with `*` or `control`.
Unbound `host` keys are also rejected. Unbound legacy `*` keys remain supported.
Assignment, clear, and RFID require `control`; state and assignment reads accept
`read` or a higher scope. Read-only and empty-scope keys cannot edit slots.

Clear deletes Hive's Filament assignment without a metadata write or RFID request.
`record: "not_found"` means there was no assignment to delete. It returns a fresh
report when available. It does not restore metadata previously written to the
printer. RFID reread is a separate explicit AMS action. External positions 254
and 255 return HTTP 422 with `external_rfid_unsupported`. RFID command acceptance
and a fresh report do not prove that reading the tag has completed.
RFID requires the new Bambu material protocol and a reported empty extruder
(`hw_switch_state: 0`). Loaded or unknown extruder status returns typed HTTP 409;
an unsupported protocol returns `rfid_protocol_unsupported` with HTTP 422.
The API never substitutes a G-code command.

`clearAssignments(printerId, [position], { expectedVersion })` deletes the
assignment only while its saved version is current. `expectedVersion` is the
`version` of the assignment that `getAssignment` or `get` returned. Name exactly
one position with it, or the call throws a `RangeError` before it sends anything.
A different saved version, or no saved assignment, fails with HTTP 409 and
`assignment_changed`, and nothing is deleted. A clear with `expectedVersion`
reads the printer afterward, as a clear without it does. Pass `{ signal }` to
cancel a clear.

Positions are zero-based physical indices. For a standard AMS, position is
`ams_id * 4 + slot_id`, including AMS HT position 512 for unit 128, tray 0.
Standard AMS positions span 0–127. HT positions are 512, 516, 520, 524, 528, 532,
536 and 540; the other HT tray indices are invalid. External main/deputy positions 255/254 use canonical
addresses `{ams_id:255,slot_id:0}` and `{ams_id:254,slot_id:0}`. Assignment accepts at most two slots per request; clear and selected batch reads accept up to 32.
Split larger assignments into separate requests. The SDK rejects oversized
assignment batches locally, and the public API enforces the same bound.
Single-nozzle legacy `vt_tray` reports expose one external position, 255, even
when the wire tray id is 254. Dual-nozzle reports preserve both external slots.
The client rejects empty or oversized selections and invalid addresses before
making a request.

Busy or claimed printers return HTTP 409. A control-scope refusal returns HTTP 403. `PrintHiveApiError` preserves server status and error code. The client
never automatically retries assignment, clear, or RFID requests, including
network failures and HTTP 503/504. After an uncertain write, inspect slot state
before deciding whether to send another command. Every method accepts an
optional `AbortSignal`, as its last argument or as `clearAssignments`'s `signal` option.

Any non-terminal job hold keeps edits blocked unless its stored
`print_options.filament_route_state` is `waiting` with a nonempty
`filament_waiting_reasons` array. A 409 error includes
`error.body.reason: "printer_held_by_job"`, `error.body.holdingJob: { id, status }`,
and `error.body.message` giving status-specific guidance: PAUSED means resume
or cancel; IN_PROGRESS means wait or stop; QUEUED/RETRYING means wait or cancel.
Not every `printer_busy` 409 names a job, so read `error.body.holdingJob` only
after `error.body.reason === "printer_held_by_job"`. When an assign or clear write
waits more than five seconds for the printer row, which a claim or another printer
write can hold, the API stores nothing for that call and returns a 409 with
`error.body.code: "printer_busy"`, neither `reason` nor `holdingJob`, and
`error.body.message: "Another update is holding the printer. Retry editing filament."`
Retry after a short delay. For an assignment batch, check `error.body.slots` first,
because slots saved before the timeout keep their receipts. A printer that is
printing or has unknown status, with no job hold, also returns `printer_busy`
without `reason` or `holdingJob`; its `message` is the only detail.
If a job takes the printer after saving, those details appear in the slot's
skipped `printerSync` receipt. The API sends no metadata command in that case.
Terminal job holds permit metadata edits without changing bed-clear readiness.
A recorded filament wait permits assign, clear and RFID so the operator can
correct it. Allowed edits re-evaluate the job through the material-claim path.
`reevaluations` reports `resolved`, `waiting`, `not_waiting` or `unavailable` for
that material route; it grants no bed-clear, printer readiness or physical movement.
A mid-batch hold stops later storage writes with 409 and preserves completed
per-slot receipts in the error body's `slots`. Inspect those receipts before retrying.
The error body also retains `reevaluations` for waiting jobs affected by saved
slots. Load prompts at those saved positions are resolved even when a later slot
is refused.

Use `list(printerId)` for polling, or `list(printerId, { positions: [0, 512] })`
for a subset. Poll no faster than once every two seconds. One snapshot supplies
the whole batch. Concurrent reads are coalesced by printer, and GET reuses a
successful snapshot for less than two seconds with its original `observedAt`.
Write verification always uses an independent post-action read. A legacy saved
row without a setting ID or valid hex color has no firmware
expectation and returns fresh facts as `reported`. `get(printerId, position)`
reads one slot through its own operation, which answers as the batch read does for
that selection. Its returned `position` is the server canonical address: `get(printerId, 254)` can return position 255 for
a legacy single external tray, including offline or failed-live reads. Batch `freshness` distinguishes
an unavailable read from a fresh snapshot with no reported slots.

Unless you explicitly configure `PrintHive({ timeoutMs })`, assignment uses a
55-second client timeout. The two-slot command/pacing/read budget is at most
45.25 seconds, leaving proxy headroom; other methods keep the 30-second default.
Your configured timeout takes precedence but does not increase the two-slot
request cap. A timeout or abort can occur after saving or sending, so inspect
state before deciding whether to retry.

Single external addressing is driven by stored `vt_tray` without `vir_slot`.
Reads merge legacy 254 rows into 255. Assignment stores 255 and removes the old
alias in one transaction; clear deletes both. Untouched production rows need a
separate follow-up backfill migration. Deploy the storage RPC migration before
the updated API; this PR performs no bulk production-row migration.

RFID validates the selected unit/tray against stored topology and returns 422
`slot_not_present` for an absent source. Assignment can save that intent, but
skips delivery with the same reason. A Pulse HTTP 200 carrying a printer ACK
timeout is `command_outcome_unknown`, not a confirmed rejection or not-sent result.
Missing reliable extruder state returns `filament_state_unknown` with operator guidance.

Mock verification covers API contracts and simulated reports. It does not
establish firmware behavior on physical printers. This release has not been
published to npm.
