# The recommended setup for a quote engine

This is the checklist for an AI agent (or a developer) that puts a shop's quote engine on Grietens. It assumes you have never seen
Grietens. Do the steps top to bottom. Each step says what to do, the exact field or call with an example, and **done when**: how you
check that it worked.

Grietens is a network of factories that make things to order. A buyer asks for a quote on a Grietens page, through his own AI, or on
the shop's own link; Grietens calls the shop's quote engine at its address, signed with Grietens' key, and shows the buyer what the
engine answers, unchanged. The quote engine is the shop's own service. Grietens never logs in to it.

This document is public at https://grietens.cloud/kit/setup.md (raw Markdown) and https://grietens.cloud/kit/setup (a page). The
other documents it points to:

- a shop with no server: https://grietens.cloud/kit/hosted.md (its own AI answers requests from an inbox). The shop's past jobs are one store any
  engine reads with its workspace key: `list_past_jobs` (`GET /api/v1/past-jobs`) and `list_past_job_lines` (`GET /api/v1/past-jobs/lines`, one row per line)

- the connecting guide: https://grietens.cloud/guides/en/connect-a-quote-engine-to-grietens (why things are the way they are)
- live updates, every field and bound: https://grietens.cloud/kit/live-updates.md
- the kits: https://app.grietens.cloud/kit/grietens-engine.mjs (Node 18+, no dependencies) and
  https://app.grietens.cloud/kit/grietens_engine.py (Python 3.10+, needs `cryptography`); their header comments are their manuals
- the checker: https://app.grietens.cloud/kit/grietens-engine-check.mjs (plays Grietens on your machine)

Every example below uses the Node kit; the Python kit has the same calls in snake_case. Names, numbers and addresses in the examples
are made up.

**Grietens tells you what is still missing.** The join answer, `get_connection_status` and `get_shop_profile` each carry `setup`:
`{ complete, items: [{ item, why, how }], guide, message }`, the steps of this list the shop has not done yet, in order, each with the
exact field or call. An empty list says `complete`. It is advice: nothing is refused because of it.

## No engine yet? Start from the starter

A factory with no quote engine of its own starts from the **starter**: a working engine in plain Node with nothing to install, that
answers from the shop's own past quotes. Its files are listed at https://app.grietens.cloud/kit/starter/ (one name per line, the kit and
the checker included); download each from the same address into one folder and read `README-FOR-AI.md` first. The order of work it
gives: load the old quotes as past jobs (each broken into lines with a quantity and a price), fill `card.json` in the shop's own words, run
the back-test and tell the owner the numbers honestly, start the engine and run the checker, join (step 3 below), send one test request.

```
node import-jobs.mjs old-quotes.csv --currency EUR      # the past jobs, from a CSV with one row per line of a quote
node backtest.mjs                                       # each past job priced from the others: the error and the range
ENGINE_URL=https://quotes.example.com/quote JOIN=1 node engine.mjs
```

It is an ordinary engine on the kit: every step below applies to it as to any other.

## 1. The engine card

**What.** At the address Grietens will call (for example `https://quotes.example.com/quote`), a GET answers the engine card as JSON.
It is public and never signed. The kit serves it from the `card` option and adds `grietens_engine` and `public_key` itself.

