Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/write-verbs-save-act.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@tanstack/cms-core': minor
'@tanstack/cms-api': minor
'@tanstack/cms-client': minor
---

`save` and `act` are the canonical writes, rooted in the operations registry beside `get` and `list` (`writeVerbs`, `saveInput`, `actInput` in `@tanstack/cms-core`). Every write is an action of the collection's document state strategy, and both return `{ id, collection, doc, state: { label, published, revision, changeSet }, availableActions }`.

- Server: `cmsAs(cms, ctx).save({ collection, id, doc, create?, publish?, expectedRevision?, expectedPendingVersion?, instruction? })` and `.act({ collection, id, action, publishAt?, reason?, expectedVersion? })`, and the argument forms `saveAs(ctx, options)` and `actAs(ctx, options)`. `save` merges `doc`, a patch, onto the caller's own open change set or the live document. The caller picks the action: an agent `submit`s for review, a publisher `edit`s (a draft of a published document unless `publish` is set), and anyone else `submit`s. `act` runs an action the strategy offers the caller (`approve`, `reject`, `discard`, `schedule`, or a custom step). `documentWriteState(collection, id)` reads the `state` on its own.
- HTTP and Start: the `save` (`content.write`) and `act` operations, and Start server functions.
- Client: `client.save(options)` and `client.act(options)`, typed from `Register`.
- Agents: `save_document`, named `<verb>_<noun>` from the registry. An agent's save is always staged for review. `act` is not an agent tool.
- Reads that feed a write: `get` takes `staged: false` (in `getInput`, so on every surface) to read the committed document without its staged changes, published or not. It is the canonical form of `readDocumentAs` in an `edit` or system context.

**Breaking:** `save`, `act` and `save_document` are reserved operation names, so an app op with one of these names fails as a duplicate.

