# AI CAD prototype REST API (v1, local)

Server: `python server/app.py [--host 127.0.0.1] [--port 8080] [--lan] [--retention-hours 24]`
Base URL: `http://127.0.0.1:8080/v1`. Website on the same port: `http://127.0.0.1:8080/` is the main page
(`landing.html`: the two sites side by side, animated, with the features); `/app` is the editor with every mode.

Two sites (tasks3 2026-11-24), one page: `/light` is the site for everyone (Simple only, with lessons), `/pro` the one
for professionals (Autodraw, Pro and Automation, with a tour); `/app` has every mode. On a real server the host decides:
`AICAD_EDITION_HOSTS="aicad.app=light,pro.aicad.app=pro"` (other hosts: `AICAD_EDITION`, default `all`). The page
learns it from its `<meta name="aicad-edition">`.

Accounts, plans and AI credits (tasks3 2026-11-24, `accounts.py`) are on only with `AICAD_ACCOUNTS=1`. Then:
- every AI request costs one credit: assistant turns, `standards/check` and `standards/classify` with `ai`,
  `ai/labels`, `scripts/write`;
- without signing in an AI request answers 401 `E_SIGN_IN`, with no credits left 402 `E_NO_CREDITS`;
- `GET /sessions` lists nothing;
- a session belongs to whoever made it (`access.py`): the browser (the HttpOnly cookie `aicad_browser`, set by the
  201 that made it) and the signed-in user (also added later, when that browser signs in). Others get 404 `E_NOT_FOUND`.
  This machine (the loopback without a proxy's `X-Real-IP` / `X-Forwarded-For`) reaches every session;
- `/mcp` and `/admin/*` answer only this machine (403 `E_FORBIDDEN` through the proxy);
- `/v1` and `/mcp` take `AICAD_RATE_PER_MIN` requests a minute per client (default 600; the proxy's `X-Real-IP`), then
  429 `E_RATE_LIMIT` with `Retry-After`; an owner keeps `AICAD_MAX_WORKERS_PER_USER` workers live (default 4: the
  least recently used close and reopen when used); uploads up to `AICAD_MAX_UPLOAD_MB` (default 50).

| Method | Path | Body | Returns |
|---|---|---|---|
| GET | `/me` | | `{accounts, google_client_id, user: null \| {id, email, name, plan, credits: {plan, daily, daily_left, bonus_left, left}, trial, trial_used, learn}, plans}` |
| POST | `/auth/email` | `{email}` | `{sent}`: a 6-digit code mailed (`AICAD_SMTP_HOST`, `_PORT`, `_USER`, `_PASSWORD`, `_FROM`; none: the server's log; `AICAD_ACCOUNTS_DEV=1`: also `dev_code`); once in 30 s; the mail not sent: 502 `E_MAIL` (the code dropped, ask again at once) |
| POST | `/auth/email/verify` | `{email, code, agree?, name?}` | `{user, new}` and the HttpOnly cookie `aicad_session` (30 days); an e-mail without an account: 409 `E_NEW_ACCOUNT` (the code kept) unless `agree: true` (the Terms and the Privacy policy accepted), then the account is made (Free: 10 AI requests; `new: true`) |
| POST | `/auth/google` | `{credential, agree?}` | the same, from a Google ID token (RS256, checked against Google's keys for `AICAD_GOOGLE_CLIENT_ID`) |
| PATCH | `/me` | `{name}` | `{user}`: the user's name |
| DELETE | `/me` | | `{deleted}`: the account, its sign-ins and codes (its events kept without it); signed out |
| POST | `/auth/logout` | | `{signed_out}` |
| GET | `/plans` | | `{plans: [{id, name, price, daily, once, features}], trial_days, payments, me}` (an event `plans_view`); `payments` is false, or with card payments on (`billing.py`) `{provider: "paddle", client_token, environment: sandbox \| production, prices: {home, pro}, trial_days}` |
| POST | `/plans/trial` | `{plan: home \| pro}` | the user: a 7-day trial without a card, once (`trial_start`); with card payments on 409 (the trial comes with the card at the checkout) |
| POST | `/plans/subscribe` | `{plan}` | `{recorded, payments: false, message}`: no payments yet, the wish to pay is recorded (`subscribe_intent`) |
| POST | `/plans/checkout` | `{plan: home \| pro}` | card payments on: what the page opens Paddle's checkout with: `payments` + `{price_id, email, custom_data: {aicad_user}}` (`checkout_open`) |
| POST | `/billing/paddle` | Paddle's webhook (raw) | `Paddle-Signature: ts=..;h1=..` checked (HMAC-SHA256 of `ts:body`, 5 minutes): 401 `E_SIGNATURE` else `{ok, user, plan, status}`; each `event_id` once (`{duplicate: true}`); `subscription.*` sets the plan until the period's end + 3 days (canceled / paused: now); `transaction.completed` records the amount |
| GET | `/billing/manage` | | the user's subscription: `{cancel, update_payment_method}` (Paddle's links, with `AICAD_PADDLE_API_KEY`) or `{message}` |

The user (`/me`) also has `subscription: null | {status: trialing | active | past_due | canceled | paused, until}`;
the funnel also counts `checkout_open`, `sub_trialing`, `sub_active`, `sub_canceled` and has `revenue` per currency
(`{total, payments}`, in the currency's lowest units).
| POST | `/me/learn` | `{learn}` | the lessons' progress kept in the account |
| GET | `/admin/funnel` | | from this machine only: per event (`signup`, `plans_view`, `trial_start`, `subscribe_intent`) its events, users and plans; `users` |

Status: local prototype. No authentication, binds to 127.0.0.1 only. CORS is open (`*`).
`--lan` (for a phone on the same Wi-Fi) listens on all interfaces, prints this machine's LAN addresses and accepts them
as origins (IP literals only, so DNS rebinding stays refused). Anyone on that network can then use the server.

## Conventions

- **Bodies.** Requests and responses are JSON (UTF-8). The exceptions are DWG upload and download, which use raw bytes.
- **Units.** Coordinates and sizes are in drawing units (mm for our drawings). Values are rounded to 0.1.
- **Handles.** Entity handles are hex strings, as AutoCAD shows them (for example `3D24`).
- **Sessions.** A session is one uploaded DWG. The worker reads it once and keeps it in memory.
- **Versions.** Every edit that changes something saves a new version. Version 0 is the upload and is never modified.
- **Dry run.** Every edit takes `?dry_run=1` (or `"dry_run": true` in the body): it runs, reports what it would change
  (`"dry_run": true`, `"summary": "Would do: ..."`, the full `result`), and is then dropped. No version is made.
- **Locked layers.** Edits leave objects on locked layers alone, as AutoCAD does, and list them in `result.skipped_locked`;
  `"force": true` edits them anyway.
- **Checked against AutoCAD.** Every edit below is also made by AutoCAD itself on the same drawing, and the two results
  are compared as AutoCAD reads them (`tests/test_core_ops.py`, see `testset/README.md`).
- **Errors.** Every error has the body `{"error": {"code": "E_...", "message": "..."}}`:

| HTTP | Codes |
|---|---|
| 400 | `E_INVALID_ARGUMENT`, `E_BAD_REQUEST` |
| 404 | `E_NOT_FOUND`, `E_UNKNOWN_METHOD` |
| 409 | `E_CONFLICT`, `E_EXISTS`, `E_CONFIRM`, `E_NO_DOCUMENT` |
| 413 | `E_TOO_LARGE` |
| 422 | `E_UNREADABLE`, `E_UNSUPPORTED` (e.g. DXF of a drawing with ACA objects) |
| 500 | `E_WRITE`, `E_WORKER_DIED`, `E_INTERNAL` |

### Limits

- DWG or DXF upload: up to 50 MB.
- JSON body: up to 2 MB.
- A session's worker closes after 15 min idle. It reopens automatically on the next call.
- Sessions older than `--retention-hours` (default 24) are deleted with their files. Set it to 0 to keep them.

---

## Endpoints

| Method | Path | Body | Returns |
|---|---|---|---|
| GET | `/health` | | `{ok, version, sessions}`; `version` is the product version (file `VERSION`) |
| GET | `/docs` | | this reference as Markdown (rendered page: `http://127.0.0.1:8080/docs`) |
| GET | `/samples` | | `{samples: [{name, title}]}` |
| GET | `/furniture-library` | | `{items, tags}`: the furniture catalog the assistant places from (MCP `dwg_furniture_library`, `dwg_furniture_place`; the page's library, `tools/export_library.mjs`) |
| GET | `/samples/{name}/file` | | the sample's DWG bytes (the website opens it on the device) |
| GET | `/assistant` | | `{backend, available, reason}`: whether the assistant can run |
| GET | `/standards` | | the [standards database](#standards-database): `{standards, countries, profiles}` in brief |
| GET | `/standards/{id}` | | one standard record (`us-ncs`, `de-din-1356-1`, ...) |
| GET | `/standards/countries/{cc}` | | a country profile (`ru`, `de`, ...) |
| GET | `/standards/profiles[/{id}]` | | the drawing standards the editor applies (`aicad-default`) |
| GET | `/standards/targets` | | what a drawing converts to: `{countries: [{country, name, profile, language, own_layer_standard}], profiles, languages}` |
| POST | `/analysis` | `{facts}`: the core's `analysis_facts` of a drawing on the device | the [analysis](#analysis-how-the-drawing-is-made) of those facts |
| POST | `/autofix` | `{facts, gaps?, standard?, name?}`: a drawing on the device (its core's `analysis_facts` and `wall_gaps`) | the [auto-fix](#auto-fix) plan: `{standard, fixes, steps, summary}` (the page runs the steps as one version) |
| POST | `/sessions/{id}/autofix` | `{standard?, tolerance?, dry_run?}` | the [auto-fix](#auto-fix) plan + Edit result: one version |
| GET | `/sessions/{id}/analysis` | | the [analysis](#analysis-how-the-drawing-is-made) of the session's drawing |
| POST | `/standards/convert-plan` | `{layers: [name], to, from?}` | the [conversion](#standards-database) plan: `{from, to, rename, props, kept, unrecognized, missing, steps, by_words, ambiguous}`; a layer no profile names is taken by the element's word in its name when it is the only one for that element (`by_words`); several for one element, a state word (existing, new, demolished) or a tag / hatch layer: kept (`ambiguous` lists the several) |
| POST | `/ai/labels` | `{texts: [str], language?, decimal_separator?}` | `{texts, changed, cost_usd}`: translated by the assistant's model (with `language`), area numbers reformatted |
| POST | `/scripts/write` | `{request, layers?: [str]}` | `{script, steps, errors, cost_usd}`: an Automation script written by the assistant's model from the request (the website's AI panel); read by the scripts' own reader, wrong lines sent back to the model once; `# cannot: ...` when the commands cannot do it; 503 without the assistant |
| POST | `/sessions/{id}/standards/convert` | `{to, from?, translate = true, dry_run?}` | the plan + Edit result: layers and labels converted, one version |
| POST | `/standards/check` | `{layers: [Layer with by_type, blocks?], to, ai?}` | [check](#standards-database) of a layer table against a standard: `{standard, from, issues, counts, cost_usd}` |
| POST | `/sessions/{id}/standards/verify` | `{to, ai?, fix?, dry_run?}` | the same on a session; `fix` applies every fixable issue as one version |
| POST | `/sessions/{id}/walls/add` | `{points: [[x, y]...], closed?, thickness, layer, walls_as?: lines \| outline}` | Edit result: a wall added to the [wall outline](#walls-as-their-outline), drawn as `walls_as` says (the standard's `draw.walls`; default: the drawing's way, else lines) |
| POST | `/sessions/{id}/walls/redraw` | `{wall_layer, walls_as: lines \| outline, repair?}` | Edit result: the walls on the layer drawn again that way (converting to another standard), doors and windows staying on them. A drawing made elsewhere whose wall lines do not close its material (an outline drawn twice, open polylines, wall ends left open at a door) is read leniently and its closed outline written instead (`repaired: true`); `repair: true` does only that (nothing else redrawn) |
| POST | `/sessions/{id}/blocks/cutter` | `{blocks: [name] \| select, cut: bool, confirm_shared?}` | Edit result + `blocks`: the blocks (named, or of the selected references) marked to cut walls or not (cutters); their references standing on walls cut their gaps or close them. 409 `E_CONFIRM` when the block has references beyond the selection, until `confirm_shared: true` |
| POST | `/sessions/{id}/openings/redraw` | `{door?: {block, symbol}, window?: {block, symbol}}` | Edit result: every door / window reference takes that block (made, or redrawn with that symbol), keeping its place, turn and scale |
| POST | `/sessions/{id}/units` | `{units: mm \| cm \| m \| in \| ft, scale? = false}` | Edit result + `{units, measurement: metric \| imperial, scaled, objects, dimstyles, constraints_removed}`: the drawing's [units](#units-and-measurement-systems), converted (`scale`) or only set |
| POST | `/sessions/{id}/view` | `{window?: [x0, y0, x1, y1]}` | Edit result + `{window, updated}`: the view AutoCAD opens the file at (its `*Active` viewport, from above). Without `window`: the drawing's extents, only when the stored view shows none of them. Every save does the latter by itself (a new drawing's default view is 10 units round 0,0); the summary's `view` is the stored window. AutoCAD shows the whole window, keeping its lower left corner |
| POST | `/sessions/{id}/dimstyles` | `{name? \| names?: [..] \| "*", terminator?: tick \| arrow, tick_size?, extend?, text_height?, scale?, paper?: mm, redraw? = true}` | Edit result + `styles: [{name, terminator, tick_size, arrow_size, extend, text_height, scale}]`, `redrawn`: [dimension styles](#dimensions-by-the-standard) (sizes on paper); without changes it reads them |
| POST | `/sessions/{id}/walls/cut` | `{at, width, kind: door\|window, wall_layer, side?, hinge?, along?, layer?, dim_layer?, dims?, walls_as?, block?, symbol?}` | Edit result + `{thickness, block, insert, dimension, gap}`: an opening cut through the wall at `at`, its block and dimension |
| POST | `/sessions/{id}/walls/at` | `{at, wall_layer}` | `{along, across, face, thickness, from, to}`: the wall of the outline at a point |
| POST | `/sessions/{id}/walls/model` | `{wall_layer}`, or `{wall_layers?, opening_layers?, scale?}` for [any drawing](#walls-of-any-drawing-layer-categories) | `{walls: [{id, a, b, t, length, band, out, ends, openings, cuts?, materials?}], nodes: [{p, walls}]}`: [the walls recognised](#walls-as-objects-simple-mode), `materials` [their components](#materials) |
| POST | `/sessions/{id}/walls/edit` | `{wall_layer, dim_layer?, walls_as?, op: remove, at: [[x, y]...]}` \| `{..., op: thickness, at, thickness}` \| `{..., op: node, from, to}` | Edit result + `{walls, removed_walls}` |
| GET | `/sessions/{id}/plan-materials` | | `{materials: [{name, pattern, scale, angle, color, group, notes, objects}]}`: the drawing's [materials](#materials) |
| POST | `/sessions/{id}/plan-materials` | `{name, pattern?, scale?, angle?, color?, group?, notes?, new_name?}` | Edit result + `{material, new}`: a material made (`new`) or changed (its hatches follow, in `changed`) |
| POST | `/sessions/{id}/objects/plan-material` | `{select, name \| null, transparency?, force?}` | Edit result + `{hatches}`: the objects take the material (hatches: its hatch and colour); `null` removes it |
| POST | `/sessions/{id}/walls/3d` | `{wall_layer, wall_height?, door_height?, window_height?, sill?}` | `{gltf, walls, doors, windows, wall_height, unit_mm}`: [the plan in 3D](#the-plan-in-3d-simple-mode) |
| POST | `/sessions/{id}/walls/3d-settings` | `{wall_height \| null}` | Edit result: the drawing's wall height |
| POST | `/sessions/{id}/walls/material` | `{wall_layer, at, name \| null, layer? = A-WALL-PATT, replace?}` \| `{wall_layer, at, components: [{name \| null, thickness, hatch?}], from?, layer?, replace?}` | Edit result: the wall through `at` takes the [material](#materials) (its hatch over the wall) or loses it; or its components side by side |
| POST | `/sessions/{id}/stairs` | `{a: [x, y], b: [x, y], width, layer?, dim_layer?, dim_offset? = 600 mm}` | Edit result (`created`: the stair, its dimension) + `block`: a [stair](#stairs-simple-mode) from the bottom step's middle `a` to the top step's middle `b` |
| POST | `/sessions/{id}/walls/floor` | `{select, layer}` | Edit result: rooms' fills become their [floors](#simple-mode-rooms) |
| POST | `/sessions/{id}/walls/rooms` | `{fill_layer, label_layer, label_height? = 250 mm, unit? = m² (ft², sq ft, SF: square feet), decimals?, decimal_separator?, min_area? = 0.5 m²}` (sizes in the drawing's units) | Edit result + `rooms: [{area, at, fill, label}]`: the [rooms the walls close](#simple-mode-rooms) |
| GET | `/standards/layer-index` | | `{layers: {layer name (lower case): element}}` of every profile (the simple mode's display) |
| GET | `/sessions/{id}/drawing-properties` | | `{title, subject, author, keywords, comments, revision_number, hyperlink_base, custom}` (DWGPROPS) |
| POST | `/sessions/{id}/drawing-properties` | `{title?, ..., custom?: {name: value \| null}}` | Edit result (`updated`); null removes a custom property |
| POST | `/standards/classify` | `{layers: [{name, description?, objects?, by_type?}], ai?}` | `{elements: {layer: {element, by: "name"\|"ai", confidence}}, cost_usd}` |
| POST | `/sessions?name=<file>.dwg` (or `.dxf`) | file bytes | 201 [Session](#session) with summary; a DXF is kept as `upload.dxf` and converted to `v0.dwg` |
| POST | `/sessions/new` | `{units?: "mm"\|"cm"\|"m"\|"in"\|"ft", name?}` | 201 Session: an empty drawing |
| POST | `/sessions/sample/{name}` | | 201 Session with summary |
| POST | `/sessions/generate` | [generate spec](#generate-a-dwg) | 201 Session with summary |
| GET | `/sessions` | | `{sessions: [Session]}` |
| GET | `/sessions/{id}` | | Session with summary |
| DELETE | `/sessions/{id}` | | `{deleted: id}` |
| **Layers** | | | |
| GET | `/sessions/{id}/layers[?detail=1]` | | `{current, layers: [Layer]}`; `detail` adds `by_type` |
| POST | `/sessions/{id}/layers` | `{name, `[layer properties](#layers)`}` | Edit result |
| PATCH | `/sessions/{id}/layers/{name}` | `{new_name?, `layer properties`}` | Edit result |
| DELETE | `/sessions/{id}/layers/{name}[?move_to=X]` | | Edit result |
| POST | `/sessions/{id}/layers/update` | `{layers: [names or wildcards], set: {properties}}` | Edit result |
| POST | `/sessions/{id}/layers/current` | `{name}` | Edit result |
| POST | `/sessions/{id}/layers/rename` | `{map?: {old: new}, rules?: [{pattern, replace, case?}], merge?, dry_run?}` | Edit result (`result.plan`) |
| POST | `/sessions/{id}/layers/merge` | `{sources: [...], target, create_target? = true}` | Edit result |
| GET | `/sessions/{id}/layers/roles` | `?geometry=0` (stored and name only, instant) | `{layers: [{name, role, stored, source, suggested, suggested_by}], scale}`: [layer categories](#walls-of-any-drawing-layer-categories) |
| POST | `/sessions/{id}/layers/roles` | `{layers: [...], role}` or `{roles: {name: role}}` | `{changed}` (role `wall` / `opening` / `other`, null: back to the suggestion) |
| **Objects** | | | |
| POST | `/sessions/{id}/objects/query` | `{select?, offset?, limit?}` | `{total, offset, items: [Entity]}` |
| POST | `/sessions/{id}/objects/count` | `{select?, by?}` | `{total, by, groups, rows}` |
| GET | `/sessions/{id}/objects/{handle}` | | [Properties](#properties) of one object |
| POST | `/sessions/{id}/objects/set-layer` | `{select, layer, color?, force?}` | [Edit result](#edit-result) |
| POST | `/sessions/{id}/objects/set-props` | `{select, color?, linetype?, lineweight?, transparency?, linetype_scale?, material?, force?}` | Edit result |
| POST | `/sessions/{id}/objects/prop-set` | `{select, key, value, force?}` | Edit result: one property of every selected object that has it (Properties palette) |
| GET | `/sessions/{id}/hatch/patterns` | | `{patterns: [{name, description, lines: [[angle, x, y, dx, dy, [dashes]]]}], gradients: [{name, label}], units}`: the hatch pattern library (lines in drawing units at scale 1) |
| POST | `/sessions/{id}/hatch/boundary` | `{point, window?: [x0, y0, x1, y1], style? = outer}` | `{loops: [{points: [[x, y, bulge]], outer, sources}], area}`: the region around a point (AutoCAD's BOUNDARY), for previews |
| POST | `/sessions/{id}/objects/properties` | `{select}` | `{count, types, groups}`: the properties the selected objects share (the `GET /objects/{handle}` format; a differing value is `null` with `varies: true`) |
| POST | `/sessions/{id}/objects/transform` | `{select, move \| rotate \| scale \| mirror, force?}` | Edit result |
| POST | `/sessions/{id}/objects/copy` | `{select, vector, times?, force?}` | Edit result (`result.created`, `result.copies`) |
| POST | `/sessions/{id}/objects/attach` | `{select, host, force?}` | Edit result + `{host, attached, skipped}`: the objects [hang on the host](#attached-objects) |
| POST | `/sessions/{id}/objects/detach` | `{select, force?}` | Edit result + `{detached}` |
| POST | `/sessions/{id}/objects/attachments` | `{handle}` | `{host: {handle, type} \| null, children: [{handle, type}]}` (direct ones) |
| POST | `/sessions/{id}/objects/delete` | `{select, force?}` | Edit result |
| POST | `/sessions/{id}/objects/create` | `{type, layer?, color?, linetype?, lineweight?, ...}` | Edit result (`result.created`) |
| POST | `/sessions/{id}/objects/edit` | `{handle, ...geometry}` | Edit result |
| POST | `/sessions/{id}/objects/explode` | `{select}` | Edit result (`created`, `removed`) |
| POST | `/sessions/{id}/objects/offset` | `{handle, distance, side: [x, y]}` | Edit result |
| POST | `/sessions/{id}/objects/trim` / `extend` | `{handle, pick: [x, y], edges?}` | Edit result |
| POST | `/sessions/{id}/objects/fillet` | `{first: {handle, pick}, second: {handle, pick}, radius}` or `{handle, radius}` | Edit result |
| POST | `/sessions/{id}/objects/chamfer` | `{first, second, distance1, distance2?}` or `{handle, distance1, distance2?}` | Edit result |
| POST | `/sessions/{id}/objects/break` | `{handle, first, second?}` | Edit result |
| POST | `/sessions/{id}/objects/join` | `{select, source?}` | Edit result + `joined`, `discarded` |
| POST | `/sessions/{id}/objects/lengthen` | `{handle, pick, delta \| percent \| total \| angle}` | Edit result + `length` |
| POST | `/sessions/{id}/walls` | `{start, end \| points, closed?, width?, height?, layer?, style?}` | Edit result (`result.created`) |
| POST | `/sessions/{id}/slabs` | `{points \| boundary \| inside_walls, elevation?, thickness?, overhang?, layer?, style?}` | Edit result (`result.created`, `points`, `area`) |
| POST | `/sessions/{id}/roofs` | `{points \| boundary \| walls, height?, slope?, slopes?, gables?, overhang?, thickness?, layer?}` | Edit result (`result.created`, `slopes`) |
| POST | `/sessions/{id}/roof-slabs` | `{points \| boundary, height?, slope?, thickness?, overhang?, layer?, style?}` | Edit result |
| POST | `/sessions/{id}/doors` | `{wall, offset, width?, height?, sill?, layer?, style?}` or `{at, direction, ...}` | Edit result |
| POST | `/sessions/{id}/windows` | the same (defaults 1200 x 1400, sill 900) | Edit result |
| **Text, attributes, blocks** | | | |
| POST | `/sessions/{id}/text/query` | `{select?, include_attributes? = true, include_dimensions? = true}` | `{total, items: [Text]}` (`?format=csv`) |
| POST | `/sessions/{id}/text/replace` | `{find, replace?, select?, match_case?, regex?, whole_word?, include_attributes?, include_dimensions?}` | Edit result |
| POST | `/sessions/{id}/text/set` | `{items: [{handle, value, tag?}]}` | Edit result |
| POST | `/sessions/{id}/attributes/query` | `{select?, tags?}` | `{inserts, total, items}` (`?format=csv`) |
| POST | `/sessions/{id}/attributes/set` | `{select?, values?: {TAG: value}, expressions?: {TAG: expr}}` (or `{tag, value}`) | Edit result |
| GET | `/sessions/{id}/blocks[?include_anonymous=1]` | | `{count, blocks: [Block]}` |
| POST | `/sessions/{id}/blocks/rename` | `{name, new_name}` | Edit result |
| POST | `/sessions/{id}/blocks/insert` | `{block, point, scale?, rotation?, layer?, attributes?, space?, rows?, columns?, row_spacing?, column_spacing?}` | Edit result |
| POST | `/sessions/{id}/walls/opening` | `{wall, at, width, kind: door \| window, side?, hinge?: start \| end, layer?, dim_layer?, dims? = true}` | Edit result: a door or window cut into a wall (a polyline with a width): the wall split at the gap (its tied dimensions keep their points), the A-DOOR / A-WINDOW block (made on first use) scaled and turned along the wall, a tied dimension of the gap |
| POST | `/sessions/{id}/blocks/define` | `{name, items: [entity_create objects]}` | Edit result: a block definition made of these objects (base 0,0, layer 0), if the drawing lacks it (the simple mode's furniture library) |
| POST | `/sessions/{id}/blocks/create` | `{name, select, base, keep? = convert \| retain \| delete, redefine?, layer?}` | Edit result: a block from model-space objects (`convert`: they become one reference at `base`); `redefine` replaces an existing block's contents |
| GET | `/sessions/{id}/blocks/{name}/preview` | | `{name, items}`: the block's contents as drawing items, relative to its base point |
| POST | `/sessions/{id}/blocks/replace` | `{select, block, keep_attributes? = true, force?}` | Edit result |
| **Quantities and cleanup** | | | |
| POST | `/sessions/{id}/measure` | `{select?, by? = "layer"}` | lengths, areas per object and group (`?format=csv[&table=groups]`) |
| POST | `/sessions/{id}/areas` | `{select?, min_area?, label_layers?}` | closed shapes with area, perimeter, texts inside (`?format=csv`) |
| POST | `/sessions/{id}/cleanup/purge` | `{what?, keep?}` | Edit result (`result.purged`, `result.counts`) |
| POST | `/sessions/{id}/cleanup/overkill` | `{select?, tolerance?, zero_length?, force?}` | Edit result (`result.duplicates`) |
| POST | `/sessions/{id}/cleanup/audit` | `{fix?}` | `{report}`; with `fix`: Edit result |
| **Materials and styles** | | | |
| GET | `/sessions/{id}/materials` | | [Materials](#materials-and-styles): render materials with usage, ACA material definitions |
| GET | `/sessions/{id}/styles` | | [Styles](#materials-and-styles): text, dimension, linetype, ACA styles with usage |
| POST | `/sessions/{id}/materials` | `{name?, library?, color?, opacity?, tile_mm?, description?}` | Edit result: new render material |
| PATCH | `/sessions/{id}/materials/{name}` | `{new_name?, library?, color?, opacity?, texture?: "", tile_mm?, description?}` | Edit result |
| GET | `/sessions/{id}/characteristics` | | [Characteristics](#characteristics): every entity and layer in AutoCAD's form, the color the 3D page paints and where it comes from |
| GET | `/sessions/{id}/materials/{name}/usage` | | what a change would affect: `{name, objects, by_type, layers}` (objects counted as ACA shows them) |
| POST | `/sessions/{id}/objects/aca-material` | `{select, material? \| name?/library?/color?/opacity?/tile_mm?, include_glass?, confirm_style_wide?}` | Edit result: [only the selected ACA objects' style](#materials-and-styles) changes; 409 `E_CONFIRM` if the style is also used by unselected objects |
| GET | `/material-library` | | CC0 textures: `{slug, name, category, tile_mm, rgb, license, source, preview}` |
| GET | `/material-library/{slug}.jpg` | | 256 px preview |
| GET | `/sessions/{id}/db[/{handle}][?depth=n]` | | database explorer: root dictionary tree, or any object (see `kb/explorer.md`) |
| **Versions and files** | | | |
| GET | `/sessions/{id}/versions` | | `{current, versions: [{n, op, summary, time}]}` |
| GET | `/sessions/{id}/diff?from=a&to=b` | | added / removed / changed objects (default: previous to current) |
| POST | `/sessions/{id}/batch` | `{steps: [{method, params}], dry_run?, summary?}` | several edits as one version (`summary`: its history line, else one per step; 1-1000 steps; `"$steps[i].result.created"` takes an earlier step's value, and inside a list it is spliced in) |
| POST | `/sessions/{id}/undo` | | Session |
| POST | `/sessions/{id}/redo` | | Session |
| POST | `/sessions/{id}/versions/{n}` | | Session |
| GET | `/sessions/{id}/file[?version=n][&format=dxf][&dwg_version=2013]` | | DWG or DXF bytes |
| POST | `/sessions/{id}/file?summary=...` | DWG bytes | Session: a new version from the bytes (the website syncs a drawing edited on the device before the assistant works on it) |
| GET, POST | `/sessions/{id}/drawing` | `{handles?}` (POST) | [Drawing](#drawing): model space as 2D items for the editor; with `handles` only those objects |
| GET | `/sessions/{id}/view` | | HTML page (3D + plan) |

---

## Objects

### Session
```json
{"id": "b5fcf66e0701", "name": "test.dwg", "version": 2, "versions": 3,
 "can_undo": true, "can_redo": false, "last_change": "Changed color of 1 objects",
 "summary": { ... }}
```

- `version` is the index of the current version.
- `versions` is the number of versions.
- `summary` is included only by `GET /sessions/{id}` and the create calls.
- `recovered` (v0.100) is there only when the drawing was read with repairs: the strict DWG read rejected it and a
  failsafe read kept what it could (AutoCAD opens such files; its AUDIT lists their errors). `{"error": the strict
  read's error, "skipped": records left out, "messages": [the first diagnostics]}`. A saved copy lacks what was left
  out; `skipped` 0 means only objects whose contents could not be decoded, kept unchanged. MCP `dwg_open` returns it
  too.

### Summary
```json
{"file": "v0.dwg", "version": "AC1032", "units": "mm", "entities": 13, "spaces": {"model": 10, "paper": 3},
 "by_type": {"AEC_WALL": 6, "AEC_DOOR": 2, "VIEWPORT": 3},
 "by_layer": {"A-Wall": 6, "A-Door": 2},
 "layers": 8, "layer_names": ["0", "A-Door", "A-Wall", "Defpoints"],
 "blocks": 6, "block_references": {"TAG": 2, "_ArchTick": 0}, "xrefs": [], "layouts": ["Model", "Work"],
 "aca": {"AEC_WALL": 6, "AEC_DOOR": 2}, "proxy_entities": 0, "unsupported_objects": 5,
 "current_layer": "0", "extents": [[12686.0, 16049.4], [29780.3, 29293.0]]}
```

- `units`: the drawing's insertion units (`mm`, `cm`, `m`, `in`, `ft`, `unitless`).
- `block_references`: top-level references per named block (dynamic blocks under their own name).
- `unsupported_objects`: objects acadrust keeps as stored bytes (they are written back unchanged).

- `entities` counts model-space and paper-space entities. Block definition contents are not counted.
- `extents` is the XY box of model space, or `null`.
- `file` is the stored file name of the current version.

### Layer
```json
{"name": "A-Wall", "color": 113, "rgb": "#66cc99", "on": true, "frozen": false, "locked": false, "plot": true,
 "new_vp_freeze": false, "linetype": "Continuous", "lineweight": 50, "transparency": 0, "description": "",
 "material": "Global", "current": false, "xref": false, "objects": 6, "objects_in_blocks": 0}
```

- `lineweight`: 1/100 mm, or `"Default"`. `transparency`: percent 0-90. `material`: render material name or `Global`.
- `objects` counts model-space and paper-space entities on the layer; `objects_in_blocks` those inside block definitions.
- Every property is checked against AutoCAD both ways: AutoCAD reads what the core writes, and the core reads what AutoCAD
  writes (`testset/objects/layers__*`).

### Entity
```json
{"handle": "3D21", "type": "AEC_WALL", "layer": "A-Wall", "color": "bylayer", "space": "model",
 "bbox": [[12686.0, 23104.0], [17287.1, 28631.0]]}
```

Fields that depend on the type:

| Field | Types | Meaning |
|---|---|---|
| `text` | TEXT, MTEXT | Raw value. MTEXT formatting codes are included. |
| `text` | DIMENSION | Text override, if one is set. |
| `measurement` | DIMENSION | Measured value. |
| `block` | INSERT | Block name. |
| `attributes` | INSERT | `{tag: value}`. |
| `wall` | AEC_WALL | `{start, end, length, width, height}`, when acadrust can read the geometry. Walls created by acadrust are readable. |
| `size` | AEC_WINDOW, AEC_DOOR | `{width, height}`. |

`bbox` is the XY bounding box. It is omitted when it cannot be computed.

### Properties

`GET /sessions/{id}/objects/{handle}` returns the object's properties as a list of groups. An unknown handle returns 404.

```json
{"handle": "3D3C", "type": "AEC_WINDOW", "layer": "A-Glaz", "rgb": "#7fbfff",
 "groups": [
  {"id": "general", "title": "General", "props": [
    {"key": "type", "label": "Type", "kind": "text", "value": "AEC_WINDOW"},
    {"key": "layer", "label": "Layer", "kind": "text", "value": "A-Glaz", "edit": "layer"},
    {"key": "color", "label": "Color", "kind": "color", "value": {"color": "bylayer", "rgb": "#7fbfff"}, "edit": "color"},
    "..."]},
  {"id": "dimensions", "title": "Dimensions", "props": [
    {"key": "width", "label": "Width", "kind": "length", "value": 1010.0},
    {"key": "height", "label": "Height", "kind": "length", "value": 1510.0}]},
  {"id": "anchor", "title": "Anchor", "props": [
    {"key": "host", "label": "Anchored to", "kind": "ref", "value": {"handle": "3D24", "type": "AEC_WALL"}},
    {"key": "sill", "label": "Sill height", "kind": "length", "value": 1000.0}]},
  {"id": "position", "title": "Position", "props": ["..."]},
  {"id": "extents", "title": "Extents", "props": ["..."]}]}
```

- `rgb`: the displayed color (the object's own color, otherwise its layer's).
- A property has `key`, `label`, `kind` and `value`. Editable properties also have `edit`, and attribute properties have `tag`.

| `kind` | `value` |
|---|---|
| `text`, `number`, `length`, `percent`, `bool` | plain value; `length` is in drawing units |
| `angle` | degrees, 0..360 |
| `point` | `[x, y]` or `[x, y, z]` |
| `lineweight` | 1/100 mm; -1 ByLayer, -2 ByBlock, -3 Default |
| `color` | `{color, rgb}` (see [Colors](#colors)) |
| `ref` | `{handle, type}` or `null` |
| `refs` | `[{handle, type}]` |

| `edit` | Request the website sends |
|---|---|
| `layer` | `objects/set-layer` |
| `color` | `objects/set-props` with `color` |
| `lineweight` | `objects/set-props` with `lineweight` |
| `attribute` | `attributes/set` with the property's `tag` |

Groups by object type. The groups are defined in `core/src/bin/aicad/props.rs`; a group with no data is left out.

| Type | Groups |
|---|---|
| every object | `general`: type, class (ACA), handle, layer, color, linetype, lineweight, transparency, space |
| LINE | general, `geometry` (start, end, length, angle), `extents` |
| CIRCLE | general, `geometry` (center, radius, diameter, circumference), extents |
| ARC | general, `geometry` (center, radius, start/end/total angle, arc length), extents |
| LWPOLYLINE | general, `geometry` (vertices, closed), extents |
| TEXT, MTEXT | general, `text` (contents, height, style; MTEXT width), `position` (insertion point, rotation), extents |
| INSERT | general, `block` (name, scale), `attributes` (editable), position, extents |
| DIMENSION | general, `dimension` (kind, measurement, text override), extents |
| 3DFACE | general, `geometry` (corners) |
| AEC_WALL | general, `dimensions` (length, width, height), `baseline` (start, end, angle), `anchored` (openings), extents |
| AEC_DOOR, AEC_WINDOW, AEC_OPENING | general, `dimensions` (width, height), `anchor` (wall, offset along wall, sill height), position, extents |
| other AEC_* | general, position, extents |
| any other type | general, extents |

Wall `dimensions` and `baseline`, and the opening's offset along the wall, are present only when acadrust can read the wall geometry. Walls created by acadrust are readable; ACA-made walls in test.dwg are not yet.

Groups added for materials, styles and display (format background: `kb/aca.md`, `kb/materials.md`):

| Group | Types | Properties |
|---|---|---|
| `style` | ACA objects | style name and type; component materials as "definition -> render material"; wall cleanup group |
| `material` | ACA objects, 3DFACE, INSERT, other 3D | object material (edit `material`: ByLayer / ByBlock / a render material), layer material |
| `display` | ACA objects | object and style display overrides (count), and which source applies |

### Materials and styles

`GET /materials`:
```json
{"render": [{"name": "General.Chip", "handle": "1679", "diffuse": "#a5a399", "opacity": 100.0, "texture": "", "description": "",
             "used_by": {"layers": [], "objects": 0, "aca_material_defs": ["Standard"]}}],
 "aca_material_defs": [{"name": "Standard", "handle": "DC9", "render_materials": ["General.Chip"]}]}
```

`GET /styles`:
```json
{"text": [{"name": "Arch-Dim", "font": "romans.shx", "height": 0.0, "width_factor": 0.75, "objects": 0}],
 "dimension": [{"name": "Aec_Stair_M", "objects": 0}],
 "linetype": [{"name": "CENTER2", "description": "Center (.5x) ___ _ ___ _ ___ _ ___ _ ___ _ ___", "layers": 0, "objects": 0}],
 "aca": [{"collection": "AEC_WALL_STYLES", "label": "wall styles",
          "items": [{"name": "Standard", "handle": "27BA", "type": "AEC_WALL_STYLE", "objects": 6, "material_defs": ["Standard"]}]}]}
```

**Creating and changing render materials.**
- **`library`** is a slug from `/material-library`. It sets the texture, its real-world tile size and the base colour; on create it also gives the default name.
- **`texture`** can only be an image inside the library or the session folder; `""` removes the texture. Other paths return 400, because the 3D page embeds the file.
- **`opacity`** is a percentage (100 = opaque). **`tile_mm`** is a number or `[x, y]`.
- **ACA objects show their style's materials.** Changing the render material behind a style's material definition changes them, and every other object using it. For example, `PATCH /materials/General.Chip {"library": "brick_red"}` makes the walls, doors, window frame and stair of `test.dwg` brick (verified in local ACA). Check `GET /materials/{name}/usage` first.

**Only some ACA objects: `POST /objects/aca-material`.**
- The selected objects' style gets its own copies of its material definitions (named `"<definition> - <material>"`), pointing at the material. Other styles, and so other object types, keep theirs.
- Give `material` (an existing render material), or `name`/`library`/`color`/`opacity`/`tile_mm` for a new one (an existing name is reused).
- All objects of the same style change. If some of them are not selected, the call returns 409 `E_CONFIRM` with the counts. Ask the user, then repeat with one of:
  - `only_selected: true`: only the selected objects change. They get their own copy of the style, named `"<style> (<material>)"`, in the same style dictionary. Verified in local ACA: `LIST` shows the new style, AUDIT finds 0 errors, and only that wall renders concrete.
  - `confirm_style_wide: true`: every object of the style changes.
- Result `style_copies`: the style copies made.
- Window glass definitions (opacity below 100) are kept unless `include_glass: true`.
- Example: `{"select": {"types": ["wall"]}, "color": "blue", "name": "Walls blue"}` on `test.dwg` makes the 6 walls blue; doors, window and stair keep `General.Chip` (verified in local ACA, Realistic plot).
- Result: `{changed, material, styles, material_defs, kept}`.

**Materials in edits.**
- `set-props {material}` takes `ByLayer`, `ByBlock` or a render material name; `PATCH /layers/{name} {material}` takes a render material name.
- An unknown name returns 404, and the message lists the available names.
- **ACA objects** take their materials from the style components when shown in ACA. The object material matters for export and rendering of exploded pieces; see `kb/materials.md`.

### Characteristics

`GET /characteristics` returns the drawing in the form AutoCAD reports it (`entget` / `tblsearch` fields). The core tests (`tests/run_core_tests.py`) compare it with AutoCAD's cached answers in `testset/`.
```json
{"entities": [{"handle": "3D21", "type": "AEC_WALL", "space": "model", "layer": "A-Wall", "color": "ByLayer",
               "linetype": "ByLayer", "lineweight": "ByLayer", "material": "ByLayer",
               "render": {"rgb": "#a5a399", "source": "ACA style Standard material General.Chip", "texture": null, "opacity": 100.0},
               "display": {"rgb": "#66cc99", "aci": 113, "source": "ByLayer: layer A-Wall color 113"}}],
 "layers": [{"name": "A-Wall", "color": "113", "on": true, "frozen": false, "locked": false, "linetype": "Continuous",
             "lineweight": "50", "material": "Global"}],
 "materials": ["ByBlock", "ByLayer", "General.Chip", "Global"]}
```
- `color`: `ByLayer`, `ByBlock`, an ACI number as text, or `#rrggbb` (true color). `lineweight`: `ByLayer`, `ByBlock`, `Default` or 1/100 mm.
- `render`: the color the 3D page paints (shaded): the first opaque render material of the ACA style, the object or the layer, else the display color; `source` says which.
- `display`: the line/wireframe color: the object's color, else its layer's (ByBlock outside a block = ACI 7); `aci` is the effective index.
- INSERTs take both colors from their block's content, by AutoCAD's rules: content ByBlock → the insert's value; content ByLayer on layer 0 → the insert's layer; content ByLayer on another layer → that layer; an explicit value → its own. The 3D page draws block contents with the same rules.

### Drawing

`GET|POST /sessions/{id}/drawing` (worker `drawing`; the website's editor reads it, from the local core or the server):
```json
{"version": 3, "current_layer": "0",
 "items": [{"handle": "3D5B", "dxf": "LINE", "kind": "Curve", "layer": "Lines", "visible": true, "rgb": [255, 255, 255],
            "dash": false, "paths": [[[0, 0], [3000, 0]]], "geo": [["L", 0, 0, 3000, 0]]}],
 "ents": [{"h": "3D5B", "type": "LINE", "layer": "Lines", "def": {"start": [0, 0], "end": [3000, 0]}}],
 "missing": []}
```
- `items`: everything drawn in model space, in world XY: `Curve {paths, dash, geo?}`, `Text {text, pos, xdir, ydir,
  height, wf, attach, halign?, valign?, j?, shx?, ttf?, fit?, mw?, h0?}` (`j`: a justified text's justification, drawn from
  its insertion point as AutoCAD draws it; `halign` / `valign`: one drawn from its alignment point (no insertion point
  stored); `shx`: the SHX font's file stem, e.g. "txt"; `ttf`: a TrueType font's family; `fit`: an Aligned / Fit text's length between its two points; `mw`: an MTEXT's column width, its
  lines wrapped to it; `h0`: an MTEXT's own height when its text has `\H`, `\p` or tab codes: the editor sets each line
  in its height and its paragraphs by their indents, tab stops and alignment, which are in its units), `Hatch {loops, solid, pattern, pat?}` (`pat`: pattern lines `[bx, by, dx, dy,
  ox, oy, [dashes]]`), `Point {pos}`. Block contents carry their INSERT's handle (a MINSERT's rows and columns all of
  them); ACA objects and proxies are drawn from
  their proxy graphics; dimensions from their graphics block, or drawn here when they have none.
- `geo`: exact primitives for object snaps: `["L", x1, y1, x2, y2]`, `["A", cx, cy, r, a0, a1]` (radians,
  counter-clockwise), `["C", cx, cy, r]`, `["E", cx, cy, mx, my, ratio, t0, t1]`, `["N", x, y]`.
- `ents`: every top-level model-space object; `def` is what its grips change through `objects/edit` (LINE start/end,
  CIRCLE center/radius, ARC center/radius/angles in degrees, LWPOLYLINE points `[x, y, bulge]`, ELLIPSE, POINT, TEXT/MTEXT
  and INSERT `at` with the shown grip point `grip`).
- With `handles`: only those objects; `missing` lists the ones that no longer exist.

### Edit result
```json
{"version": 3, "new_version": true, "summary": "Moved 6 objects to layer A-Wall-Ext (new layer)",
 "result": {"changed": ["3D21", "3D23"], "created_layer": true, "layer": "A-Wall-Ext"},
 "session": { Session without summary }}
```

- **Nothing matched.** When an edit changes nothing, the response has `"new_version": false` and `"summary": "Nothing matched; no change"`. The version stays the same.
- **Long lists.** Lists in `result` longer than 200 items are cut to 200. A `<key>_total` field gives the full count.
- **Failed edit.** If an edit fails, the in-memory drawing is reloaded from the current version, so no partial change remains.
- **Edit after undo.** An edit made after an undo discards the later versions, so redo is no longer possible.

---

## Selector (`select`)

All given parts must match (AND). An empty or missing selector matches **every** model-space and paper-space entity. Contents of block definitions are never matched.

> **Warning:** an empty selector in `delete`, `set-layer` or `set-props` acts on the whole drawing.

| Field | Value | Match |
|---|---|---|
| `types` | string or list | Type name or alias. Glob `*` and `?`, case-insensitive. |
| `layers` | string or list | Layer name. Glob, case-insensitive. |
| `handles` | string or list of hex | Exact handles. A malformed handle returns 400. |
| `text` | string | Case-insensitive substring of the TEXT/MTEXT value, an INSERT attribute value or a DIMENSION text override. |
| `block` | string | Block name of an INSERT (glob). Only INSERT entities can match. |
| `color` | [color](#colors) | The entity's own color, exactly. For example, `"bylayer"` matches entities whose color is ByLayer. |
| `space` | `model`, `paper`, `all` (default) | Model space or layouts. |
| `bbox` | `[[x1, y1], [x2, y2]]` | Plan window: objects whose extents lie inside it. Block references use their block's contents. |
| `bbox_mode` | `inside` (default), `crossing` | `crossing`: objects that touch the window. |

`block` also matches a dynamic block reference by the dynamic block's own name.

### Type names

- Basic types: `LINE`, `LWPOLYLINE`, `POLYLINE`, `ARC`, `CIRCLE`, `ELLIPSE`, `SPLINE`, `TEXT`, `MTEXT`, `INSERT`, `DIMENSION` (all dimension kinds), `HATCH`, `3DFACE`, `SOLID`, `VIEWPORT`.
- ACA types: `AEC_WALL`, `AEC_DOOR`, `AEC_WINDOW`, `AEC_STAIR`, `AEC_OPENING`, and other `AEC_*`.

Aliases:

| Alias | Expands to |
|---|---|
| `wall(s)` | AEC_WALL |
| `door(s)` | AEC_DOOR |
| `window(s)` | AEC_WINDOW |
| `opening(s)` | AEC_OPENING |
| `stair(s)` | AEC_STAIR |
| `aca`, `aec` | AEC_* |
| `lines` | LINE |
| `polyline(s)`, `pline` | LWPOLYLINE, POLYLINE |
| `text`, `texts` | TEXT, MTEXT |
| `dim(s)`, `dimension(s)` | DIMENSION |
| `block(s)`, `insert(s)` | INSERT |
| `hatches` | HATCH |
| `circles` | CIRCLE |
| `arcs` | ARC |
| `face(s)` | 3DFACE |

Example: `{"types": ["wall", "door"], "layers": ["A-*"], "space": "model"}`

## Colors

**Input** can be any of:
- an ACI number 0..256 (0 = ByBlock, 256 = ByLayer);
- `"bylayer"` or `"byblock"`;
- a name: `red` 1, `yellow` 2, `green` 3, `cyan` 4, `blue` 5, `magenta` 6, `white`/`black` 7, `gray`/`grey` 8;
- `"#rrggbb"`;
- `[r, g, b]`.

**Output** is one of: an ACI number, `"bylayer"`, `"byblock"`, `"none"`, or `[r, g, b]`.

---

## Endpoint details

### Create a session

**Upload.** `POST /sessions?name=plan.dwg` (or `plan.dxf`), `Content-Type: application/octet-stream`, body = file bytes.
- 400 if the name does not end in `.dwg` or `.dxf`.
- 422 if a .dwg does not start with `AC1`, or the file cannot be read.
- A DXF is kept as `upload.dxf`; version 0 is its DWG form.

**New drawing.** `POST /sessions/new {"units": "mm"}`: an empty drawing (layer 0, standard styles, model and one layout).

**Samples.** `POST /sessions/sample/{name}` with one of these names (only files that exist are listed by `GET /samples`):
- `aca-sample`: ACA drawing with 6 walls, 2 doors, 1 window and 1 stair;
- `house`: small house;
- `room`: room from a hand sketch, with dimensions.

#### Generate a DWG

`POST /sessions/generate` builds a new DWG with ACA objects. The body is in mm:
```json
{"name": "room.dwg",
 "layers":  [{"name": "A-Flor", "aci": 8}],
 "walls":   [{"from": [0, 0], "to": [4000, 0], "width": 200, "height": 2700, "layer": "A-Wall"}],
 "doors":   [{"wall": 0, "offset": 500, "sill": 0, "width": 900, "height": 2100}],
 "windows": [{"wall": 0, "offset": 2200, "sill": 900, "width": 1200, "height": 1400}],
 "faces":   [{"layer": "A-Flor", "pts": [[0, 0, 0], [4000, 0, 0], [4000, 3000, 0], [0, 3000, 0]]}],
 "dims":    [{"p1": [0, 0], "p2": [4000, 0], "offset": 600, "text": "<>"}]}
```

- **Anchored openings.** Doors and windows given as `{wall: index, offset, sill}` are anchored to that wall, and ACA cuts them.
  - `offset` is measured from the wall start.
  - The default sill is 0 for doors and 900 for windows.
- **Free openings.** Openings given as `{at: [x, y, z], dir: [dx, dy], ...}` stand free and are not anchored.
- **Dimensions.** In dimension text, `<>` stands for the measured value.
- **Errors.** A spec error returns 400 with the builder's message.

### Read

- `GET /sessions/{id}/layers`: layers sorted by name, plus the current layer.
- `POST /sessions/{id}/objects/query`: `offset` defaults to 0; `limit` defaults to 100, maximum 1000.
- `POST /sessions/{id}/objects/count`: `by` is one field or several joined by commas: `type` (default), `layer`, `block`,
  `color`, `linetype`, `style`. `groups` keys are the values joined by ` | `; `rows` gives each combination as an object.
  Example: `{"by": "layer,type"}` -> `{"total": 13, "groups": {"A-Wall | AEC_WALL": 6}, "rows": [{"layer": "A-Wall", "type": "AEC_WALL", "count": 6}]}`.

### Edit objects

- **`objects/set-layer`** `{select, layer, color?}`
  - Creates the layer if it is missing. `color` applies only to a new layer (default 7).
  - `result`: `{changed, created_layer, layer}`. Entities already on the layer are not listed in `changed`.
- **`objects/set-props`** `{select, color?, linetype?, lineweight?, transparency?, linetype_scale?, material?}`
  - At least one property. `linetype`: loaded in the drawing, `ByLayer` or `ByBlock`. `lineweight`: 1/100 mm, `ByLayer`,
    `ByBlock`, `Default` or `"0.35mm"`. `transparency`: percent 0-90, `ByLayer`, `ByBlock`.
- **`objects/prop-set`** `{select, key, value}`: AutoCAD's Properties palette. `key` is a property key from
  `GET /objects/{handle}` whose prop has `"edit": "value"`; its `"input"` says what `value` is: `number` (lengths;
  angles in degrees), `point` (`[x, y]`; a `null` coordinate keeps each object's own), `bool`, `text`, or `choice`
  (one of `"options"`). Objects without that property are skipped (`result.skipped`); if none has it: 400.
  - General: `linetype`, `linetype_scale`, `transparency` (and `layer`, `color`, `lineweight`, `material` as in
    set-layer / set-props).
  - LINE `start`, `end`, `length` (start and direction kept), `angle` (start and length kept). CIRCLE `center`,
    `radius`, `diameter`, `circumference`, `area`. ARC `center`, `radius`, `start_angle`, `end_angle`, `total_angle`
    and `arc_length` (start kept). ELLIPSE `center`, `major_radius`, `minor_radius` (a full ellipse swaps its axes when
    the minor one grows past the major), `ratio`, `rotation`, an arc's `start_angle` / `end_angle` (from the major
    axis). POINT `position`. LWPOLYLINE `closed`, `width` (global), `elevation`, `vertex:N` (1-based).
  - SPLINE (v0.093; shown: method Fit / CV, degree, fit / control point count, length): a fit one's `closed`,
    `start_tangent` / `end_tangent` (degrees, or `Auto`: no bending at that end; open ones), `knots` (Chord, Square
    root, Uniform), `fit:N`; a CV one's `cv:N`. The curve is made again through the fit points.
  - ATTDEF `tag` (no spaces, made upper case), `prompt`, `default`, `invisible`, `constant`, `verify`, `preset`,
    `lock_position`, and as a TEXT: `style`, `justify` (it stays where it is), `height`, `width_factor`, `oblique`,
    `position`, `rotation`.
  - SOLID `corner:N`, `thickness`. Old-style POLYLINE `closed`, 2D `width` (global), `elevation`, `vertex:N` (a 3D
    one's `[x, y]` keeps its Z, `[x, y, z]` sets it).
  - A block reference's attribute text (v0.095, EATTEDIT's Text Options; group `attribute_text`): `atext:TAG:height`,
    `atext:TAG:rotation`, `atext:TAG:position` (its anchor), `atext:TAG:width_factor`, `atext:TAG:oblique`,
    `atext:TAG:style`, `atext:TAG:justify` (it stays where it is), on the first attribute with that tag.
  - TEXT `contents`, `style`, `justify` (the text stays where it is; the alignment point moves), `height`,
    `width_factor`, `oblique`, `position`, `rotation`. MTEXT `contents`, `style`, `justify`, `height`, `width`,
    `position`, `rotation`, the background mask (v0.101): `mask` (true: on as AutoCAD turns it on, the drawing
    background colour and offset factor 1.5; false: off), `mask_offset` (1 to 5; 1: the text's box), `mask_window`
    (true: the drawing background colour), `mask_color` (a colour of its own). INSERT `position`, `rotation`, `scale_x`, `scale_y`, `scale_z` (attributes keep their place
    in the block). DIMENSION `text` (override; empty = measured), `style`. HATCH `fill` (Pattern, Solid, Gradient),
    `pattern`, `scale`, `angle`, `gradient`, `color1`, `color2`, `gradient_angle`, `centered`, `tint`, `island_style`
    (an associative picked hatch finds its islands again).
  - Every change to a justified TEXT recomputes its insertion point from the alignment point, as AutoCAD does when it
    edits one (AutoCAD draws a TEXT from its insertion point and does not recompute it on open): Arial metrics for
    TrueType styles (within 1% of the height of AutoCAD's own placement), an estimate for SHX fonts.
- **`objects/transform`** exactly one of:
  - `move: [dx, dy, dz?]`
  - `rotate: {base: [x, y], angle}` (degrees, counter-clockwise)
  - `scale: {base: [x, y], factor}`
  - `mirror: {p1, p2}`: texts stay readable, as AutoCAD with MIRRTEXT 0. Where a text would read backwards, it keeps its
    anchor and swaps left/right alignment (AutoCAD keeps the alignment and measures the string with the font: the same
    look, other stored codes).
  - ACA objects can only be moved. A wall takes the doors and windows anchored to it along; when the core cannot move one
    of them (a door made in ACA, layout unknown to acadrust), nothing in that group moves and `result.skipped` says why.
  - A dimension's graphics block (made by AutoCAD) goes with it: moved, turned, mirrored. Scaling an aligned or linear
    dimension (its measurement changes) drops the block: the dimension is drawn anew (by the editor, by AutoCAD on
    opening).
  - Objects of classes the core does not know (custom objects, proxies) are not changed (`skipped`): the graphics stored
    in them would stay where they are.
  - `result`: `{changed, skipped, skipped_locked}`.
- **`objects/copy`** `{select, vector, times = 1}`: `times` copies, each `vector` further. ACA objects, viewports and
  objects of unknown classes are not copied (`skipped`); nor are dimensions other than aligned and linear ones that
  have an AutoCAD graphics block (a copy cannot share it; aligned and linear copies are drawn anew).
  `result.created`: the new handles; `result.copies`: `{source: [its copies in order]}`.
- Objects [attached](#attached-objects) to a selected object are moved, copied and deleted with it (`result.attached`:
  how many were added to the selection).
- Every object's comment: `prop-set {key: "comment", value}` (empty removes it); shown as the `comment` group of its
  properties; kept in the DWG as XDATA `AICAD_NOTE`.
- A block reference's size (`size` group): `width`, `depth` (its block's extents along its own axes times its scales;
  `prop-set` resizes it: furniture keeps its back edge and middle, a door / window its hinge end, a door's leaf grows
  with it, its gap in the wall follows), `height_3d` (for 3D, XDATA `AICAD_SIZE`), `elevation_3d` (how high above the
  floor it stands: a window's Sill height, else Above floor; doors have none; XDATA `AICAD_ELEV`). `objects/edit`
  `{handle, stretch: {side: left | right | back | front, to}}` moves one side of its extents to a point (doors and
  windows: left / right, along their wall; a [stair](#stairs-simple-mode) is rebuilt at its new size).
- **`objects/delete`** `{select}`
  - Deleting an ACA wall also deletes the doors and windows anchored to it, with their anchor objects.
  - `result`: `{removed, selected, cascade}`. `cascade` is the number of extra objects deleted this way.

### Drawing and modify commands

Every one of these is also made by the local AutoCAD with its own command (LINE, PLINE, RECTANG, CIRCLE, ARC, TEXT,
-HATCH, DIMALIGNED, DIMLINEAR, entmod for grips, ROTATE/SCALE/MOVE, EXPLODE, OFFSET, FILLET, CHAMFER, TRIM, EXTEND) and
the two results compare equal as AutoCAD reads them (`tests/test_core_ops.py`).

- **`objects/create`** `{type, layer? = "0" (created when missing), color?, linetype?, lineweight?, ...}`:
  - `line {start, end}`; `polyline {points: [[x, y] | [x, y, bulge]], closed?, width?}`; `rectangle {corner1, corner2}`;
  - `circle {center, radius}`; `arc {center, radius, start_angle, end_angle}` (degrees, counter-clockwise) or
    `{start, mid, end}`; `ellipse {center, major_axis, ratio, start_angle?, end_angle? | start_param?, end_param?}` (an
    elliptical arc, as ELLIPSE's Arc option: angles from the major axis or the ellipse's parameters, degrees,
    counter-clockwise); `point {at}`; `solid {points: 3 or 4 [x, y]}` (SOLID's order: the third point across from the
    first, so a square is 0,0 1,0 0,1 1,1);
  - `spline {points, closed?, start_tangent?: [dx, dy], end_tangent?}`: AutoCAD's SPLINE (Fit): the cubic curve through
    the points as AutoCAD makes it (checked against AutoCAD 2021's own control points and knots, to 1e-6: knots at the
    chord lengths, at each end the given unit tangent or no bending; a closed one without tangents gets the tangent of
    the periodic spline, written with it, so AutoCAD draws the same curve). Kept as fit points, as AutoCAD keeps them.
    `spline {control_points, degree? = 3, knots? (clamped uniform), weights?}`: its CV method;
  - `3dpoly {points: [[x, y, z]], closed?}`: a 3D polyline (3DPOLY; [x, y] is at Z 0);
  - `3dface {points: 3 or 4 [x, y, z]}`: a 3D face (3DFACE), its corners in order round it ([x, y] is at Z 0);
    `objects/edit` takes `points` or `vertex {index, point}` (a corner given as [x, y] keeps its Z);
  - `qleader {points, spline?, arrow? = true, dimstyle?}`: an old-style LEADER with no annotation (AutoCAD's LEADER,
    None): an arrowhead at the first point, straight segments (or a spline) through the others; arrowhead and size from
    the dimension style (Standard unless named). A text beside it is an MTEXT of its own. `objects/edit`:
    `points`, `vertex {index, point}`;
  - `xline {base, through | direction}`, `ray {base, through | direction}`: construction lines (XLINE: both ways, RAY:
    from the base point); drawn far past the drawing and marked `"inf"`, left out of zoom extents;
  - `text {at, text, height, rotation?, style?, align?: left|center|right|middle}`;
    `text {at, end, text, align: aligned, height?}` / `{at, end, text, align: fit, height, width_factor?}`: TEXT's Align
    / Fit along the baseline `at`..`end` (Align: the height filling it, Fit: the width factor), as AutoCAD computes
    them (txt, simplex, romans, isocp: their glyphs measured with TEXTBOX; `tests/test_core_ops.py` text_aligned,
    text_fit); `mtext {at, text, height, width?, rotation?, style?, attachment?: top_left ... bottom_right}` (no
    `width`: no column, AutoCAD's width 0);
  - `attdef {at, tag, prompt? = tag, default?, height, rotation?, style?, invisible?, constant?, verify?, preset?,
    lock_position? = true}`: an attribute definition (ATTDEF; `blocks/create` takes it into the block, `blocks/insert`
    then asks for its value);
  - `leader {points: [[x, y] arrowhead, ..., [x, y] landing], text, height?, arrow?, landing?, frame?}`: a text with a leader,
    AutoCAD's MULTILEADER (Standard multileader style; text height and arrow size from the Standard dimension style
    unless given, written as overrides so AutoCAD draws it the same): a closed filled arrowhead, the leader through the
    points, a horizontal dogleg (`landing`, default twice the arrow) toward the side the leader runs to, and the text
    after it with its first line's middle on the landing; `frame: true` frames the text (comments). `objects/edit` moves
    its `arrow`, its `landing` (the note goes along) or its text (`text_at`: the landing goes along, the arrow stays) and
    changes its `text`; the dogleg turns round when the landing passes the leader's last bend. `prop-set` keys
    `contents`, `height`;
  - `hatch {pick: [x, y] | picks: [[x, y]...] (+ window?) | boundary: handle | boundaries: [handles] | points, pattern? =
    SOLID | a library name, scale?, angle? | gradient: {name, color1, color2?, angle?, centered? = true, tint?}, style? =
    outer | normal | ignore, associative? = true}`:
    - `pick`: the region around the point, as AutoCAD's HATCH / BOUNDARY finds it: any lines, arcs, circles and polylines
      around it (split where they cross, dead ends dropped), islands inside it per `style` (outer: the outermost islands;
      normal: all, alternating; ignore: none); several picks make one hatch. Written as AutoCAD writes picked regions
      (polyline paths, seed points). `boundary(ies)`: closed polylines or circles, edge by edge as AutoCAD's -HATCH does.
    - Associative hatches (picks and boundary objects) follow their boundary objects in every later edit (and in
      AutoCAD); they lose the association when a boundary object is deleted or the hatch is moved alone.
    - Patterns: `GET /hatch/patterns`: our library, then the patterns the drawing's own hatches use that are not in it
      (`drawing: true`; AutoCAD's ANGLE, AR-CONC, a custom one...: a hatch keeps its pattern's lines, so it can be used
      again without its .pat file; taken at scale 1 and angle 0). Gradient names as AutoCAD stores them: LINEAR, CYLINDER, INVCYLINDER, SPHERICAL,
      INVSPHERICAL, HEMISPHERICAL, INVHEMISPHERICAL, CURVED, INVCURVED (also -HATCH's GR_LINEAR...).
  - `dimension {kind: rotated, p1, p2, at, rotation}` (DIMLINEAR's Rotated: the dimension line at an angle, degrees);
    `{kind: radius | diameter, handle: a circle or arc | center + radius?, point: toward where it meets the circle, at?}`
    (DIMRADIUS / DIMDIAMETER: the chord point toward `point`); `{kind: angular, vertex, p1, p2, at}` (three points: the
    sector between the two ends that holds `at`, the arc at `at`'s radius) or `{kind: angular, line1: [[x, y], [x, y]],
    line2, at}` (two lines, also ones that meet only when extended); `{kind: ordinate, feature, leader, axis?: x | y,
    origin? = [0, 0]}` (DIMORDINATE: X datum when the leader runs more up / down than sideways, as AutoCAD picks it).
    Stored as AutoCAD 2021's commands store them (`tests/test_core_ops.py` compares their points, measurement and
    kind; AutoCAD places the text itself, as it does for its own: a radius' beside its arrowhead, an angle's over the
    arc's middle). `objects/edit` takes the same fields (`point`, `at`, `vertex`, `p1`, `p2`, `line1`, `line2`,
    `feature`, `leader`), as their grips do;
  - `dimension {kind? = aligned | linear | horizontal | vertical, p1, p2, at: a point of the dimension line, text?, ties?,
    dimstyle? (one of the drawing's; Standard otherwise; every kind takes it), readable?}`; `readable: true` (the
    dimensions the core and the simple mode add themselves: doors, windows, walls, rooms, stairs, roofs) takes a style
    whose text reads on the plan: the current one when its text is 50 mm to 1 m in the drawing (DIMTXT x DIMSCALE,
    INSUNITS), else the readable style the drawing's dimensions use most, else a copy of the current one, `<name> 1-<k>`,
    DIMSCALE k the common plot scale (1:50, 1/4" = 1'-0" ...) nearest 2.5 mm text at 1:50 (bug 2026-11-16: an imperial
    plan's current Architectural style at DIMSCALE 1 drew 1/8" text on a 75 ft plan). A dimension the core draws itself
    (no graphics block yet) writes its value as its style does, as AutoCAD 2021 writes it (checked): DIMLUNIT decimal,
    engineering (8'-4.00"), architectural (8'-4 1/2"), fractional, scientific; DIMDEC, DIMZIN (feet and inches, leading
    and trailing zeros), DIMLFAC, DIMRND, DIMDSEP, DIMPOST; rounded half up;
    `ties: [first, second]` (each null or `{handle, osnap: start | end | mid, segment?}`) makes it associative as
    AutoCAD's DIMASSOC = 2 does (an AcDbDimAssoc object in the dimension's extension dictionary): when the core moves,
    reshapes, trims or deletes the tied objects, the dimension follows (or keeps its points when the object is gone);
    AutoCAD moves it too (checked: MOVE of the line in AutoCAD 2021). Editing the dimension's own points unties it.
- **`objects/edit`** `{handle, ...}`: DIMENSION (aligned, linear) `p1`, `p2`, `at`; LINE `start`, `end`; CIRCLE `center`, `radius`; ARC `center`, `radius`, `start_angle`,
  `end_angle`; LWPOLYLINE `points` (all), `vertex {index, point, bulge?}`, `insert_vertex {index, point}`,
  `remove_vertex`, `closed`, `width`; ELLIPSE `center`, `major_axis`, `ratio`, `start_param` / `end_param` or
  `start_angle` / `end_angle` (an arc's ends, degrees); SPLINE `fit` (all fit points; the curve is made through them
  again, a closed one's tangent chosen again), `closed`, `vertex {index, point}` (a fit point, or a control point when it
  has no fit points), `control_points` (all; a fit spline becomes a CV one); old-style POLYLINE (2D: `points` with
  bulges, `vertex {index, point, bulge?}`, `closed`; 3D: `points`, `vertex {index, point}`, a point given as [x, y]
  keeping its Z, `closed`); SOLID `points`, `vertex {index, point}`;
  ATTDEF `at`, `height`, `rotation`; POINT `at`; TEXT/MTEXT `at`, `height`, `rotation`, `width_factor` / `width`; INSERT
  `at`, `rotation`, `scale` (uniform; attributes follow);
  - ACA wall: `length`, `width`, `height` (walls made here or in ACA; the start stays) and `start`, `end` (walls made
    here). A shorter wall must still hold its openings; when the width changes off the wall's centre line (Left/Right
    justification) its openings are re-placed with it.
  - ACA door/window: `width`, `height`; in a wall also `offset` (wall start to the opening's start) and `sill`. The
    opening is rebuilt where ACA puts it for its new anchor. Openings made in ACA itself are only resized in place
    when acadrust can (axis-aligned), never moved: that needs ACA (422 with the reason).
- **`objects/explode`** `{select}`: polylines into lines and arcs; block references into their contents with their own
  properties (nested references stay references; attribute definitions come out as ATTDEFs with their defaults);
  MTEXT into TEXT lines (lines with a font override sit by font metrics in AutoCAD, up to a few cm off here);
  dimensions and hatches as acadrust explodes them; ACA objects, viewports, arrays and unevenly scaled references are
  skipped.
- **`objects/offset`** `{handle, distance, side}`: a parallel copy of a line, arc, circle or polyline on the side of
  `side`; polyline corners are extended to meet (OFFSETGAPTYPE 0); same layer and properties.
- **`objects/trim`** `{handle, pick, edges?}`: removes the part of a line, arc, circle or polyline containing `pick` up
  to the nearest crossings with the cutting objects (`edges` selector; default every curve in model space). A middle
  piece splits the object in two; a circle becomes an arc. An object that crosses nothing is not changed (400).
- **`objects/extend`** `{handle, pick, edges?}`: the end of a line, arc or open polyline nearer `pick` grows to the
  next boundary.
- **`objects/fillet`**: two lines (`first`/`second`: handle + a point on the part to keep) trimmed or extended to an
  arc of `radius` (0 = sharp corner; the arc takes their layer when they share one, else the current layer); or
  `{handle, radius}`: every corner between two straight segments of a polyline.
- **`objects/chamfer`**: the same with `distance1` / `distance2` and a joining line.
- **`objects/break`** `{handle, first, second?}` (AutoCAD's BREAK): the part between the two points (their nearest
  points on the object) goes. A line, an arc or an open polyline keeps the pieces either side (one when a point is at
  an end); a circle keeps the arc from `second` counterclockwise to `first`; a closed polyline opens. Without `second`
  (BREAKATPOINT) an open object splits in two at `first`.
- **`objects/join`** `{select, source?}` (AutoCAD's JOIN): the source (`source`, else the first of `select.handles`)
  takes the others in: lines on one line become one line, arcs on one circle one arc counterclockwise from the
  source's start (a circle when they go all the way round), gaps closed; otherwise lines, arcs and open polylines that
  meet end to end become one polyline (closed when the chain closes). The result keeps the source's properties;
  objects that do not join stay (`discarded`).
- **`objects/lengthen`** `{handle, pick, delta | percent | total | angle}` (AutoCAD's LENGTHEN): the end of a line, arc
  or open polyline nearer `pick` moves along it: `delta` adds a length (negative shortens), `percent` makes the length
  that percent, `total` that length, `angle` adds degrees to an arc's sweep. A polyline changes its end segment only.

### New walls, doors and windows

- **`POST /walls`** `{start, end}` or `{points: [[x, y], ...], closed?}`: one straight ACA wall per segment, centred on
  the line. `width` 200, `height` 2700 (mm), `layer` A-Wall (created with ACA's color and lineweight if missing),
  `style`: a wall style of the drawing by name (default "Standard": the drawing's own, made only when it has none).
  ACA joins walls that meet at their ends. A wall shorter than its width is refused.
- **`POST /doors`**, **`POST /windows`**:
  - in a wall: `{wall, offset}`, `offset` = from the wall's start to the opening's start along the wall. The opening is
    anchored to the wall (`AEC_ANCHOR_OPENINGBASE_TO_WALL`) and ACA cuts it. It must fit along the wall, must not
    overlap the wall's other openings (409), and `sill + height` must not exceed the wall height.
  - free-standing: `{at: [x, y], direction: [dx, dy]}`.
  - Defaults: door 900 x 2100, sill 0, layer A-Door; window 1200 x 1400, sill 900, layer A-Glaz. `style` as for walls.
  - Any straight ACA wall can host them: walls made here and walls made in ACA itself (their length, width,
    height and justification are read from the wall record).
  - The opening is placed exactly where ACA puts it for its anchor: its insertion is the frame's outer corner, back
    along the wall by the style's frame width and half the frame depth beside the wall's centre line (windows: also one
    frame width below the sill). When ACA later re-evaluates the anchor (e.g. the wall moves), nothing jumps.
- The drawing must be DWG 2018 (acadrust writes ACA records in that format); otherwise 422.
- Checked in the local AutoCAD: `LIST` reports the requested start/end points, lengths, heights, opening sizes, anchor
  wall and offsets; a twin of ACA's own door lands exactly where ACA had it; moving the host walls (ACA re-places the
  anchored openings) moves nothing; AUDIT 0 errors; the plan and 3D plots show the cut openings
  (`tests/test_core_ops.py create`).

### New slabs, roofs and roof slabs

Floors, ceilings and roofs are real ACA objects (not hatches or faces): AutoCAD Architecture opens them as its own,
lists them, renders them with their materials and schedules them.

- Outline (all three): `points` (plan, mm, at least 3; edge i runs from point i to i + 1; made counter-clockwise, per-edge
  lists follow), or `boundary` (handle of a closed polyline of straight segments), or, for slabs `inside_walls` and for
  roofs `walls`: wall handles of a closed chain of straight walls, or `"all"`. The outline then runs along the walls'
  inner faces (slab) or outer faces (roof); walls whose ends lie within a wall width of each other are joined.
- **`POST /slabs`** (`AEC_SLAB`): `elevation` = the slab's top (default 0, a floor), the body goes down by `thickness`
  (default 250); `overhang` moves every edge out (default 0); layer A-Slab; `style` a slab style of the drawing (default
  "Standard": the drawing's own, else made as ACA's with its slab edge style). Result: `points`, `top`, `thickness`,
  `area` (ACA's gross area, overhangs included).
- **`POST /roofs`** (`AEC_ROOF`): planes rise from the outline (the plate line) at `slope` degrees (default 30) or `slopes`
  per edge; `gables`: edge indices that end in a vertical gable (90 degrees; a gable roof on a rectangle: `[1, 3]`);
  `height` = plate height (default: the walls' top when built on walls, else 3000); `overhang` (default 300) moves the
  eaves out (the planes continue down to them); `thickness` (default 200) is measured normal to the roof. Layer A-Roof.
  A roof has no style: its material definition is its own (ACA's "Standard").
- **`POST /roof-slabs`** (`AEC_ROOFSLAB`): one flat sloped plate. The first edge is the eave at `height` (default 3000);
  the plate rises across the outline at `slope` (default 30); `thickness` 250; `overhang` (default 0) applies to the
  eave only and the eave face is plumb, as ACA's ROOFSLABADD makes them. Layer A-Roof-Slab; `style` as for slabs.
- **`objects/edit`** on them: slab `thickness`, `elevation`, `overhang`, `points`; roof slab `thickness`, `overhang` (eave),
  `height` (eave), `slope`; roof `height`, `slope` (gables stay), `slopes`, `gables`, `overhang`, `thickness`, `points`.
  `objects/transform` moves, rotates, scales and mirrors them (a roof only in plan). Records the core does not fully
  know are refused (it checks that re-encoding the unchanged record gives back the stored data).
- **`objects/aca-material`** works on them: a slab or roof slab through its style (as walls), a roof through its own
  material definition (only the selected roofs change; no confirmation needed).
- Query rows carry `slab` / `roof` / `roof_slab` values (points, thickness, top, slope(s), gables, overhang, areas);
  Properties show them in a Dimensions and an Outline group; `measure` gives a slab's gross area and perimeter, a roof's
  plan area under the eaves and, at one slope, its surface area.
- 3D page: slabs are their outline (with overhangs) extruded down by the thickness; roofs are the planes cut by the
  weighted straight skeleton of the eave outline (hips, ridges, valleys), each as thick as the roof normal to it, square
  cut at the eaves and plumb at gables. Plan: slabs at floor level are filled and counted in the floor area; roofs and
  roof slabs are drawn as thin lines.
- Checked in the local AutoCAD (`tests/test_core_ops.py slabs`): AutoCAD makes the same six objects with SLABADD,
  ROOFSLABADD and ROOFADD; `LIST` of both reads the same line for line, their 3D extents agree, the 3D page's extents
  match AutoCAD's to 0.1 mm, edits list as requested, AUDIT 0 errors.

### Layers

Layer properties (create, change, bulk change): `color` (ACI, name, `#rrggbb`, `[r, g, b]`; not ByLayer/ByBlock),
`linetype` (loaded), `lineweight` (1/100 mm, `"Default"`, `"0.35mm"`), `transparency` (0-90 %), `plot`, `on`, `frozen`,
`locked`, `new_vp_freeze` (frozen in new layout viewports), `description`, `material` (render material or `Global`).

- **`POST /sessions/{id}/layers`** `{name, ...properties}`: 409 `E_EXISTS` if the layer exists. Name rules as AutoCAD
  (up to 255 characters, none of `<>/\":;?*|,=` and backquote).
- **`PATCH /sessions/{id}/layers/{name}`** `{new_name?, ...properties}`. The name match is case-insensitive.
  - `new_name` renames the layer: every entity in all spaces and blocks follows. `0`, `Defpoints` and xref layers
    cannot be renamed.
  - Freezing the current layer is refused with a warning (it stays thawed), as in AutoCAD.
- **`POST /layers/update`** `{layers: ["A-*", "Xref*"], set: {...}}`: the same properties on every matching layer.
- **`POST /layers/current`** `{name}`.
- **`POST /layers/rename`** `{map: {old: new}}` and/or `{rules: [{pattern, replace}]}`: regex rules (groups `\1`) are
  applied in order to every layer name. A target that exists is a conflict unless `merge: true`. `dry_run` returns
  `result.plan` (`rename` / `merge` per layer, with object counts) and `result.problems`. One version for the whole map.
- **`POST /layers/merge`** `{sources, target}`: moves every object (all spaces, block contents, attributes) to the target,
  then deletes the sources; the target is created if missing.
- **`DELETE /layers/{name}[?move_to=X]`**: a layer with objects needs `move_to`. `0`, `Defpoints`, the current and xref
  layers cannot be deleted. Viewport freeze lists drop the layer.

### Text and attributes

- **`text/query`** `{select?, include_attributes = true, include_dimensions = true}` -> items
  `{handle, type: TEXT|MTEXT|ATTRIB|DIMENSION, text, raw, height, rotation, style, layer, position, space}`;
  attributes also `insert`, `block`, `tag`; dimensions `measurement`. `text` is what a reader sees (MTEXT codes and
  `%%d`-style codes resolved), `raw` the stored string.
- **`text/replace`** `{find, replace = "", select?, match_case = false, regex = false, whole_word = false}`
  - Matches the plain text and edits only the literal characters of the stored string, so MTEXT formatting stays.
    A match across a formatting code or line break is skipped and listed in `result.skipped`.
  - `regex`: Python regular expression; the replacement may use groups (`\1`, `\g<name>`).
- **`text/set`** `{items: [{handle, value}]}`: a TEXT/MTEXT/dimension by its handle, an attribute by its own handle or by
  the insert's handle + `tag`.
- **`attributes/query`** `{select?, tags?}` -> `{inserts, total, items: [{insert, block, tag, value, handle, layer, space}]}`.
- **`attributes/set`** `{select?, values?: {TAG: value}, expressions?: {TAG: expr}}` (legacy `{tag, value}` still works)
  - Expressions: `inc` / `inc:<n>` (trailing number or letter: A01 -> A02, 9 -> 10, B -> C), `seq:<start>[:<step>]`
    (numbers the selected references in reading order: top to bottom, then left to right), `date:<strftime>`
    (`date:%d.%m.%Y`), `upper`, `lower`, `prefix:<s>`, `suffix:<s>`, `replace:<old>:<new>`.
  - A tag a reference does not have is listed in `result.missing_tags`, not an error.

### Blocks

- **`GET /blocks`** -> `{name, handle, base_point, entities, by_type, attributes: [{tag, prompt, default, constant}],
  references, nested_references, anonymous, xref?, description?}`.
- **`blocks/rename`** `{name, new_name}`: every reference follows; anonymous and xref blocks cannot be renamed.
- **`blocks/insert`** `{block, point, scale? (number or [sx, sy, sz]), rotation? (degrees), layer? = "0",
  attributes?: {TAG: value}, space? = "model"}`: attributes come from the block's definitions (defaults for tags not
  given), placed and scaled with the reference, on their definition's layer (as AutoCAD). `rows?`, `columns?` (> 1),
  `row_spacing?`, `column_spacing?`: a MINSERT, AutoCAD's array of the block in one object (spacing in drawing units
  along the reference's own turned axes; AutoCAD cannot explode it).
- **`blocks/replace`** `{select, block, keep_attributes = true}`: the references show another block; attributes are
  rebuilt from its definitions (as AutoCAD's ATTSYNC) and keep their values by tag.

### Quantities

- **`measure`** `{select?, by = "layer"}` -> `{units, by, items, groups, totals: {count, length, area}, not_measured}`.
  - Lines, arcs, circles, ellipses, polylines (bulges), splines (along fit or control points), hatches, solids, 3D faces:
    `length` (open) or `perimeter` + `area` (closed). Lengths and areas equal AutoCAD's own (vlax-curve) on the test set.
  - Straight walls (made here or in ACA): `length`, `width`, `height`, `side_area`, as AutoCAD's LIST. Other ACA objects
    (and walls of an unknown layout): `footprint_area` from their plan graphics, walls also `length_approx` / `width_approx`.
  - `?format=csv` returns the items; `&table=groups` the per-group totals. CSV is UTF-8 with BOM (opens in Excel).
- **`areas`** `{select?, min_area?, label_layers?}`: closed polylines, circles, full ellipses, hatches, solids ->
  `{units, count, total_area, items: [{handle, type, layer, area, perimeter, centroid, labels: [{handle, text}]}]}`,
  largest first; `labels` are the TEXT/MTEXT whose insertion point lies inside (room names, numbers).

### Cleanup

- **`cleanup/purge`** `{what?, keep?}`: removes what nothing uses, like AutoCAD's PURGE, repeating until nothing more is
  unused. `what`: any of `layers`, `blocks`, `linetypes`, `text_styles`, `dim_styles`, `regapps`, `empty_text`,
  `zero_length` (default all). `keep`: name patterns never purged.
  - Never purged: layer 0, Defpoints, the current layer and styles, Continuous/ByLayer/ByBlock, the Standard text style,
    layouts, anonymous and xref blocks, xref-dependent names, the ACAD application name.
  - "Used" includes references from ACA objects and styles, dimension styles (arrow blocks, text styles, linetypes),
    complex linetypes and any other object of the drawing. On the test set the result equals AutoCAD's `-PURGE`.
  - Objects of classes acadrust does not read are kept as they are; `result.warnings` says how many.
- **`cleanup/overkill`** `{select?, tolerance = 1e-6, zero_length = false}`: deletes exact duplicates (same type, layer,
  color, linetype, lineweight, transparency and geometry within tolerance; the first stays), like AutoCAD's OVERKILL.
  Overlapping or collinear parts are not merged.
- **`cleanup/audit`** `{fix?}`: acadrust's structural audit (handles, owners, references, table keys): `report` with
  `errors`, `warnings`, `by_code`, the first 100 `issues`; `fix: true` applies its safe repairs as a new version.

### Attached objects

As in AutoCAD Architecture doors and windows hang on their wall, any object can hang on another (`objects/attach`; the
editor's ATTACH / DETACH commands, MCP `dwg_attach`). An attached object (a child) is moved, rotated, scaled, mirrored,
copied and deleted together with its host (`objects/transform`, `/copy`, `/delete` add the children of the selected
objects, and their children, to the selection); a block reference moved or turned by its grip or in Properties
(`objects/edit`, `/prop-set`) takes its children along. A copy of a child made with its host hangs on the host's copy; a
child copied alone keeps its host. A child edited alone stays attached; a child whose host is gone otherwise (exploded,
made into a block) is detached. No loops: the host and what it hangs on cannot be attached to it (`skipped`).
Properties list "Attached to" and "Attached objects" in the General group.

The simple mode attaches every door and window it cuts into a wall to the outline contour it is cut into, and the
opening's dimension to the door / window: deleting or moving a wall takes its doors, windows and their dimensions.
When the wall outline is rewritten (`walls/add`, `walls/cut`: contours merged or split), what hung on a contour that
changed hangs on the contour nearest to it; door and window blocks lying on the outline that hang on nothing (drawn
before attaching existed) are attached then too.

Stored in the standard DWG as the child's XDATA (application `AICAD_HOST`, a 1005 handle of the host). AutoCAD reads
and keeps it (AUDIT 0) but does not act on it: in AutoCAD the children do not follow, and its COPY gives a copied child
the original host.

### Walls as their outline

As the standards draw them (NCS A-WALL, ISO 128-23, GOST 21.201), a wall is not an object: the wall material on the
wall layer is outlined by closed polylines without width (outer contours and holes, i.e. the rooms' faces), drawn with
the layer's lineweight. (v0.053 and v0.054 wrote lines instead; such an outline, the lines that chain into closed
loops, is still read and written back as polylines.) `walls/add` unites the band of a run of walls (its thickness around the corner points, mitred
at the corners, square at open ends) with the material; `walls/cut` finds the wall at `at` (the face nearest and the
parallel face across: its thickness) and cuts a gap of `width` through it, keeping it within the wall's straight
stretch, then inserts the door or window block on the wall's centre line (`side`: the leaf's side, `hinge`: start or
end along `along`) and a dimension of the gap 400 mm (in the drawing's units, INSUNITS) out from the wall's face, in a
style that reads on the plan (`readable` above) (50 mm of wall kept to each corner). The outline is rewritten after each
change: unchanged contours keep their objects, a changed one updates the polyline it shares most corners with; float
debris (hair-thin spikes, specks under 10 mm²) is cleaned away. Room boundaries made of given objects (rooms, FLOOR's
`only`) bridge each opening: two jamb edges facing each other across a gap outside the material. A door or window
block deleted (`objects/delete` with `simple: true`, see below) closes its gap: the wall is whole there again, unless
another opening stands in it. One moved (`objects/transform`, its grip, Properties) slides along a wall with its gap: the old gap
closes, the block goes onto the centre line of the wall it was dropped on (or of its own wall, nearest), clear of the
wall's corners, junctions and other openings, and its gap is cut there; its dimension goes along. `walls/add` with
`dims: {layer, offset?}` gives an open run's walls dimensions on their inner faces (corner to corner).

The simple mode's automation (v0.114, user decision 2026-11-13, `spec/model_standard.md`: Pro is plain AutoCAD): what
follows an edit (attached objects moved / copied / deleted with their host, a door's or window's gap closed or moved
with it, rooms refreshed, wall material hatches refitted) runs only for an edit with `simple: true` in its params (any
edit route, a `batch` step too) and for the simple mode's own wall tools (`walls/add`, `walls/cut`, `walls/edit`,
`walls/redraw`, `walls/opening`). Without it an edit is plain AutoCAD: only AutoCAD's own associativity follows
(associative dimensions and hatches). The website sends `simple: true` with every edit made in the simple mode
(`localdoc.js` `editMode`; the flag is kept in the recorded edit, so a version rebuilds the same way); the assistant's
and other REST / MCP edits are plain unless they pass it.

Cutters (v0.115, user task 2026-11-14, tasks2 Autodraw: "walls and cutters"): what is put into a wall and cut out of
it. Doors and windows cut walls by default; any other block cuts them once marked (`blocks/cutter`, or a block
reference's Properties `cuts_walls`, `objects/prop-set`; the mark is the block's, kept in the NOD XRECORD
`AICAD_OPENINGS`: kind `cutter`, or a door / window with its mark taken off). A cutter that is not a door / window
stays where it is put: the wall its extents stand in (overlapping the wall's band, its X axis along the wall within 2
degrees) gets a gap through its whole thickness over the stretch its extents cover; moved (`simple: true`), the old
gap closes and a new one is cut where it stands (none when it is off the walls); placed or copied onto a wall
(`blocks/insert`, `objects/copy` with `simple: true`), it cuts there; deleted or unmarked, its gap closes. A door /
window that stands on a wall without a gap (copied there, or marked again) gets its gap cut where it stands.

### Walls of any drawing (layer categories)

Every layer has a category: `wall` (everything on it is wall material), `opening` (doors and windows: what stands in a
wall's gap) or `other` (takes no part); several layers can share one, and the walls of all wall layers make one network
(joints, rooms), the openings of any opening layer cut any wall. `GET layers/roles` tells each layer's category and
where it comes from (`source`): `stored` (set with `POST layers/roles`, kept in the drawing as the XRECORD
`AICAD_LAYER_ROLES` of the named object dictionary, by layer handle, so a renamed layer keeps it), `name` (wall / door /
window words of many languages, the standards' codes A-WALL, A-DOOR, A-GLAZ; an xref's layer, `xref|layer` or
`xref$0$layer`, by its own name), `geometry` (only when no layer named for it holds walls, 10 m of paired lines or
2 m² of wall-thin hatch: the layers with 20 m or more of lines in parallel pairs 40-800 mm apart, or wall-thin
hatches; door swings) or
`default` (other). `suggested` / `suggested_by`: the category the layer has without a stored one, and where that comes
from. `scale`: millimetres per drawing unit, from the door swings (a leaf of 550-1300 mm), else INSUNITS when the
drawing's size fits them, else its size. Suggesting by geometry walks the whole drawing (seconds in a large one);
`?geometry=0` skips it (those layers `other` / `default`). The Pro mode's Layers palette has a Visibility / Role switch
above its table; Role shows each layer's category in place of On / Frz / Lck: Auto (the suggestion, shown) or Wall /
Opening / Other set by hand, one version each, undone as any edit.

`POST walls/model` without `wall_layer` recognises the walls of the wall layers however they are drawn: hatches as their
region, lines / polylines / arcs (block contents included) noded into faces, the faces 45-600 mm thick on average being
material (each end of a face closed across to its parallel face; faces bounded by arcs for a third, a door's swing, and
broad stacks of strips, a stair's treads, left out). Doors and windows: what stands on the opening layers in a wall's
gap (the opening's handle in the wall's `openings`). ACA walls are walls by their type on any layer (not on one whose
stored category is another; with `wall_layers` given, only on those), drawn by their proxy graphics, or, saved without
them, by the baseline and width the core reads (else a thin extents box). Each wall tells its `layer`; the reply its
`layers` {wall, opening, aca_walls: the other layers ACA walls came from} and `scale`. Read-only: `walls/edit` works on
this editor's own outline (`wall_layer`).

### Analysis: how the drawing is made

`GET sessions/{id}/analysis` (MCP `dwg_analyze`; a drawing on the device: its core's `analysis_facts`, names and counts
only, sent to `POST /analysis`) tells how the drawing is made: per layer what lies on it and its `element` (wall,
door, window, furniture, plumbing_fixture, stair, dimension, text, ...: by a standard's layer names, else by the
element's word in the name, else by the wall category, else by the blocks standing on it; `element_by`); `elements`
with their layers, objects and blocks; `walls` (found, count, length, thickness, layers, `drawn_as`: ACA walls, line
pairs, polylines, hatches, blocks, multilines; what stands in their gaps); `blocks` with their references, layers,
door swings, references in wall gaps and `element` (registered here, the name's word, a swing, the layer); `standard`:
the one recorded in the drawing, else the profile whose names are 3 or more and a third of the layers in use;
`coverage`: the share of objects on layers of a known element and the unknown layers; `schema`: Markdown for the AI, a
summary with the rules to follow when editing (where new walls, doors, windows and furniture go, which blocks).
`auto_standard` {fits, problems, limits, standard}: whether the drawing keeps to the principles a standard rests on (3
walls or more recognised, on a layer of their own, not layer 0; doors or windows found; half its objects or more on
layers of a known element) and, if so, the standard made of its own layers (each element's main layer with its colour,
lineweight and linetype, the others as its alternative names; `draw.walls` as its walls are drawn; `blocks`: its own
blocks per element, for the AI; the user standard format, id `auto-...`); `limits`: what the simple mode cannot do on it
(walls not drawn as closed outlines, ACA objects). The website: switching a drawing made elsewhere to Simple uses it: one
that fits takes its own layers as its standard at once (kept on the device, recorded as `AICAD_STANDARD` `user:<id>`,
nothing renamed, one version); for one that does not, the user chooses: bring it to the standard with the AI, or work
on it as it is. The Standards palette offers "Use its own layers as its standard".

### Auto-fix

`POST sessions/{id}/autofix` (MCP `dwg_autofix`; the website's Standards palette "Fix the drawing": found first, then
applied) fixes a drawing by its standard: the given one (a profile id, a country code or a standard object), else the
one it records, each element's layer taken from it when the drawing has that layer, else from the drawing's own layers
(`auto_standard`). Block references of a door, window, furniture, plumbing or stair block (registered, named or with a
door swing) standing on a layer of no element or of another one go to the element's layer; dimensions on a layer of
another element to the dimension layer; texts on wall, door and window layers to the text layer; and the walls that
nearly meet are joined (core `wall_gaps {layers?, tolerance? = 10 mm, scale?}`: free ends of the wall layers' lines and open
polylines that miss a corner, the line they continue (`join`) or the line they run into (`tee`) by up to the tolerance;
a door's gap or a wall's thickness is far wider), so rooms that were not closed are. Nothing is renamed or deleted.
`fixes`: [{kind: layer | gaps, what, from, to, count}]; `steps`: the batch (one version, undone as any edit).

### Walls as objects (simple mode)

The simple mode treats each wall as one object, recognised from the outline every time (nothing else is stored):
`walls/model` returns, per wall, its centre line `a`-`b` (from junction to junction, or to its free end), thickness `t`,
`band` (the polygon it covers), `out` (+1 / -1: the side of its normal that is outside the building, 0: rooms or open
air on both sides), its `ends` (`L`: the ends of two walls meet; `T`: it ends on another's side; `free`) and the door
and window blocks in it; `nodes` are the junctions. Recognition: each face paired with the nearest parallel face
across the material (up to 1 m); collinear pieces of one thickness join across the material between them (a T's
junction) and across their openings; pieces other walls cover are dropped; ends go on into an L's corner. The door and
window blocks are those of the standard, the blocks marked to cut walls and, in a drawing made elsewhere, unmarked
blocks on an opening layer (Doors, Windows, A-GLAZ...); one drawn over unbroken wall lines is in the wall it stands
over, and the wall gives `cuts` (one quad per such opening, face to face over its width: the gap Simple shows).

`walls/edit` changes the walls concerned (the wall, the walls joined to it and ending on it) and rebuilds the material
from the whole model (every wall's band on a 0.001 mm grid, united at once; what the outline held besides the walls,
a pier or column, kept) before writing the outline back, so edits leave no cracks or slivers: `remove` (the walls through the points go with their doors, windows, their dimensions and the wall
dimensions measuring them; the walls joined to them keep their length), `thickness` (the room side stays and the wall
grows outwards; a wall with rooms or open air on both sides grows on both; the walls joined to it follow its new
centre line), `node` (the walls' ends at `from` go to `to`, a T junction sliding along the wall it is on; walls ending
on a moved wall meet it again). Doors and windows move with their wall (with what hangs on them), windows take its
thickness; aligned dimensions on `dim_layer` measuring from junction to junction (as WALL makes them) follow.

### Simple-mode rooms

`walls/rooms` (core `rooms_auto`; the simple mode's WALL runs it in the same version as the wall): the rooms the walls
(the outline on `wall_layer`, and polylines with a width) close, through their door and window gaps, each get a solid fill on `fill_layer`
bounded by the walls only (furniture, doors, dimensions inside do not cut it; associative to the walls) and their area
as a centred text on `label_layer` ("27.84 m²", the unit, decimals and decimal separator given). Run again it is a
refresh: a fill whose room changed (a partition split it, a wall moved or went) is replaced with its area label, the
labels of the rooms kept are brought up to date, labels the user rewrote stay. The settings are kept in the drawing
property `AICAD_ROOMS`; from then on every edit that touches a wall (move, grips, delete, openings; also through the
API and MCP) refreshes the rooms in the same version. The default standard's room-fill layer `A-AREA-PATT` is 80 %
transparent and not plotted (AutoCAD plots the plan without it). With `dim_layer`, each new room also gets its
interior dimensions: one aligned dimension per side 300 or longer, inside the room 400 from the face, of two parallel
equal sides facing each other one (a rectangle: width and depth); they hang on the room's fill (attached objects) and
are replaced with the room; a side already measured by a dimension is skipped.

`walls/floor` `{select, layer}` (core `room_floor`, user task 2026-11-07: one object per room): the rooms' fills selected
become their rooms' floors: moved to `layer` (the floor finish layer, made if missing) and marked (XDATA `AICAD_ROOM`);
handle, area label, interior dimensions and association stay. Give the floor a material afterwards
(`objects/plan-material`). `rooms_auto` keeps a marked hatch as its room's fill on any layer (a room with a floor gets no
second fill) and, when its room changes, fits it to the room again in place (around its seed point, else its middle;
re-associated with the walls) instead of replacing it, so the material stays; a floor whose room is open stays as it is
until the room closes. The simple mode's Materials palette and FLOOR (ceramic tiles) do this to the room clicked.

### Stairs (simple mode)

`stairs` (core `stair_create`; the simple mode's STAIR) makes a straight flight from the bottom step's middle `a` to the
top step's middle `b` (300 or longer), `width` wide: a block of its own ("Stair n", in the flight's own axes: X along
the flight, Y across) with its outline, treads about 280 apart and the walking line with its arrow, referenced at `a`
and turned to the flight, on `layer` (default `A-FLOR-STRS`). Its length's aligned dimension is in model space on
`dim_layer` (default `A-ANNO-DIMS`), `dim_offset` off its left side (600 mm in the drawing's units unless given), and [hangs on it](#attached-objects): AutoCAD does
not draw a dimension inside a block that has no graphics block of its own. The reference keeps its length and width as
XDATA `AICAD_STAIR`; `drawing` gives them as `def.stair: [length, width]`. A stair stretches: `objects/edit {handle,
stretch: {side, to}}` (`right`: the top end, `left`: the bottom end, `front` / `back`: its left / right side) rebuilds
its block at the new size (a reference sharing its block with copies gets a block of its own first), the treads
following its length, and its dimension follows keeping its distance; Properties' Size group gives its Width and
Length (`prop-set` `width` / `depth`: the bottom step and the axis stay).

### The plan in 3D (simple mode)

`POST /sessions/{id}/walls/3d` `{wall_layer, wall_height?, door_height?, window_height?, sill?}` (tasks2 2026-11-17:
Simple and Autodraw draw the 3D model from the plan by themselves; core `plan3d.rs`, on the device in the website) ->
`{gltf, walls, doors, windows, wall_height, unit_mm}`. The walls recognised from the plan stand on the floor up to the
drawing's wall height (`walls/3d-settings`), else `wall_height`, else the default; each door, window and cutter cuts
its wall from its height above the floor (a window's sill: `prop-set` `elevation_3d`, XDATA `AICAD_ELEV`; else 900) up
by its height (`height_3d`, XDATA `AICAD_SIZE`; else doors 2100, windows 1500, cutters the wall's), a lintel above.
Defaults in metric drawings: walls 2700, doors 2100, windows 1500 on a 900 sill; in inches or feet: 9'-0", 6'-8",
4'-0" on 3'-0". A wall's material shows as its colour, its components side by side; a window is a pane of glass in its
opening, a door its leaf as its block draws it (90 or 30 degrees); a floor slab lies under the building's outline (the
wall material with its doors and windows closed), a room's floor material on top. `gltf`: glTF 2.0, its buffer
embedded, in metres with Y up (a drawing point (x, y, z) is (x, z, -y) times `unit_mm` / 1000), flat-shaded; each node
has `extras` `{id, category, name}` (a wall: the simple mode's id `W:x,y`; a door / window: its handle). Only the
outer faces of the walls are made (no faces between pieces or components). The website fills it into the 3D page
(`/viewer.html`, `window.AICAD_UNIT_MM`), with the view cube, and a click on a wall there selects it.

`POST /sessions/{id}/walls/3d-settings` `{wall_height: number | null}` -> `{updated, wall_height}`: the drawing's wall
height (every wall), kept as the `AICAD_3D` drawing property (JSON; converted with the drawing's units); null: back to
the default. In the simple mode's wall Properties: Height.

### Materials

What an object is made of (user tasks 2026-11-06; core `matlib.rs`; "plan materials", to tell them from the render
materials of `/materials`). A material has a name, a hatch (`pattern` from `hatch/patterns` or `SOLID`, `scale`,
`angle` in degrees), a `color` (#rrggbb), a `group` and `notes` (make, size, links to products). In the DWG it is an
AutoCAD render material of the same name (its diffuse colour; its description holds the notes) and an XRECORD in the
dictionary `AICAD_MATERIALS` of the named object dictionary (codes 1 name, 2 pattern, 40 scale, 50 angle, 300 colour,
301 group, 302 notes in pieces of 250 characters, 70 = 1). Objects take it as their Material (code 347: AutoCAD's
Properties shows it); a hatch also takes its pattern, scale, angle and colour, 50 % transparent (solid: 80 %).
Changing a material's hatch or colour restyles its hatches; renaming it keeps its objects. Properties show it in the
`plan_material` group (a choice of the drawing's materials; `prop-set {key: "plan_material", value: name | "None"}`)
with its notes; ACA objects keep their style's materials. `drawing` gives an object's material as `mat: {name, color}`.

The built-in library is `standards/materials.json` (`GET /v1/standards/materials`), shared by the website and MCP
`dwg_plan_material`. The website's Materials palette (`js/tabs/materials.js`, `js/cad/materials.js`) lists the drawing's
materials, the built-in library (walls and structure with the standards' section hatches: concrete dots and triangles, GB/T 50001;
brick 45° lines; stone broken lines, GOST 2.306; gypsum board small crosses; floors at real size: 600 / 300 tiles,
parquet, planks) and the user's own (kept on the device); a click gives the material to the selection. A room's area
(the simple mode's room fill) stands for its floor: the floor hatch on the standard's floor layer, made if the room has
none. The simple mode shows a selected hatch's materials instead of the hatch panel and draws objects in their
material's colour.

A wall's material (`walls/material`, core `wallmodel.rs` `wall_material`): a hatch of the material over the wall's
band, clipped to the wall material (door and window gaps stay open, a junction is hatched once), on the standard's
`wall_pattern` layer (A-WALL-PATT), with XDATA `AICAD_WALLMAT` (the wall's centre and direction, the wall layer).
After any edit of the wall outline (walls added, cut, edited, moved, copied) each such hatch is made again for the wall
it belongs to now (the wall whose band holds its stored centre or its own centre, else the nearest wall running within
35° of the same way, within twice its thickness or 800); a hatch whose wall is gone goes with it. The simple mode's
wall Properties have a Material choice; the Materials palette gives a selected wall its material.

A wall of several components side by side (tasks2 2026-11-17: concrete and gypsum; `walls/material` with
`components`): the wall stays one band of material in the DWG (its outline is what the standard draws, so recognising,
editing and converting walls are unchanged); each component is a strip of the band across its thickness, a hatch of its
material whose `AICAD_WALLMAT` also holds the strip (fractions of the thickness from the wall's right face). The list
goes from the face on the side of `from`, else the outside (`out`), else the right face (going from `a` to `b`);
thicknesses are shares of the wall's thickness (the wall keeps its thickness: `walls/edit` thickness first if their sum
should be it); a component without a name stays unhatched; one with `hatch` (another drawing's hatch) is made of that
hatch's material, else of one made from the hatch ("<PATTERN> hatch", its pattern, scale, angle and colour), and that
hatch goes. After an edit each strip is made again at its share of the wall's thickness (a thicker wall: every
component in proportion), on the side it stood on (where the hatch stands now when the wall kept its thickness: the
plan moved, turned or mirrored; else by the stored direction). `name` alone (one material) replaces the components.
A line runs between the components (at each boundary inside the wall, also next to an unhatched one): a LINE on the
layer of the wall's hatches, ByLayer, within the wall material (door gaps open, a junction's mitre ends it), with XDATA
`AICAD_WALLSEP` (the wall layer); made again with the strips, never a wall face (walls of any drawing leave it out).
`walls/model` tells each wall's `materials` `[{name, t, h?, own?, pattern?}]` from the outside face (else the right
face; parts without a hatch: `{name: null, t}`): its own material hatches, else (recognised) the strips of another
drawing's hatches across it: two or more hatches each lying within the wall's band over part of its thickness, along a
third of its length or more (`own: false`, with their `pattern`). In the simple mode's wall Properties: a Components
card (each component's material and thickness, a new sum making the wall that thick; × gives a component's place to
the one beside it; Add a component splits the room side one: plaster, 20 mm; another drawing's components: Edit these
components takes them over). MCP `dwg_plan_material` `components` with `wall_at`.

### Standards database

National and international CAD drawing standards (`standards/` in the repository; format `standards/SCHEMA.md`):

- **records** (`/standards/{id}`): what a standard prescribes: layer naming (format, fields, codes, the layer of each
  building element: `wall`, `door`, `window`, `stair`, `furniture`, `dimension`, ...), lines, material hatching, text,
  dimensions, room labels, how renovation drawings show existing / demolished / new work; every fact with its sources and
  a confidence (`v` from the standard's text or a table reproducing it, `i` from secondary sources);
- **countries** (`/standards/countries/{cc}`): the standards that apply in a country and its practice;
- **profiles** (`/standards/profiles/{id}`): drawing standards the editor applies. `elements` maps an element key to its
  layer `{layer, color (ACI or #rrggbb), lineweight (1/100 mm), linetype, description}`; `area_label` `{unit, decimals}`;
  `decimal_separator`; `status_suffix` (existing / demolish / new); `draw.walls`: how the standard draws walls,
  `lines` (line pairs: the default standard's and the country profiles', the most common way in real drawings) or
  `outline` (the material's contours as closed polylines); `draw.door` / `draw.window`: `{block, symbol}`, the block
  doors / windows are drawn with (default A-DOOR / A-WINDOW) and its symbol: door `leaf90` (leaf at 90 degrees with a
  quarter arc) or `leaf30` (one line at about 30 degrees, no arc: GOST 21.201 Table 7 a); window `double_glass` (wall
  faces and a glazing pair) or `three_lines` (GOST 21.201 Table 4). The symbol comes from the records' structured
  `graphics.<kind>.symbol` (the profile's record, then its country's standards). The core remembers the door / window
  blocks it made (NOD XRECORD `AICAD_OPENINGS`) and recognises them as doors / windows whatever their names. The simple mode draws with `aicad-default` (US NCS
  layer names: A-WALL, A-DOOR, A-GLAZ, A-FLOR-STRS, A-FURN, A-ANNO-DIMS, ...; pastel colours); the layers it creates
  take the profile's properties (an existing layer of that name is kept as it is).

Converting to another country's standard (`/standards/convert-plan`, `/sessions/{id}/standards/convert`, MCP
`dwg_convert_standard`, the website's Standard palette):

- `to` is a country code or a profile id. A country with its own layer standard in the database (US NCS, GB AEC UK,
  DE Bavarian state list, FR, CN GB/T 50001, JP MLIT, CA PSPC, BR) gets that profile (`standards/profiles/`, built by
  `tools/standards_db.py profiles`); any other gets `aicad-default` with the country's language and decimal separator.
- The drawing's layers are recognised by name through every profile (element layers and their alternative names;
  `from` = the profile that fits best). Each recognised layer becomes the target's layer of the same element:
  `layers_rename` with `merge` (several sources into one target), then `layer_update` with the target's colour,
  lineweight, `Continuous` linetype and description. Unrecognised layers are kept and listed; elements the target has
  no layer for are kept (`missing`).
- Labels (TEXT, MTEXT, attribute values; not dimension texts): translated into the target's language by the assistant's
  model (tokens; only the strings are sent, `POST /ai/labels`), and area numbers (`27.84 m²`) get the target's decimal
  separator. The website runs it on the device: plan and labels from the server, the edits locally, one version.
- Walls (v0.112, user decision 2026-11-13, `spec/model_standard.md`): the plan ends with `walls_redraw` on the target's
  wall layers, drawing the walls the way the target's `draw.walls` says (`lines` or `outline`; the plan's `to.draw`);
  doors and windows stay on them. Then `openings_redraw` gives every door / window the target's block (`draw.door`,
  `draw.window`: block name and symbol). A drawing made here then records the target as its standard
  (`AICAD_STANDARD`; a country without a profile of its own by its code, e.g. `RU`: `GET /standards/profiles/RU` is
  the default layers drawn as its standards draw), so the simple mode reads and writes it by that one.
- Dimensions (v0.124): when the target's `draw.dimensions` names a terminator, the plan ends with `dimstyle_set
  {names: "*", terminator}`: every dimension style ends its dimension lines that way ([below](#dimensions-by-the-standard)).

### Units and measurement systems

`units` (core `units_set`, units.rs; user task 2026-11-16: the user chooses the imperial or the metric system) sets the
drawing's units as AutoCAD's UNITS / -DWGUNITS do: INSUNITS, MEASUREMENT (0 imperial: in, ft; 1 metric), LUNITS /
LUPREC (architectural to 1/16" in imperial, decimal in metric) and, when the system changes, every dimension style's
format (architectural to 1/16" with zero inches kept, DIMLFAC 12 in a drawing in feet; or decimal: whole mm, 1 place in
cm, 2 in m). `scale: true` converts the drawing, every size kept in real life: model space scaled about the origin;
block references scale with their point while their blocks keep their own units (dynamic blocks keep their parameters
and constraints, unit blocks such as the doors' stay so; the block records say the old units), the graphics blocks of
dimensions and tables and the stairs' blocks are scaled; polyline widths, hatch patterns, LTSCALE, fixed text heights,
limits, extents and views follow; the dimension styles keep their size (sizes on paper in inches in imperial, in
millimetres in metric: 2.5 mm text at DIMSCALE 50 becomes 0.0984"); the core's own sizes (stairs, 3D heights, the rooms'
settings and their labels, now in ft² or m², the plan materials' hatch scales) too. Model space's parametric
constraints go (they hold the old coordinates). A drawing with ACA objects, proxies or custom objects is not converted
(422 E_UNSUPPORTED). Checked in AutoCAD 2021: the imperial sample to mm and a metric plan to inches plot the same as
before, AUDIT 0 errors, the dimensions written in the new system. Without `scale` only the units change (a drawing whose
INSUNITS were wrong). New drawings in inches (`sessions/new {units: in}`) get an architectural Standard style (3/32" text
and arrows at 1/4" = 1'-0", DIMSCALE 48; 4 in feet). The website: the status bar's units button converts the drawing or
sets its units, and chooses the units of new drawings (also beside New drawing on the start page): by the drawing
standard (US NCS: feet and inches), metric or imperial; Simple's sizes, dimensions, area labels, stairs, floor tiles,
furniture and comments follow the drawing's system (js/cad/units.js).

A dimension or leader the simple mode adds (`readable`) takes a style whose text reads on the plan, and its offsets
are in the drawing's units (400 / 600 mm). A drawing standard gives its dimension sizes in millimetres on paper
(`paper: mm`): an imperial drawing takes them in inches.

When an edit deletes geometry an AutoCAD constraint group depends on (a wall cut of the simple mode through lines with
dimensional constraints), the group goes as DELCONSTRAINT takes it away (core assoc.rs: the group, its dependencies,
the variables only it uses and its constraint dimensions; no reactor is left): AutoCAD's AUDIT finds no error.

### Dimensions by the standard

A standard's `draw.dimensions` (`{terminator: tick | arrow, tick_size?, extend?, text_height?}`, sizes on paper in
mm as AutoCAD's dimension style dialog gives them; DIMSCALE scales them in the drawing) says how its dimension lines
end. The default standard and the profiles whose records say so (NCS, GB/T 50001, DIN 1356-1, PSPC, GOST 21.101 for
`RU`, ...) end them with oblique ticks, the most common way in real plans (of 512 surveyed plans 130 have dimensions:
94 mostly with ticks, 86 % of their dimensions, nearly all with the dimension line past the extension lines; 36 with
arrows or dots). A new drawing (`POST /sessions/new`, the website's New) takes the standard's in its Standard style;
converting sets every style's.

`POST /sessions/{id}/dimstyles` (core `dimstyle_set`): `tick` sets DIMTSZ (`tick_size`, else the style's own, else
0.4 x the text height) and, when the style has none, DIMDLE 0.6 x the text height (the surveyed plans' medians: 0.38
and 0.6; 1 and 1.5 at 2.5 text); `arrow` clears DIMTSZ and the tick arrowhead blocks (closed filled). The dimensions of
the changed styles that the core draws anew lose their graphics block (`redrawn`; AutoCAD makes it again on opening),
so they show the new ends. `terminator` read back: `tick` (DIMTSZ, or the `_ArchTick` / `_Oblique` / `_Integral`
blocks, as AutoCAD's dialog sets them), `dot`, `none`, `arrow`. The analysis reports the drawing's own
(`dimensions: {count, terminator, styles}`), and an auto-standard takes it.

A dimension without its graphics block is drawn as AutoCAD 2021 draws it (probed: `testset/dims/`,
`tests/test_dim_ends.py`): DIMTSZ strokes from q - (t, t) to q + (t, t) in the line's frame (t = DIMTSZ x DIMSCALE);
the style's arrowhead block (DIMBLK, or DIMBLK1 / DIMBLK2 with DIMSAH) at DIMASZ; the dimension line DIMDLE past the
extension line after a tick, `_None` or a small dot, the arrowhead's size short of it after any other arrowhead.
Per-dimension overrides (XDATA) are not read.

A new dimension or leader (`objects/create`, Simple's room, wall, door and stair dimensions) takes `dimstyle`, else the
drawing's current dimension style (its DIMSTYLE, as AutoCAD; v0.125, was Standard); `dimstyles` without a name edits
that one.

Checking against a standard (`/standards/check`, `/sessions/{id}/standards/verify`, MCP `dwg_check_standard`, the
Standard palette's "Check"): the input is the layer table only (names, properties, `by_type`, block names per layer).
Issues, each `{kind, layer, ..., fixable, steps}` (`steps`: the batch steps that fix it):
- `rename`: a layer a standard gives to an element under a name that is not this standard's -> the standard's layer
  (renamed or merged, with its properties);
- `ai` (with `ai: true`, tokens): a layer no standard knows, classified by the assistant's model from its name (any
  language) and contents -> the standard's layer of that element; `confidence` >= 0.6;
- `props`: one of the standard's layers whose colour, lineweight or linetype (`Continuous`) differs;
- `unknown` (kept), `missing` (an element the standard has no layer for; kept).

Drawings made here carry custom drawing properties (DWGPROPS, kept in the DWG summary info and the DXF header; AutoCAD
reads them, AUDIT 0): `AICAD_CREATED_BY` (`AI CAD <version>`), `AICAD_STANDARD` (profile id or `user:<id>`) and
`AICAD_STANDARD_NAME`; a drawing made elsewhere and brought to a standard gets `AICAD_CONVERTED_BY` instead of
`AICAD_CREATED_BY`. `POST /sessions/new` sets them (default standard); the summary lists them under `properties`.
The website opens a drawing without them in the Pro mode.

A user's own standard: everywhere a standard is taken (`to` of the conversion, the check and their session routes;
`from`), it may be a standard object in the profile format instead of an id: `{name, elements: {element: {layer,
color?, lineweight?, linetype?, description?, alt?}}, language?, decimal_separator?}`. It is checked (element keys,
valid layer names, ACI or `#rrggbb` colours, lineweights in 1/100 mm) and not stored: the website keeps the user's
standards on the device and sends the one in use with each request. `/standards/classify` maps the layers of the
user's file to elements (by name through every profile; with `ai` the rest by the assistant's model).

### Versions and files

- `GET /sessions/{id}/versions`: `time` is in Unix seconds; `op` is the edit name (`upload`, `set_layer`, ...).
- `POST /sessions/{id}/undo` and `/redo` return the Session. They return 409 when there is nothing to undo or redo.
- `POST /sessions/{id}/versions/{n}` makes version n current. Later versions stay until the next edit.
- `GET /sessions/{id}/file[?version=n]` returns the DWG.
  - Content type: `application/acad`, sent as an attachment.
  - File name: `<name>.dwg` for v0, `<name>_v<n>.dwg` for later versions.
  - `dwg_version=2018|2013|2010|2007|2004|2000` writes another DWG version; `format=dxf` writes DXF. Both are refused
    (422 `E_UNSUPPORTED`) when the drawing holds ACA objects or other classes stored as their source version's bytes.
- `GET /sessions/{id}/diff?from=a&to=b`: `{from, to, counts, added: [{handle, type, layer}], removed: [...],
  changed: {handle: {property: {from, to}}}}`. Properties: layer, color, linetype, lineweight, transparency, material,
  text, block, attributes, measurement, bbox, `geometry` (a key that changes with any geometric change).
- `POST /sessions/{id}/batch` `{steps: [{method, params}], dry_run?}`: the steps run in order on the worker and are saved
  as ONE version (one undo); an error in any step drops them all. Methods: the worker's edit methods (`set_layer`,
  `set_props`, `delete`, `transform`, `copy`, `layer_create`, `layer_update`, `layers_update`, `layer_current`,
  `layers_rename`, `layers_merge`, `layer_delete`, `text_set`, `attr_set`, `block_rename`, `block_insert`,
  `block_replace`, `purge`, `overkill`, `audit`, `aca_material_set`, `material_create`, `material_update`) and reads
  (`query`, `count`, `get`, `text_list`, `attributes`, `blocks`, `measure`, `areas`, ...). A parameter
  `"$steps[i].result.<path>"` takes a value from an earlier step, e.g. `{"handles": "$steps[0].result.created"}`.
- `GET /sessions/{id}/view` returns a self-contained HTML page: a 3D view plus a plan toggle (three.js from jsDelivr). It is cached per version.
  - It draws ACA walls, doors, windows and stairs, 3DFACEs and aligned dimensions.
  - Entities on layers that are off or frozen are not drawn.
  - Lines, polylines, arcs, circles, texts, hatches, block contents and dimensions are drawn too.

---

## Examples (curl)

```sh
B=http://127.0.0.1:8080/v1
# upload
curl -s -X POST "$B/sessions?name=test.dwg" -H "Content-Type: application/octet-stream" --data-binary @test.dwg
# list walls
curl -s -X POST $B/sessions/<id>/objects/query -H "Content-Type: application/json" -d '{"select":{"types":["wall"]}}'
# move all walls to a new red layer
curl -s -X POST $B/sessions/<id>/objects/set-layer -H "Content-Type: application/json" \
     -d '{"select":{"types":["wall"]},"layer":"A-Wall-Ext","color":"red"}'
# rename a layer and turn it blue
curl -s -X PATCH $B/sessions/<id>/layers/A-Wall-Ext -H "Content-Type: application/json" -d '{"new_name":"A-WALL-EXT","color":5}'
# undo, then download the current version
curl -s -X POST $B/sessions/<id>/undo
curl -s -o out.dwg $B/sessions/<id>/file
```

## Assistant chat

| Method | Path | Body | Returns |
|---|---|---|---|
| GET | `/sessions/{id}/chat` | | `{backend, available, reason, busy, messages}` |
| POST | `/sessions/{id}/chat` | `{message, selection?: [handle], view?: {window, attention?, mode, px}}` | server-sent events (`text/event-stream`) |
| DELETE | `/sessions/{id}/chat` | | `{cleared: true}`: starts a new conversation |
| POST | `/sessions/{id}/ui/{request}` | `{image, window, px}` or `{error}` | `{ok: true}`: the page's answer to the assistant's `look` request (404 when nobody waits) |

**Backends** (`AICAD_AGENT`, agent.py). `cli` (default): the machine's Claude Code (`claude -p`) through `/mcp`.
`api`: the Claude API through the `anthropic` package (`server/requirements.txt`), the tools run in the server's own
process; for a server facing the internet. Its settings: the SDK's credentials (`ANTHROPIC_API_KEY`, ...),
`AICAD_API_MODEL` (default `claude-opus-5-5`), `AICAD_AGENT_EFFORT` (default `medium`). It sends the notes the model
writes between tool calls as `text` events, retries a refused request on the model Anthropic recommends (server-side
`fallbacks`), and refuses tool calls on any session but the chat's own. `deepseek`: DeepSeek's models through its
OpenAI-format API (plain HTTP, no package): `DEEPSEEK_API_KEY` (or `DEEPSEEK_API_KEY_FILE`), `AICAD_DEEPSEEK_MODEL`
(default `deepseek-flash`; `deepseek-v4-pro`), `AICAD_DEEPSEEK_THINKING` (`enabled` by default, `disabled`),
`AICAD_AGENT_EFFORT`; the same tools but `dwg_look` (its pictures do not go to this API), the same session rule. The
backend serves every AI request, the one-shot ones too (`standards/check` and `classify` with `ai`, `ai/labels`,
`scripts/write`). The events and the storage are the same.

**What the user sees** (user task 2026-11-06).
- `view` is the website's view when the message is sent: `window` `[x0, y0, x1, y1]` in drawing units, `attention`
  (the area the user marked for the assistant with the frame button, or null), `mode` (`simple` / `pro`), `px` (the
  canvas size). The agent's message then starts with a `[View: ...]` line and, with an area, an `[Attention area: ...]`
  line listing the objects in it (counts by type, layer and block; up to 60 handles).
- While the run lasts, the agent's `dwg_look` and `dwg_show` reach the page through the same stream as `ui` events
  (table below): `look` asks for a picture of the view or of a window (the page answers with `POST
  /sessions/{id}/ui/{request}`: a JPEG data URL, the window it shows and its size; the tool waits up to 20 s);
  `show` selects objects (`handles`, `select`) and/or fits the view to `window` (`zoom`). The page shows objects
  the agent has just made once its version comes back.

**Selection.**
- `selection` holds the objects the user has selected on the website: the object clicked in 3D or in Properties, or the rows checked in the Objects tab. It accepts up to 500 hex handles.
- The server looks them up and starts the agent's message with a `[Selection: ...]` line, which gives each object's handle, type, layer and size. So "this wall" (in any language) resolves to these handles. With nothing selected, the line says so.
- The user message in `messages` keeps `selection` (the handles found).
- An invalid selection returns 400.

**Events.** Each event is a line `data: {...}`:

| `type` | Fields | Meaning |
|---|---|---|
| `status` | `text` | progress note |
| `tool` | `id`, `name`, `input` | the agent called a `dwg_*` tool |
| `tool_result` | `id`, `name`, `is_error`, `summary` | result of that call |
| `text` | `text` | assistant text |
| `done` | `text`, `cost_usd`, `duration_ms`, `turns` | the run finished |
| `error` | `message` | the run failed |
| `ui` | `action` (`look`: `id`, `window?`; `show`: `handles`, `select`, `window`, `zoom`) | the agent looks at the page or shows objects there |

**Rules.**
- Edits made by the agent are normal versions: they appear in History and can be undone.
- Only one run per session at a time: a second request returns 409.
- History is stored in `meta.json`, with each tool step and its summary.

**Backend.** Selected with the `AICAD_AGENT` environment variable (`server/agent.py`):

| Value | Backend | Notes |
|---|---|---|
| `cli` (default) | local Claude Code (`claude -p`) connected to `/mcp` | Uses the machine's Claude login. Built-in tools are off, only the `dwg_*` tools in `agent.AGENT_TOOLS` are allowed (no `dwg_open`/`dwg_export`), no settings, CLAUDE.md or MCP servers are loaded from the machine. Options: `AICAD_CLAUDE`, `AICAD_AGENT_MODEL` (default `sonnet`), `AICAD_AGENT_EFFORT` (default `medium`). |
| `api` | Claude API with the same tools, run in-process | Planned. The swap-in steps are in `ClaudeApiBackend`. The events and storage stay the same. |

## MCP (for AI agents)

Endpoint: `http://127.0.0.1:8080/mcp` (Streamable HTTP, POST only). It runs in the same server as the REST API, so an agent's edits show up on the website and in its history.

**Protocol support.**
- Revision `2026-07-28`, stateless: `server/discover`, per-request `_meta`, and the headers `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`, which are checked against the body.
- Older revisions `2025-11-25`, `2025-06-18`, `2025-03-26`, `2024-11-05`, through the `initialize` handshake. No protocol sessions are created.

**Connect.**
- **Claude Code:** `claude mcp add --transport http aicad http://127.0.0.1:8080/mcp`
- **stdio clients** (for example Claude Desktop): run the bridge `python server/mcp_stdio.py`, which forwards to the HTTP endpoint. Config:
  ```json
  {"mcpServers": {"aicad": {"command": "python", "args": ["C:\\Personal\\projects\\ai-cad-software\\ai-cad\\server\\mcp_stdio.py"]}}}
  ```

The aicad server must be running for either one.

**Tools.** `dwg_open` returns a `session_id`; every other tool takes it.

| Tool | Does |
|---|---|
| `dwg_open` | open a local .dwg / .dxf path (only read), a sample, or an empty drawing (`new_units`) |
| `dwg_sessions`, `dwg_summary`, `dwg_layers` | list sessions, drawing summary, layers with every property |
| `dwg_autofix` | fix the drawing by its standard: element blocks, dimensions and texts to their layers, wall gaps of a few mm joined (dry_run first) |
| `dwg_analyze` | how the drawing is made: elements by layer, walls, blocks, the standard followed, and a schema for the AI (read before editing a drawing made elsewhere) |
| `dwg_materials`, `dwg_styles`, `dwg_db` | materials, styles, low-level database explorer |
| `dwg_material_library`, `dwg_material_create`, `dwg_material_update` | CC0 texture library; create or change render materials (library textures only). A material shown on more than one object type is refused until `confirm_shared: true` |
| `dwg_set_aca_material` | give selected ACA objects (e.g. only the walls, or one wall) their own material; if the style is shared with unselected objects it is refused until `only_selected: true` (own style copy) or `confirm_style_wide: true`. `dwg_set_props` refuses `material` on ACA objects, because ACA ignores it |
| `dwg_query`, `dwg_count`, `dwg_get` | find objects (selector incl. `bbox`), count by any fields, properties of one object |
| `dwg_set_layer`, `dwg_set_props`, `dwg_delete`, `dwg_transform`, `dwg_copy` | edit selected objects (an empty selector needs `confirm_all: true`) |
| `dwg_attach` | hang the selected objects on a host (`host`), or `detach: true`: they move, copy and delete with it ([Attached objects](#attached-objects)) |
| `dwg_plan_material` | without `name`: the drawing's and the built-in [materials](#materials); with `name`: give it to `select` and to the walls through `wall_at` (from the drawing, the library, or made from `pattern` / `color`; `notes`); `name: null` removes it |
| `dwg_set_property` | one property of the selected objects, as the Properties palette (`objects/prop-set`): length, radius, vertex, text justification, block scale... |
| `dwg_layer_create`, `dwg_layer_update`, `dwg_layers_update`, `dwg_layer_current`, `dwg_layers_rename`, `dwg_layers_merge`, `dwg_layer_delete` | layers: every property, bulk, current, rename by map or regex rules, merge, delete with `move_to` |
| `dwg_text_list`, `dwg_text_replace` | texts (plain and stored), replace with regex / whole word, MTEXT formatting kept |
| `dwg_attributes_list`, `dwg_attr_set` | block attributes; values and expressions (`inc`, `seq:`, `date:` ...) |
| `dwg_draw`, `dwg_edit_object`, `dwg_explode`, `dwg_offset`, `dwg_trim`, `dwg_extend`, `dwg_fillet`, `dwg_chamfer` | draw plain objects; change one object's geometry (also ACA walls and openings); modify commands |
| `dwg_slab_create`, `dwg_roof_create`, `dwg_roofslab_create` | ACA slabs (floors inside walls), roofs (hip, gable, any outline) and roof slabs |
| `dwg_wall_create`, `dwg_door_create`, `dwg_window_create` | new ACA walls (a line or a room through points), doors and windows in them or free-standing |
| `dwg_blocks`, `dwg_block_rename`, `dwg_block_insert`, `dwg_block_replace` | block definitions and references |
| `dwg_furniture_library`, `dwg_furniture_place` | the furniture catalog (the website's library) and placing its pieces: against the nearest wall by default, on the furniture / fixture layer, all in one version |
| `dwg_measure`, `dwg_areas` | lengths, areas, counts per group; rooms with their labels; `csv_path` writes a CSV file |
| `dwg_purge`, `dwg_overkill`, `dwg_audit` | cleanup like AutoCAD's PURGE / OVERKILL / AUDIT |
| `dwg_batch`, `dwg_diff` | several edits as one version; what changed between versions |
| `dwg_history`, `dwg_undo`, `dwg_redo` | versions. During a website assistant turn, undo/redo of a version made before the user's message is refused unless `user_asked: true` |
| `dwg_export` | save the current version to a local .dwg (any version) or .dxf path (no overwrite unless asked; `test.dwg` is protected) |
| `dwg_view` | links to the website and the 3D page |
| `dwg_look`, `dwg_show` | the website assistant only, while the user waits for its answer: a picture of what the user sees (the view, the marked area or a window; MCP image content); select objects on the user's screen and zoom to them, or move the view. Elsewhere they report that no website is connected |

Every edit tool takes `dry_run: true` (report only) and, where objects are selected, `force: true` (also objects on
locked layers).

**Results and errors.**
- Results come as `structuredContent` plus the same JSON as text.
- Tool errors (bad arguments, unknown handle, nothing to undo) are results with `isError: true`, so the model can correct itself.
- Protocol errors are JSON-RPC errors: unknown tool `-32602`, unknown method `-32601`/404, unsupported version `-32022`/400, header mismatch `-32020`/400.

## Worker protocol (internal)

The server runs `core/target/release/aicad.exe`, one process per session (methods: header of `core/src/bin/aicad/main.rs`). It exchanges JSON lines over stdin/stdout:
- request: `{"id", "method", "params"}`;
- reply: `{"id", "result"}` or `{"id", "error": {code, message}}`.

The methods match the endpoints: `open`, `save`, `summary`, `layers`, `query`, `count`, `set_layer`, `set_props`, `delete`, `layer_create`, `layer_update`, `layer_delete`, `text_replace`, `attr_set`, the material methods `materials`, `material_usage`, `material_create`, `material_update`, `aca_material_set`, and `characteristics`. The full list is in the header of `core/src/bin/aicad/main.rs`.