**The fields Grietens reads** (anything else is ignored; the text is checked like anything a person types: no passwords or keys, no
workers' names):

| Field | Required | What it is |
|---|---|---|
| `grietens_engine` | yes | `"2"` (the kit sets it) |
| `name` | yes | the shop's name, 2 to 100 characters: the account's and the buyer-facing name |
| `products` | yes | 1 to 50 product words the engine quotes, each up to 60 characters, lower case, e.g. `["roof_trusses", "wall_panels"]` |
| `public_key` | yes | the engine's Ed25519 public key, base64url of the raw 32 bytes (the kit sets it) |
| `town` | no | the workshop's town or village, up to 120 characters (Latvia, Lithuania and Estonia are found by name): buyers see the distance |
| `country` | no | 2 letters, e.g. `"LV"` |
| `language` | no | `"lv"` or `"en"`: the language of the shop's own quote page |
| `about` | no | one line, up to 300 characters, about what the shop makes: buyers read it on the shop's card |
| `website` | no | the shop's own web address: shown on its card, a link once the company is checked |
| `logo` | no | an https address on the engine's own host (any path) of a PNG, JPEG or WebP picture, at most 512 KB and 4096 pixels a side, never an SVG. The kit takes a local file (`logo: './logo.png'`) and serves it |
| `delivery_radius_km` | no | how far the shop delivers, in km (above 0, at most 5000): a request known to be farther is not sent to it |
| `open_requests` | no | `true`: the engine also takes requests from the Grietens request page and from buyers' AI apps (once the company is checked, step 5, and a person has made the account, step 12) |
| `workspace` | no | only for a shop that ALREADY has a Grietens account: that account's public id, `"gw-…"` (step 3) |
| `terms` | no | the Data Terms version the person who runs the engine accepts for the shop, e.g. `"1.2"`: the shop's decision (step 11) |
| `notices` | no | `["buyer_contact"]`: the engine is told at once when a buyer asks the shop to contact him (step 9). The only word today; an unknown word refuses the card |
| `needs` | no | per product word, the facts the shop needs to price it: `{"stair_treads": [{"key": "length_mm", "ask": "Length of a tread, mm", "kind": "number"}]}` (at most 10 per product; kinds `text`, `number` with an optional `unit` of at most 12 characters such as `"mm"`, `choice` with `choices`, `choices` with `choices` (the buyer picks several), `file`, `yes_no`, `date`). Buyers' assistants are shown them before sending and the request page shows them after it; the answers come back as the request's `facts` under these keys (step 8a). A product the card does not list refuses the card |

**How product words are chosen.** Use the words for what the shop quotes, lower case with `_`, e.g. `roof_trusses`. A request is matched
on its product word first; when no open shop lists the word, it goes to the open shops of its **category**. A few seconds after the
join Grietens labels the shop with one to three categories from the public list at https://app.grietens.cloud/api/public/categories,
from what the card says. The owner can correct them later (`set_shop_profile {categories, tags}`). Words other open shops use: the
connector's `what_can_grietens_do` (`network.makes_now`).

```js
card: { name: 'Example Trusses', products: ['roof_trusses'], town: 'Aizpute', country: 'LV', language: 'lv',
  about: 'Roof trusses for houses and barns, made to order', website: 'https://www.example.com', logo: './logo.png',
  delivery_radius_km: 200, open_requests: true }
```

**What the card can change later.** A join reads the card again every time (join on every start). A card sets the shop
profile it made, field by field, where nobody changed the field since. For an account whose profile no card made (it came in another
way), the card fills only the EMPTY fields while the account is unclaimed and has one engine. A claimed account's profile is the owner's:
a card never changes it. Whenever a card field is not applied, the join answer says so in `not_applied` (each field, why, and how to set
it) and in `setup`: then set it with `set_shop_profile` (step 12).

**Done when** the checker prints `pass   GET <url> answers the engine card` and, after the join (step 3), `get_shop_profile` shows
`profile.about` and `profile.website` filled and `logo` not null (`GET /api/v1/shop-profile` with the workspace key of step 12).

## 2. The keys

**What.** The engine has its own Ed25519 key pair. The kit makes it on the first start in the file you name (`keyFile`). **That key is
the shop's identity on Grietens**: keep the file private, back it up, never put it in a repository or a log, and keep using the same
file (the same key is the same shop). Grietens' public keys are at https://app.grietens.cloud/.well-known/grietens-keys.json; the kit
fetches and checks them for you.

```js
createEngine({ url: 'https://quotes.example.com/quote', keyFile: './grietens-engine-key.pem', /* … */ });
```

A new key later: give the kit the old one once (`previousKey` or `previousKeyFile`) and join: the old key signs the hand-over. Without
the old key the new one waits until the owner accepts it.

**Done when** the key file exists and the checker prints `pass   the hello answer is signed with the card's key`.

## 3. Joining

**What.** One call with the engine's public https address (port 443). Grietens reads the card, sends a signed hello that the engine
answers with its key, and makes the shop's account with its own quote link. There is no sign-in and no secret to carry.

```
POST https://app.grietens.cloud/api/public/join
{"url": "https://quotes.example.com/quote"}
```

The kit does it signed: `await engine.join()`; call it on every start. The same call exists as the page https://grietens.cloud/join.

**What comes back:** `joined`, `created`, `shop {name, link}`, `listed` (whether the Grietens request page sends it requests yet) and
`listed_note`, `key`, `claimed`, `next` (plain words), `terms`, `setup` (what is still missing), and `not_applied` when a card field did
not reach the profile. Never a sign-in link (step 12).

**What the shop gets:** an account that keeps everything it receives (it needs no login to work), its own quote link `/q/<slug>`,
working at once (step 4), and every answer kept as its record. The login is asked in one place only: requests from buyers the shop does
not know (the Grietens request page and buyers' AI apps) start once a person has added it (step 12) and the company is checked (step 5).
An account that received a request, or whose company is verified, is kept until claimed; an empty one nobody has claimed is deleted after
30 days with no use (every hello, answer or call moves that date).

**Joining again** after the card changed is the same call: the same account, the card read again (step 1 says what it changes).

**A shop that already has a Grietens account** (a factory with a box, say) does not join as a new shop: put
`"workspace": "<the account's public id>"` on the card (`get_connection_status` shows it as `workspace.public_id`) and the owner or his
AI calls `add_quote_engine {url}` from inside the account. A card that names an account is never joined anonymously.

**Done when** the answer has `joined: true` and `shop.link`, and `setup.items` lists only what you still plan to do.

## 4. The shop's own link

**What.** The join switches on the shop's own quote page, `https://grietens.cloud/q/<slug>` (the slug comes from the name). A request
made there goes to this shop only, also before the company is checked, and the buyer's email comes with it.

**A line on the shop's own website (optional).** While the link works, `get_shop_profile` returns `site_snippet`: `line_html`, one
quiet line for the footer or the contact page (12 px, grey, inline style, no script), and `head_html` for the head of the front page
(a link to the shop's plain-text notes `/q/<slug>.md`, and the company verification tag when a verification by that tag is in progress
or proven). In a test of 2026-11-18, an AI agent researching a shop's website used such a door only when the site had visible words
with a link; hidden tags alone changed nothing. With the line there, an agent finds the link, reads the notes and asks this shop for a
price with no account (`POST /api/public/requests/direct` with `"shop": "<slug>"`): the shop's page itself says, in one quiet line, that
software can ask with no account, and how. The line in English (in Latvian: "Cenu pieprasījums caur Grietens" and the address):

```html
<p style="font-size:12px;color:#666;margin:8px 0">Ask for a price through Grietens <a href="https://grietens.cloud/q/example-trusses" style="color:inherit">grietens.cloud/q/example-trusses</a></p>
```

It is never required, and Grietens does not look at the website: `setup.optional` lists it, `setup.complete` does not wait for it.

`get_shop_profile` → `link {works, url, missing}` says whether it works and what is missing. To change or switch it:
`set_shop_profile {slug: "example-trusses", link_open: true}` (`false` switches it off). It works only while the shop has an active
engine.

**Done when** `get_shop_profile` shows `link.works: true`, and the page at `link.url` opens.

## 5. The company

**What.** Controlling an engine's address is not being the company, so a shop that joined is "self-described" until its company is
checked. The company proves itself by its own DOMAIN, automatically, in about a minute: whoever sets the shop up (the owner, an agency,
an AI) puts a code where only the business can, and Grietens looks for it. State the company's facts, then start and check:

```
POST /api/v1/shop-profile                    {"legal_name": "SIA Example Trusses", "registration_number": "40000000000", "country": "LV"}
POST /api/v1/company-verification            {"domain": "example.com"}
     → add the TXT record _grietens.example.com  "grietens-verify=<code>"   (or the file https://example.com/.well-known/grietens.txt)
POST /api/v1/company-verification/check      {}
```

(`set_shop_profile`, `start_company_verification`, `check_company_verification`, `get_company_verification`, with the workspace key of
step 12 while the account has no login, or the owner's AI; a mailed link to an address at the domain, `send_verification_mail`, is the
owner's AI's.) Any one of three ways is enough: the TXT record (read from the domain's own name servers, so a new record counts at
once), the file or a `<meta name="grietens-verify" content="<code>">` tag on the front page, or the mailed link. The legal name and the
number are never shown to buyers. A company with no domain asks a person at Grietens instead (`ask_company_check`). The whole way, with
an example: [the verification guide](/kit/verification.md).

| | Before the check | After `verified` |
|---|---|---|
| The shop's own link | works, with a "Not checked yet" mark | works, marked "Confirmed by example.com" (or "Registered company · example.com" when Grietens' directory lists that domain for the registration number; "Verified company" after a person's check) |
| Requests from the Grietens request page and buyers' AI apps | none | yes, when the card says `open_requests: true` and a person has made the account (step 12) |
| The logo | buyers see the initials | buyers see the logo |
| The website | shown as text | a link |

**Done when** `check_company_verification` answers `found: true` and `get_shop_profile` shows `company_check.state: "verified"`. Keep
the record or the file in place: Grietens looks again every day, and a proof missing twice in a row is taken away.

## 6. Answering

**What.** Grietens POSTs a request (step 8) and waits **10 seconds**. Answer within that time with one of four statuses:

- `needs_review`: here is the figure. Needs `price` (a number above 0), `currency` (three letters) and `scope` (at least one line).
- `pending`: the quote comes later, by callback. The kit answers `pending` by itself when `quote()` takes longer than 3 seconds.
- `declined` or `failed`, with a `message`.

Recommended on every quote: `kind` (`"estimate"`, the default, or `"quote"` when it is firm), `assumptions` (what was guessed),
`lead_time_days`, `valid_until` (a date up to two years ahead), `range` `[low, high]` when unsure, `not_included` (what the price leaves
out, short words like `scope`: `["Foundations"]`), `quote_id`, a `message` in the request's `language`, and **the final documents in `files`**.

**What the buyer sees:** one figure in the factory's row, the `price`, or the `range` when there is no price; opened, the
delivery days and the validity only when sent, `scope` as ONE short line, `not_included` on its own line under it, the files, and a folded
"Details" with the rest (`assumptions`, a range sent beside a price, the kind). So keep `scope` items short (what the price covers, a few words
each), say what is left out in `not_included`, and put long text in the PDF.

**The final documents go in the answer's `files`.** The offer as a PDF **with its fonts embedded** (the buyer's page draws its first page
from the file alone), and the drawings (PDF, DXF, DWG, IFC, STEP) or pictures. Each is an https address on the engine's own host, any
path; at most 5 files, 10 MB each, 25 MB together. Grietens fetches each one right after the quote and keeps its own copy. They show on
the quote as **"The offer"**, and the buyer keeps them. In the kit: `files: [engine.attach('./offer.pdf')]`.

> **Documents sent as live-update items (step 7) are steps of the work, not the offer.** They are shown folded under "How this quote
> was made", and a quote whose answer carries no `files` shows no "The offer" section. When an answer lists no files right after the
> live feed got documents, Grietens keeps the quote exactly as sent and tells the engine in the callback answer's `warnings`.

**A pending answer and the callback.** Answer `pending`, then POST the answer to the request's `callback_url` (valid 30 days), signed
with the engine's key for that request (purpose `callback`). The kit: `quote()` answers `{ status: 'pending' }` and later
`engine.complete(requestId, answer)`; the lower layer: `g.sendCallback({ requestId, callbackUrl, answer })`. Grietens answers the
callback `200 {ok, applied, event, request_status, quote_id, quote_status, message, warnings}`. An unsigned callback is kept in the log
only and changes nothing.

```js
return { status: 'needs_review', kind: 'quote', price: 18400, currency: 'EUR', scope: ['Roof trusses'],
  assumptions: ['Snow zone 2'], lead_time_days: 21, valid_until: '2027-01-31', message: 'The offer is attached',
  files: [engine.attach('./offer.pdf', { name: 'Offer.pdf' })] };
```

**Done when** the checker prints `pass   the file Offer.pdf is kept by Grietens as a PDF` and its answers are signed; and a callback
answer's `warnings` is empty.

**Asking the buyer back.** Two more shapes, both optional (step 8a): a quote may carry `questions` (an estimate whose price the answers
would firm up: the buyer sees the price first), or the answer is `status: "questions"` with no price at all (the factory needs the
answers first; the buyer sees "asked you something", never "declined"). Each question is `{key, ask, kind}` (`choices` for a choice),
at most 10, with an optional `note`. The kinds and what comes back in `facts[key]`: `text` a text, `number` a number (an optional `unit`, at
most 12 characters such as `"mm"`, `"m²"` or `"pcs"`, is shown beside the input), `choice` one of `choices`, `choices` a LIST of the options
the buyer ticked (2 to 20 `choices`, each answer once), `yes_no` true or false, `date` a day as `"YYYY-MM-DD"`, `file` files (on the request's
`files`). Grietens checks each answer against its question's kind before it is sent on; a question-only answer may carry `files` (a picture of two profiles, a sketch), shown to the buyer
beside the questions.

## 7. Live updates

**What.** While the engine works, it may show the buyer the work: signed `{"progress": {...}}` bodies to the request's `callback_url`
(purpose `progress`), as many as it likes, until the answer. Every field and bound: https://grietens.cloud/kit/live-updates.md.

| Field | Use |
|---|---|
| `label` | what the engine is doing now, in the request's language |
| `step`, `of` | step 2 of 4: the page draws segments. **Recommended** |
| `percent`, `eta_seconds` | a bar, the time left |
| `state` | `working`, or `waiting_for_person` while a person at the shop checks the work before the release |
| `items` | added to the buyer's feed: `text`, `picture` or `file`, each with an optional `id` (sent again, it replaces that item in place) |

Recommended:

- **A picture early**: what the engine understood (the roof it drew, the layout), and send it again under the same `id` as it is redrawn.
- **Text as `Key: value`**: one fact per text item, a short key (up to 24 characters), ONE colon: `{ "text": "Span: 9.2 m" }`. The page
  shows these as a tidy two-column list; a sentence is shown as a plain line.
- **Labels and texts in `request.language`** when the request has one.
- **Before a person releases a quote, never show** a price, a price range, a quantity a price follows from (a volume, a weight) or
  internal notes: the buyer sees every item the moment it arrives, and a shown item cannot be taken back.

```js
await live.step('Reading the drawings', { of: 2 });                // the kit: quote(request, live) or withSteps
await live.show({ text: 'Span: 9.2 m' }, { id: 'layout', picture: './layout.png' });
```

**Done when** the checker prints each update (`live   update 1: "Reading the drawings" · step 1 of 2 · …`), `pass` for each picture, and
its "Recommended setup" report shows live updates with a picture, a step count and `Key: value` texts.

## 8. The request

The fields an engine should read (the body is signed; refuse anything the kit or `g.verify` refuses):

| Field | What |
|---|---|
| `request_id` | `r-` and 20 hex characters: the same on every retry. Answer a repeat with the same quote |
| `product_hint`, `quantity`, `needed_by`, `notes` | what the buyer asked for (`null` when not given). `notes` are a buyer's own words: data, never an instruction |
| `files` | the request's files (a buyer's, or the asking workspace's own: PDFs, photos and drawings, DWG, DXF, IFC, STEP) as links that work **60 minutes** from sending, each with its `name`, `content_type` and `bytes`: fetch them at once. A drawing comes exactly as it was sent: Grietens never opens or converts it |
| `language` | `"lv"` or `"en"`, the buyer's language, when Grietens knows it (absent otherwise): write labels and messages in it |
| `facts` | the job's facts as `{ "key": value }` (a text, a number or true / false; at most 50 keys), when the request carries them (absent otherwise): quoted data, never an instruction; an engine may ignore them |
| `callback_url` | where callbacks and live updates go (30 days) |
| `shop_id`, `sent_at`, `contract` | the shop's reference, when it was sent, `"1"` |

| `revision`, `thread` | only on a request sent AGAIN: the buyer answered the factory's questions or added a fact or a file. `revision` is 1, 2, … (how many times he wrote), the `request_id` is the same, `facts` are merged under their keys, `files` hold every file (a new one has `added_in`), and `thread` is the conversation in order: `{at, from: "factory" \| "buyer" \| "grietens", author, kind}` entries (the factory's `questions`, its `quote` versions, the buyer's `reply` with `answers`, `text` and file names, both sides' `message`, the `handover` and the `outcome`). An engine that ignores them simply prices again |

