# AMS — full reference for coding agents
AMS builds an agentic webpage for each visitor: an agent composes your own React components (blocks) on a canvas, from your data sources. Human docs: https://docs.40rty.ai. Packages: `@40rty/ams-sdk` (headless: provider, canvas, block declarations, hooks), `@40rty/ams-ui` (optional shell and components), `@40rty/ams-cli` (command `forty`). `Spacefront*` and `--fourty-*` identifiers are API names.
## Two modes (the words to use)
- **Conversational UI** (the default): every question opens its own page — the visitor's words, the answer as a headline, then blocks drawn with the store's cards. Shell: `ShellScaffold` + `ConversationCanvas` + `PageComposer` from `@40rty/ams-ui/conversation`; `forty create` starts here.
- **Classic** (only on request): the store's own page, reshaped by the agent, with the chat side panel beside it.
- **Island** is the floating prompt box, used in both modes — a component, never a mode.
- Either way the shell owns the scroller: `ShellScaffold scrollRef={useScrollContainerRef()}`. The page around a hosted shell does not scroll, so a `min-h-screen` shell that expects the document to scroll cannot scroll at all.
## Agentic build contract (read first)
The agentic webpage is NEVER a route in the customer's app. It is a separate
deployment of the same codebase built with `FORTY_AGENTIC=1`: `/` renders the
agentic page; every other route (products, collections, cart, checkout) stays the
app's own. Without the flag the app builds exactly as before. Supported
frameworks: Shopify Hydrogen and Next.js (App Router).
Hydrogen:
- `app/forty/route.tsx` — `loader` returns `{token: context.env.FORTY_DEV_TOKEN}`; `links` returns the shell stylesheets; default export renders `` inside the app layout.
- `app/forty/routes.ts` — `agenticRoutes(routes)`: with `FORTY_AGENTIC=1`, every root index route (`_index`, `($locale)._index`) gets `file: 'forty/route.tsx'`; otherwise unchanged.
- `app/routes.ts` — `export default hydrogenRoutes(agenticRoutes([...(await flatRoutes())])) satisfies RouteConfig;`
- Set `PUBLIC_CHECKOUT_DOMAIN` (Hydrogen's consent API needs it; without it messages are dropped).
- Add `@40rty/ams-sdk` to `optimizeDeps.include` in `vite.config.ts`.
- CSP in `app/entry.server.tsx`: add the API origin to `defaultSrc` and `connectSrc` (https and wss) — NOT `scriptSrc`, which replaces Hydrogen's defaults and the app never hydrates.
- With pnpm, allow `esbuild` and `workerd` in `"pnpm": {"onlyBuiltDependencies": [...]}`.
- Store env: `npx shopify hydrogen link && npx shopify hydrogen env pull`.
Next.js:
- `app/forty/page.tsx` — Server Component: ``.
- `app/forty/AgenticPage.tsx` — `'use client'`, mounts ``.
- `next.config` — `rewrites: async () => process.env.FORTY_AGENTIC === '1' ? { beforeFiles: [{ source: '/', destination: '/forty' }] } : []` (merge with existing rewrites).
- Wrap store components that read the URL (variant pickers, galleries) in ``.
Both: `app/forty/catalog.ts`, `app/forty/catalogs/*.md`, `app/forty/components.tsx`, `app/forty/Shell.tsx`, `forty.config.json`.
Deployment: managed — `forty deploy` serves the agentic build at `.40rty.app/`.
Self-hosted — deploy the agentic build as a second environment (e.g.
`ask.example.com`) and `forty origin add `. Local preview and `forty doctor`:
run the dev server with `FORTY_AGENTIC=1`.
No app: a component package (`forty create `), published with `forty publish`
and served by AMS. Entry exports `catalog`, `renderers` (one per block plus
`agentText` and `turn`) and optionally `shells`. Components import only React,
`@40rty/ams-sdk` and optionally `@40rty/ams-ui`.
## Blocks
A block is one thing the agent can put on the canvas:
| Half | What | Where |
|---|---|---|
| Declaration | type name, props schema, examples, usage manifest — read by the agent | `app/forty/catalog.ts` + `app/forty/catalogs/.md`; sent to AMS as data on publish |
| Component | the React component that draws it, behind a thin adapter | `app/forty/components.tsx`; never leaves the repository (self-hosted) |
Blocks are the components the agent may use, not the entities it searches.
### Which blocks to offer
| Tier | Type | Why | Props |
|---|---|---|---|
| Required | `productGrid` | Any "show me…" | `title`, `products` (1–12) |
| Required | `collectionList` | "What do you sell?" | `title`, `collections` (2–4) |
| Required | `agentText` | The agent's words on the canvas | `text` — render with `renderInline(text, keyPrefix)` |
| Required | `turn` | One exchange: the ask and what was composed | `prompt`, `children` |
| Next | `comparisonTable` | "A or B?" | `products` (2–4), `verdict`, `highlightedProductId`, `attributeRows` |
| Next | `productDetail` | "Which one should I get?" | `product`, `reason` |
| Useful | `faq` | Shipping, returns, sizing | `title`, `items` |
| Useful | `collectionHero` | Opener for a broad ask | `collection`, `heading`, `cta` |
| With data | `reviews`, `bundle`, `sizeGuide`, `giftFinder` | Needs a reviews app, bundles or size data | — |
On Shopify `productGrid` and `collectionList` are required by these exact names.
### Declare
```ts app/forty/catalog.ts
import { z, resolved, ProductSchema, CollectionSchema, type HostComponents } from '@40rty/ams-sdk';
export const catalog: HostComponents['catalog'] = {
productGrid: {
type: 'productGrid',
propsSchema: z.object({
title: z.string().describe('section heading'),
products: resolved(ProductSchema, 'product', { min: 1, max: 12 }).describe('the products to show'),
}),
examples: [{ title: 'Featured', products: ['gid://shopify/Product/', 'gid://shopify/Product/'] }],
},
comparisonTable: {
type: 'comparisonTable',
propsSchema: z.object({
products: resolved(ProductSchema, 'product', { min: 2, max: 4 }).describe('the distinct products to compare'),
verdict: z.string().optional().describe('one-line call: the pick and the deciding reason'),
highlightedProductId: z.string().optional().describe('the pick — one of `products`'),
attributeRows: z.array(z.object({
id: z.string(), label: z.string(),
values: z.record(z.union([z.string(), z.number(), z.boolean()])).describe('a value for every product'),
winner: z.string().optional(),
})).optional().describe('judgment rows; price and stock come from the products'),
}),
examples: [{ products: ['gid://shopify/Product/', 'gid://shopify/Product/'] }],
},
};
```
- Import `z` from `@40rty/ams-sdk`, never from `zod` — the engine reads schemas with the SDK's copy.
- Key and `type` must match.
- Every `.describe()` is read by the agent — write it for a person.
- `resolved(Schema, hydrator, { min, max })`: the prop holds entity IDs; the named hydrator resolves them. `max: 1` makes it a single record, not a list.
- `examples`: a filled-in instance with placeholder IDs.
Manifest, one per block:
```md app/forty/catalogs/collectionHero.md
# collectionHero
A full-width banner over one collection's image, with a headline — use to open a fresh conversation or spotlight one collection.
## Don't Use When
The visitor asked a specific question — answer it with `productGrid`.
```
Lead each manifest with ONE sentence that says what the block shows and when to use
it; put detail below.
### Render
Keep the app's own components; add one adapter per block mapping agent props to
them. `/forty:setup` writes these.
```tsx app/forty/components.tsx
function ProductGrid({ title, products = [] }) {
return (
{title && {title}
}
{products.filter(isLoaded).map((p) => )}
);
}
export const fortyComponents = {
catalog,
renderers: { productGrid: ProductGrid, collectionList: CollectionList, agentText: AgentText, turn: Turn },
};
```
- A `resolved()` prop arrives first as IDs, then as full records once hydrated: render what has loaded, skip the rest.
- One mapper function per entity (product, collection) from the SDK shape (`id`, `title`, `handle`, `images`, `variants` with prices and options) to your component's props. Tolerate missing fields (no images, variants without `selectedOptions`).
- Add-to-cart goes through the app's own cart. If its product card has none, keep it that way in `productGrid`; put add-to-cart in `comparisonTable` / `productDetail`.
- Every block needs a renderer, plus `agentText` and `turn`.
- A session keeps the blocks it opened with — reload after `forty dev` / `forty publish` to see a new type.
Hooks for blocks: `useProductCard(product)` (image, price, click, quick-add),
`useCart()` (`addLine`/`updateLine`/`removeLine`; managed packages only —
self-hosted keeps its cart), `useCanvasActions()` (`navigate`/`ask`/`dispatchAction` from a click),
`useCommerceActions()` / `useContentActions()` (product, collection, article, newsletter verbs),
`useHydrationState()`.
## Data and hydrators
A space's data sources are what the agent searches; `forty connect shopify` attaches a
Shopify store. The agent sends only IDs (`gid://shopify/Product/123`), so it never
invents a price or title. In the page, a hydrator resolves each ID from the source.
Shopify hydrators are built in: `product`, `collection`, `article`, `page`, `policy`.
Other sources need a connector in AMS — contact 40rty.
## forty.config.json
Written by `forty init`; every command reads it.
| Field | |
|---|---|
| `apiUrl` | AMS API endpoint (written by `forty init`; don't edit) |
| `spaceSlug` | The space |
| `sourceId` | Package id for releases |
| `label` | Space display name |
| `catalog` | Module exporting `catalog` (e.g. `app/forty/catalog.ts`, package: `src/catalog.ts`) |
| `manifests` | Folder of `.md` manifests |
| `bundle` | Package only: `{ "entry": "src/index.ts", "css": "dist/package.css" }` |
Each `forty publish` (and each save under `forty dev`) sends: the catalog as JSON
(types, props, descriptions, examples — no code), every manifest, the
`package.json` version as the release label, and for a package only, the built
components and stylesheet.
## AMS UI
`npm install @40rty/ams-ui lucide-react`. Theme with six variables:
```css
:root {
--fourty-surface: #fff;
--fourty-fg: #000;
--fourty-accent: #ff0; /* hover, selected, chips */
--fourty-accent-fg: #000;
--fourty-radius: 16px;
--fourty-font-family: 'Your Font', sans-serif;
}
```
Drop-in shell components (each needs its stylesheet; they resist host global CSS
such as `form button { width: 100% }`). They coordinate: on desktop the island steps
aside while the panel is open; on a phone the island carries the conversation;
presence sits atop the open panel, else above the island.
```tsx app/forty/Shell.tsx
```
`SpacefrontIsland` (`@40rty/ams-ui/island` + `island.css`):
`placeholder`, `emptyText`, `workingText`, `pillLabel` (`'Ask'`),
`container` (`'viewport'` | `'column'`), `stopKeyPropagation` (`true`).
Tokens: `--fourty-island-offset-bottom` (clear fixed bottom bars),
`--fourty-island-inset-left` / `-right` (centre over a column). Give the canvas
bottom padding equal to the island's height.
`SpacefrontThreadPanel` (`@40rty/ams-ui/thread-panel` + `thread-panel.css`):
`title` (`'Assistant'`), `placeholder`, `emptyText`, `workingText`, `tabLabel`
(`'Ask'`), `width` (`400`), `autoOpen` (`true`; stays closed once closed),
`storageKey` (`'fourty-thread-panel'`; `null` to forget), `stopKeyPropagation`.
Sets `--fourty-thread-panel-inset` on `` while open on desktop — pad the
canvas by it. Escape closes. Tokens: `--fourty-panel-offset-top`, `-offset-bottom`,
`-inset-right`, `-z-index`.
`SpacefrontPresence` (`@40rty/ams-ui/presence` + `presence.css`):
`thinkingText`, `factsLabel`, `confirmLabel`, `placement` (`'auto'` | `'inline'`).
Renders nothing when there is nothing to show.
Building blocks in `@40rty/ams-ui/shell` (styled by AMS UI's stylesheet; best for
packages): `Composer`, `ComposerChipStrip`, `InlineCompletion`,
`AnimatedPlaceholder`, `TypedPlaceholder`; `AttachButton`, `AttachmentStrip`,
`ClearSessionButton`, `ConversationHistoryButton`, `ShareCanvasButton`;
`VoiceControl`, `VoiceIsland`, `DictationButton`, `ListeningWaveform`; `SideDock`,
`LauncherDock`, `BottomSheet`, `DragSheet`; `ShellScaffold`, `DefaultMobileShell`,
`ConversationTransition`, `ChromeSurface`; `ShellMenuChrome`, `MenuNavBar`,
`MenuDrawer`, `MenuTrigger`, `MenuFlyout`; `Button`, `Spinner`, `Skeleton`.
Custom shell from SDK hooks: `useFourtySession()` (`sendMessage`, running, suggestions,
errors), `useComposerDraft()`, `useThreadRows()`, `useComposerChipSelect()`,
`useAgentPresence()`, `usePresenceNotch()`, `useConsumeStandingSignal(type)`,
`useGoHome()`, `useCart()`.
The agent's closing question arrives apart from its prose. By default the
engine writes it as the prose's last line, so a shell needs no code for it. To
draw it yourself, export `turnAsk: 'shell'` from the package and render
`useTurnAsk()` (`{ kind, parts }`, each `{ answer }` part a reply) after the prose:
`` from `@40rty/ams-ui/shell`, or your own design over
`turnAskSegments(ask)` and `useTurnAskReply()`. Only the answers are buttons.
`` (from `@40rty/ams-sdk`) answers
every hook from a scripted `scene` (`turns`, `pending`, `error`, `suggestions`,
`scan`, `facts`, `voice`, `question`) with no network; `onSend` receives each
message, chip and reply. Use for design review, visual tests, Storybook.
## Shopify
- Search uses Shopify's global catalog by shop id. Development, unpublished and password-protected stores and `mock.shop` return nothing; products must be on the Shop channel.
- `forty connect shopify` reads `PUBLIC_STORE_DOMAIN` / `PUBLIC_STOREFRONT_API_TOKEN` (or `SHOPIFY_STORE_DOMAIN` / `SHOPIFY_STOREFRONT_ACCESS_TOKEN`) from `.env`; `--domain`, `--storefront-access-token` win. The platform verifies the token, finds the store's market and its Global shop id (a store Global does not index searches its own catalog), adopts the store's name for an auto-named space; the CLI then runs one real agent search and warns loudly on zero results.
- `forty connect shopify-catalog [--market-country US] [--currency USD] [--saved-catalog ]` binds no store: every store on Shopify, through Shop, optionally through a Dev Dashboard saved catalog.
- No app: the SDK's cart hooks drive the Shopify cart.
## CLI
Install `npm install -D @40rty/ams-cli`; run `npx forty ` from the repo
root. Before install use `npx --package @40rty/ams-cli forty` — the unscoped `forty`
npm package is unrelated. There is no `--help`: unknown flags are ignored, so
`forty publish --help` publishes. Without a TTY the CLI never prompts; a missing
answer fails naming the flag.
- `forty create ` — new conversational UI package from the starter (`my-store` → `@my-store/spacefront`): the conversation-page shell with a working scroller, the store's blocks plus the conversation blocks, `src/brand.ts` and `prompts/composition.md`; dir must be empty. Writes no config; the first `forty dev` does.
- `forty login` — browser sign-in; stores an org API key in `~/.config/forty/credentials.json` (revocable in the console).
- `forty whoami` — the organization, its spaces, and `staff: yes|no`. A 40rty organization's spaces are 40rty demos: build them in the `40RTY-ai/brands` repo and release by merging, never from a laptop.
- `forty init [--space | --create ] [--source <@org/name>] [--self-hosted | --package]` — writes `forty.config.json`; detects app vs package from `package.json`; refuses if config exists. A new space starts locked to visitors.
- `forty dev [--once]` — runs init if needed; stores a draft on every save; prints `https://.40rty.app/?preview=` (package) or writes `FORTY_DEV_TOKEN` to `.env` (app). `--once` stores and exits.
- `forty publish [--keep-locked] [--origin ]` — new numbered release, made live. A space `forty init` created opens to visitors on its first release unless `--keep-locked`; a space locked in the console stays locked.
- `forty releases` / `forty rollback [n]` — list / make an earlier release live (default: previous).
- `forty connect --list` / `forty connect [-- ]...` — the connectors this deployment carries and the fields each takes / connect one (a field left out is read from `.env` by the names the connector declares). See Shopify.
- `forty origin add ` — registers a deployed origin (one space per origin). `localhost` needs none while a draft exists.
- `forty domain add ` / `forty domain` — serve the space on a custom domain and print DNS records / list domains and status.
- `forty doctor [url] [--ask "" | --no-ask]` — checks blocks, credential, space, store binding, `PUBLIC_CHECKOUT_DOMAIN` (Hydrogen), preview token, engine, agentic wiring and CSP; with a deployed URL also CORS. Then asks the space one question (`what do you sell?` by default) and passes when a composed block carries an entity. Non-zero exit on failure; each failure names its fix.
- `forty deploy [--env KEY]... [--detect]` — Hydrogen or Next.js only: builds a temporary copy with `FORTY_AGENTIC=1` and serves it on `.40rty.app` (and custom domains), every path. Deploys `SESSION_SECRET`, store domain/token, every `PUBLIC_` key and keys not named like secrets; `--env KEY` adds one; `FORTY_*` never deploys. `--detect` prints the app's own production target as JSON.
- `forty hosting self` — hands the space back to your hosting (register the origin first); `forty deploy` switches back.
- `forty feedback ""` (or pipe output in) — problem report with versions and the last failed command; secrets stripped.
Env: `FORTY_API_KEY` (org key, wins over login — CI), `FORTY_DEV_TOKEN` (preview credential; keep out of git).
## Troubleshooting (forty doctor)
| Check | Fix |
|---|---|
| signed in | `forty login` (CI: `FORTY_API_KEY`) |
| space belongs to this organization | `forty init --space ` or `--create ` |
| store has a storefront token / shop id | `forty connect shopify` (store domain + token in `.env`, or `--domain` / `--storefront-access-token`) |
| product search returns results | Use the live, published store |
| .env sets PUBLIC_CHECKOUT_DOMAIN | Set it to the checkout domain (or `*.myshopify.com`) |
| FORTY_DEV_TOKEN / a session opens | `forty dev --once`, restart the dev server |
| engine served for sdk X | `npm install @40rty/ams-sdk@latest` |
| CSP script-src lets the app run | Move the AMS origin from `scriptSrc` to `defaultSrc` |
| CSP allows the API (https / wss) | Add the origin to `defaultSrc` and `connectSrc` |
| api accepts calls from your origin | `forty origin add ` |
| agent answered with your components | Read the printed error; check manifests' first sentences and that every type has a renderer |
- Page renders but nothing works — the CSP `scriptSrc` trap.
- New block never appears — reload; sessions keep their opening blocks.
- Island send button full-width — host CSS styles bare `button`; use the AMS UI drop-ins.
- Visitors see nothing after publishing — the space is locked (`--keep-locked`, or locked in the console).