`saveDoc`, `createDoc` and `actOnChange` (operations), and `create_document` and `update_document` (agent tools), are deprecated in favour of `save` and `act`. They now run on the same path and keep their bags and results.
2 changes: 1 addition & 1 deletion docs/agents/content-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const reply = await chat({

### Tools and Permissions

The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`.
The agent uses the [agent tools](../mcp/operations-registry#the-agent-tool-registry-opschemas): `list_collections`, `list_documents`, `get_document`, `search_documents`, `list_revisions`, `list_translations`, and the write tools `save_document`, `create_document` and `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, and `schedule_document`.

The tools run with the signed-in user's session, so the agent sees only the collections and fields that user may read, and preserves fields they may not write. Every write is **staged** in the [review queue](./review-queue) with `actor: 'content-agent'`, even when an admin is chatting. When the agent stages something, the page shows a **Review changes** link to `/review`.

Expand Down
2 changes: 1 addition & 1 deletion docs/agents/review-queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ An agent often makes several edits to the same document before anyone reviews th

The pending change belongs to the door that opened it: an agent proposal (`agent`), an author's save (`review`) or a publisher's draft (`draft`). While it is open, a write through another door fails with `CONFLICT` and `details: { pendingId, source }` naming it. Approve, reject or discard it first.

Agents can read their own staged work. `get_document` (in the agent's `edit` mode) and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue.
Agents can read their own staged work. `get_document` (in the agent's `edit` mode), `save_document` and `update_document` read the pending version, including a document that hasn't been committed yet, so an agent can create a document, read it back, and refine it before anyone approves. `list_documents` lists committed documents; staged creates appear in the review queue.

## Reviewing Changes

Expand Down
27 changes: 26 additions & 1 deletion docs/api/cms-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,31 @@ console.log(about?.doc, first.items.length, next?.total)

`get` resolves to `{ id, collection, doc }`, or `null` when the document is missing or the caller can't see it. `list` resolves to `{ items: [{ id, collection, doc }], total, nextCursor? }`. Both are public: anonymous callers read published documents, and callers who may read drafts see the working copy unless the client's `mode` is `live`.

### `save(options)` and `act(options)`

The canonical writes, the `save` and `act` operations, with the bags of [`saveAs` and `actAs`](./cms-core-server#saveasctx-options-and-actasctx-options). `save` takes a patch: only the fields to change. Both resolve to `{ id, collection, doc, state, availableActions }`. `state.label` names where the document stands (`Published`, `Draft`, `Pending Review`), and `state.revision` and `state.changeSet?.version` are what the next save sends as `expectedRevision` and `expectedPendingVersion`.

```ts validate=type
import { createCmsClient } from '@tanstack/cms-client'

const cms = createCmsClient({
baseUrl: 'https://cms.example.com',
getAuthHeader: () => 'Bearer tscms_example',
})

const saved = await cms.save({ collection: 'post', id: 'hello', doc: { title: 'Hello again' } })
if (saved.availableActions.some((a) => a.type === 'approve'))
await cms.act({ collection: 'post', id: 'hello', action: 'approve' })
const next = await cms.save({
collection: 'post',
id: 'hello',
doc: { excerpt: 'Short' },
expectedRevision: saved.state.revision,
expectedPendingVersion: saved.state.changeSet?.version ?? 0,
})
console.log(next.state.label)
```

### `op(name, input)` and `call<T>(name, input?)`

`op(name, input)` calls any built-in operation by name: a `POST` with a JSON body to `<baseUrl>/api/cms/v1/ops/<name>`, resolving to the `result`. Input and output are typed per operation. `call<T>(name, input?)` hits the same endpoint for untyped or dynamic operations — including agent tools (`list_documents`, `search_documents`, …) and app-defined operations registered with `defineCms({ ops })`. The list of operations and their access levels is in [Routes & HTTP Endpoints](./routes-and-endpoints#operations).
Expand All @@ -101,7 +126,7 @@ console.log(found?.collection, redirect?.to, custom.count)

### `collection(name)`

Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads; for content, use the client's `get` and `list`:
Typed helpers for one collection, wrapping the older document operations. Its `list` and `get` are the admin editor's reads, and `save` and `create` the deprecated `saveDoc` and `createDoc`; for content, use the client's `get`, `list` and `save`:

| Method | Operation | Access | Returns |
| --- | --- | --- | --- |
Expand Down
104 changes: 100 additions & 4 deletions docs/api/cms-core-server.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ Contexts are frozen and come from the builders. A copied object is not a context
### `cmsAs(cms, ctx)`

```ts
function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsReads
function cmsAs(cms: Cms | CmsConfig, ctx: AccessContext): CmsAs // CmsReads & CmsWrites
```

The read verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned). `get` and `list` are the canonical reads (see [`getAs` and `listAs`](#getasctx-options-and-listasctx-options)). The older vocabulary is bound too: `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`.
The read and write verbs bound to `ctx`, scoped to `cms` (a `createCms` instance or the config `defineCms` returned). `get` and `list` are the canonical reads (see [`getAs` and `listAs`](#getasctx-options-and-listasctx-options)), and `save` and `act` the canonical writes (see [`saveAs` and `actAs`](#saveasctx-options-and-actasctx-options)). The older vocabulary is bound too: `queryDocuments`, `groupDocuments`, `queryDocumentSummaries`, `listDocuments`, `readDocument`, `readDocumentWithPending`, `readSingleton`, `readDocumentBySlug`, `findDocumentBySlug`, `populateRelations`, `findReferences`, `listTranslations` and `listRevisions`, plus `context`. They take the same arguments as the `…As` functions below, without the context. Documents the context can't read come back as missing, and fields it can't read are removed. `postRead` hooks receive the context as `access`.

```ts validate=type
import { defineCms } from '@tanstack/cms-core'
Expand Down Expand Up @@ -110,7 +110,7 @@ export async function sitemapIds() {
}
```

Each verb also has an argument form taking the context first: `getAs(ctx, options)`, `listAs(ctx, options)`, `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These read against the registered CMS.
Each verb also has an argument form taking the context first: `getAs(ctx, options)`, `listAs(ctx, options)`, `saveAs(ctx, options)`, `actAs(ctx, options)`, `queryDocumentsAs(ctx, options)`, `readDocumentAs(ctx, collection, id)`, `readDocumentBySlugAs`, `findDocumentBySlugAs`, `readSingletonAs`, `readDocumentWithPendingAs`, `queryDocumentSummariesAs`, `listDocumentsAs`, `groupDocumentsAs`, `populateRelationsAs`, `findReferencesAs`, `listTranslationsAs` and `listRevisionsAs`. These run against the registered CMS.

### Checks

Expand Down Expand Up @@ -139,6 +139,7 @@ function listAs(ctx: AccessContext, options?: ListOptions): Promise<ListResult>

type GetOptions = {
collection: string
staged?: boolean // `false`: the committed document, without staged changes
locale?: string // with `locator`: match the document in this locale
populate?: boolean // default false
} & ({ id: string } | { locator: string }) // exactly one
Expand Down Expand Up @@ -168,10 +169,28 @@ interface ListResult<TDoc = Doc> {
}
```

The canonical reads. One bag each, the same at every layer: the store (`cmsAs(cms, ctx).get/list`), HTTP and Start (the `get` and `list` operations), `@tanstack/cms-client` (`client.get/list`), and the agent tools (`get_document`, `list_documents`). The bag carries no visibility. The context decides it:
The canonical reads. One bag each, the same at every layer: the store (`cmsAs(cms, ctx).get/list`), HTTP and Start (the `get` and `list` operations), `@tanstack/cms-client` (`client.get/list`), and the agent tools (`get_document`, `list_documents`). The writes, `save` and `act`, follow the same pattern. The bag carries no visibility. The context decides it:

- A `live` context reads published documents only.
- A `preview` or `edit` context reads the working copy, with staged changes overlaid.
- `get` with `staged: false` reads the committed document instead, published or not: the row a write must see. Use it for a read that feeds a write, such as a read-modify-write or a check for an existing document before a create.

```ts validate=type
import { commitDocument, getAs, systemContext } from '@tanstack/cms-core/server'

const CARTS = systemContext('carts are server-owned records')

export async function addToCart(cartId: string, variantId: string) {
const cart = await getAs(CARTS, { collection: 'cart', id: cartId, staged: false })
const items = JSON.parse(String(cart?.doc.itemsJson ?? '[]')) as Array<string>
await commitDocument(
'cart',
cartId,
{ ...cart?.doc, itemsJson: JSON.stringify([...items, variantId]) },
{ expectedRevision: Number(cart?.doc._revision ?? 0) },
)
}
```

A `locator` is the document's slug or its id, with leading slashes ignored. A document that is missing, or that `ctx` can't see, is `null` from `get` and absent from `list`. Documents are redacted for `ctx`, and filtering or sorting on a field it can't read is `FORBIDDEN`. Both functions validate the bag (`getInput`, `listInput` from `@tanstack/cms-core`) and throw `BAD_REQUEST` for an invalid one.

Expand Down Expand Up @@ -464,6 +483,83 @@ How a save behaves depends on the document and the caller:

Every commit records a revision and bumps `_revision`. Pass the revision you loaded as `expectedRevision` to fail with `CONFLICT` when someone else saved in the meantime.

`saveAs` and `actAs` are the canonical writes: they pick the door from the caller and report where the document stands. The functions after them are the doors themselves.

### `saveAs(ctx, options)` and `actAs(ctx, options)`

```ts
function saveAs(ctx: AccessContext, options: SaveOptions): Promise<WriteResult>
function actAs(ctx: AccessContext, options: ActOptions): Promise<ActResult>

interface SaveOptions {
collection: string
id: string
doc: Record<string, unknown> // the fields to change; `null` clears one
create?: boolean // fail with CONFLICT when the document exists
publish?: boolean // a published document: go live now instead of a draft
expectedRevision?: number // the live `_revision` you loaded (0 for none)
expectedPendingVersion?: number // the open change set's version (0 for none)
instruction?: string // review queue note and revision summary
}

interface ActOptions {
collection: string
id: string
action: string // one of the document's `availableActions`
publishAt?: string | null // `schedule`
reason?: string // for the audit trail
expectedVersion?: number // the open change set's version you loaded
}

interface WriteResult<TDoc = Doc> {
id: string
collection: string
doc: TDoc // the working copy: the open change set, else live (redacted)
state: {
label: string // the strategy's name for the state: 'Published', 'Draft', 'Pending Review', …
published: boolean
revision: number // the next `expectedRevision`
changeSet: { id: string; version: number; source: 'agent' | 'review' | 'draft'; publishAt: string | null } | null
}
availableActions: Array<ActionDescriptor> // what ctx can do next
}

type ActResult<TDoc = Doc> = Omit<WriteResult<TDoc>, 'doc'> & { doc: TDoc | null }
```

The canonical writes, one bag each at every layer: the store (`cmsAs(cms, ctx).save/act`), HTTP and Start (the `save` and `act` operations), `@tanstack/cms-client` (`client.save/act`), and the agent tool `save_document`. Each is an action of the collection's [document state strategy](../agents/review-queue#choosing-the-flow-document-state-strategies).

`save` merges `doc`, a patch, onto the caller's working copy: their own open change set, else the live document. A missing document is created, with the collection's field defaults. Who the caller is picks the action:

- **An agent** (an agent context, or the `save_document` tool) `submit`s: the change is staged for review, and `publish` is ignored.
- **A caller who may publish the collection** (or a system context) `edit`s: the change commits, except that a published document gets a draft unless `publish` is set (as `commitDocument` and `saveDraft` do).
- **Anyone else** (an author) `submit`s for review.

Another door's open change set refuses the save with `CONFLICT` until it's resolved. A public context is `UNAUTHORIZED`.

`act` runs one of the actions the strategy offers `ctx` now (`approve`, `reject`, `discard`, `schedule`, or a custom one such as `approve:legal`). An action that isn't offered is `FORBIDDEN`, and the change-carrying actions (`edit`, `submit`, `draft`, `import`) are `save`'s. Its `doc` is `null` once the document is gone (a rejected create, an applied delete).

The result feeds straight back into an editor: `doc` is the next baseline, and `state.revision` and `state.changeSet?.version` are the next save's `expectedRevision` and `expectedPendingVersion`.

```ts validate=type
import { accessContext, cmsAs, resolveSession } from '@tanstack/cms-core/server'
import type { Cms } from '@tanstack/cms-core'

export async function rename(cms: Cms, request: Request, id: string, title: string) {
const db = cmsAs(cms, accessContext({ session: await resolveSession(request) }))
const current = await db.get({ collection: 'post', id })
const saved = await db.save({
collection: 'post',
id,
doc: { title },
expectedRevision: typeof current?.doc._revision === 'number' ? current.doc._revision : 0,
})
if (saved.availableActions.some((a) => a.type === 'approve'))
await db.act({ collection: 'post', id, action: 'approve' })
return saved.state.label
}
```

### `commitDocument(collection, id, doc, options?)`

```ts
Expand Down
2 changes: 1 addition & 1 deletion docs/api/cms-core.md
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ interface OpSchema {
const opSchemas: Array<OpSchema>
```

The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations` (read), and `create_document`, `update_document`, `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry).
The agent tool set, shared by the content agent, the HTTP MCP server, and WebMCP: `list_collections`, `list_documents`, `get_document`, `read_document` (deprecated), `search_documents`, `list_revisions`, `list_translations` (read), and `save_document`, `create_document` (deprecated), `update_document` (deprecated), `delete_document`, `unpublish_document`, `restore_revision`, `schedule_document` (write, always staged for review). The server runs them with `runOp()` from `@tanstack/cms-core/server`. See [Shared Operation Registry](../mcp/operations-registry).

These agent tools are separate from the HTTP API operations (`saveDoc`, `getPublicDocument`, …) in [`@tanstack/cms-api`](./cms-api).

Expand Down
Loading
Loading