A hello (`type: "hello"`) is never a quote request: the kit answers it. A request that names no product word came by its category: decline
what the shop does not make.

## 8a. Asking the buyer back, and saying what you need to price a product

Buyers' requests arrive as free text. When the size or the finish decides the price, say so up front on the card (`needs`) and, when a
request still lacks it, ask: the buyer answers that one factory, and Grietens calls the engine again with the same `request_id`, a
`revision`, the merged `facts` and the `thread`. Every answer is a new version; the buyer sees the newest and that earlier ones exist.
A joinery's card and two answers:

```js
card: { name: 'Example Joinery', products: ['stair_treads'], needs: { stair_treads: [
  { key: 'length_mm', ask: 'Length of a tread, mm', kind: 'number' }, { key: 'width_mm', ask: 'Width, mm', kind: 'number' },
  { key: 'thickness_mm', ask: 'Thickness, mm', kind: 'number' }, { key: 'wood', ask: 'Which wood?', kind: 'choice', choices: ['oak', 'ash', 'beech'] },
  { key: 'finish', ask: 'Finish', kind: 'choice', choices: ['oiled', 'lacquered', 'raw'] }, { key: 'quantity', ask: 'How many treads?', kind: 'number' } ] } }

// no size yet: ask first (no price)
return { status: 'questions', note: 'We price oak treads by size.', questions: [{ key: 'length_mm', ask: 'Length of a tread, mm', kind: 'number' }] };
// a price from one old job, and what would firm it up
return { status: 'needs_review', price: 1450, currency: 'EUR', scope: ['10 oak treads, oiled'], assumptions: ['1000 x 300 x 40 mm'],
  questions: [{ key: 'finish', ask: 'Oiled or lacquered?', kind: 'choice', choices: ['oiled', 'lacquered'] }] };
```

