# agent-cms documentation # Introduction Source: https://agent-cms-docs.vercel.app/docs/introduction An add-on CMS that runs inside your Next.js app, edited by people and agents alike. agent-cms runs **inside your existing web app**: no separate server, no new database. People edit in admin screens you copy into the app; AI agents read and write the same documents through tools. Use it for anything a CMS is for: a blog, release notes, a help center, internal docs, a notice board. ## What you get - **Collections over one table set.** Every collection lives in the same `cms_*` tables, so adding one needs no migration. Each has typed `fields` (zod), categories, slugs and house-style checks. - **Versions.** Every save is a full snapshot. Drafts, publish, unpublish, archive, restore. A stale save is a conflict that carries the other person's copy, and the editor merges the two line by line. - **Agents as editors.** One tool list, three ways in: MCP, a CLI and REST, plus the same tools as functions for the agent in your own app. Agents change one section at a time, check a draft before saving, and people review what they changed block by block. - **Search built for answering.** Korean-aware, returns sections with citation ids such as `cms://docs/install#tables`. - **Admin screens you own.** Screens copied into your app with shadcn, built on your own parts. - **Safe defaults.** Every collection is `public` or `internal`; API keys are hashed, scoped and can expire; publishing, deletes and refusals go to an audit log. ## This site These pages are agent-cms documents. Organisation members edit them in the admin, agents edit them with an API key, and any agent can read them over MCP without a key. See [Read the docs with an agent](/agents). ## Next - [Install](/docs/install) the package. - Follow the [Quick start](/docs/quick-start) to get a collection, a route and the admin running. --- # Install Source: https://agent-cms-docs.vercel.app/docs/install Add the package, run init, and create the tables. ## Install the package ```sh npm i @mainsoft/agent-cms drizzle-orm zod npx @mainsoft/agent-cms init ``` Peer dependencies: `drizzle-orm`, `zod` (`^3.25` or `^4`), nothing else. The package never calls a model, so there is no model library to install. `init` writes `agent-cms.config.ts`, `lib/cms.ts`, the API route, a schema re-export and `.env.example` lines. It never overwrites a file. ### The full name, and other package managers Write the full name after `npx`. The scope is part of the command: `agent-cms` without `@mainsoft/` is another project's package on npm, so leaving it out stops with `could not determine executable to run` in any folder where this package is not installed (a monorepo root, an agent's shell, a new project). ```sh bunx @mainsoft/agent-cms init pnpm dlx @mainsoft/agent-cms init # or `pnpm exec agent-cms init` once it is installed yarn agent-cms init # after `yarn add @mainsoft/agent-cms drizzle-orm zod` ``` Two things to know: - **yarn 1** does not install peer dependencies by itself. Without `drizzle-orm` and `zod` the CLI stops and names the missing package. - **pnpm 11 and later** skip versions published in the last day by default (`minimumReleaseAge`), so on the day of a release `pnpm add` gives you the one before it. ## Create the tables Re-export the tables from your Drizzle schema so drizzle-kit sees them, or put the SQL in a migration: ```ts export { cmsDocuments, cmsVersions, cmsApiKeys, cmsHits, cmsMeta, cmsAudit } from "@mainsoft/agent-cms/tables"; ``` ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply npx @mainsoft/agent-cms doctor ``` `migrate check` prints what is missing as SQL and exits with 1 when the database is behind. `migrate apply` runs the idempotent DDL. `doctor` checks tables, columns, the schema version and broken rows. > [!note] > The CMS checks `cms_meta.schema_version` on its first call. When the database is behind, it answers `schema_outdated` (503) with the command to run. ## Other table names `cmsTables({ prefix: "blog_", schema: "content" })` gives a set with another prefix or Postgres schema. Pass it to `new DrizzleRepo(db, { tables })` and to `defineConfig({ tables })`. --- # Quick start Source: https://agent-cms-docs.vercel.app/docs/quick-start One collection, the API route and the admin screens in a Next.js app. ## 1. Define a collection ```ts import { createCms, defineCollection, DrizzleRepo } from "@mainsoft/agent-cms"; import { z } from "zod"; export const posts = defineCollection({ slug: "posts", label: "Blog", visibility: "public", categories: ["News", "Engineering"], fields: z.object({ tags: z.array(z.string()).default([]) }), url: (d) => `/blog/${d.slug}`, }); export const cms = createCms({ repo: new DrizzleRepo(db), collections: [posts] }); ``` ## 2. Mount the route Create `app/api/cms/[...path]/route.ts`: ```ts import { createCmsHandler } from "@mainsoft/agent-cms/http"; const handler = createCmsHandler({ cms, resolveUser }); export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE }; ``` `resolveUser(req)` returns your signed-in user as `{ kind: "user", id, label, isAdmin }`, or `null`. That one route serves REST under `/api/cms` and MCP at `/api/cms/mcp`. ## 3. Add the admin ```sh npx @mainsoft/agent-cms add cms-shell cms-doc-list cms-doc-editor cms-versions cms-keys cms-audit cms-command ``` Wrap the screens in `CmsProvider` and give each one a page. See [Admin screens](/docs/admin-screens). ## 4. Show a page ```ts const doc = await cms.get({ kind: "anonymous" }, "posts", slug); ``` Render `doc.body` with `parseMarkdown` (see [Rendering](/docs/rendering)). ## 5. Let an agent in Create an API key in the admin, then register `https://your-app/api/cms/mcp` in your coding agent with `Authorization: Bearer `. See [MCP](/docs/mcp). --- # Collections Source: https://agent-cms-docs.vercel.app/docs/collections Visibility, fields, categories, access rules and hooks. A collection is a kind of document: posts, guides, notices. All collections share the same tables, so adding one needs no migration. ## Options ```ts defineCollection({ slug: "posts", label: "Blog", visibility: "public", // required: "public" or "internal" categories: ["News", "Engineering"], versions: { max: 100, drafts: true }, // edits wait for publish search: { enabled: true }, fields: z.object({ cover: z.string().url().optional() }), admin: { fields: { cover: { label: "Cover image" } } }, url: (d) => `/blog/${d.slug}`, access: { write: ({ actor }) => actor.kind === "user" && actor.isAdmin }, }); ``` ## Visibility Every collection says whether it is `public` or `internal`. An `internal` collection must say who may read it (`access.read`); the CMS refuses to start otherwise, so nothing is public by accident. ## Fields `fields` is a zod object. The editor builds its form from it, and `cms.get` returns `fields` typed as the zod output. On `update`, `fields` is a JSON Merge Patch: keys you send replace, `null` removes, the rest stay. ## Access The default: anyone reads published documents of public collections; admins write and publish; API keys do what their scopes allow (`read`, `write`, `publish`, `admin`, optionally per collection). Override `read`, `write` and `publish` per collection. `managed: true` makes a collection writable only by your app code (the `system` actor). ## Hooks `afterChange` hooks and `cms.onChange` listeners get `{ contentChanged }` as a second argument: false when only a draft changed and the public copy is the same, so you can skip revalidating pages. `timeZone` on `createCms` (default `UTC`) decides which calendar day a usage count lands on. --- # Versions and drafts Source: https://agent-cms-docs.vercel.app/docs/versions-and-drafts Snapshots, publishing, restoring and comparing versions. Every save is a full snapshot with its author, note and changed fields. ## Drafts With `versions: { drafts: true }` (the default), saving a published document changes its working copy only. The public page keeps showing the published version until someone publishes. The list shows these documents as **Modified since publish**. With `drafts: false`, every save publishes (useful for release notes). ## Publish, unpublish, archive ```ts await cms.publish(actor, "posts", "hello"); await cms.unpublish(actor, "posts", "hello"); // back to draft await cms.archive(actor, "posts", "hello"); // hidden, kept ``` `republishedAt` records when a document goes public again. ## Restore and compare ```ts await cms.restore(actor, "posts", "hello", 3, { publish: true }); const diff = await cms.diff(actor, "posts", "hello", 3, 5); ``` The **Version history** screen shows the same: side by side or unified, with word highlights. ## Limits `versions.max` (default 100) keeps the newest N versions per document; the published version is always kept. --- # Editing together Source: https://agent-cms-docs.vercel.app/docs/editing-together Conflicts, merging, autosave, agent review, preview links and bulk actions. People and agents edit the same documents, so agent-cms never lets one save silently overwrite another. ## Conflicts A document GET sends `ETag: "v"`. Send it back as `If-Match` on PATCH or DELETE, or pass `expectedVersion`. When someone saved in between, the write fails with `conflict_version` (409) and carries the other copy as `current`. `requireIfMatch: true` on the handler refuses writes without a version (428). ## Merge `mergeDocs(base, mine, theirs)` from `@mainsoft/agent-cms/diff` (browser-safe) merges the body line by line and the other values field by field. Where both sides changed the same lines, you pick theirs, mine or both; "both" puts theirs first, then mine. The editor opens the **Merge** screen for this. ## Autosave The editor keeps unsaved edits with `PUT …/autosave` without creating versions, and offers to restore them. ## Agent changes Each body hunk that an API key or your assistant saved is a review item until a person accepts it or reverts it: ```ts const open = await cms.agentChanges(actor, "docs", "install"); await cms.reviewChanges(actor, "docs", "install", { hunks: "all" }); ``` In the editor every agent block has **Accept** and **Revert**, and the toolbar has **Accept all**. Reverts are saved as one version. ## Draft preview links With `previewSecret` (32+ characters) on `createCms`, sign a link to one exact version: ```ts const { url } = await cms.createPreviewLink(actor, "posts", "hello", { ttl: "24h" }); ``` Your public page reads it: ```ts const token = searchParams.cms_preview; const doc = token ? (await cms.readPreview(token)).doc : await cms.get(anon, "posts", slug); ``` Links cannot be revoked one by one; rotating `previewSecret` revokes all. ## Bulk actions ```ts await cms.bulk(actor, "posts", "publish", [{ slug: "a" }, { slug: "b" }]); ``` Actions: `publish`, `unpublish`, `archive`, `unarchive`, `delete`. Each document runs on its own and you get `{ slug, ok, error? }` for each. --- # Search Source: https://agent-cms-docs.vercel.app/docs/search Section-level search with citation ids, and search misses for your app. ## How it works The index is in memory and built from published documents. It understands Korean (particles, verb endings, 2-grams) and returns **sections**, each with a citation id such as `cms://docs/install#create-the-tables`. ```ts const { hits } = await cms.search(actor, "install tables", { collections: ["docs"] }); ``` Over REST: `GET /api/cms/search?q=…&collections=docs,guides`. ## Search misses When a search finds nothing, agent-cms can tell your app, which decides what to store: ```ts createCms({ onSearchMiss: async (e) => { // { query, normalized, collections, actor, source, at, nearest } if (e.actor.kind === "anonymous") return; await saveMiss(e); }, }); ``` It is called only when the caller asked (`search(…, { reportMiss: true })`, `GET /search?miss=1`, `read_for_answer`), never awaited, and its errors go to `onError`. `normalized` ignores particles and word order, so group by it. > [!tip] > This site keeps its misses in its own `site_search_misses` table and shows them on an admin screen added through `extraNav`. --- # Rendering Source: https://agent-cms-docs.vercel.app/docs/rendering Turn a document body into your own components. `@mainsoft/agent-cms/markdown` runs in the browser and on the server. `parseMarkdown` gives a small block tree; you render it with your own components. ```ts import { extractToc, parseMarkdown } from "@mainsoft/agent-cms/markdown"; const blocks = parseMarkdown(doc.body); const toc = extractToc(blocks); ``` ## Blocks - `heading` (levels 2 and 3) with a stable `id` for anchors - `p`, `list` (ordered or not), `hr` - `quote`, with an optional callout kind: `> [!tip]`, `> [!note]`, `> [!warning]` - `code` with its language - `links`: a row of `[[link:key|label]]` app links Inline parts are `text`, `strong`, `code`, `link` and app links. ## Example This site renders every page this way: headings get anchor links, callouts become the amber notes, and shell code blocks get npm, pnpm, yarn and bun tabs. --- # Media library Source: https://agent-cms-docs.vercel.app/docs/media-library Pictures, video and files in your own bucket. Uploads go straight from the browser to the storage. > [!note] > On npm from 0.10.0 (0.8.0 and 0.9.0 were not published on their own). Without `media` in `createCms` the feature is off and nothing changes. Documents can hold images, video and files. The files live in your own storage bucket; the CMS keeps a row per file and hands the browser a signed address, so uploads go straight to the storage and never through your app server (which is why a 5GB video works on a serverless host). Without `media` the feature is off and nothing changes. ## Set up ```ts import { s3Storage } from "@mainsoft/agent-cms/storage-s3"; const s3 = (bucket: string, publicUrl?: string) => s3Storage({ bucket, region: "auto", endpoint: process.env.S3_ENDPOINT, accessKeyId: process.env.S3_KEY!, secretAccessKey: process.env.S3_SECRET!, publicUrl }); export const cms = createCms({ // … media: { stores: { // The first store is the default. `public`: anyone with the address can read. public: { label: "Public", visibility: "public", adapter: s3("site-media", "https://media.example.com") }, // `private`: opened through the CMS after a permission check, with a link that works for 5 minutes. private: { label: "Private", visibility: "private", adapter: s3("site-private"), accept: ["application/pdf"], maxFileSize: 100 * 1024 ** 2 }, }, // accept: ["image/*", "video/*", ".pdf"], // what every store takes; default below // maxFileSize: 5 * 1024 ** 3, // default 5GB imageUrl: ({ url, width }) => `/_next/image?url=${encodeURIComponent(url)}&w=${width}&q=75`, }, }); ``` `s3Storage` works with AWS S3 (leave `endpoint` out, set `region`), Cloudflare R2 (`region: "auto"`, the account's S3 endpoint) and MinIO or any other S3-compatible server. It signs requests itself (`aws4fetch`), so there is no AWS SDK to install. Another kind of storage is a `StorageAdapter` (`./storage`). **Cloudflare R2**, checked against a real bucket on 2026-11-20 (the same contract test CI runs against an S3-compatible server): single and multipart uploads from a browser, signed links, copy, list and the CORS rule all work. Three things to know. Make the R2 key an **Object Read & Write** token limited to that bucket. A public store needs the bucket's public address as `publicUrl`: the `pub-….r2.dev` address or a custom domain (the S3 endpoint itself never serves files without a signature). And set the CORS rule in the dashboard (R2, the bucket, Settings, CORS policy) or with Cloudflare's API: your site's origin and the methods `GET`, `HEAD`, `PUT`. `storage check` tells you if it is missing. ## Vercel Blob From 0.11.0. Install `@vercel/blob` and give a store the Blob adapter: ```ts import { vercelBlobStorage } from "@mainsoft/agent-cms/storage-vercel-blob"; stores: { public: { visibility: "public", adapter: vercelBlobStorage({ token: process.env.BLOB_READ_WRITE_TOKEN!, access: "public" }) }, private: { visibility: "private", adapter: vercelBlobStorage({ token: process.env.BLOB_PRIVATE_READ_WRITE_TOKEN!, access: "private" }) }, } ``` `access` is how the Blob store was created. A private store is read through signed links only. `prefix` puts every key under one folder of the store. | | S3-compatible | Vercel Blob | |---|---|---| | Browser uploads straight to the storage | yes | yes | | Large files | 16MB parts, four at a time | one request per file | | A failed part is retried by itself | yes | not supported on this store: the file starts again | | Carry on after a reload | yes | not supported on this store | | CORS rule | yours to set | nothing to set | | Stored type | what the CMS signed | read from the extension by Blob | | File manager, share links, replace, image sizes | yes | yes | The signed address holds an upload to the size it declared. Share links last at most seven days. A 150MB file went up in one request when we measured; Vercel's own advice is to use parts above 100MB, which this adapter cannot do, so think about `maxFileSize` for the store. Checked against real public and private Blob stores with `@vercel/blob` 2.9.0 on 2026-11-20. ## CORS The bucket needs a CORS rule that lets your site `PUT` to it. Add `media` (the same object) to `agent-cms.config.ts` and run: ``` npx @mainsoft/agent-cms storage check --origin https://your-site.example ``` It uploads, reads, moves and deletes a test file in every store for real (also in parts, also with a browser-style signed address), tests the CORS rule, prints the rule to paste into the bucket, and lists what each store accepts. `npx @mainsoft/agent-cms storage cleanup` removes uploads that were started and never finished (`doctor` tells you when there are any). ## What may be uploaded What may be uploaded is yours to decide, at three levels: `media.accept` for the app, `stores..accept` for one store (replaces the app-wide list), and `admin.fields..accept` for one field (narrows its store's list). Entries are MIME types (`image/png`), groups (`image/*`) or extensions (`.pdf`); `["*/*"]` takes anything. Unset, the default (`DEFAULT_ACCEPT`) takes images, video, sound, PDF, office documents, plain text and ZIP; web pages and programs only when you list them. `maxFileSize` has the same three levels. The server checks the name and declared type when an upload starts, and the first bytes of what actually arrived when it ends: a web page named `photo.png` is deleted again (`asset_type_mismatch`). ## Your own check `media.scan` is called once for every file that arrives: when a browser upload completes, when a file is imported or stored by the server, and when a file that was already in the bucket gets registered. It is where a virus scanner or a content policy goes: ```ts media: { stores: { /* … */ }, scan: async ({ url, bytes, name, mime, size }) => { // `url`: a signed address that works for 10 minutes. `bytes` instead when the CMS holds the file in memory. const verdict = await myScanner.check(url ?? bytes); return verdict.clean ? true : { ok: false, reason: verdict.name }; }, }, ``` A refused file is deleted from the storage and never becomes usable (a registered one is left where it was); the caller gets `asset_rejected` and the audit log has the reason. A check that throws refuses the file too. ## In a document In a document a file is named by its id, so moving or renaming it never breaks a page: ```md ![The new dashboard](asset:8k2m4x9pq1zt/dashboard.png "Caption under the picture") Read [the full report](asset:r7w2k9m4x1pa/report-2026.pdf). ``` An image line of its own is a media block (a picture, a video player or a download card, by the file's type). `![alt](https://…)` shows an image from elsewhere. For a field, use the `image` or `file` widget; the value is the file's id: ```ts import { assetId } from "@mainsoft/agent-cms"; fields: z.object({ cover: assetId().optional(), brochure: assetId().optional() }), admin: { fields: { cover: { widget: "image" }, brochure: { widget: "file", accept: [".pdf"], maxFileSize: 20 * 1024 ** 2 } } }, media: { requireAlt: true }, // an image without alt text stops a save (default: a warning) ``` Saving checks the files a document names: one that does not exist or is the wrong kind for its field is an error; a missing alt text or a private file in a public document is a warning. ## On your page On your page, ask for the files a document uses and render the block tree as before: ```ts const doc = await cms.get(anon, "posts", slug); const files = await cms.assetsFor(doc); // { [id]: { url, width, height, alt, kind, mime, … } } const cover = files[doc.fields.cover]; {cover.alt} ``` `parseMarkdown` gives `{ t: "media", asset, alt, caption }` blocks; look the `asset` up in `files`. By default the CMS stores originals only, and resizing is your framework's or CDN's job, through `media.imageUrl`. ## Image sizes From 0.11.0, the CMS can make the sizes itself. It is an optional module: install `sharp` and name the sizes. Node runtime only; on the Edge runtime the app fails at start with the reason. ```ts import { sharpTransforms } from "@mainsoft/agent-cms/image-sharp"; media: { stores: { … }, transforms: sharpTransforms({ presets: { thumb: { width: 480 }, card: { width: 800, height: 450, fit: "cover" }, full: { width: 1600 } }, formats: ["webp"], // webp (default), avif, jpeg, png }), } ``` ```tsx {cover.alt} ``` - Only the sizes you name exist: `/api/cms/files//?size=card`. Another name answers 404 (`unknown_image_size`). - A size is made the first time it is asked for and kept in the same store under `_cms/derived/`. After that the route redirects to the stored copy. Copies are deleted with the original and when it is replaced. - Limits: 4096px on the long side, four at a time, ten seconds each, 40MB of input. Past a limit, or when sharp fails, the original is served. SVG and GIF are served as they are. Nothing is enlarged. - With the module on, pictures an agent imports or the CLI uploads get their list thumbnail from the server. **Focal point.** In a file's panel, "Focal point" lets an editor click the part of a picture that must stay in view; the arrow keys move it too. Sizes with `fit: "cover"` are cropped around it, and `assetsFor` returns it as `focal: { x, y }` (0 to 1). Agents set it with `update_asset`. There is no crop editor: the original is never changed. ## Who may do what Listing files and opening private ones: signed-in people and keys. Uploading, importing, alt text, tags, new folders: admins and keys with `write`. Moving, renaming and deleting: admins and keys with `publish`. A store's `access: { read, write, delete }` replaces any of the three. Deleting a file that documents use fails with `asset_in_use` and the list of documents until the caller confirms. Uploads, moves and deletes are in the audit log. The file route is `GET /api/cms/files//`: it checks permission and redirects to the public address or to a short-lived signed one (`media.linkTtlSeconds`, default 300). Set `media.filesUrl` when your handler is not mounted at `/api/cms`. ## In the admin In the admin, add the screen (`npx @mainsoft/agent-cms add cms-media`) and a page for it; the sidebar shows "Media" by itself when the app has a library: ```tsx // app/admin/media/page.tsx "use client"; import { CmsMedia } from "@/components/cms/cms-media"; export default function MediaPage() { return ; } ``` The browser sends files straight to the storage, four parts at a time for large ones, tries a failed part again three times, and "Try again" sends only what is still missing. It also makes a small picture of each image and video (480px, WebP) for the library, and reads width, height and length. "Import from URL" fetches a public https address into the open folder (addresses inside your network are refused, as for agents), and the pencil in a file's panel renames it; the extension stays, so the type cannot change. "Replace" puts new content at a file's address, and `media.stripMetadata` removes camera data from photos before they are sent. The [media library screen](/components/cms-media) has the details. `` lets an extension package put its own control next to a file's alt text field. ## Agents and the CLI Agents get six more tools when the app has a media library: `list_assets`, `get_asset` (read), `import_asset` (fetch an https address into the library; addresses inside your network are refused), `update_asset` (write), `move_asset` and `delete_asset` (publish). From a terminal: ``` npx @mainsoft/agent-cms upload ./hero.png ./talk.mp4 --folder launch --alt "The launch screen" --tag launch ``` ## The whole bucket The library shows the files the CMS knows. The [file manager](/docs/file-manager) shows a bucket as it is. --- # File manager Source: https://agent-cms-docs.vercel.app/docs/file-manager The storage bucket as it is, folder by folder. Move, share and delete files, also ones nobody uploaded through the CMS. > [!note] > On npm from 0.10.0. The [media library](/docs/media-library) shows the files the CMS knows. The file manager (`npx @mainsoft/agent-cms add cms-files`, a page with ``) shows a bucket as it is, folder by folder: files another program put there appear too. The sidebar shows "Files" to whoever may look around a store (by default whoever may read it; a store's `access.browse` narrows that). ## Files the CMS did not know - A file the CMS did not know gets a row when someone opens it, tags it, shares it or an agent registers it. From then on it works in documents like any other file. `npx @mainsoft/agent-cms storage sync [--store name] [--folder path]` registers everything at once and lists files the CMS knows that are gone from the bucket (it deletes nothing). - Several files and whole folders can be moved or deleted at once (up to 1000 objects per request). A move copies and deletes, one file after the other: files that fail are reported, and moving again takes the rest. A name that is taken at the destination gets a number; nothing is overwritten. Deleting shows the documents that use any of the files first. - "Make a link" gives an address for someone outside. For a private store it works for 1 hour, 24 hours or 7 days and **cannot be taken back** (it is a signed address); for a public store it is the file's public address. Making one needs the permission to delete in that store, and is in the audit log. - The CMS's own folder (`_cms/`, thumbnails) is hidden and cannot be touched. ## Agents Agents get three more tools: `list_store_files` (read), `register_asset` (write) and `create_share_link` (publish). ## REST `GET /stores/:store/files?folder=` lists a folder. `POST /stores/:store/files/_register`, `_move` and `_delete` act on keys (`check: true` on a delete only counts what would go and which documents use it). `POST /assets/:id/share` with `{ ttl: "1h" | "24h" | "7d" }` makes a link. --- # Publishing flow Source: https://agent-cms-docs.vercel.app/docs/publishing-flow Scheduled publishing, review requests, comments, releases and the trash, and the one cron call they need. > [!note] > On npm from 0.10.0. Coming from an older version? Read [Upgrade to 0.10](/docs/upgrade-0-10) first. The editor, the document list and two more screens (`cms-trash`, `cms-releases`) cover what happens between "saved" and "public". Nothing here needs set-up except the cron call. ## The cron call Schedules, scheduled releases and emptying the trash run when something calls one route. Their precision is the interval of that call. ```ts // lib/cms.ts createCms({ cronSecret: process.env.CRON_SECRET /* ... */ }); ``` ```json // vercel.json { "crons": [{ "path": "/api/cms/_cron", "schedule": "*/10 * * * *" }] } ``` Vercel sends `Authorization: Bearer $CRON_SECRET` by itself once the project has that variable. On Vercel's Hobby plan a cron runs once a day at most, and a shorter schedule fails the deployment: keep a daily one there and let another scheduler make the frequent call (this site uses a GitHub Actions schedule every ten minutes). Anywhere else, call `GET` or `POST /api/cms/_cron` with the same header. Without `cronSecret` the route answers 404, and a wrong secret gets 401. The answer says what ran: ```json { "published": ["posts/launch"], "unpublished": [], "failed": [], "releases": [], "purged": { "documents": 0, "assets": 0 } } ``` ## Schedule The arrow beside "Publish" sets a time to publish and a time to unpublish, entered on the clock of `createCms({ timeZone })`. - What goes out is the version that was current when it was scheduled. An edit after that shows a warning with "Schedule the latest version". - The version is checked again when its time comes. A version with errors is not published; it is reported in `failed` with its error code. - The list has a "Scheduled" tab, and each row shows its time. ## Review ```ts defineCollection({ name: "guide", review: { agents: "required" } }); ``` - `agents: "required"` keeps what an API key or an agent wrote from going public until a person approves it. - `everyone: "required"` asks the same of people. Whoever asked cannot approve their own request. - The editor shows the request with "Send back" and "Approve and publish". The list has an "In review" tab. - A save while a request is open moves the request to the new version. No tool approves a review: agents can ask (`request_review`) and read the list (`list_review_requests`). ## Comments Comments go on a section or on selected text, with replies and "Resolve". - They follow the text while it is edited. When the text is gone they move to "Lost their place" at the bottom. - A preview link made with "Allow comments" lets someone without an account comment. `readPreview(token)` returns `comments: true` for such a link, and `` on your page shows the box (see [Preview comments](/components/cms-preview-comments)). - Agents read, answer and resolve comments with `list_comments`, `add_comment` and `resolve_comment`. ## Releases A release publishes several documents together, now or at a set time. - Put a document in from the editor's menu ("Add to a release") or from the release screen. Each item is to publish or to unpublish. - The version is pinned when the document goes in. If it was edited since, the row shows "v5 → v7". - Publishing is all or nothing: if one document cannot go out, nothing does, and the screen lists what blocked it. - A document is in one open release at a time. There is no rollback: to undo, unpublish or restore a version. ## Trash Deleted documents and files stay for 30 days. ```ts createCms({ trash: { days: 30 } }); // 0 deletes at once, as before 0.10 ``` - The address of a deleted document stays taken until it is deleted for good. - Restoring a document that was published makes it public again. - A deleted file's public address keeps working until it is deleted for good. - Only admins delete for good or empty the trash. The cron call removes what is older than `trash.days`. ## Smaller things - **Editing together.** The editor and the list show who else has a document open, with their cursors in the body. When someone else saves, the editor takes the new version and merges it with unsaved edits when the two do not overlap. It asks every 15 seconds, every 3 while someone else is there; `presenceMs={0}` turns it off. - **Paste.** Text copied from a web page or a document program is pasted as markdown (headings, lists, bold, links, tables, code). Colours and font sizes are left out, and the editor says so once. - **Versions** take a name and a pin. Pinned versions are never cleaned up. - **Saved filters** keep a tab, a search, a category and an author under a name, for yourself or (admins) for everyone. ## Tools for agents Fifteen tools come with the flow: `label_version`, `preview_document`, `schedule_document`, `unschedule_document`, `request_review`, `list_review_requests`, `list_comments`, `add_comment`, `resolve_comment`, `list_trash`, `restore_from_trash`, `list_releases`, `create_release`, `add_to_release`, `publish_release`. The key's scopes decide which of them an agent sees. The routes are on the [REST API](/docs/rest-api) page. --- # Webhooks, jobs and plugins Source: https://agent-cms-docs.vercel.app/docs/webhooks Signed webhooks with retries, the background jobs that send them, collection hooks, plugins and telemetry. > [!note] > From 0.12.0. Coming from an older version? Read [Upgrade to 0.12](/docs/upgrade-0-12) first. Other services learn what happened through **webhooks**: a signed POST when a document is published, a review is asked for, a file arrives. They are off until you set a key, and they are sent by the same cron call that runs scheduled publishing. ```ts createCms({ // ... cronSecret: process.env.CMS_CRON_SECRET, // POST /api/cms/_cron with `Authorization: Bearer ` secretsKey: process.env.CMS_SECRETS_KEY, // 32+ characters: openssl rand -base64 32 }); ``` Signing secrets are stored encrypted with `secretsKey` (AES-256-GCM). Changing the key makes the stored secrets unreadable, so keep it with your other long-lived secrets. An admin makes a webhook in the admin (`cms-webhooks`) or with `POST /webhooks`: a name, an https address, which events, which collections. The signing secret is shown then and can be read again from the same screen. **Events:** `doc.created`, `doc.updated`, `doc.published`, `doc.unpublished`, `doc.archived`, `doc.deleted`, `doc.restored`, `review.requested`, `review.approved`, `review.rejected`, `asset.uploaded`, `asset.moved`, `asset.deleted`, `release.published`, `comment.created`. No events checked means all of them. **What is sent.** Never the document's text: ```json { "id": "…", "event": "doc.published", "at": "2026-11-21T03:00:00.000Z", "actor": { "kind": "user", "id": "u1", "label": "Kim", "agent": null }, "collection": "posts", "slug": "launch", "version": 3, "url": "https://example.com/posts/launch" } ``` **The receiver** checks the signature (`X-CMS-Signature: t=,v1=`, five minutes of tolerance). `verifyWebhook` has no Node imports, so it also runs on edge runtimes: ```ts import { verifyWebhook } from "@mainsoft/agent-cms/webhooks"; export async function POST(req: Request) { const event = await verifyWebhook(req, process.env.CMS_WEBHOOK_SECRET!); // throws WebhookVerifyError if (event.event === "doc.published") revalidatePath(`/${event.collection}/${event.slug}`); return new Response("ok"); } ``` A delivery can arrive twice (the answer got lost, the CMS tried again): `event.id` is the same on every attempt. **Delivery.** Nothing is sent inside the request that caused it. The event is written to a jobs table and goes out with the next cron call, so the delay is your cron interval. An answer outside 2xx, a redirect, or no answer in 10 seconds counts as a failure and is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours. After 20 failed deliveries in a row the webhook is switched off (the audit log says so, the screen shows why, "Turn on" starts it again). The history keeps 30 days and has "Send again". **Addresses.** Only https addresses on the public internet: private, loopback and link-local addresses are refused when the webhook is saved and again before every delivery. `webhooks: { allowInsecure: true }` lifts this for local development only. **Who.** Admins and keys with the `admin` scope. There is no agent tool that makes a webhook: an agent cannot open a way out for data by itself. ## Background jobs Webhook deliveries are one kind of job. The same table runs your own: ```ts cms.jobs.define<{ id: string }>("report.build", { retryAfter: [60, 600], run: async ({ id }) => build(id) }); await cms.jobs.enqueue("report.build", { id: "2026-11" }, { runAt: tomorrow }); ``` `POST /_cron` runs scheduled publishing, then the jobs that are due (for about 20 seconds; the rest waits for the next call), then housekeeping. Two calls at the same moment never run the same job. Without a cron service, `npx @mainsoft/agent-cms cron --watch` calls it every 30 seconds (`AGENT_CMS_URL`, `AGENT_CMS_CRON_SECRET`). `GET /jobs?state=failed` lists what gave up, `POST /jobs/:id/retry` tries again, and `doctor` warns when there are any. ## Hooks, plugins, telemetry **Collection hooks** run inside a write: ```ts defineCollection({ slug: "posts", hooks: { beforeChange: [({ content, prev }) => (prev ? undefined : { keywords: [...content.keywords, "new"] })], // return fields to change them beforePublish: [({ content }) => { if (!content.summary) throw new Error("Write a summary before publishing"); }], beforeDelete: [({ slug }) => { if (slug === "home") throw new Error("The home page cannot be deleted"); }], afterChange: [/* as before */], }, }); ``` A hook that throws refuses the write with `hook_rejected` (422) and your message. `beforePublish` also runs for schedules, releases and approvals. **Plugins** add to the CMS from another package: ```ts import { definePlugin } from "@mainsoft/agent-cms"; export const stats = definePlugin({ name: "stats", // routes live under /api/cms/stats/ sql: ['CREATE TABLE IF NOT EXISTS "stats_days" (…)'], // collected in cms.plugins.sql for your migrations setup(ctx) { ctx.on("doc.published", (e) => ctx.enqueue("rollup", { slug: e.slug })); ctx.job("rollup", { run: async (p) => { /* … */ } }); ctx.route("GET", "summary", ({ actor, cms }) => Response.json({ /* … */ })); // actor is already checked ctx.tool({ name: "stats_summary", description: "…", input: z.object({}), run: () => ({ /* … */ }) }); ctx.me((actor) => ({ canSee: actor.kind !== "anonymous" })); // GET /_me → plugins.stats ctx.nav({ label: "Stats", href: "/admin/stats" }); // the admin sidebar shows it }, }); createCms({ /* … */, plugins: [stats] }); ``` `ctx.secrets` seals values the plugin keeps in the database (null without `secretsKey`). **Telemetry.** `createCms({ onEvent })` gets every request (`method`, `path`, `status`, `ms`, `actor`, `via`), every event, every job run, every cron call and every error the CMS reports. Connect it to your tracing; it is never awaited. --- # Automations, roles and the dashboard Source: https://agent-cms-docs.vercel.app/docs/automations Rules that run after something happens, who may write and publish in each collection, and the numbers of your content on one screen. > [!note] > From 0.13.0. Coming from an older version? Read [Upgrade to 0.13](/docs/upgrade-0-13) first. ## Automations An automation is a rule an admin makes on a screen: **when** something happens, **if** some conditions hold, **do** a list of actions. | Part | Choices | |---|---| | When | A document is created, updated, published, unpublished or deleted. A review is asked for. A file is uploaded. Every day. Every Monday. | | If | `category`, `actor` (`person` or `agent`), `title`, or a field such as `fields.tags`: is, is not, contains, is empty, is not empty | | Do | Send a webhook. Add a keyword. Set a field. Put the document into a release. Call a function of your app. | ```ts createCms({ cronSecret: process.env.CRON_SECRET, // automations run with the cron call automations: { actions: { // "Call an app function" on the screen lists these names. notifySales: async ({ automation, doc, event }) => { await slack.send(`${automation.name}: ${doc?.title}`); }, }, }, }); ``` How they run: - An event that matches becomes a background job. The work happens on the next `POST /_cron`, not inside the request that caused it. Without a cron service: `npx @mainsoft/agent-cms cron --watch`. - What an automation changes is saved as a new version by "automation: ", so the history shows it. - A change made by an automation never starts another automation. - Each run is kept for 30 days as Done, Skipped (the conditions did not hold) or Failed, with a line per action. - A new automation made on the screen starts switched off. One made through the API is on unless you send `enabled: false`. "Try it" on the screen, or `POST /automations/:id/test` with `{ collection, slug }`, checks one document against the conditions and lists the actions that would run. Nothing is changed. ```sh curl -X POST https://app.example.com/api/cms/automations \ -H "authorization: Bearer $AGENT_CMS_KEY" -H "content-type: application/json" \ -d '{"name":"News keyword","trigger":{"event":"doc.published","collection":"posts"}, "conditions":[{"field":"category","op":"is","value":"News"}], "actions":[{"type":"add_keyword","name":"news"}]}' ``` Only admins (or a key with the `admin` scope) can make automations, and no agent tool makes one. ## Roles A role says, for each collection, whether its people may **write**, **publish** and **delete**. An admin role may do everything, including keys, webhooks, automations and roles. The CMS decides in this order: 1. The system (cron, automations). 2. The collection's own `access` functions in code. When code decides an operation, the roles screen shows "Set in code" and cannot change it. 3. Roles. 4. The default: admins only. An app that never makes a role behaves exactly as it did before 0.13. People are put into a role by the id your `resolveUser` returns. To let the screen find them by name: ```ts createCms({ users: { search: async (q) => (await findUsers(q)).map((u) => ({ id: u.id, label: u.name })), get: async (id) => { const u = await findUser(id); return u ? { id: u.id, label: u.name } : null; }, }, }); ``` Without `users` a person is added by typing their id. A role name can be used once; the second one answers `name_taken`. You cannot delete, leave, or take the admin box off the role that makes you an admin (`role_last_admin`): it would lock you out of this screen. API keys are outside roles: a key has its own scopes and collections. ## The dashboard `GET /_stats?days=7|14|30` and the `cms-dashboard` screen: - **Documents, Published, Waiting for review, Scheduled**: the same numbers as the lists. - **Changes**: versions saved per day, split into people and agents. - **Most read**: needs hit counting (`cms.recordHits`, see [Search](/docs/search)). - **Recent activity**: publishes, schedules, deletes, reviews, uploads. A caller sees only collections they may read, and only admins see who did what. --- # Export and import Source: https://agent-cms-docs.vercel.app/docs/import-export Documents as markdown files, between two installations or from WordPress, CSV and JSON. An import shows what it would do before it does it. > [!note] > From 0.13.0. Documents travel as markdown files with frontmatter, one per document: ``` content/ guide/getting-started.md posts/hello-world.md _meta.json # version, time, counts _assets/manifest.json # the files the documents use _assets// # the files themselves (--with-files) ``` ## From the command line ```sh export AGENT_CMS_URL=https://app.example.com/api/cms AGENT_CMS_KEY=sgk_… npx @mainsoft/agent-cms export ./content # published copies npx @mainsoft/agent-cms export ./content --drafts # working copies where the key may write npx @mainsoft/agent-cms export ./content --collection guide,posts --with-files npx @mainsoft/agent-cms import ./content --dry-run --diff # one line per file, with the changed lines npx @mainsoft/agent-cms import ./content npx @mainsoft/agent-cms import ./content --publish # publish what was public when exported npx @mainsoft/agent-cms put guide ./guide # one folder into one collection ``` What an import does: - It never deletes. - A new address becomes a draft. An address that exists gets a new version; the public copy stays until someone publishes. - `--on-conflict file-wins` (default) saves the file, `db-wins` skips documents that exist, `newest` follows the later change. - A file that fails the collection's checks is reported with the reason and the rest goes on. - With `_assets/` in the folder, files the target does not have are uploaded first and every `asset:ID` in the documents is pointed at the new id. Running it again uploads nothing twice. ## From the admin The `cms-transfer` screen (admins) takes an export file (`.json`) or markdown files, shows a table of what each would do, lets you untick files, and imports the rest as drafts. The Export tab downloads the bundle. ## From somewhere else ```sh npx @mainsoft/agent-cms import ./wordpress.xml --from wordpress --collection posts --dry-run npx @mainsoft/agent-cms import ./wordpress.xml --from wordpress --collection posts --publish npx @mainsoft/agent-cms import ./rows.csv --from csv --collection guide npx @mainsoft/agent-cms import ./items.json --from json --collection guide ``` | Source | What is read | |---|---| | `wordpress` | A WordPress export file (Tools → Export). Posts and pages (`--types post,page,…` picks others). HTML becomes markdown, categories and tags become keywords, the post's slug is the address, published posts can be published with `--publish`. Attachments, menus and revisions are left out. | | `csv` | The first row names the columns: `slug`, `title`, `summary`, `body` (or `html`, `content`), `category`, `keywords` (or `tags`), `status`. Other columns become fields. | | `json` | An array, or `{ "documents": [...] }`, of objects with the same keys. Keys the CMS does not know become fields. | Addresses are made usable (lowercase letters, digits, hyphens) and unique. A title with no such characters, a Korean one for example, becomes `doc-1`, `doc-2`: rename them after the import. In code: ```ts import { filesFromSource, htmlToMarkdown } from "@mainsoft/agent-cms"; const files = filesFromSource("wordpress", xml, { collection: "posts" }); const report = await cms.transfer.import(actor, files, { dryRun: true }); ``` Pictures inside WordPress posts keep pointing at the old site (only `https` addresses survive). Bring them into the media library with the `import_asset` tool or the media screen's "Import from URL". ## REST - `GET /export?collections=a,b&drafts=1&download=1` → `{ files, documents }` - `POST /import` with `{ files, dryRun, diff, publish, onConflict, collection, only, assetMap }` → `{ items, applied }` Up to 2000 files per request; the CLI sends them in batches of 100. --- # Limits, key rotation, retention and events Source: https://agent-cms-docs.vercel.app/docs/operations Requests per minute for keys and strangers, addresses a key may be used from, a new secret without downtime, how long logs are kept, and a live stream of what happens. > [!note] > From 0.14.0. Everything here is off until you set it. See [Upgrade to 0.14](/docs/upgrade-0-14). ## Request limits ```ts createCms({ rateLimit: { perMinute: 600, anonymousPerMinute: 120 }, }); ``` | Who | Counted by | Limit | |---|---|---| | An API key | The key | Its own `rateLimit`, else `perMinute` | | No key and no session | The caller's address | `anonymousPerMinute` | | A signed-in person | Not counted | None | Over the limit the answer is 429 with `Retry-After` in seconds: ```json { "error": "rate_limited", "message": "Too many requests. Try again in 42 seconds", "params": { "retryAfter": 42, "limit": 60 } } ``` A minute is a fixed window: the count starts over when the clock minute ends. Counts live in the server process. With several servers, or on a serverless host, give a store they share; it needs one method: ```ts rateLimit: { perMinute: 600, store: { hit: async (bucket, ttlMs) => { const n = await redis.incr(bucket); if (n === 1) await redis.pexpire(bucket, ttlMs); return n; }, }, } ``` The address comes from `X-Forwarded-For` (first entry), then `X-Real-IP`. A server that is not behind a proxy setting those should say where it is: `createCmsHandler({ clientIp: (req) => … })`. ## A key's own limit and addresses On the keys screen, or: ```ts await cms.createKey(admin, { name: "deploy", scopes: ["read", "write"], rateLimit: 60, allowedIps: ["203.0.113.0/24", "2001:db8::/32"] }); ``` From any other address the key answers 403 `forbidden_ip`. Up to 50 addresses or ranges, IPv4 and IPv6. ## Rotating a key "Rotate" on the keys screen, or `POST /keys/:id/rotate` with `{ "graceMinutes": 60 }`: - A new secret is made with the same name, scopes, collections, expiry and limits. It is shown once. - The old secret keeps working for the grace time (60 minutes by default, up to 7 days, `0` to stop it now), so callers can switch without a break. - The list shows the old key with "Works until …", then as "Replaced". `DELETE /keys/:id?reason=leaked` keeps a note with a revoked key. ## Retention ```ts createCms({ retention: { auditDays: 365, hitsDays: 400, revokedKeysDays: 90, deliveriesDays: 14 }, }); ``` | Option | What goes | |---|---| | `auditDays` | Audit log entries older than this | | `hitsDays` | Read counts older than this (the dashboard reads 30 days at most) | | `revokedKeysDays` | Keys revoked longer ago than this | | `deliveriesDays` | Webhook deliveries (they are kept 30 days without it) | The cron call applies the rules at most once a day and writes one audit entry when it deleted something. Documents, their versions (`versions.max` on a collection) and the trash (`trash.days`) are not part of it. Look before it runs: ```sh npx @mainsoft/agent-cms retention --dry-run # needs an admin key ``` ```json { "dryRun": true, "items": [{ "what": "audit", "days": 365, "before": "2025-11-21T00:00:00.000Z", "rows": 1204 }] } ``` ## Events as they happen ```ts const es = new EventSource("/api/cms/_events?collections=posts"); es.addEventListener("doc.published", (e) => refresh(JSON.parse(e.data).slug)); es.addEventListener("resync", (e) => JSON.parse(e.data).documents.forEach((d) => refresh(d.slug))); ``` `GET /_events` is a Server-Sent Events stream of the same events webhooks carry (`doc.created`, `doc.updated`, `doc.published`, …). - Someone who may write in a collection hears everything about its documents. - A reader, such as a stranger on a public collection, hears only what changes the public copy: published, unpublished, archived, deleted, restored. - Events without a collection (files, releases) go to admins. - Every message has an id, a time. When the browser reconnects it sends the id back, and the first message is one `resync` listing the documents saved since (up to 200). `?since=` does the same by hand. > [!warning] > The stream is fed by the server process that answers it. With several servers, a change made through another one arrives with the next `resync`, not live. Hosts that cut long responses (serverless) end the stream after their time limit; `EventSource` reconnects by itself. In code: `const stop = cms.subscribe((event) => …)`. ## More hooks ```ts defineCollection({ slug: "posts", hooks: { beforeValidate: [({ input, prev }) => (!prev && !input.slug && input.title ? { slug: slugify(input.title) } : undefined)], afterPublish: [(doc) => revalidatePath(`/blog/${doc.slug}`)], afterDelete: [(doc) => searchIndex.remove(doc.id)], afterRead: [(doc, { actor }) => (actor.kind === "anonymous" ? { ...doc, fields: { ...doc.fields, internalNote: undefined } } : undefined)], }, }); ``` | Hook | When | Can it stop the action | |---|---|---| | `beforeValidate` | Before the input is checked. Return fields to change them | Yes, by throwing | | `beforeChange`, `beforePublish`, `beforeDelete` | Before the save, publish or delete (0.12) | Yes | | `afterChange`, `afterPublish`, `afterDelete` | After it happened | No. Errors go to `onError` | | `afterRead` | Before one document leaves `get` (not lists or search) | Yes, by throwing | `afterPublish` also runs for a scheduled publish and for a release. --- # Agents edit documents like code Source: https://agent-cms-docs.vercel.app/docs/agent-files Read a document as a numbered file, search many, replace exact text, push files from your editor, keep agents' edits as suggestions, and keep HTML exactly as written. > [!note] > New in 0.15.0. Needs schema 8 (`npx @mainsoft/agent-cms migrate apply`). ## One document, one file Every document reads as one text file: frontmatter lines (slug, title, summary, category, keywords, then one line per field) and the body. Agents read it with line numbers and change it by replacing exact text, the way coding agents edit code. The same edit works for body text, HTML blocks and fields. ```text --- slug: new-dashboard title: The new dashboard cover: "asset:a8f2c0d1e2f3/banner.jpg" --- ## What changed ``` ## Tools - `read_document`: the file with line numbers; `offset` and `limit` for long documents, `outline: true` for headings and blocks with their lines. - `grep_documents`: matching lines across documents. Literal text by default, `regex: true` for a regular expression. Narrow with `collections`, `slugs` or `glob` (`guide/2026-*`). - `edit_document`: `edits: [{ oldString, newString, replaceAll? }]`. The old text must be unique; several edits apply in order as one version, all or none. When the text is not found, the answer lists the closest lines. - `write_document`: the whole file. Replacing needs `expectedVersion`. - `document_file_link`: a 10-minute link to download or upload the file. ## From the command line ```bash npx @mainsoft/agent-cms pull guide new-dashboard # edit guide/new-dashboard.md with any editor npx @mainsoft/agent-cms push ``` If someone edited the document in the CMS meanwhile, `push` merges both. When both changed the same lines, the file gets `<<<<<<<` markers and nothing is saved until you fix them. ## Suggestions With `agentEdits: "suggest"` on a collection, edits by API keys and agents wait as suggestions. A person applies or rejects them (`POST /collections/:c/:slug/suggestions/:id/apply`). ## HTML blocks and HTML documents ````text :::html
…
::: ```` HTML is stored exactly as written. Parts that would do nothing on the page (scripts, `onclick`, frames from other hosts) come back as warnings with their line. Draw HTML with `sanitizeHtml` from `@mainsoft/agent-cms/html`, or in a sandboxed frame with `isolatedHtml`. Adding or changing HTML needs the `html` permission (keys: the `html` scope). Whole-HTML documents are switched on per collection with `body: { formats: ["markdown", "html"] }`. --- # Sign-in of its own Source: https://agent-cms-docs.vercel.app/docs/sign-in People, passwords, passkeys, two-step codes, single sign-on and invitations, for apps without a login. Most apps already have a login and pass it in with `resolveUser`. When yours does not (or for the standalone server), the CMS can sign people in itself. ```ts import { createAuth } from "@mainsoft/agent-cms/auth"; import { createCmsHandler } from "@mainsoft/agent-cms/http"; const auth = createAuth({ cms, origin: "https://cms.example.com", // passkeys and mail links use it appName: "Example CMS", sendMail: async ({ to, subject, text }) => { /* Resend, SES, SMTP… */ }, oidc: { issuer: "https://accounts.google.com", clientId, clientSecret, label: "Google", allowedDomains: ["example.com"] }, }); export const handler = createCmsHandler({ cms, auth }); ``` Nothing new goes into the database schema: people, sessions, passkeys and one-time links live in `cms_records`. ## The first admin While nobody has an account, the server prints a setup code where it logs (valid for 15 minutes; a new one comes with the next request after that): ``` [agent-cms] No one can sign in yet. Open https://cms.example.com/admin/setup and enter the setup code K7M2-9XQ4 (valid for 15 minutes). ``` `POST /auth/setup` with the code makes the first admin. After that, setup is closed. ## Ways to sign in | | | |---|---| | Password | At least 12 characters; common and guessable ones are refused (the 10,000 most common, the email name, runs like `abcdefgh…`). Hashed with scrypt (N=2^17, r=8, p=1); weaker hashes are replaced at the next sign-in. Turn passwords off with `passwords: false`. | | Passkey | WebAuthn without a library: ES256, EdDSA, RS256; no email typed first. A passkey counts as two factors. | | Two-step code | Any authenticator app (TOTP, RFC 6238), a QR code on setup, ten recovery codes that work once. "Trust this device" skips the code for 30 days. | | Single sign-on | OpenID Connect with PKCE: Google, Microsoft Entra, Okta, Keycloak, Auth0… `allowedDomains` limits who may sign in (and lets them in without an invitation, unless `autoCreate: false`). | ## Sessions - An `HttpOnly`, `SameSite=Lax` cookie; on HTTPS it is `__Host-cms_session` and `Secure`. Only a hash of it is stored. - 30 days from the last use, at most 90 days. - Ten wrong passwords for one email in 15 minutes pause password sign-in for that email (passkeys and SSO still work); fifty tries from one address in 15 minutes pause that address. - Changing the password ends your other sessions; a reset ends all of them; switching someone off or taking admin away ends theirs at once. - Making or rotating API keys, turning two-step off, removing a passkey, and switching people off or making them admin need a confirmation in the last 10 minutes (`POST /auth/reauth`, or a passkey). - Requests that change something must come from the CMS's own page (login CSRF is refused). ## People Admins invite by email (`POST /users/invite`, links valid for 7 days, with a role and optionally as admin). Without `sendMail` the answer has the links to copy. The policy `requireMfa` makes everyone set up a passkey or two-step codes before anything else. At least one admin always stays. Every step is in the audit log (`auth.*` actions). ## From code ```ts await auth.createUser({ email: "park@example.com", name: "Park", password, isAdmin: true }); const link = await auth.resetLink("park@example.com"); ``` The routes are listed under "sign-in", "account" and "people" in `/openapi.json`. --- # The CMS on its own Source: https://agent-cms-docs.vercel.app/docs/standalone-server npx @mainsoft/agent-cms dev or serve — the admin, the API, MCP and sign-in on one port, without a web app. You do not need a Next.js app to use agent-cms. The package ships a built admin and a server. ## Try it ```bash npx @mainsoft/agent-cms dev ``` Open the address it prints. Nobody can sign in yet: the terminal shows a **setup code** (valid 15 minutes) that the first admin signs up with. `dev` makes a "Posts" collection; it keeps documents in `.agent-cms/dev` when `@electric-sql/pglite` is installed (`npm i -D @electric-sql/pglite`), in memory otherwise. ## Run your own collections Put your `createCms` in `server` in `agent-cms.config.ts` and run `serve`: ```ts import { defineConfig } from "@mainsoft/agent-cms/config"; export default defineConfig({ db: async () => (await import("./cms")).db, server: { cms: async () => (await import("./cms")).cms, appName: "Acme", trustProxy: true, // behind HTTPS auth: { sendMail: async (m) => { /* your mail service */ } }, }, }); ``` ```bash npx @mainsoft/agent-cms migrate apply && npx @mainsoft/agent-cms serve --port 3000 ``` Or from code: `import { startServer } from "@mainsoft/agent-cms/serve"; await startServer({ cms, port: 3000 })`. ## What the server does - `/admin`: the admin, with a strict Content Security Policy (`frame-ancestors 'none'`, no inline scripts except one by its hash). - `/api/cms`: REST, MCP (`/api/cms/mcp`) and the sign-in. - `GET /healthz` for load balancers; a graceful stop on SIGTERM (requests in flight finish, up to 10 seconds). - The scheduler every minute: publishing at a time, webhook deliveries, automations, retention. - Built files are cached for a year; the page is never cached. ## Docker `examples/server` in the repository has a `Dockerfile` and a `compose.yaml` with Postgres and MinIO: ```bash export CMS_PREVIEW_SECRET=$(openssl rand -base64 32) CMS_SECRETS_KEY=$(openssl rand -base64 32) docker compose up --build docker compose logs cms | grep "setup code" ``` See [Sign-in](/docs/sign-in) for passkeys, two-step codes, single sign-on and invitations. --- # Several servers, caching and sites Source: https://agent-cms-docs.vercel.app/docs/scaling The change log carries events between servers; a read cache, paging in the database, drivers, Edge, several sites and metrics. Since 0.17.0 (schema 9) every change is written to a numbered **change log** (`cms_changes`). Each server follows it, so the events stream, the read cache and the search index hear what any server did. ## Following other servers Nothing to set up: a server that has listeners (an open events stream, a cache) looks at the log every 2 seconds. To hear at once, give it a signal: ```ts import { connectPostgres } from "@mainsoft/agent-cms/db"; import { memoryCache } from "@mainsoft/agent-cms/changes"; const { repo, signal } = await connectPostgres(process.env.DATABASE_URL!); // pg or postgres.js: LISTEN/NOTIFY const cms = createCms({ repo, collections, cache: memoryCache({ max: 2000 }), changes: { signal, keepDays: 7 } }); ``` On serverless hosts there is no long-lived listener: followers poll. Clients can poll too: `GET /api/cms/_changes?since=` returns `{ changes, last, more, reset }`. `reset: true` means the log no longer reaches back that far: reload. The events stream (`/_events`) uses the same numbers as message ids. A browser that reconnects sends its last id and gets the events it missed, in order. ## Read cache `cache` takes `memoryCache()` or any store with `get(key)` and `set(key, value, ttlMs)` (Redis, Upstash, Next's cache). Readers' documents and lists are cached; editors never read from it. A publish, unpublish, archive, delete or restore empties the collection's entries at once on this server and within one poll elsewhere. Collections with their own `access.read` rule are not cached. ## Paging and indexes Lists are filtered, sorted and cut in the database; the cursor is the last row (`k.…`), so a page never repeats or skips documents when new ones arrive. `doctor` checks the eleven indexes schema 9 adds and `doctor --fix` removes rows that point at nothing (versions, file uses and comments of documents that are gone). ## Drivers `connectPostgres(url, { driver })`: `pg`, `postgres-js`, `neon-serverless` (WebSocket, transactions), `neon-http` (no transactions: each change runs as separate statements and version checks still prevent lost updates), `pglite` (`memory:` or a folder). ## Edge The core and the REST handler need no Node built-ins: run them on Vercel Edge or Cloudflare Workers with a driver that works there (`neon-http`, `neon-serverless`). Webhooks need Node's crypto for their sealed secret (Workers: `nodejs_compat`). ## Several sites ```ts import { createTenantHandler, migrateTenant, tenantTables } from "@mainsoft/agent-cms/tenants"; export const handler = createTenantHandler({ resolve: (req) => new URL(req.url).hostname.split(".")[0], create: async (site) => { await migrateTenant(db, site); const cms = createCms({ repo: new DrizzleRepo(db, { tables: tenantTables(site) }), collections }); return createCmsHandler({ cms, resolveUser }); }, }); ``` Each site has its own Postgres schema (`tenant_`), so no query can mix them up, and a site can be dumped or dropped on its own. ## Metrics `server.metricsToken` (or `CMS_METRICS_TOKEN`) turns on `GET /metrics` on the standalone server (Prometheus text, bearer token). In your own app: `const m = createMetrics(); createCms({ onEvent: m.onEvent })` and serve `m.text()`. Paths are grouped (`/collections/:c/:slug`). ## Measuring `npm run bench -- --docs 10000` in the repository times reads, lists, search, saves and publishes (PGlite, or `DATABASE_URL`). --- # Your own agent Source: https://agent-cms-docs.vercel.app/docs/ai-sdk Give the agent in your app the CMS tools, in-process or from another service. The package itself never calls a model. > [!note] > This page used to be "AI SDK tools". The `./ai` entry (`cmsTools`, `remoteCmsTools`) was removed in 0.8.0: agent-cms hands agents tools and depends on no model library. What replaces it is below; [Upgrade to 0.8](/docs/upgrade-0-8) has the before and after. ## In-process `toolsFor(cms, actor)` lists the tools this actor may use: a name, a description and a zod schema for the input. `callTool` runs one. Wrap them in whatever your agent framework calls a tool: ```ts import { toolsFor, callTool } from "@mainsoft/agent-cms/tools"; const actor = { kind: "system", label: "assistant" } as const; const tools = toolsFor(cms, actor).map((t) => ({ name: t.name, description: t.description, input: t.input, // a zod object; toJsonSchema(t.input) from ./mcp gives JSON Schema run: (args: unknown) => callTool(cms, actor, t.name, args), })); ``` `callTool(cms, actor, name, args, { only })` checks the input, runs the tool with the actor's permissions, and records the call as made by an agent. `toolsFor(cms, actor, only)` and the `only` option narrow the list. ## From another service A script, a scheduled job or another service uses a key: ```ts import { createCmsClient } from "@mainsoft/agent-cms/client"; import { toolErrorResult } from "@mainsoft/agent-cms/tools"; const api = createCmsClient({ url: "https://app.example.com/api/cms", key: process.env.AGENT_CMS_KEY! }); const tools = await api.listTools(); // only what this key may use: { name, description, inputSchema } const run = (name: string, args: Record) => api.call(name, args).catch((e) => toolErrorResult(e) ?? Promise.reject(e)); ``` `listTools()` asks the server which tools the key may use, so a read-only key is offered read tools only. ## For a signed-in person When the agent works with a signed-in person's permissions, say so on the actor: ```ts await callTool(cms, { ...user, agent: { label: "assistant" } }, "patch_document", args); ``` Permissions are exactly the person's. The version, the document and the audit log also record the agent's name, the edit shows up under "Agent changes" for review, and the admin shows it as "assistant, Kim". Only code that calls the CMS in-process can set this; REST and MCP never accept it. ## Errors are results Tool errors come back as results, not throws, so the model can re-read and retry: `{ error: "conflict_version", kind: "conflict", message, params: { expected, current } }`. Every code is on the [errors](/docs/errors) page. ## The tools - **read:** `list_collections`, `search_documents`, `read_for_answer`, `list_documents`, `get_document` - **write:** `create_document`, `update_document`, `patch_document`, `diagnose_document`, `list_versions`, `restore_version` - **publish:** `publish_document`, `unpublish_document`, `archive_document`, `delete_document`, `bulk_documents` - **With a [media library](/docs/media-library):** `list_assets`, `get_asset` (read), `import_asset`, `update_asset` (write), `move_asset`, `delete_asset` (publish) - **With the [file manager](/docs/file-manager):** `list_store_files` (read), `register_asset` (write), `create_share_link` (publish) The same list is served over [MCP](/docs/mcp), so a coding agent and the agent in your app see one set of tools. For answering questions from your documents, see [Answering](/docs/answering). --- # MCP Source: https://agent-cms-docs.vercel.app/docs/mcp Connect coding agents to your CMS, with a key or read-only without one. The route you mounted serves MCP at `/api/cms/mcp` (official MCP SDK, streamable HTTP, stateless). ## With a key Create a key in the **API keys** screen, then register the server with the header `Authorization: Bearer sgk_…`: ```sh claude mcp add --transport http my-cms https://app.example.com/api/cms/mcp --header "Authorization: Bearer sgk_…" ``` The key's scopes decide which tools the agent sees. Published documents are also MCP resources (`cms:///`), and two prompts (`answer_from_cms`, `edit_document`) show the safe way to work. ## Without a key (read only) For public docs any agent may read, turn on anonymous read: ```ts createCmsHandler({ cms, resolveUser, mcp: { anonymous: "read" } }); ``` A request without a key then gets the read tools only (`list_collections`, `search_documents`, `read_for_answer`, `list_documents`, `get_document`) and sees published documents of collections anyone may read. Write tools are not listed. The default stays off (401 without a key). > [!tip] > This site does exactly that. Try it: [Read the docs with an agent](/agents). --- # CLI Source: https://agent-cms-docs.vercel.app/docs/cli Read and write documents from a shell, for agents and scripts. ## Connect ```sh export AGENT_CMS_URL=https://app.example.com/api/cms AGENT_CMS_KEY=sgk_… npx @mainsoft/agent-cms collections ``` `--env ` reads `AGENT_CMS_URL` and `AGENT_CMS_KEY` from a file instead. These commands talk to the app over HTTP, so they run from any folder: `npx` fetches the package when it is not installed there. Keep the scope in the command (`bunx @mainsoft/agent-cms …` and `pnpm dlx @mainsoft/agent-cms …` work the same way). `agent-cms` without `@mainsoft/` is another project's package on npm and stops with `could not determine executable to run`. ## Commands ```sh npx @mainsoft/agent-cms search "install tables" --collections docs npx @mainsoft/agent-cms get posts hello-world --draft npx @mainsoft/agent-cms put posts ./hello-world.md --publish --note "launch post" npx @mainsoft/agent-cms patch posts hello-world ./ops.json --expected-version 3 --dry-run npx @mainsoft/agent-cms call archive_document '{"collection":"posts","slug":"old","archived":true}' ``` `put` creates the document. To update one that exists, pass the version you read as `--expected-version N`; if someone saved since, `put` fails with a conflict instead of overwriting. `--force` skips that check. ## File format Markdown with frontmatter. Keys other than `slug`, `title`, `summary`, `category` and `keywords` go into `fields`: ```md --- title: Hello, world summary: Our first post category: News tags: [launch] --- Body in **markdown**. ``` ## Export, import, OpenAPI From 0.13.0. ```sh npx @mainsoft/agent-cms export ./content --drafts --with-files npx @mainsoft/agent-cms import ./content --dry-run --diff npx @mainsoft/agent-cms import ./wordpress.xml --from wordpress --collection posts npx @mainsoft/agent-cms put guide ./guide npx @mainsoft/agent-cms openapi > openapi.json ``` `export` writes one markdown file per document; `import` reads them back as drafts and says what it would do with `--dry-run`. `--from json|csv|wordpress` reads content from somewhere else. See [Export and import](/docs/import-export). `openapi` prints the REST API as an OpenAPI 3.1 document for what the key may read. ## Local commands `init`, `doctor`, `migrate check | print | apply` and `add` work on your project, without a server. See [Install](/docs/install) and [Admin screens](/docs/admin-screens). --- # Answering questions Source: https://agent-cms-docs.vercel.app/docs/answering Find sections, cite them, and keep document text from acting as instructions. `lookupForAgent` from `@mainsoft/agent-cms/agent` is the helper behind the `read_for_answer` tool. Use it when your assistant answers a user from the CMS. ```ts import { lookupForAgent, verifyCitations } from "@mainsoft/agent-cms/agent"; const found = await lookupForAgent(cms, actor, ["docs"], question, { budget: 3000, countTokens }); ``` ## What you get - matching sections, each with a citation id (`cms://docs/install#create-the-tables`) and its URL - `[[link:key|label]]` links resolved - whether a person or an agent wrote each section - `context`: the sections wrapped in `` tags that tell the model the text is reference, not instructions With `budget` and your tokenizer (`countTokens`) it packs sections to fit. ## Check the answer `verifyCitations(citations, lookup)` checks that an answer's citation ids exist and its quotes appear in them. --- # Admin screens Source: https://agent-cms-docs.vercel.app/docs/admin-screens Copy the screens into your app, theme them, and keep them up to date. The screens are source files you copy into your app and then own, like shadcn/ui. They use your shadcn/ui parts and talk to the CMS through `createRestClient` from `@mainsoft/agent-cms/client`. ## Add them With the shadcn CLI, from this site's registry: ```sh npx shadcn add https://agent-cms-docs.vercel.app/r/cms-doc-editor.json ``` Or with the agent-cms CLI: ```sh npx @mainsoft/agent-cms add cms-shell cms-doc-list cms-doc-editor cms-versions cms-keys cms-audit cms-command npx @mainsoft/agent-cms add cms-media cms-files # with a media library (0.10.0 and later) npx @mainsoft/agent-cms add cms-trash cms-releases cms-preview-comments # trash, releases, comments on preview links (0.10.0 and later) npx @mainsoft/agent-cms add cms-webhooks # webhooks (0.12.0 and later) npx @mainsoft/agent-cms add cms-dashboard cms-automations cms-roles cms-transfer # dashboard, automations, roles, import and export (0.13.0 and later) ``` Files go to `/cms/`. The shadcn parts and the screens an item needs come along. Browse every screen with a live demo in [Components](/components). ## Wire them ```tsx `/admin/${c}/${s}`} /> ``` `extraNav` adds your app's own screens to the sidebar. UI text is English; pass `messages={ko}` from `cms-messages` for Korean. ## Theme them The screens use the shadcn variables (`--background`, `--primary`, `--radius`, fonts). Change those and the screens follow. This site's admin is the same screens with its own variables; the gallery switches between the two looks. ## Update them ```sh npx @mainsoft/agent-cms add --diff # what a new release would change in your copies npx @mainsoft/agent-cms add --update # update files you did not edit; yours get a .new copy ``` `agent-cms.json` records what was copied. `--diff` and `--update` only know about copies made with `agent-cms add`. --- # REST API Source: https://agent-cms-docs.vercel.app/docs/rest-api The routes under /api/cms. Auth: an `Authorization: Bearer sgk_…` key, else your session user (`resolveUser`), else anonymous (published reads only). A write that uses the session must come from a page of the app itself. The handler compares the browser's `Origin` with the address of the request (`Host`, or `X-Forwarded-Host` behind a proxy) and answers 403 `cross_site` when they differ. Requests with a key are not checked. If the admin is served from another address, list it: `createCmsHandler({ cms, resolveUser, trustedOrigins: ["https://admin.example.com"] })`. ## Documents ```text GET /collections/:c list (?fields=summary&state=&q=&category=&by=&limit=&cursor=, ?drafts=1) POST /collections/:c create {doc, publish?, note?} GET /collections/:c/:slug read (?draft=1 for the working copy) PATCH /collections/:c/:slug update {doc, expectedVersion?, publish?, note?} DELETE /collections/:c/:slug to the trash (kept 30 days by default) POST /collections/:c/:slug/patch {ops, expectedVersion?, dryRun?} POST /collections/:c/:slug/publish | archive | unarchive | unpublish ``` ## Editing helpers ```text GET /collections/:c/_counts numbers per state GET /collections/:c/_schema fields as JSON Schema + admin hints POST /collections/:c/_diagnose {doc, slug?} → every problem, nothing saved POST /collections/:c/_bulk {action, items:[{slug, expectedVersion?}]} PUT /collections/:c/:slug/autosave {doc, baseVersion} DELETE: discard GET /collections/:c/:slug/changes agent changes waiting for review POST /collections/:c/:slug/review {hunks: [...] | "all", action?} POST /collections/:c/:slug/preview {ttl: "1h" | "24h" | "7d", comments?} ``` ## Versions ```text GET /collections/:c/:slug/versions[/:n] GET /collections/:c/:slug/diff?a=&b= POST /collections/:c/:slug/versions/:n/restore {publish?} ``` ## Publishing flow ```text POST /collections/:c/:slug/schedule {publishAt?, unpublishAt?, expectedVersion?} DELETE: cancel POST /collections/:c/:slug/review/request {note?} | review/approve {publish?} | review/reject {note?} GET /reviews?collection= documents waiting for a review GET /collections/:c/:slug/comments | POST {body, anchor?, quote?, threadId?} POST /collections/:c/:slug/comments/:id/resolve {resolved?} GET /preview/comments?token= | POST comments through a preview link that allows them POST /collections/:c/:slug/presence {cursor?, selection?} DELETE: leave GET /collections/:c/_presence who has which document open PATCH /collections/:c/:slug/versions/:n {label?, pinned?} POST /collections/:c/_preview {doc, slug?} → blocks, diagnostics, diff; nothing saved GET /collections/:c/_filters | POST {name, query, shared?} | DELETE /collections/:c/_filters/:id GET /releases | POST {name} GET /releases/:id | PATCH {name} | DELETE POST /releases/:id/items {items} | DELETE /releases/:id/items/:documentId POST /releases/:id/publish | POST /releases/:id/schedule {publishAt | null} GET /trash?kind=document|asset | POST /trash/_restore {items} | POST /trash/_purge {items | all: true} GET /_cron run what is due (Authorization: Bearer ) ``` See [Publishing flow](/docs/publishing-flow). ## Webhooks and jobs Admins and keys with the `admin` scope. ```text GET /webhooks {webhooks, events, enabled} POST /webhooks {name, url, events?, collections?, enabled?} → {webhook, secret} PATCH /webhooks/:id the same fields | DELETE GET /webhooks/:id/secret the signing secret POST /webhooks/:id/test send a ping now → {delivery} GET /webhooks/:id/deliveries?limit= the last 30 days, newest first POST /webhooks/deliveries/:id/retry queue the same event again GET /jobs?state=waiting|failed|done&kind= {waiting, failed, jobs} POST /jobs/:id/retry give a failed job another round POST /_cron Bearer cronSecret: schedules, due jobs, housekeeping → {published, …, jobs} ANY //… routes a plugin added ``` ## Automations, roles, dashboard, export From 0.13.0. Admins (or a key with the `admin` scope) unless noted. | Method and path | What it does | |---|---| | `GET /automations` | Automations, with the triggers and actions that can be picked | | `POST /automations`, `PATCH /automations/:id`, `DELETE /automations/:id` | Make, change, delete | | `GET /automations/:id/runs` | Run history (30 days) | | `POST /automations/:id/test` `{collection, slug}` | What would happen to one document; nothing is changed | | `GET /roles`, `POST /roles`, `PATCH /roles/:id`, `DELETE /roles/:id` | Roles and what they allow | | `POST /roles/:id/members` `{id, label?}`, `DELETE /roles/:id/members/:userId` | People in a role | | `GET /roles/_users?q=` | Find people (from `createCms({ users })`) | | `GET /_stats?days=7\|14\|30` | The dashboard's numbers. Anyone signed in, for what they may read | | `GET /export?collections=&drafts=1&download=1` | Documents as markdown files. Anyone who may read | | `POST /import` `{files, dryRun?, diff?, publish?, onConflict?, collection?, only?, assetMap?}` | Read files into drafts. Needs write | | `GET /openapi.json` | This API as an OpenAPI 3.1 document. Anyone, for what they may read | | `POST /keys/:id/rotate` `{graceMinutes?}` | A new secret for the same key; the old one works for the grace time (0.14.0) | | `GET /retention`, `POST /retention` `{dryRun?}` | The retention rules; delete what they allow, or only count (0.14.0) | | `GET /_events?collections=&since=` | What happens, as a Server-Sent Events stream. Anyone, for what they may read (0.14.0) | See [Automations, roles and the dashboard](/docs/automations), [Export and import](/docs/import-export) and [OpenAPI and other servers](/docs/openapi). ## Files Only with a [media library](/docs/media-library); without one these answer `media_disabled`. ```text GET /assets?store=&folder=&kind=image,video&q=&tag=&cursor=&limit= GET /assets/_folders | POST {path, store?} | DELETE ?path=&store= POST /assets/_import {url, folder?, store?, alt?, tags?} https only, public addresses only POST /assets/uploads {name, mime, size, folder?, store?, alt?, tags?, replace?} → {asset, upload} GET /assets/uploads/:id which parts arrived DELETE: give up POST /assets/uploads/:id/parts {parts: [1, 2]} → signed addresses for those parts POST /assets/uploads/:id/complete {width?, height?, duration?} → the file is checked and joins the library GET /assets/:id | PATCH {alt?, tags?, focal?: {x, y} | null} | DELETE ?confirm=1 POST /assets/:id/move {folder?, name?} POST /assets/:id/share {ttl?: "1h" | "24h" | "7d"} POST /assets/:id/thumb the small picture, as the request body GET /files/:id/:name 302 to the file; ?thumb=1, ?download=1, ?size= GET /stores/:store/files?prefix=&q=&cursor= everything in the bucket (file manager) POST /stores/:store/files/_register | _move | _delete ``` `upload` is `{kind: "single", url, headers}` (PUT the file there) or `{kind: "multipart", partSize, partCount}` (ask for part addresses, PUT each part). With `replace: ` the upload becomes that file's new content once it passed the checks. `?size=` needs [image sizes](/docs/media-library#image-sizes); an unknown name answers `unknown_image_size`. ## Other ```text GET /_me who am I, what may I do GET /search?q=&collections=a,b&miss=1 GET /preview?token= GET /keys | POST /keys | DELETE /keys/:id GET /audit?cursor=&action=&outcome=&actorKind= POST /mcp ``` A document GET sends `ETag: "v"`; writes take `If-Match`. See [Editing together](/docs/editing-together). --- # Errors Source: https://agent-cms-docs.vercel.app/docs/errors One error shape on every transport, with fine codes and coarse kinds. REST, MCP, the tools (`callTool`) and the CLI return the same shape: ```json { "error": "conflict_version", "kind": "conflict", "message": "…", "params": { "expected": 3, "current": 4 } } ``` `error` is the fine code, `kind` the coarse class. Validation errors add `diagnostics` (every problem at once); conflicts add `current` (the other copy). ## Kinds - `not_found`: `not_found`, `version_not_found`, `key_not_found`, `route_not_found` - `unauthorized`: `unauthorized`, `invalid_key`, `key_expired`, `preview_invalid`, `preview_expired` - `forbidden`: `forbidden_read`, `forbidden_write`, `forbidden_publish`, `forbidden_keys`, `key_too_wide`, `cross_site`, … - `invalid`: `invalid_slug`, `invalid_title`, `invalid_field`, `slug_locked`, `schema_outdated`, … - `conflict`: `conflict_version`, `slug_taken` - `precondition`: `precondition_required` (428, when `requireIfMatch` is on) With a [media library](/docs/media-library), files add their own: - `not_found`: `asset_not_found`, `unknown_store`, `unknown_image_size` - `forbidden`: `forbidden_media` - `invalid`: `asset_type_not_allowed`, `asset_type_mismatch` (the content is not what the extension says), `asset_too_large` (413), `upload_incomplete`, `asset_rejected` (your `media.scan` said no), `asset_replace_type` (a file is replaced by one of the same type only), `import_blocked`, `import_failed`, `invalid_folder`, `media_disabled` - `conflict`: `asset_in_use` (with the documents in `current`), `folder_not_empty` The full list is `ERROR_CODES` in `@mainsoft/agent-cms/errors`. ## Messages Messages are English by default. Pass `messages: ko` from `@mainsoft/agent-cms/messages/ko` to `createCms` for Korean. --- # Security Source: https://agent-cms-docs.vercel.app/docs/security API keys, scopes, expiry and the audit log. ## API keys Keys look like `sgk_…` and are stored as sha256 only; the secret is shown once when you create it. Each key has scopes and optionally a list of collections: - `read`: read documents and search - `write`: create and edit (not publish) - `publish`: publish, unpublish, archive, delete - `admin`: everything, including keys A key can have an expiry date; expired keys answer `key_expired`. A key cannot create a key wider than itself (`key_too_wide`). ## Audit log Key changes, publishing, deletes and refused requests go to `cms_audit`: who, through which channel (REST, MCP, tools, CLI), what and the result. The **Audit log** screen filters it. ## Agent text `read_for_answer` wraps sections in `` tags that tell the model the text is reference, not instructions. See [Answering questions](/docs/answering). --- # OpenAPI and other servers Source: https://agent-cms-docs.vercel.app/docs/openapi The REST API as an OpenAPI 3.1 document with a typed schema per collection, and how to mount the handler on Express, Fastify, Hono and others. > [!note] > From 0.13.0. ## The document ```sh curl https://app.example.com/api/cms/openapi.json npx @mainsoft/agent-cms openapi > openapi.json # what your key may read ``` It describes this installation as it is configured: - Every route of the [REST API](/docs/rest-api) with its parameters, body and answer. - For each collection the caller may read, its own paths (`/collections/posts`, `/collections/posts/{slug}`) and schemas (`PostsDoc`, `PostsInput`) built from the collection's fields, so a generated client has real types. Categories are an enum. - Parts that are switched off (media, cron, preview links) are left out. - A stranger gets only public collections; a key or a session gets what it may read. A test in the package sends every documented route to the real handler and fails when the two disagree, in either direction. ```sh npx openapi-typescript https://app.example.com/api/cms/openapi.json -o cms.d.ts ``` In code: `openApiDocument(cms, { basePath, origin, actor })` and the route list `API_ROUTES`. ## Other servers The handler takes a web `Request` and returns a web `Response`. Frameworks that already speak those need nothing else: ```ts // Hono app.all("/api/cms/*", (c) => handler(c.req.raw)); // SvelteKit: src/routes/api/cms/[...path]/+server.ts export const GET = ({ request }) => handler(request); export const POST = GET, PATCH = GET, PUT = GET, DELETE = GET; // Bun, Deno Bun.serve({ fetch: handler }); ``` For servers that speak Node's `(req, res)`: ```ts import { toNodeHandler } from "@mainsoft/agent-cms/adapters/node"; const handler = createCmsHandler({ cms, resolveUser, basePath: "/api/cms" }); app.use("/api/cms", toNodeHandler(handler)); // Express http.createServer(toNodeHandler(handler)).listen(3000); // node:http ``` `toNodeHandler(handler, { origin, maxBodyBytes })`: `origin` is the address people open when the server cannot tell from `Host` and `X-Forwarded-Proto`; bodies over `maxBodyBytes` (8MB by default) answer 413 `body_too_large`. It works after a body parser such as `express.json()` too. `toWebRequest(req)` gives your `resolveUser` code the same `Request` it would get elsewhere. The admin screens are React components and talk to the API only, so they run in any React app. From another language, generate a client from the document above. --- # Upgrade to 0.6 and 0.7 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-6 What changed, what to run, and how to move cms_gaps before anything drops it. > [!warning] > If you used 0.5 search gaps, copy `cms_gaps` into a table of your own **before** you change your schema. Removing `cmsGaps` from your Drizzle schema can make drizzle-kit generate a `DROP TABLE`. ## New package name The package is now `@mainsoft/agent-cms` on npmjs.com. Remove the `@mainsoft-2024` lines from `.npmrc`, then: ```sh npm uninstall @mainsoft-2024/agent-cms npm i @mainsoft/agent-cms ``` Import paths change their scope only: `@mainsoft-2024/agent-cms/http` becomes `@mainsoft/agent-cms/http`. Copied screens: run `npx @mainsoft/agent-cms add --update`. ## Database ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply ``` 0.6 adds columns and the `cms_audit` table. Until you run it, the CMS answers `schema_outdated` (503). ## Code - Every collection needs `visibility: "public"` or `"internal"`; internal ones need `access.read`. - Errors: `error` is now a fine code (`conflict_version`), the old value is in `kind`. - `update` treats `fields` as a JSON Merge Patch (`null` removes a key). - Gaps are gone from the library. Use `onSearchMiss` and your own table (see [Search](/docs/search)). - Peer `zod` is `^3.25` or `^4`. ## Moving cms_gaps 1. Create your own table (for example `app_search_misses`). 2. Copy the rows with one `INSERT … SELECT` and compare the counts. 3. Keep `cms_gaps` while you switch; agent-cms never reads, writes or drops it, and `doctor` only warns. 4. Collect new misses with `onSearchMiss`. 5. Drop `cms_gaps` last, when you no longer need it. The full SQL, the Drizzle table and an `onSearchMiss` upsert are in [UPGRADE-0.6.md](https://github.com/mainsoft-2024/agent-cms/blob/main/UPGRADE-0.6.md). ## 0.7 Nothing to change. `mcp: { anonymous: "read" }` is new and off by default. --- # Upgrade to 0.8 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-8 The ./ai entry is gone, the schema is version 3, agents can act for a person, and the media library is opt-in. 0.8.0 was not published to npm on its own. It is part of 0.10.0, the first release after 0.7.0: coming from 0.7.0, do this page first, then [Upgrade to 0.10](/docs/upgrade-0-10). ## 1. `./ai` is gone: the package no longer calls into a model library agent-cms hands agents tools. It never calls a model, and from 0.8 it does not depend on any library that does. The `./ai` entry (`cmsTools`, `remoteCmsTools`, `remoteCmsToolsFor`) and the optional `ai` peer dependency are removed. MCP, REST, the CLI and `./tools` are unchanged. If you used `cmsTools`, wrap the same tool list yourself. It is about ten lines with whatever your agent framework calls a tool: ```ts import { toolsFor, callTool } from "@mainsoft/agent-cms/tools"; const actor = { kind: "system", label: "assistant" } as const; const tools = Object.fromEntries( toolsFor(cms, actor).map((t) => [ `cms_${t.name}`, // the old `prefix` option { description: t.description, inputSchema: t.input, // a zod object execute: (args: unknown) => callTool(cms, actor, t.name, args), }, ]) ); ``` `callTool` does what the old wrapper did: it checks the input, runs the tool with the actor's permissions, records the call as made by an agent (`via: "ai"`), and returns a CMS error (`{ error, kind, message, params }`) as a result instead of throwing. `toolsFor(cms, actor, only)` replaces the `only` option. If you used `remoteCmsTools` or `remoteCmsToolsFor`: ```ts import { createCmsClient } from "@mainsoft/agent-cms/client"; import { toolErrorResult } from "@mainsoft/agent-cms/tools"; const api = createCmsClient({ url, key }); const tools = await api.listTools(); // only what the key may use; each has a JSON Schema const run = (name: string, args: Record) => api.call(name, args).catch((e) => toolErrorResult(e) ?? Promise.reject(e)); ``` ## 2. Schema version 3 ```sh npx @mainsoft/agent-cms migrate check # what is missing npx @mainsoft/agent-cms migrate apply # or `migrate print` and run the SQL yourself ``` The step only adds things, and is safe to run twice: - `cms_documents.updated_by_agent`, `cms_versions.author_agent`, `cms_audit.actor_agent` (text, nullable). - Tables `cms_assets` and `cms_asset_refs` for the media library that ships with 0.8. They stay empty until you configure a file store. Until it has run, the CMS answers `schema_outdated`, as with every schema change. ## 3. An agent acting for a person When an agent in your app works with a signed-in person's permissions, say so on the actor: ```ts await callTool(cms, { ...user, agent: { label: "assistant" } }, "patch_document", args); ``` Permissions are exactly the person's. The version, the document and the audit log also record the agent's name, the edit shows up under "Agent changes" for review, and the admin shows it as "assistant, Kim". Only code that calls the CMS in-process can set this; REST and MCP never accept it (the handler drops it even if `resolveUser` returns it). Type changes that follow: `CmsDoc.updatedByAgent`, `CmsVersion.authorAgent`, `AuditEntry.actorAgent` and `DocSummary.updatedByAgent` are new (`string | null`). `AgentChange.authorKind` can now be `"user"`, and `AgentChange.behalf` names the person the agent acted for. A custom `CmsRepo` has new methods for files (`insertAsset` … `listAssetRefs`); `MemoryRepo` and `DrizzleRepo` implement them. ## 4. The media library is opt-in Nothing changes until you pass `media` to `createCms` ([Media library](/docs/media-library)). Two things to know even if you never do: - `parseMarkdown` has a new block (`media`) and two new inlines (`image`, `file`). A renderer with an exhaustive `switch` needs cases for them; one that ignores unknown blocks shows nothing for a media line. - A line that is only `![alt](https://…)` used to render as text and is now an image block. `![alt](asset:…)` in a body is checked on save: without a media library it fails with `asset_missing`. When you turn it on: re-export `cmsAssets` and `cmsAssetRefs` from your Drizzle schema next to the other tables, add the same `media` object to `agent-cms.config.ts`, and run `npx @mainsoft/agent-cms storage check --origin https://your-site` once per environment. ## 5. Admin screens Run `npx @mainsoft/agent-cms add --update` (or `--diff` first) to get this version of the screens you copied. What changed in them: - `cms-doc-editor` now imports `./cms-media-picker` (and `cms-upload.ts` with it), also in apps without a media library; `add` brings both. - `cms-shell`'s `hrefFor` may be asked for `{ kind: "media" }`. The default is `/media`; add that page with `cms-media` when you turn the library on. - New strings start with `media_` in `cms-messages.ts` (English and Korean). --- # Upgrade to 0.10 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-10 The schema is version 4, deleting means the trash, schedules need a cron call, and four screens have new parts. 0.10.0 is the first npm release after 0.7.0 and contains 0.8.0 and 0.9.0. Coming from 0.7.0, do [Upgrade to 0.8](/docs/upgrade-0-8) first. 0.9.0 needs nothing. ## 1. Schema version 4 ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply # or `migrate print` and run the SQL yourself ``` The step only adds things and is safe to run twice: - columns on `cms_documents` (`deleted_at`, `deleted_by`, `schedule`, `due_at`, `review`), on `cms_versions` (`label`, `pinned`, `approved_by`, `approved_at`) and on `cms_assets` (`deleted_at`, `deleted_by`) - the tables `cms_comments`, `cms_releases`, `cms_saved_filters` and `cms_presence` Re-export `cmsComments`, `cmsReleases`, `cmsSavedFilters` and `cmsPresence` from your Drizzle schema next to the other tables. ## 2. Deleting now means the trash `cms.remove`, `DELETE /collections/:c/:slug`, the `delete_document` tool and deleting a file used to be final. They now put the document or file in the trash for 30 days. - A trashed document is not found by `get`, `list`, search or agents. Its address stays taken: creating a document with the same slug fails with `slug_in_trash` until it is restored or purged. - A trashed file's object stays in the bucket until it is purged, so a public address keeps answering until then. - `createCms({ trash: { days: 0 } })` keeps the old behaviour. Tests that count rows after a delete want this, or `cms.trash.purge(admin, "all")`. - Old trash is emptied when `cms.runScheduled()` runs (next section). ## 3. A cron call for schedules and the trash Scheduled publishing and emptying the trash happen when `cms.runScheduled()` runs. Set `createCms({ cronSecret })` and call the route every few minutes: ``` POST /api/cms/_cron Authorization: Bearer ``` `GET` works too. Without `cronSecret` the route answers 404. On Vercel, a cron job with `CRON_SECRET` sends exactly this header. Calling it from two places at once is safe. > [!note] > Nothing publishes on its own. If no one calls the route, a scheduled document stays "Scheduled" after its time has passed. ## 4. Admin screens ```sh npx @mainsoft/agent-cms add --update npx @mainsoft/agent-cms add cms-trash cms-releases ``` - `cms-doc-editor` has two more files, `cms-flow.tsx` and `cms-paste.ts`. - `cms-doc-list` needs the shadcn `label` part; `cms-versions` needs `dialog` and `input`. - `cms-shell` links to "Releases" and "Trash" for people who can edit. The target that `hrefFor` receives has two new kinds, `releases` and `trash`: add the two routes in your app. - `cms-preview-comments` is optional: the comment box for guests on your public preview page, for links made with "Allow comments". ## 5. Review is opt-in Nothing changes until a collection asks for it: ```ts defineCollection({ slug: "guide", review: { agents: "required" } }); ``` From then on an API key, or an agent acting for a person, cannot publish a version nobody approved (`review_required`). `everyone: "required"` also stops people from approving their own request. ## 6. Type changes `CmsDoc` has `deletedAt`, `deletedBy`, `schedule`, `dueAt`, `review`. `CmsVersion` has `label`, `pinned`, `approvedBy`, `approvedAt`. `DocSummary` has `schedule` and `review`; `DocCounts` has `scheduled` and `review`. `CmsAsset` has `deletedAt`, `deletedBy`. A custom `CmsRepo` has new methods (`updateVersion`, comments, releases, filters, presence), and `findDoc`, `findDocById` and `findAsset` take `{ trashed }`. `MemoryRepo` and `DrizzleRepo` implement them. --- # Upgrading to 0.11 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-11 Schema version 5 adds three columns for files. The editor now fills the window's height. Vercel Blob and image sizes are off until you turn them on. Coming from 0.10.x. Nothing is removed and no call changes its meaning. There is one schema step and one layout change in a copied screen. ## 1. Schema version 5 ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply # or `migrate print` and run the SQL yourself ``` The step adds three columns to `cms_assets` and is safe to run twice: `focal_x`, `focal_y` (a picture's focal point, empty by default) and `rev` (how many times the file was replaced, 0 by default). Apps that create their tables at start get them by themselves. `CmsAsset` gained `focalX`, `focalY` and `rev`, and the `AssetInfo` that `assetsFor` returns gained `focal`. Code that builds a `CmsAsset` by hand (your own `CmsRepo`, test fixtures) has to fill them in. ## 2. Update the copied screens ```sh npx @mainsoft/agent-cms add --update ``` `cms-doc-editor` got a new file (`cms-body-tools.tsx`). `cms-upload.ts`, `cms-media.tsx`, `cms-media-picker.tsx`, `cms-parts.tsx` and `cms-messages.ts` changed. > [!warning] > **The editor's height.** On wide screens the editor used to grow with its content and scroll with the page. It now takes the window's height and scrolls inside itself, which is what lets the text and the preview scroll together. If your admin has a bar above the editor, pass the height that is left: ``. Phones are unchanged. ## 3. New, off until you turn it on - **Vercel Blob:** `npm install @vercel/blob`, then [`vercelBlobStorage`](/docs/media-library#vercel-blob) as a store's adapter. - **Image sizes:** `npm install sharp`, then [`media.transforms`](/docs/media-library#image-sizes). Node runtime only. - **Camera data:** `media.stripMetadata: true`. - Replacing a file, the focal point and carrying on an upload after a reload need no setting. They appear in the media screen after step 2. ## 4. If you wrote your own storage adapter Nothing to do. `StorageAdapter` gained three optional members: `multipart` (set it to `false` if your storage cannot take a file in parts; the CMS then sends every file in one request), `settle(key, options)` (called once after a browser upload passed its checks) and `size` in the options of `presignPut` (the size the uploader declared). A replaced file keeps its address. The CMS adds `?v=` to the addresses it hands out; how long a CDN in front of a public bucket keeps the old content is the CDN's setting. --- # Upgrading to 0.12 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-12 Schema version 6 adds three tables for jobs and webhooks. The cron call now also sends webhooks. Webhooks stay off until you set secretsKey. ## 1. Schema version 6 Three new tables: `cms_jobs`, `cms_webhooks`, `cms_webhook_deliveries`. Nothing existing changes. ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply # or `migrate print` and run the SQL yourself ``` If your Drizzle schema file re-exports the tables, add `cmsJobs`, `cmsWebhooks` and `cmsWebhookDeliveries` (a fresh `init` writes them). ## 2. The cron call does more `POST /_cron` used to run scheduled publishing and empty the trash. It now also runs background jobs, which is how webhooks go out. Its answer has a new `jobs` field (`{ran, ok, retried, failed, waiting}`); the old fields are unchanged. If you call it once a day, webhooks are delivered once a day: call it every minute or so when you use them. Without a cron service: `npx @mainsoft/agent-cms cron --watch`. ## 3. Webhooks are opt-in Nothing is sent until you set `secretsKey` (32+ characters) and an admin makes a webhook. Add the screen with `npx @mainsoft/agent-cms add cms-webhooks` and a page at `/admin/webhooks`. ## 4. Screens `npx @mainsoft/agent-cms add --update` brings `cms-shell` (the Webhooks entry, plugin menu entries) and `cms-messages`. Other screens are unchanged. ## 5. Types - `CollectionConfig.hooks` gained `beforeChange`, `beforePublish`, `beforeDelete`. - `CreateCmsOptions` gained `secretsKey`, `webhooks`, `plugins`, `onEvent`. - A custom `CmsRepo` needs the new job and webhook methods (`insertJob`, `claimJobs`, … `failWebhook`, `pruneDeliveries`); `MemoryRepo` and `DrizzleRepo` have them. - New error codes: `webhook_not_found`, `delivery_not_found`, `forbidden_webhooks`, `secrets_key_missing`, `webhook_url_blocked`, `webhook_event_unknown`, `hook_rejected`. --- # Upgrading to 0.13 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-13 Schema version 7 adds one table for automations and roles. Four new screens. Nothing changes for an existing app until you use them. ## 1. Schema version 7 One new table: `cms_records`. It holds automations, their run history and roles. Nothing existing changes. ```sh npx @mainsoft/agent-cms migrate check npx @mainsoft/agent-cms migrate apply # or `migrate print` and run the SQL yourself ``` If your Drizzle schema file re-exports the tables, add `cmsRecords` (a fresh `init` writes it). ## 2. Roles change nothing until you make one Who may do what is decided in this order: the system, then a collection's own `access` functions in code, then roles, then the default (admins only). An app that never makes a role behaves exactly as before. See [Automations, roles and the dashboard](/docs/automations). ## 3. Automations run with the cron call An automation's work is a background job, so it runs on the next `POST /_cron`, the same call that sends webhooks. A new automation made on the screen starts switched off. ## 4. Screens `npx @mainsoft/agent-cms add --update` brings `cms-shell` (Dashboard, Automations, Roles, Import and export) and `cms-messages`. Then add the new ones and a page for each: ```sh npx @mainsoft/agent-cms add cms-dashboard cms-automations cms-roles cms-transfer ``` | Screen | Page | Who sees the menu entry | |---|---|---| | `CmsDashboard` | `/admin/dashboard` | Everyone who is signed in | | `CmsAutomations` | `/admin/automations` | Admins | | `CmsRoles` | `/admin/roles` | Admins | | `CmsTransfer` | `/admin/transfer` | Admins | ## 5. REST and CLI - New routes: `GET /openapi.json`, `GET /_stats`, `GET /export`, `POST /import`, `/automations…`, `/roles…`. `GET /_me` returns `dashboard`, `automations`, `roles`. - `openapi.json` is now a reserved name: a collection cannot have that slug. - New commands: `export [--with-files]`, `import `, `import --from json|csv|wordpress`, `openapi`. See [Export and import](/docs/import-export) and [OpenAPI and other servers](/docs/openapi). - New entry `@mainsoft/agent-cms/adapters/node`. ## 6. Types - `CreateCmsOptions` gained `users` and `automations`. - A custom `CmsRepo` needs the record methods (`insertRecord`, `findRecord`, `findRecordByKey`, `listRecords`, `updateRecord`, `deleteRecords`) and `versionsSince`; `MemoryRepo` and `DrizzleRepo` have them. - New error codes: `name_taken`, `role_not_found`, `role_last_admin`, `forbidden_roles`, `automation_not_found`, `automation_invalid`, `forbidden_automations`. --- # Upgrading to 0.14 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-14 No schema change. Request limits, key rotation, retention, more hooks and the events stream are all off until you set them. From 0.13.x. See [Limits, key rotation, retention and events](/docs/operations). There is no schema change and nothing behaves differently until you set one of the new options. ## 1. Screens ```sh npx @mainsoft/agent-cms add --update # cms-keys, cms-messages ``` The keys screen gains "Rotate", "Requests per minute" and "Allowed addresses". ## 2. Request limits are off until you set them ```ts createCms({ rateLimit: { perMinute: 600, anonymousPerMinute: 120 }, }); ``` - `perMinute` is for each API key; a key's own `rateLimit` wins over it. - `anonymousPerMinute` is for each address that sends no key and has no session. Signed-in people are not counted. - Over the limit: 429 `rate_limited`, `Retry-After` in seconds. - Counting is per server process. With several servers, or on serverless, give a shared store: ```ts rateLimit: { perMinute: 600, store: { hit: async (bucket, ttlMs) => { const n = await redis.incr(bucket); if (n === 1) await redis.pexpire(bucket, ttlMs); return n; } }, } ``` The caller's address is read from `X-Forwarded-For` (first entry), then `X-Real-IP`. If your server is not behind a proxy that sets those, a client can send the header itself: pass `createCmsHandler({ clientIp: (req) => … })`. ## 3. Rotating a key `POST /keys/:id/rotate` with `{ "graceMinutes": 60 }` returns a new secret. The old one works until the grace time ends. `0` cuts it off at once. A rotated key shows as "Replaced" in the list once its time is over. ## 4. Retention is off until you set it ```ts createCms({ retention: { auditDays: 365, hitsDays: 400, revokedKeysDays: 90 } }); ``` It runs with the cron call, at most once a day. Try it first: `npx @mainsoft/agent-cms retention --dry-run` (an admin key). ## 5. Types - `CreateCmsOptions` gained `rateLimit` and `retention`; `CmsHandlerOptions` gained `clientIp`. - `CmsKey` gained `rateLimit`, `allowedIps`, `revokedReason`, `rotatedTo`. A key with `revokedAt` in the future is a rotated key that still works: compare with the current time before calling it revoked. - A custom `CmsRepo` needs `prune(what, before, dryRun)`, and `revokeKey` must accept a time in the future. `MemoryRepo` and `DrizzleRepo` do both. - New hooks on a collection: `beforeValidate`, `afterPublish`, `afterDelete`, `afterRead`. - New error codes: `rate_limited` (429), `forbidden_ip`, `forbidden_admin`, `invalid_ip_range`, `invalid_rate_limit`. - `retention`, `_events` and `auth` are reserved names: a collection cannot have those slugs. --- # Upgrading to 0.15 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-15 Schema 8 adds one column. The block editor, HTML, agent file tools and publish checks are all opt-in. From 0.14.x. **Schema 8**: one new column, `cms_documents.body_format` (`text`, default `'markdown'`). Everything else is off until you use it. ## 1. Database ```sh npx @mainsoft/agent-cms migrate check # shows the one step npx @mainsoft/agent-cms migrate apply # or run the printed SQL yourself ``` The step is `ALTER TABLE cms_documents ADD COLUMN IF NOT EXISTS body_format text NOT NULL DEFAULT 'markdown'`. Existing documents stay markdown. ## 2. Screens ```sh npx @mainsoft/agent-cms add --update # every screen you have npx @mainsoft/agent-cms add cms-block-editor # optional: the block editor ``` Pass the block editor as a slot, ideally lazily: ```tsx const CmsBlockEditor = lazy(() => import("@/components/cms/cms-block-editor")); const slots = { blockEditor: CmsBlockEditor }; ``` Without the slot the editor stays the markdown text box. The body is stored as markdown either way. ## 3. Korean screen text The `ko` catalogs (screens and server errors) now use 음슴체 ("저장 실패", "대표 이미지 없음"). If you overrode Korean strings, check that yours still match the tone. ## 4. HTML - `:::html` blocks and HTML documents are stored as written. What would not work on the page comes back as `html_inert` warnings. - Adding or changing HTML needs the role permission `html` (admins have it). API keys need the new `html` scope. Running HTML (`:::html isolated` with `html: { render: "isolated" }`) needs `html_scripts`. - To render HTML on your site use `@mainsoft/agent-cms/html` (`sanitizeHtml`, `markdownToHtml`, `bodyToSafeHtml`). Never insert a stored body as HTML without it. - HTML documents are off: turn them on per collection with `body: { formats: ["markdown", "html"] }`. ## 5. Agents New tools `read_document`, `grep_documents`, `edit_document`, `write_document`, `document_file_link`; the old tools stay. If an agent should only suggest, set `agentEdits: "suggest"` on the collection. ## 6. Types and behaviour - `Inline` gains `em`, `del`, `br`, and `strong` may carry `kids`; `Block` gains `todo`, `table`, `toggle`, `columns`, `html`, `raw`, and `list.start`. A renderer with a `switch` over block types should handle (or skip) the new ones. - `DocContent.format` (`"html"` or absent), `CollectionConfig.body.formats`, `html`, `agentEdits`, `publishChecks`. - New error codes: `forbidden_html`, `forbidden_html_scripts`, `raw_link_invalid`, `raw_link_expired`, `suggestion_not_found`, `suggestion_stale`, `format_not_allowed`, `edit_not_found`, `edit_not_unique`, `edit_invalid`, `file_invalid`, `pattern_invalid`, `publish_check_failed`, `zip_too_large`; validation errors carry `issues`. - `update_document`, `patch_document` and `edit_document` refuse unknown fields. - The Node adapter ignores `X-Forwarded-For` unless `toNodeHandler(handler, { trustProxy: true })`. - `grep` and `raw` are reserved: a collection cannot use those slugs. --- # Upgrading to 0.16 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-16 No schema change. People are found by name or email; the CMS can sign people in and run on its own. No schema change: everything new lives in `cms_records`. Nothing changes until you use it. 1. `npm i @mainsoft/agent-cms@0.16` and `npx @mainsoft/agent-cms add --update` (the screens changed a lot: roles, transfer, media, preview link). 2. Roles: people are now found by name or email, so the screens no longer ask for ids. `POST /roles/:id/members` also takes `{ "email": "…" }`; such a member shows `pending: true` until that person first uses the admin. The CMS remembers who has used the admin (records of kind `person`); `GET /roles/_users` returns them with `lastSeenAt`. 3. The shell needs the `dropdown-menu` part (`npx shadcn add dropdown-menu`) for the account menu. ## Optional: the CMS's own sign-in ```ts import { createAuth } from "@mainsoft/agent-cms/auth"; const auth = createAuth({ cms, sendMail /* optional */, oidc /* optional */ }); export const handler = createCmsHandler({ cms, auth }); // instead of resolveUser ``` Add the pages: `npx @mainsoft/agent-cms add cms-login cms-people cms-account`, then routes `/admin/login`, `/setup`, `/invite`, `/reset` (outside the admin frame), `/admin/people` and `/admin/account`. The first admin signs up with the setup code the server prints. ## Optional: run the CMS on its own ```bash npx @mainsoft/agent-cms dev # try it npx @mainsoft/agent-cms serve # with server: { cms } in agent-cms.config.ts ``` See `examples/server` for Docker and compose. --- # Upgrading to 0.17 Source: https://agent-cms-docs.vercel.app/docs/upgrade-0-17 Schema 9 adds the change log and indexes. Events reach every server; lists are paged in the database. **Schema 9**: one new table (`cms_changes`, the change log) and eleven indexes. Run ```sh npx @mainsoft/agent-cms migrate check # prints the SQL npx @mainsoft/agent-cms migrate apply # or run it yourself ``` The step is safe to run again (`IF NOT EXISTS`). On big tables, create the indexes `CONCURRENTLY` yourself first if writes must not wait. `npx @mainsoft/agent-cms doctor` reports any index that is still missing. ## What changes without you doing anything - **Lists are paged in the database.** `cms.page()`, `GET /collections/` and `list_documents` filter, sort and cut in SQL and page by the last row (cursor `k.…`). Old numeric cursors still work. `total` is still there. - **Events reach every server.** Every event is written to the change log; the events stream (`/_events`) follows it, so a browser hears what any server did. Message ids are numbers in the log; a client that comes back gets exactly what it missed. The log keeps 7 days (`changes.keepDays`), pruned by the cron call. - **The core no longer imports `node:crypto`.** It runs on Edge runtimes. Webhook secrets still need Node's crypto (Node, Bun, Deno, Workers with `nodejs_compat`). - **Links like `/\host`** are no longer links (browsers read them as another site). - **`afterRead` runs on list rows too** (`ctx.list` is true there). ## New, when you want it | Option | What it does | |---|---| | `createCms({ cache: memoryCache() })` | Readers are served from a cache; publishing empties it here at once and on other servers within `changes.pollMs` | | `createCms({ changes: { signal } })` | Other servers hear changes at once (`pgChangeSignal`, `postgresJsChangeSignal`), not on the next look (2 s) | | `@mainsoft/agent-cms/db` | `connectPostgres(url)` with `pg`, `postgres`, `@neondatabase/serverless` (WebSocket or HTTP) or PGlite | | `DrizzleRepo(db, { transactions: "auto" })` | Works on drivers without transactions (neon-http), with a warning | | `@mainsoft/agent-cms/tenants` | Several sites in one app: a Postgres schema per site | | `fieldAccess`, `fieldHooks`, `hooks.beforeRead` | Hide or lock single fields per reader; field hooks; refuse reads | | Roles on media stores | A role can let people upload (`write`) and delete without being an admin | | `slots.editorActions`, `editorPanel`, `fieldAddon` | Your buttons and panels in the document editor | | `server.metricsToken` / `CMS_METRICS_TOKEN` | Prometheus numbers on `/metrics`; or `createMetrics()` with `onEvent` | | `GET /_changes?since=` | Polling instead of the stream | | `config.plugins` | `migrate` includes plugin tables | | CLI | `doctor --fix`, `import --from notion`, `user create`, `user reset-link`, `npm run bench` | ---