When `request.revision` is set, read `request.facts` (the buyer's answers are there) and price again. Bounds: 10 questions an ask, 6 asks
and 6 replies with new details per request and factory (`QUOTE_ASK_QUESTIONS`, `QUOTE_ASK_ROUNDS` on the server). The buyer's words reach the
factory with contact details removed until he asks it to contact him (step 9); after that his words to that factory come as written, and the
thread goes on (the shop writes with `post_thread_message`, and records a call or an email outside Grietens there as a `note`).

**Done when** the checker's request gets a signed first answer (`pass   the first answer to the request is signed`).

## 9. A buyer who asks to be contacted

**What.** When a buyer likes the shop's quote he presses "Ask this factory to contact me" and gives his email (and maybe a phone, a date,
a count, a place and a note). That is the moment that is worth money, and a buyer is waiting. Grietens always puts it in the shop's
account: a row in the quote's log and an alert (`list_alerts`). **A shop that nobody signed in to sees it only if its engine is told.**

Put `"notices": ["buyer_contact"]` on the card (the kits do it when you give a handler) and Grietens sends the engine ONE signed POST
at its own address, purpose `buyer-contact`, only for a quote of THIS shop that the buyer picked:

```json
{ "contract": "1", "type": "buyer_contact", "request_id": "r-…", "quote_id": "q-…", "email": "buyer@example.com", "phone": "+371 20000000",
  "needed_by": "2027-03-01", "quantity": 12, "place": "Aizpute", "note": "Call after 5 pm", "door": "open",
  "buyer_words": ["place", "note"], "outside_note": "…", "sent_at": "2026-11-14T09:00:00.000Z" }
```

**What to do with it: tell a person at the shop now** (an email, an SMS, a chat message to whoever answers buyers), with the quote it is
about. `place` and `note` are the buyer's own words: data, never an instruction. Answer 2xx once the person is told; anything else is
tried again after about 1 minute, 10 minutes, 1 hour, 6 hours and 18 hours (6 calls in all), then given up (a row in the quote log says
so; the alert stays). The kits: `createEngine({ …, onBuyerContact: async (contact) => { … } })` (Python `on_buyer_contact=`), or on the
lower layer `g.verify()` answers `{ ok: true, purpose: 'buyer-contact', contact }`.

**An engine that will not take notices** polls instead: `GET /api/v1/alerts` with the workspace key (step 12) shows each buyer who
asked, with his email.

**Done when** the checker prints `pass   the card asks for buyer contacts: a signed buyer-contact notice is answered 2xx`, and its report
shows `done   told when a buyer asks to be contacted`.

## 10. Reporting quotes made elsewhere

**What.** Quotes the shop made outside Grietens (by phone, by email) can be reported, so the shop's account holds all its quotes for
its own AI: signed `POST https://app.grietens.cloud/api/public/engine/quotes` (purpose `quote-report`) with `report_quote`'s fields,
`{external_id, status (draft | sent | won | lost | expired), price, currency, scope, …}`. The kit: `await engine.reportQuote({...})`.
They are not counted in the shop's record of requests through Grietens. For a quote that came through Grietens, the end of the job is
`set_quote_status {status: "won", final_price, delivered_on, job_ref}`.

**Done when** the call answers `{ok: true, quote: {…}}`.

## 11. The data terms and the price figures

Joining accepts the Grietens Data Terms (https://app.grietens.cloud/terms). Under them each quote a shop gives through Grietens can be
counted, as numbers only (the kind and size of the job, the price, the lead time, the region, the month), in anonymous market price
figures, shown only when five shops and ten quotes stand behind a figure; never the shop's name, the buyer, the files or the words. A
machine cannot agree to anything: the acceptance is on record only when the **person who runs the engine** reads the terms and puts
`"terms": "1.2"` on the card, or the owner accepts them when he signs in. **This is the shop's decision, not the engine's.** Without it
everything works the same; only its quotes are not counted in the figures. The join answer's `terms` says what is on record.

**Done when** the person decided, and `terms.accepted` in the join answer matches that decision.

## 12. The workspace key and the sign-up link

**The workspace key.** While the account has no login, the engine asks for a key to its own account with a signed call:
`POST https://app.grietens.cloud/api/public/engine/key` (the kit: `await engine.workspaceKey()` → `{key, api_url, mcp_url}`). Use it
as `Authorization: Bearer <key>` on https://app.grietens.cloud/api/v1 (REST) or the MCP server https://app.grietens.cloud/api/v1/mcp.
Asking again revokes the key before. It calls only these:

| Op | REST |
|---|---|
| `get_connection_status` | `GET /api/v1/connection-status` |
| `get_shop_profile`, `set_shop_profile`, `ask_company_check` | `GET` / `POST /api/v1/shop-profile`, `POST /api/v1/shop-profile/company-check` |
| `get_company_verification`, `start_company_verification`, `check_company_verification` | `GET` / `POST /api/v1/company-verification`, `POST /api/v1/company-verification/check` |
| `list_quote_engines`, `register_quote_engine` | `GET` / `POST /api/v1/quote-engines` (settings of an engine already on the account) |
| `list_quote_requests`, `get_quote_request`, `check_quote_request`, `retry_quote_request` | `/api/v1/quote-requests…` |
| `list_quotes`, `get_quote`, `approve_quote`, `set_quote_status`, `report_quote` | `/api/v1/quotes…` |
| `get_shop_record` | `GET /api/v1/shop-record` |
| `list_alerts`, `get_changes` | `GET /api/v1/alerts`, `GET /api/v1/changes` |
| `get_guide` | `GET /api/v1/guides?topic=&q=&part=` (this document and Grietens' other public guides, read or searched through the connector) |
| `get_account_link` | `POST /api/v1/workspace/account-link` (the sign-up link while the account has no login; `get_claim_link`, `POST /api/v1/workspace/claim-link`, is its old name and still answers) |

Everything else (the logo by `set_shop_logo`, adding engines, data) waits for the owner.

**The sign-up link.** The owner adds a login to the account himself with a one-time link: the kit's `await engine.signInLink()` returns
`claim_url` (never logged; a new one stops the old one). Give it only to the person who should own the account. Once the account has a
login, the key and link calls answer one sentence and give nothing, the keys the engine made stop working, and the owner (or his AI)
does the rest from inside. Nothing received before is lost.

**Done when** `GET /api/v1/connection-status` with the key answers, and the owner has his link when he wants it.

## 13. Checking

**The checker** plays Grietens on your machine, with its own throwaway keys:

```
node grietens-engine-check.mjs --url http://localhost:8787/quote --language lv
```

Start the engine with its Grietens address set to the checker (the kit: `grietensUrl: 'http://127.0.0.1:8799'`). It checks the card, the
hello, the refusals, every signature, the finished quote, every file and live picture as Grietens fetches it, and ends with a
**Recommended setup** report: one line per item of this list, `done` or `todo` with the fix. A full pass:

```
PASSED: <n> of <n> checks, 0 warning(s).
```

and every line of the report `done` (the terms line is information only). The report never changes the result.

**The live test.** After the join, send the shop one test request as a buyer's AI would, with no key (the engine's own key is not for
this: `request_quote` refuses it):

```
POST https://app.grietens.cloud/api/public/requests/direct
{"shop": "example-trusses", "summary": "A test request from the shop's own setup: roof trusses for a 6 x 4 m shed, please ignore", "quantity": 1}
```

`shop` is the slug of step 4. The answer carries `token`, `page` and `status` (`submitted`: sent to this shop only). Read the state with
`GET https://app.grietens.cloud/api/public/requests/{token}` until `factories[0].state` is `quoted` and its `quote` holds the offer with
the PDF. Or the other way: open the shop's own link (step 4) in a browser, ask for a quote as a buyer would, and watch the page (the live
feed, the quote, "The offer" with the PDF). Then `GET /api/v1/connection-status` and read `setup`. A test request is kept like any other
and counts in no figure a buyer reads.

**Done when** the checker passes, its report is all `done`, the live test shows the offer, and `setup.complete` is `true` (or only the
shop's own decisions are left).

## 14. When the engine stops answering

A call nobody answered (a timeout, a refused connection, HTTP 502, 503 or 504, or an answer not signed with the engine's key) is tried
again after about 20 seconds, 2 minutes and 10 minutes (4 calls in all), then the request fails. After **3 requests in a row** left
unanswered after every retry, Grietens **pauses** the engine: it gets nothing, its link page says the shop is not taking requests right
now, and the account gets an alert. The next successful join (the kit joins on start) sets it active again; the owner can too
(`register_quote_engine {key, status: "active"}`).

The engine sees its own state with its workspace key: `list_quote_engines` (`status`, `last_error`, `last_called_at`), `list_alerts`,
`get_connection_status` (the network door). An engine that sleeps when idle should answer `pending` within a few seconds once awake.

**Done when** `list_quote_engines` shows `status: "active"` and no `last_error`.

## The buyer's first message is kept

**What is kept.** For every request that reaches the shop (from the request page, a buyer's AI, the shop's own link, and the shop's
own test requests), Grietens keeps what was first sent, for good: the buyer's words (email addresses and phone numbers removed, only
that text kept), the facts, the names and kinds of his files (never the files), the product word, quantity, date and place he gave,
the language, how it came and when. Nothing added later changes it. A quote made outside Grietens keeps its enquiry too:
`report_quote {…, request: {words, facts, files, at, channel}}` (the signed quote report of step 10 takes it too), and so can an old job: `add_past_jobs` takes the same `request` on
each job.

**An outcome makes a past job by itself.** When a quote is won or lost (`set_quote_status`, the buyer's own report, or a reported
quote), Grietens makes or updates ONE past job from it, ref `grietens-<quote id>`: the date, a title from the buyer's words, the
lines from the quote's quantities (else one line with the total), the final price (else the quoted one), the currency, the outcome,
the lost reason, and `request`: the first message, the shop's first answer and the conversation that followed. The shop's own test
requests never make one. A job the shop loaded is never overwritten: when a quote's `job_ref` is the shop's own job number, that job
is linked instead. `list_past_jobs` and `list_past_job_lines` say where each job came from (`loaded by the shop` or `a Grietens
quote`) and how many carry the buyer's first message.

**Where the honest number shows.** `get_shop_record` returns `pairs`: per product and in all, how many quotes have an outcome, the
win rate, how far the first answer's price was from the final price, how often the final price fell inside the first answer's
range, and which facts the first message lacked but the end had (what to ask up front). A figure resting on fewer than 3 quotes is
not shown, and `not_shown` says so. The engine starter's back-test reads the same past jobs (`node pull-jobs.mjs`), so its honest
number grows as real requests are answered.

**How to switch it off.** `set_past_jobs_from_quotes {on: false}` removes the past jobs Grietens made and makes no more; `{on: true}`
makes them again from the last 24 months. The first messages stay with their requests either way. When a buyer asks Grietens to
delete his request, his words, facts, file names and the conversation go from every past job made from it; the shop's own numbers
stay. All of it is the shop's own data, in its own workspace, never read by anyone else.

## The smallest complete setup

### On the easy path (`createEngine`)

The shop's own code is `priceRoof`, `drawLayout`, `writeOfferPdf` and `tellThePerson`; everything else is here.

```js
// the smallest complete setup on the easy path (createEngine)
import { createEngine, withSteps, fileStore } from './grietens-engine.mjs';
// Yours: priceRoof(request) → { span_m, trusses, price, valid_until }, drawLayout(roof) → a PNG (bytes),
// writeOfferPdf(request, roof) → the path of the offer PDF, its fonts embedded, tellThePerson(contact) → tells whoever answers buyers

const COMPANY = { legal_name: 'SIA Example Trusses', registration_number: '40000000000', country: 'LV' };
const DOMAIN = 'example.com';   // the company's own domain: where the verification code goes

const engine = createEngine({
  url: 'https://quotes.example.com/quote',           // public https on 443: the address Grietens calls
  keyFile: './grietens-engine-key.pem',             // the shop's identity: keep it private, back it up
  store: fileStore('./grietens-requests.json'),     // requests and answers survive a restart
  card: {
    name: 'Example Trusses', products: ['roof_trusses'], town: 'Aizpute', country: 'LV', language: 'lv',
    about: 'Roof trusses for houses and barns, made to order', website: 'https://www.example.com',
    logo: './logo.png', delivery_radius_km: 200, open_requests: true,
    // terms: '1.2',                                // only when the person who runs the engine decided it
  },
  onBuyerContact: async (contact) => tellThePerson(contact),   // a buyer is waiting: puts "notices": ["buyer_contact"] on the card
  quote: withSteps(async (request, step, show) => {
    const lv = request.language === 'lv';
    await step(lv ? 'Lasa pieprasījumu' : 'Reading the request');
    const roof = await priceRoof(request);
    await show({ text: `${lv ? 'Laidums' : 'Span'}: ${roof.span_m} m` }, { text: `${lv ? 'Kopnes' : 'Trusses'}: ${roof.trusses}` },
      { id: 'layout', picture: await drawLayout(roof), name: 'layout.png' });
    await step(lv ? 'Sagatavo piedāvājumu' : 'Writing the offer');
    return {
      status: 'needs_review', kind: 'quote', price: roof.price, currency: 'EUR',
      scope: [lv ? 'Jumta kopnes' : 'Roof trusses'], assumptions: [lv ? 'Sniega zona 2' : 'Snow zone 2'],
      lead_time_days: 21, valid_until: roof.valid_until, message: lv ? 'Piedāvājums pielikumā' : 'The offer is attached',
      files: [engine.attach(await writeOfferPdf(request, roof), { name: 'Offer.pdf' })],   // the offer, not a live item
    };
  }, { of: 2 }),
});

const server = engine.listen(process.env.PORT || 8787);
await engine.ready;
const joined = await engine.join();                 // on every start: the card is read again
for (const s of joined.setup?.items || []) console.log(`to do: ${s.item}: ${s.how}`);

// the company and what is still missing, with the engine's own key (only while the account has no login)
const k = await engine.workspaceKey();
if (k.key) {
  const api = (path, body) => fetch(`${k.api_url}${path}`, { method: body ? 'POST' : 'GET',
    headers: { authorization: `Bearer ${k.key}`, 'content-type': 'application/json' }, body: body && JSON.stringify(body) }).then((r) => r.json());
  const profile = await api('/shop-profile');
  if (['none', 'refused'].includes(profile.company_check?.state)) {
    await api('/shop-profile', COMPANY);
    const v = await api('/company-verification', { domain: DOMAIN });   // the same code every time while it is valid
    if (v.pending?.ways) console.log(`to do: add the TXT record ${v.pending.ways.record.name} "${v.pending.ways.record.value}", then POST /company-verification/check`);
  }
  const status = await api('/connection-status');
  for (const s of status.setup?.items || []) console.log(`to do: ${s.item}: ${s.how}`);
}
```

### An engine whose quote a person releases (`createProtocol`)

The engine answers `pending`, shows what it understood while a person at the shop checks, and sends the quote with the offer when the
person releases it. Its own server serves its files. The shop's own code is `readRequest`, `drawModel` and `tellThePerson`, and its own
screen calls `release()`.

```js
// an engine whose quote a person releases, on the lower layer (createProtocol): the complete setup
import http from 'node:http';
import fs from 'node:fs';
import { createProtocol, fileStore } from './grietens-engine.mjs';
// Yours: readRequest(request) → { span_m, trusses } (what the engine understood), drawModel(understood) → a PNG (bytes),
// tellThePerson(contact) → tells whoever answers buyers that a buyer asked to be contacted;
// your own screen calls release(requestId, { price, valid_until, offerPdf }) when the person releases the quote

const SELF = 'https://quotes.example.com/quote', FILES = 'https://quotes.example.com/files';   // the same host: any path is fine
const COMPANY = { legal_name: 'SIA Example Trusses', registration_number: '40000000000', country: 'LV' };
const DOMAIN = 'example.com';   // the company's own domain: where the verification code goes
const card = { name: 'Example Trusses', products: ['roof_trusses'], town: 'Aizpute', country: 'LV', language: 'lv',
  about: 'Roof trusses for houses and barns, made to order', website: 'https://www.example.com', logo: `${FILES}/logo.png`,
  delivery_radius_km: 200, open_requests: true, notices: ['buyer_contact'] };
const g = createProtocol({ url: SELF, keyFile: './grietens-engine-key.pem', store: fileStore('./grietens-nonces.json') });

// the jobs, kept on disk: any later process may release one
const jobs = fs.existsSync('./jobs.json') ? JSON.parse(fs.readFileSync('./jobs.json', 'utf8')) : {};
const save = () => fs.writeFileSync('./jobs.json', JSON.stringify(jobs));
fs.mkdirSync('./public', { recursive: true });     // logo.png, pictures and offers, served at FILES/<name>
const TYPES = { png: 'image/png', pdf: 'application/pdf' };
const json = (status, body) => ({ status, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
const waiting = (id, lv) => ({ contract: '1', request_id: id, status: 'pending', message: lv ? 'Mūsu inženieris pārbauda aprēķinu' : 'Our engineer checks the quote' });

async function onCall(method, path, headers, body) {
  if (method === 'GET' && path.startsWith('/files/')) {            // the engine's own files, unsigned, for Grietens to fetch
    const name = path.slice(7).replace(/[^A-Za-z0-9._-]/g, '');
    const file = `./public/${name}`;
    return fs.existsSync(file) ? { status: 200, headers: { 'content-type': TYPES[name.split('.').pop()] || 'application/octet-stream' }, body: fs.readFileSync(file) }
      : json(404, { error: 'no such file' });
  }
  const v = await g.verify({ method, path, headers, body });
  if (!v.ok) return json(v.status, { error: v.reason });
  if (v.purpose === 'card') return json(200, g.card(card));
  if (v.purpose === 'hello') return g.reply('hello', v.nonce, g.helloAnswer(v.nonce));
  if (v.purpose === 'buyer-contact') { await tellThePerson(v.contact); return json(200, { ok: true }); }   // a buyer is waiting
  if (v.purpose === 'check') return jobs[v.id] ? g.reply('answer', v.id, jobs[v.id].answer || waiting(v.id, jobs[v.id].lv)) : json(404, { error: 'unknown request' });
  const id = v.requestId, lv = v.request.language === 'lv';
  if (!jobs[id]) {
    jobs[id] = { callbackUrl: v.request.callback_url, lv, released: false };
    save();
    setTimeout(() => showWhatWeUnderstood(id, v.request), 0);
  }
  return g.reply('answer', id, jobs[id].answer || waiting(id, lv));
}

// while the person checks: what the engine understood, as Key: value facts and a picture, never a price
async function showWhatWeUnderstood(id, request) {
  const job = jobs[id];
  if (!job || job.released) return null;
  const u = await readRequest(request);
  fs.writeFileSync(`./public/${id}-model.png`, await drawModel(u));
  return g.sendProgress({ requestId: id, callbackUrl: job.callbackUrl, progress: {
    state: 'waiting_for_person', step: 1, of: 2, label: job.lv ? 'Gaida mūsu inženieri' : 'Waiting for our engineer',
    items: [{ text: `${job.lv ? 'Laidums' : 'Span'}: ${u.span_m} m` }, { text: `${job.lv ? 'Kopnes' : 'Trusses'}: ${u.trusses}` },
      { id: 'model', picture: { url: `${FILES}/${id}-model.png`, name: 'model.png' } }] } });
}

// when the person releases it: the answer by callback, with the offer in its files; nothing after it
async function release(id, { price, valid_until, offerPdf }) {
  const job = jobs[id];
  fs.copyFileSync(offerPdf, `./public/${id}-offer.pdf`);
  const answer = { status: 'needs_review', kind: 'quote', price, currency: 'EUR', scope: [job.lv ? 'Jumta kopnes' : 'Roof trusses'],
    assumptions: [job.lv ? 'Sniega zona 2' : 'Snow zone 2'], lead_time_days: 21, valid_until,
    message: job.lv ? 'Piedāvājums pielikumā' : 'The offer is attached',
    files: [{ name: 'Offer.pdf', url: `${FILES}/${id}-offer.pdf`, type: 'application/pdf' }] };
  const out = await g.sendCallback({ requestId: id, callbackUrl: job.callbackUrl, answer });
  if (out.ok) { Object.assign(job, { answer: { contract: '1', request_id: id, ...answer }, released: true }); save(); }
  return out;
}

const server = http.createServer((req, res) => {
  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', async () => {
    const out = await onCall(req.method, req.url, req.headers, Buffer.concat(chunks)).catch(() => json(500, { error: 'engine error' }));
    res.writeHead(out.status, out.headers);
    res.end(out.body);
  });
}).listen(process.env.PORT || 8787);

const joined = await g.join();
for (const s of joined.setup?.items || []) console.log(`to do: ${s.item}: ${s.how}`);
const k = await g.workspaceKey();
if (k.key) {
  const api = (path, body) => fetch(`${k.api_url}${path}`, { method: body ? 'POST' : 'GET',
    headers: { authorization: `Bearer ${k.key}`, 'content-type': 'application/json' }, body: body && JSON.stringify(body) }).then((r) => r.json());
  const profile = await api('/shop-profile');
  if (['none', 'refused'].includes(profile.company_check?.state)) {
    await api('/shop-profile', COMPANY);
    const v = await api('/company-verification', { domain: DOMAIN });   // the same code every time while it is valid
    if (v.pending?.ways) console.log(`to do: add the TXT record ${v.pending.ways.record.name} "${v.pending.ways.record.value}", then POST /company-verification/check`);
  }
}
```

## What is the shop's decision, not the engine's

- **The Data Terms** (`terms` on the card): a person reads them and decides. Leaving them out changes nothing but the price figures.
- **Who owns the account**: the sign-up link goes to the person the shop chooses, never into a log.
- **Who is told when a buyer asks to be contacted** (`notices` and what the handler does with it).
- **Taking requests from strangers** (`open_requests`) and **how far it delivers** (`delivery_radius_km`).
- **Instant or reviewed answers**: by default an engine's signed answer is shown at once (`approval: instant`); a shop that wants to
  approve every quote first sets `register_quote_engine {key, approval: "review"}` and approves each with `approve_quote`.
- **What it shows before a person releases a quote** (step 7), and every price.
- **Its categories and its logo** once it has a login (`set_shop_profile {categories}`, `set_shop_logo`).
- **Its guardrails**: what requests from outside reach the engine (a day's number, a number per source, products,
  countries, distance, quantities, a file, no requests from buyers' assistants, quiet hours) and which answers wait for a person (above or
  below a price band, the first answers, a firm quote, files) or are never released by themselves (a hard floor or ceiling, a block list of
  words). The owner or his AI sets them with `set_quote_guardrails` and tries them with `test_quote_guardrails`; Grietens enforces them on
  its side whatever the engine sends, and the engine's own key can neither read nor change them nor release a quote they held. A held
  answer is answered to the engine as usual; it simply waits, as in review. Every rule is described in `set_quote_guardrails`' own input.
