@elytracms/studio 0.0.95 → 0.0.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/convex/cms.ts +272 -16
- package/convex/delivery-folded-drift.test.ts +104 -0
- package/convex/delivery.ts +24 -8
- package/convex/depth-codec-lookalike.test.ts +192 -0
- package/convex/fixture-accounts.test.ts +305 -0
- package/convex/fixtureAccounts.ts +298 -0
- package/convex/incarnation.test.ts +149 -0
- package/convex/ingest.test.ts +145 -3
- package/convex/ingest.ts +123 -17
- package/convex/receipt-races.test.ts +184 -0
- package/convex/records-zod-copy.test.ts +76 -0
- package/convex/schema.ts +20 -1
- package/convex/strict-delete.test.ts +129 -0
- package/convex/strict-reference-race.test.ts +139 -0
- package/dist/components/ai/ai-chat-panel.js +15 -2
- package/dist/components/ai/ai-chat-panel.js.map +1 -1
- package/dist/components/ai/translate-document-action.d.ts +6 -0
- package/dist/components/ai/translate-document-action.js.map +1 -1
- package/dist/components/ai/translate-document-dialog.d.ts +1 -1
- package/dist/components/ai/translate-document-dialog.js +5 -5
- package/dist/components/ai/translate-document-dialog.js.map +1 -1
- package/dist/components/assets/asset-detail.js +5 -2
- package/dist/components/assets/asset-detail.js.map +1 -1
- package/dist/components/assets/asset-locale.d.ts +7 -0
- package/dist/components/assets/asset-locale.js +16 -2
- package/dist/components/assets/asset-locale.js.map +1 -1
- package/dist/components/assets/asset-meta-drift-notice.d.ts +13 -0
- package/dist/components/assets/asset-meta-drift-notice.js +22 -0
- package/dist/components/assets/asset-meta-drift-notice.js.map +1 -0
- package/dist/components/assets/asset-meta-label.d.ts +2 -1
- package/dist/components/assets/asset-meta-label.js +4 -2
- package/dist/components/assets/asset-meta-label.js.map +1 -1
- package/dist/components/assets/asset-metadata.d.ts +33 -13
- package/dist/components/assets/asset-metadata.js +46 -22
- package/dist/components/assets/asset-metadata.js.map +1 -1
- package/dist/components/assets/asset-search.d.ts +6 -2
- package/dist/components/assets/asset-search.js +15 -5
- package/dist/components/assets/asset-search.js.map +1 -1
- package/dist/components/assets/assets-collection-view-source.d.ts +5 -3
- package/dist/components/assets/assets-collection-view-source.js +7 -5
- package/dist/components/assets/assets-collection-view-source.js.map +1 -1
- package/dist/components/builder/canvas-rebase.d.ts +36 -12
- package/dist/components/builder/canvas-rebase.js +13 -3
- package/dist/components/builder/canvas-rebase.js.map +1 -1
- package/dist/components/builder/canvas-render-context.js +5 -4
- package/dist/components/builder/canvas-render-context.js.map +1 -1
- package/dist/components/builder/composition-field-editor.d.ts +12 -6
- package/dist/components/builder/composition-field-editor.js +6 -5
- package/dist/components/builder/composition-field-editor.js.map +1 -1
- package/dist/components/cms/asset-picker-core.d.ts +2 -2
- package/dist/components/cms/asset-picker-core.js +2 -2
- package/dist/components/cms/asset-picker-core.js.map +1 -1
- package/dist/components/cms/asset-picker.js +3 -1
- package/dist/components/cms/asset-picker.js.map +1 -1
- package/dist/components/cms/canvas-commit.d.ts +6 -0
- package/dist/components/cms/canvas-commit.js +5 -1
- package/dist/components/cms/canvas-commit.js.map +1 -1
- package/dist/components/cms/cms-store.d.ts +24 -8
- package/dist/components/cms/cms-store.js +21 -14
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/collection-table.js +4 -11
- package/dist/components/cms/collection-table.js.map +1 -1
- package/dist/components/cms/detail-editor.js +2 -2
- package/dist/components/cms/detail-editor.js.map +1 -1
- package/dist/components/cms/draft-commit.d.ts +16 -3
- package/dist/components/cms/draft-commit.js +3 -2
- package/dist/components/cms/draft-commit.js.map +1 -1
- package/dist/components/cms/use-document-draft.d.ts +107 -10
- package/dist/components/cms/use-document-draft.js +157 -42
- package/dist/components/cms/use-document-draft.js.map +1 -1
- package/dist/components/collection-view/cms-collection-view-source.js +6 -4
- package/dist/components/collection-view/cms-collection-view-source.js.map +1 -1
- package/dist/components/components/transfer-dialog.js +6 -4
- package/dist/components/components/transfer-dialog.js.map +1 -1
- package/dist/lib/ai/chat-state.d.ts +7 -0
- package/dist/lib/ai/chat-state.js.map +1 -1
- package/dist/lib/ai/tools.d.ts +8 -0
- package/dist/lib/ai/tools.js +4 -0
- package/dist/lib/ai/tools.js.map +1 -1
- package/dist/lib/cms-views/view-model.d.ts +15 -8
- package/dist/lib/cms-views/view-model.js +19 -5
- package/dist/lib/cms-views/view-model.js.map +1 -1
- package/dist/lib/collection-view/__fixtures__/document-writes.js +1 -0
- package/dist/lib/collection-view/__fixtures__/document-writes.js.map +1 -1
- package/dist/lib/collection-view/collection-view-source.d.ts +18 -7
- package/dist/lib/collection-view/collection-view-source.js.map +1 -1
- package/dist/lib/data/collection-content.js +5 -0
- package/dist/lib/data/collection-content.js.map +1 -1
- package/dist/lib/engine-version.d.ts +1 -1
- package/dist/lib/engine-version.js +1 -1
- package/dist/lib/engine-version.js.map +1 -1
- package/dist/lib/i18n/messages.de.js +15 -1
- package/dist/lib/i18n/messages.de.js.map +1 -1
- package/dist/lib/i18n/messages.en.d.ts +13 -0
- package/dist/lib/i18n/messages.en.js +16 -1
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/operations/cms-persistence.d.ts +119 -35
- package/dist/lib/operations/cms-persistence.js +441 -91
- package/dist/lib/operations/cms-persistence.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.js +80 -8
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/persona/labels.js +2 -0
- package/dist/lib/persona/labels.js.map +1 -1
- package/package.json +4 -3
package/dist/lib/ai/tools.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/lib/ai/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAA;AAS/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;A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CAAC;oBACtB,KAAK,iBAAiB;wBACpB,OAAO,MAAM,eAAe,CAAC,MAAM,CAAC,IAA8D,CAAC,CAAA;oBACrG,KAAK,YAAY;wBACf,OAAO,MAAM,UAAU,CAAC,MAAM,CAAC,IAA0C,CAAC,CAAA;oBAC5E,KAAK,aAAa;wBAChB,OAAO,MAAM,WAAW,CAAC,MAAM,CAAC,IAA4C,CAAC,CAAA;oBAC/E,KAAK,gBAAgB;wBACnB,OAAO,MAAM,cAAc,CACzB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAAmD,CAC3D,CAAA;oBACH,KAAK,cAAc;wBACjB,OAAO,MAAM,YAAY,CACvB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAA0E,CAClF,CAAA;oBACH,KAAK,mBAAmB;wBACtB,OAAO,MAAM,SAAS,CACpB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAA2D,CACnE,CAAA;oBACH;wBACE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAA;gBACvE,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO;oBACL,EAAE,EAAE,KAAK;oBACT,SAAS,EAAE,OAAO,IAAI,CAAC,QAAQ,iBAAiB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE;iBAC3G,CAAA;YACH,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * The narrow tool set the assistant works against (EC-199, reshaped by EC-334).\n *\n * Per the ratified AD, tools execute CLIENT-side against the operations layer with\n * the user's own session. This module carries the three pieces of that contract:\n *\n * 1. {@link chatToolDefinitions} — the SDK-native tool DEFINITIONS the route's\n * chat branch declares in `streamText`, deliberately WITHOUT `execute`, so the\n * SDK forwards every call to the client (the route stays a zero-data-access\n * proxy). Plain `{ description, inputSchema }` objects with zod schemas —\n * structurally the SDK's `FunctionTool`, with no SDK import (bundle discipline).\n * 2. {@link ChatToolReaders} — the operations-backed read interface the studio\n * binds client-side (search / list / get). Reads only — the engine never gains\n * a write path; apply is a separate, human-gated draft write.\n * 3. {@link createChatToolExecutor} — the client executor map `useChat`'s\n * `onToolCall` dispatches into. Readers pass through; the terminal tools run\n * the deterministic engines (`applyContentWithShape` / `translateDocument` /\n * `buildUpdateProposal`) and return a COMPACT proposal summary as the tool\n * output — the full proposal goes to the review UI via\n * `onProposal(toolCallId, …)`, never to the model.\n *\n * EC-378: `updateFields` is the edit-flow terminal tool — the model authors\n * per-field changes directly (it has `getDocument` output + the conversation as\n * context); the executor reads the CURRENT document, builds a validated update\n * proposal (`buildUpdateProposal`), and hands it to the review sink. Its target\n * (and `getDocument`'s) may be omitted to mean the document currently open in\n * the editor — resolved via the {@link ChatToolExecutorOptions.currentDocument}\n * seam ({@link resolveDocumentTarget}); the context block the panel injects is\n * ADVISORY, the resolution here is what makes \"this document\" deterministic.\n *\n * The EC-199 planner enum/schema (`plannerSchema` / `parsePlannerAction`) retired\n * with the hand-rolled orchestrator (EC-334 slice 2).\n */\nimport { z } from 'zod'\nimport { resolveDocumentTitle } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n LocaleConfig,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport { applyContentWithShape } from './apply-content'\nimport { describeComponentProps } from './chat-context'\nimport { assetCandidatesOf, relationCandidatesOf } from './leash'\nimport type { SearchedAsset, SearchedDocument } from './leash'\nimport { translateDocument } from './translate-document'\nimport type { TranslateSkip } from './translate-document'\nimport { buildUpdateProposal } from './update-fields'\nimport type { UpdateFieldChange } from './update-fields'\nimport { componentIdsOf, toWriterDocument } from './writer-form'\nimport { aiProvenance } from './provenance'\nimport type { ChatProposal } from './chat-state'\nimport type { AiProvider, ResolvedKnowledge, WriterLeash } from './types'\n\n/** A document the model may reference as a relation target (from a `searchDocuments` read). */\nexport type DocumentSearchResult = SearchedDocument\n\n/**\n * An asset the model may reference (from a `listAssets` read). EC-588: it carries the\n * two facts a field's `accept` is judged on, so each asset position's candidates can be\n * filtered to what that position takes — and the model can see what each asset is.\n */\nexport type AssetSearchResult = SearchedAsset\n\n/**\n * The client-side, operations-backed readers the executor calls. The studio binds\n * these to the user's authenticated operations client; tests bind an in-memory fake.\n * Reads only — there is no write tool (apply is a separate, human-gated draft write).\n */\nexport interface ChatToolReaders {\n searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<DocumentSearchResult[]>\n listAssets(input: { query?: string; limit?: number }): Promise<AssetSearchResult[]>\n /**\n * Fetch a full document (values + localized) — the translate flow and the model's\n * `getDocument` tool. Optional: a studio that only wires create can omit it.\n */\n getDocument?(input: { collection: string; id: string }): Promise<CmsDocument | null>\n}\n\n/** Per-search result cap (protects the wire — results become model context). */\nexport const DEFAULT_SEARCH_LIMIT = 20\n\n// --- SDK-native chat tool definitions (EC-334) --------------------------------------\n\n/**\n * One model-facing tool definition for the route's `streamText` call. Structurally\n * the SDK's `FunctionTool` WITHOUT `execute` (execution is client-side, always) —\n * typed locally so this module needs no SDK import.\n */\nexport interface ChatToolDefinition {\n description: string\n /** Zod input schema (the AI SDK accepts zod schemas as `inputSchema` directly). */\n inputSchema: z.ZodType\n}\n\n/**\n * The tool set the native chat branch declares (EC-334). No `execute` on any entry:\n * the SDK forwards each call to the client, which executes reads against the\n * operations layer with the user's session and posts the result back; the terminal\n * tools (`createDocument` / `translateDocument`) run the deterministic engines\n * client-side and return a compact proposal summary as the tool output. The route\n * itself never executes anything.\n *\n * Collections are NOT enum-leashed here — the route has zero data access, so it has\n * no catalog; the catalog reaches the model through the request `context` (system\n * prompt), and every id a proposal references must come from a tool RESULT\n * (client-validated; `applyContentWithShape` still enum-leashes relation ids).\n */\nexport const chatToolDefinitions = {\n searchDocuments: {\n description:\n 'Search documents in a collection. Use it to find the REAL ids a relation may ' +\n 'reference, or to locate an existing document — never invent an id. Returns ' +\n '{ id, title } summaries.',\n inputSchema: z.object({\n collection: z\n .string()\n .describe('Target collection id (from the catalog in the system context).'),\n query: z.string().optional().describe('Optional search text (title match).'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n listAssets: {\n description:\n 'List or search assets (images, files). Use it to find REAL asset ids — never ' +\n 'invent one. Returns { id, title, contentType, filename } summaries; an asset ' +\n 'field only takes the kinds it accepts.',\n inputSchema: z.object({\n query: z.string().optional().describe('Optional search text.'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n getDocument: {\n description:\n 'Fetch one full document (values + localized values + component ids) by collection and ' +\n 'id. Omit both to read the document currently open in the editor. Rich-text values — ' +\n 'at any depth — are returned as markdown strings where faithfully expressible. ' +\n '`components` lists, for every component on the document, the props you may change ' +\n 'with updateFields and the rules each value must satisfy.',\n inputSchema: z.object({\n collection: z\n .string()\n .optional()\n .describe('Collection id. Omit to target the currently open document.'),\n id: z\n .string()\n .optional()\n .describe(\n 'Document id (from a searchDocuments result). Omit to target the currently open document.',\n ),\n }),\n },\n createDocument: {\n description:\n 'Author a NEW document in a collection as a reviewable draft proposal. Terminal ' +\n 'step of a creation request — call it once you have gathered the real ids you ' +\n 'need. Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Target collection id.'),\n instruction: z.string().describe('What to write, refining the user request.'),\n }),\n },\n updateFields: {\n description:\n 'Change specific fields of an EXISTING document as a reviewable proposal — THE ' +\n 'tool for every edit request (change / fix / remove / replace / rewrite wording, ' +\n 'values, or a page-builder element). Call getDocument first to see the current ' +\n 'values (and component ids), then pass ONLY the fields that change. A component ' +\n 'prop (e.g. a Hero headline) — at any depth: a top-level block, a child inside a ' +\n 'section, a component embedded in rich text — is addressed as field + blockId + ' +\n 'prop. Components are never added, moved or removed by the assistant (that is done ' +\n 'on the canvas). Omit collection and id to target the document currently open in ' +\n 'the editor. A rich-text value takes the FULL new value as a MARKDOWN string ' +\n '(headings, lists, links, bold/italic, blockquotes — no images, code, tables, or HTML).',\n inputSchema: z.object({\n collection: z\n .string()\n .optional()\n .describe('Collection id. Omit to target the currently open document.'),\n id: z\n .string()\n .optional()\n .describe('Document id. Omit to target the currently open document.'),\n changes: z\n .array(\n z.object({\n field: z\n .string()\n .describe(\n 'Field name from the collection schema. The catalog in the system context ' +\n 'lists every field with its type and the rules its value must satisfy.',\n ),\n locale: z\n .string()\n .optional()\n .describe(\n \"Locale of a LOCALIZED field (defaults to the editor's working locale).\",\n ),\n blockId: z\n .string()\n .optional()\n .describe(\n 'To change a component prop: the component id (from getDocument) — any depth.',\n ),\n prop: z\n .string()\n .optional()\n .describe('With blockId: the component prop to change (from getDocument `components`).'),\n value: z\n .unknown()\n .optional()\n .describe(\n 'The new value (a rich-text field takes a markdown string). null clears the ' +\n \"field/prop. It MUST satisfy that field's rules as listed in the catalog \" +\n '(length bounds, format, allowed values, date range…); the studio validates ' +\n 'the merged document and rejects the proposal with the failing rules if it ' +\n 'does not. Where the catalog says further rules apply, keep the value ' +\n 'conventional and plausible.',\n ),\n }),\n )\n .min(1)\n .describe('The field changes — only what changes, never the whole document.'),\n }),\n },\n translateDocument: {\n description:\n 'Fill the EMPTY locale values of an existing document (search for it first to ' +\n 'get its id). Only for translation requests — never for edits (use updateFields ' +\n 'to change existing content). Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Collection id.'),\n id: z.string().describe('Document id (from a searchDocuments result).'),\n locale: z.string().optional().describe('Target locale (defaults to the active one).'),\n }),\n },\n} satisfies Record<string, ChatToolDefinition>\n\n// --- Client executor map (EC-334) ----------------------------------------------------\n\n/** One forwarded tool call, as `useChat`'s `onToolCall` receives it. */\nexport interface ChatToolCall {\n toolCallId: string\n toolName: string\n input: unknown\n}\n\n/** The coordinates of the document currently open in the editor (EC-378 seam). */\nexport interface CurrentDocumentRef {\n collection: string\n id: string\n}\n\n/**\n * Resolve a tool call's target document from its (optional) input coordinates\n * and the current-document seam (EC-378). Deterministic:\n *\n * - both given → use them verbatim;\n * - both omitted → the currently open document (error when none is open);\n * - `collection` given with `id` omitted → the open document ONLY when the\n * collections match — a named collection must never silently cross onto a\n * different open document.\n *\n * Pure — tested directly; `getDocument` and `updateFields` share it.\n */\nexport function resolveDocumentTarget(\n input: { collection?: string; id?: string },\n current: CurrentDocumentRef | null | undefined,\n): { ok: true; ref: CurrentDocumentRef } | { ok: false; errorText: string } {\n if (input.collection !== undefined && input.id !== undefined) {\n return { ok: true, ref: { collection: input.collection, id: input.id } }\n }\n if (!current) {\n return {\n ok: false,\n errorText:\n 'No target document — pass collection and id, or ask the user to open the document in the editor.',\n }\n }\n if (input.collection !== undefined && input.collection !== current.collection) {\n return {\n ok: false,\n errorText: `The open document is in collection \"${current.collection}\", not \"${input.collection}\" — pass the document id explicitly.`,\n }\n }\n return { ok: true, ref: { collection: current.collection, id: input.id ?? current.id } }\n}\n\n/**\n * A tool execution outcome: an `output` posted back as the tool result, or an\n * `errorText` posted as an `output-error` part (the model sees the failure and\n * can react — never a thrown exception into the stream).\n */\nexport type ChatToolOutcome = { ok: true; output: unknown } | { ok: false; errorText: string }\n\n/**\n * The per-conversation candidate store: every `searchDocuments` result is recorded\n * per collection, every `listAssets` result into one flat library pool (EC-381), and\n * the terminal tools may only reference the ids gathered here. The store IS the\n * {@link WriterLeash} the engines ask per position (EC-593): a relation by its target\n * collection, an asset by its declaration's `accept` (EC-588) — so a nested relation, a\n * component's asset prop and a top-level field are leashed by the same two questions\n * (the create enum + drop, the update loud refusal). Held by the panel per\n * conversation — a new conversation (EC-380 clear) starts an empty store.\n */\nexport interface ChatCandidateStore extends WriterLeash {\n record(collection: string, results: readonly DocumentSearchResult[]): void\n /** Record every `listAssets` result into the flat library pool (EC-381). */\n recordAssets(results: readonly AssetSearchResult[]): void\n}\n\nexport function createChatCandidateStore(): ChatCandidateStore {\n const searched = new Map<string, Map<string, DocumentSearchResult>>()\n const searchedAssets = new Map<string, AssetSearchResult>()\n return {\n record(collection, results) {\n const byId = searched.get(collection) ?? new Map<string, DocumentSearchResult>()\n for (const result of results) byId.set(result.id, result)\n searched.set(collection, byId)\n },\n recordAssets(results) {\n for (const result of results) searchedAssets.set(result.id, result)\n },\n relationCandidates(target) {\n return relationCandidatesOf(searched.get(target)?.values() ?? [])\n },\n // EC-588 (A4): a position's enum is the pool filtered by ITS `accept` — an image\n // field is never offered a PDF. The validator re-run at apply is the guarantee\n // (`findAsset` checks the record); this keeps the model from spending its repair\n // budget on a mismatch the leash can rule out up front.\n assetCandidates(field) {\n return assetCandidatesOf(field, searchedAssets.values())\n },\n }\n}\n\nexport interface ChatToolExecutorOptions {\n /** The (route) provider the terminal engines proxy their model calls through. */\n provider: AiProvider\n registry: CollectionRegistry\n /** The collections the assistant may target (unknown ids fail loud). */\n collections: readonly CollectionDef[]\n /** Operations-backed readers (client-side, user's session). */\n readers: ChatToolReaders\n /** Mint a fresh document id for a new draft (studio: the CMS store's minter). */\n mintDocumentId: (collectionId: string) => string\n /** Per-conversation relation-candidate store (see {@link createChatCandidateStore}). */\n candidates: ChatCandidateStore\n /**\n * Full proposal sink, keyed by `toolCallId` — the review UI's entry point.\n * The tool OUTPUT stays a compact summary; the patch never reaches the model.\n */\n onProposal: (toolCallId: string, proposal: ChatProposal) => void\n /**\n * The document currently open in the editor (EC-378 seam) — a thunk read at\n * EXECUTION time, so \"this document\" resolves against what is open NOW.\n * `getDocument` / `updateFields` fall back to it when the model omits the\n * target (see {@link resolveDocumentTarget}).\n */\n currentDocument?: () => CurrentDocumentRef | null | undefined\n /** Current knowledge snapshot (thunk — the body thunk refreshes it per request). */\n knowledge?: () => ResolvedKnowledge | undefined\n /** Target locale for localized fields. */\n locale?: string\n /** Locale config — required for `translateDocument`. */\n localeConfig?: LocaleConfig\n /**\n * THE validation option bag (EC-497) — the CMS session's\n * `gateValidateOptions(...)`, forwarded whole to every engine below. EC-473\n * made the assistant's gate the editor's gate; passing one bag instead of five\n * keys makes it stay that way, because a key can no longer be dropped by being\n * forgotten at one of the three call sites this replaced. Its `lookupManifest` is\n * also how the writer-form converter and the read form reach component props\n * (EC-593) — the props the validator judges, no second component source.\n */\n validateOptions?: ValidateDocumentOptions\n /** Max repair attempts inside `applyContentWithShape`. */\n maxRepairAttempts?: number\n /** Per-search result cap (default {@link DEFAULT_SEARCH_LIMIT}). */\n searchLimit?: number\n}\n\n/** The executor `useChat`'s `onToolCall` dispatches into. */\nexport interface ChatToolExecutor {\n execute(call: ChatToolCall): Promise<ChatToolOutcome>\n}\n\n/** A translate skip as one model-facing phrase: `menu[1].label (de): the provider returned no text`. */\nexport function describeTranslateSkip(skip: TranslateSkip): string {\n const where = skip.at.reduce<string>(\n (out, key) => (typeof key === 'number' ? `${out}[${key}]` : `${out}.${key}`),\n skip.field,\n )\n const component = skip.component ? ` in ${skip.component.componentId} \"${skip.component.nodeId}\"` : ''\n const why =\n skip.reason === 'unreadable'\n ? 'the stored value is not readable as its type'\n : skip.reason === 'not-returned'\n ? 'the provider returned no text'\n : 'the translation did not keep its formatting, links or embeds, so the original was kept'\n return `${where}${component} (${skip.locale}): ${why}`\n}\n\nfunction issueSummary(issues: readonly CmsValidationIssue[]): string {\n return issues\n .slice(0, 5)\n .map((issue) => issue.message)\n .join('; ')\n}\n\n/**\n * The `getDocument` output (EC-379 → EC-593): the document in the form the model reads\n * — the ONE converter's read side (`toWriterDocument`), so rich text is a markdown\n * string at EVERY depth where the engine's loss-guarded inverse can express it\n * faithfully (a top-level field, an object sub-field, a repeater item, a component's\n * rich-text prop), and keeps its stored `{ version: 2, content }` value otherwise (embeds,\n * internal `ref` links, out-of-subset marks), so nothing the model later echoes back can\n * silently lose structure. It used to project TOP-LEVEL rich text only (SHAPES #29: a\n * nested value read as v2 while every writer was told markdown).\n *\n * `components` is the catalog's prop half (RULES F3d): for every component on the\n * document, the props `updateFields` may change and the rules each value must satisfy,\n * read off the same declarations the validator judges (`lookupManifest`). Applies to\n * the TOOL OUTPUT only; the proposal/apply paths always read the raw stored document.\n */\nexport function modelFacingDocument(\n document: CmsDocument,\n collection: CollectionDef,\n validateOptions: ValidateDocumentOptions = {},\n): CmsDocument & { components?: Record<string, string[]> } {\n const lookupManifest = validateOptions.lookupManifest\n const read = toWriterDocument(collection, document, lookupManifest ? { lookupManifest } : {})\n if (!lookupManifest) return read\n const ids = componentIdsOf(collection, document, lookupManifest)\n if (ids.length === 0) return read\n return {\n ...read,\n components: Object.fromEntries(ids.map((id) => [id, describeComponentProps(lookupManifest(id) ?? {})])),\n }\n}\n\n/**\n * Build the client executor map. Every entry validates its input against\n * {@link chatToolDefinitions}' zod schema (the route validates UIMessages only\n * structurally — deep input validation is the client's), executes with the\n * user's session, and returns a JSON-safe outcome. EC-378's `updateFields`\n * lands as one more case in this dispatch.\n */\nexport function createChatToolExecutor(options: ChatToolExecutorOptions): ChatToolExecutor {\n const searchLimit = options.searchLimit ?? DEFAULT_SEARCH_LIMIT\n\n /**\n * EC-497 — the ONE bag every engine below is handed, assembled in exactly one\n * place instead of at each of the three former call sites.\n *\n * The executor's own `localeConfig` is a FLOOR, never an override: the session's\n * bag wins wherever it speaks, but a bag that omits the project's locales must\n * not be able to make the gate locale-blind — a localized bound would then go\n * unchecked, which is precisely the class of hole this task closed.\n */\n const validateOptions: ValidateDocumentOptions = {\n ...(options.localeConfig ? { localeConfig: options.localeConfig } : {}),\n ...(options.validateOptions ?? {}),\n }\n\n function collectionById(id: string): CollectionDef | undefined {\n return options.collections.find((c) => c.id === id)\n }\n\n async function searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<ChatToolOutcome> {\n if (!collectionById(input.collection)) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.searchDocuments({\n collection: input.collection,\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n options.candidates.record(input.collection, results)\n return { ok: true, output: results }\n }\n\n async function listAssets(input: { query?: string; limit?: number }): Promise<ChatToolOutcome> {\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.listAssets({\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n // EC-381 — leash asset fields to what the model actually searched, exactly as\n // searchDocuments feeds the relation store.\n options.candidates.recordAssets(results)\n return { ok: true, output: results }\n }\n\n async function getDocument(input: {\n collection?: string\n id?: string\n }): Promise<ChatToolOutcome> {\n if (!options.readers.getDocument) {\n return { ok: false, errorText: 'Reading documents is not available here.' }\n }\n const target = resolveDocumentTarget(input, options.currentDocument?.())\n if (!target.ok) return { ok: false, errorText: target.errorText }\n const document = await options.readers.getDocument(target.ref)\n if (!document) {\n return {\n ok: false,\n errorText: `Document \"${target.ref.collection}/${target.ref.id}\" was not found.`,\n }\n }\n // EC-379/EC-593: the model reads (and re-authors) every value in its writer form.\n const collection = collectionById(target.ref.collection)\n return { ok: true, output: collection ? modelFacingDocument(document, collection, validateOptions) : document }\n }\n\n /** EC-378 — the edit-flow terminal tool: current doc + model-authored changes → validated proposal. */\n async function updateFields(\n toolCallId: string,\n input: { collection?: string; id?: string; changes: UpdateFieldChange[] },\n ): Promise<ChatToolOutcome> {\n if (!options.readers.getDocument) {\n return { ok: false, errorText: 'Reading documents is not available here.' }\n }\n const target = resolveDocumentTarget(input, options.currentDocument?.())\n if (!target.ok) return { ok: false, errorText: target.errorText }\n const collection = collectionById(target.ref.collection)\n if (!collection) {\n return {\n ok: false,\n errorText: `Unknown collection \"${target.ref.collection}\" — use a collection id from the catalog.`,\n }\n }\n const document = await options.readers.getDocument(target.ref)\n if (!document) {\n return {\n ok: false,\n errorText: `Document \"${target.ref.collection}/${target.ref.id}\" was not found.`,\n }\n }\n const result = buildUpdateProposal({\n registry: options.registry,\n collection,\n document,\n changes: input.changes,\n // EC-381 → EC-593: the store IS the leash, asked per position.\n leash: options.candidates,\n ...(options.locale ? { locale: options.locale } : {}),\n validateOptions,\n })\n if (!result.ok) {\n return {\n ok: false,\n errorText: `The proposed changes did not pass validation: ${issueSummary(result.issues)}`,\n }\n }\n if (result.kind === 'no-change') {\n return {\n ok: true,\n output: {\n status: 'no-change',\n note: 'The requested change matches the current values — there is nothing to update.',\n },\n }\n }\n options.onProposal(toolCallId, {\n origin: 'update',\n collection: collection.id,\n documentId: document.id,\n patch: result.patch,\n patches: result.patches,\n provenance: aiProvenance(options.provider),\n attempts: 1,\n issues: result.issues,\n before: result.before,\n })\n // Compact summary only — the full patch goes to the review UI, not the model.\n const titleValues = {\n ...result.patch.values,\n ...(options.locale ? result.patch.localized?.[options.locale] : {}),\n }\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId: document.id,\n title: resolveDocumentTitle(collection, titleValues, document.id),\n changedFields: result.changedFields,\n note: 'Update proposal created; the editor reviews and applies it in the studio. Summarize the change briefly — do not repeat the content.',\n },\n }\n }\n\n async function createDocument(\n toolCallId: string,\n input: { collection: string; instruction: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const documentId = options.mintDocumentId(collection.id)\n const knowledge = options.knowledge?.()\n const result = await applyContentWithShape({\n provider: options.provider,\n registry: options.registry,\n collection,\n documentId,\n instruction: input.instruction,\n ...(knowledge ? { knowledge } : {}),\n // EC-381 → EC-593: relation and asset positions — at every depth — are leashed\n // to what was searched (the store IS the leash).\n leash: options.candidates,\n ...(options.locale ? { locale: options.locale } : {}),\n validateOptions,\n ...(options.maxRepairAttempts !== undefined\n ? { maxRepairAttempts: options.maxRepairAttempts }\n : {}),\n })\n if (!result.ok) {\n return {\n ok: false,\n errorText: `The drafted ${collection.id} did not pass validation: ${issueSummary(result.issues)}`,\n }\n }\n options.onProposal(toolCallId, {\n origin: 'create',\n collection: collection.id,\n documentId,\n patch: result.patch,\n provenance: result.provenance,\n attempts: result.attempts,\n issues: result.issues,\n })\n // Compact summary only — the full patch goes to the review UI, not the model.\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId,\n title: resolveDocumentTitle(collection, result.patch.values, documentId),\n note: 'Draft proposal created; the editor reviews and applies it in the studio. Summarize briefly — do not repeat the content.',\n },\n }\n }\n\n async function translate(\n toolCallId: string,\n input: { collection: string; id: string; locale?: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n if (!options.readers.getDocument || !options.localeConfig) {\n return { ok: false, errorText: 'Translation is not available here.' }\n }\n const document = await options.readers.getDocument({\n collection: input.collection,\n id: input.id,\n })\n if (!document) {\n return { ok: false, errorText: `Document \"${input.collection}/${input.id}\" was not found.` }\n }\n const knowledge = options.knowledge?.()\n const result = await translateDocument({\n provider: options.provider,\n collection,\n document,\n localeConfig: options.localeConfig,\n ...(input.locale ? { targetLocales: [input.locale] } : {}),\n ...(knowledge ? { knowledge } : {}),\n // EC-497: the engine gates its own output; both callers hand it the session\n // registry + THE bag so its verdict is the editor's verdict.\n registry: options.registry,\n validateOptions,\n })\n // EC-593 (ratified 4e): what could not be translated is REPORTED — to the model\n // (it tells the user) and on the proposal the editor reviews — never skipped silently.\n const skipped = result.skipped.map(describeTranslateSkip)\n if (result.total === 0 && skipped.length === 0) {\n return {\n ok: true,\n output: {\n status: 'nothing-to-translate',\n note: 'Every locale value is already filled — there is nothing to translate.',\n },\n }\n }\n if (result.translated === 0) {\n return {\n ok: false,\n errorText:\n skipped.length > 0\n ? `The translation did not produce any content. Not translated: ${skipped.slice(0, 5).join('; ')}`\n : 'The translation did not produce any content.',\n }\n }\n // EC-473 established that a translated draft is validated before it is proposed\n // (this path once proposed unvalidated content). EC-497 moved the gate INTO the\n // engine so the detail-editor's header action — the other caller — inherits it\n // instead of writing model output straight to the document. Only errors the\n // translation INTRODUCED block it; pre-existing brokenness is not the\n // assistant's doing.\n if (result.introducedErrors.length > 0) {\n return {\n ok: false,\n errorText: `The translation did not pass validation: ${issueSummary(result.introducedErrors)}`,\n }\n }\n options.onProposal(toolCallId, {\n origin: 'translate',\n collection: collection.id,\n documentId: document.id,\n patch: {\n collection: collection.id,\n id: document.id,\n values: result.document.values,\n ...(result.document.localized ? { localized: result.document.localized } : {}),\n },\n patches: result.patches,\n provenance: result.provenance,\n attempts: 1,\n // Warnings ride onto the proposal like every other path's (EC-496 renders them).\n issues: [...result.issues],\n ...(result.skipped.length > 0 ? { skipped: [...result.skipped] } : {}),\n before: {\n values: document.values,\n ...(document.localized ? { localized: document.localized } : {}),\n },\n })\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId: document.id,\n translatedUnits: result.translated,\n ...(skipped.length > 0 ? { notTranslated: skipped } : {}),\n note:\n skipped.length > 0\n ? 'Translation proposal created; the editor reviews and applies it in the studio. Tell the user which positions were NOT translated (notTranslated).'\n : 'Translation proposal created; the editor reviews and applies it in the studio.',\n },\n }\n }\n\n return {\n async execute(call: ChatToolCall): Promise<ChatToolOutcome> {\n const definition = (chatToolDefinitions as Record<string, ChatToolDefinition>)[call.toolName]\n if (!definition) {\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n const parsed = definition.inputSchema.safeParse(call.input)\n if (!parsed.success) {\n return { ok: false, errorText: `Invalid ${call.toolName} input: ${parsed.error.message}` }\n }\n try {\n switch (call.toolName) {\n case 'searchDocuments':\n return await searchDocuments(parsed.data as { collection: string; query?: string; limit?: number })\n case 'listAssets':\n return await listAssets(parsed.data as { query?: string; limit?: number })\n case 'getDocument':\n return await getDocument(parsed.data as { collection?: string; id?: string })\n case 'createDocument':\n return await createDocument(\n call.toolCallId,\n parsed.data as { collection: string; instruction: string },\n )\n case 'updateFields':\n return await updateFields(\n call.toolCallId,\n parsed.data as { collection?: string; id?: string; changes: UpdateFieldChange[] },\n )\n case 'translateDocument':\n return await translate(\n call.toolCallId,\n parsed.data as { collection: string; id: string; locale?: string },\n )\n default:\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n } catch (error) {\n return {\n ok: false,\n errorText: `The ${call.toolName} step failed: ${error instanceof Error ? error.message : 'unknown error'}`,\n }\n }\n },\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/lib/ai/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAA;AAS/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAA;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AAExD,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AAErD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAChE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAyC3C,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,CAAA;AAetC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,eAAe,EAAE;QACf,WAAW,EACT,+EAA+E;YAC/E,6EAA6E;YAC7E,0BAA0B;QAC5B,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;YACpB,UAAU,EAAE,CAAC;iBACV,MAAM,EAAE;iBACR,QAAQ,CAAC,gEAAgE,CAAC;YAC7E,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,qCAAqC,CAAC;YAC5E,KAAK,EAAE,CAAC,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,MAAM,YAAY,CACvB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAA0E,CAClF,CAAA;oBACH,KAAK,mBAAmB;wBACtB,OAAO,MAAM,SAAS,CACpB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAA2D,CACnE,CAAA;oBACH;wBACE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAA;gBACvE,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO;oBACL,EAAE,EAAE,KAAK;oBACT,SAAS,EAAE,OAAO,IAAI,CAAC,QAAQ,iBAAiB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE;iBAC3G,CAAA;YACH,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * The narrow tool set the assistant works against (EC-199, reshaped by EC-334).\n *\n * Per the ratified AD, tools execute CLIENT-side against the operations layer with\n * the user's own session. This module carries the three pieces of that contract:\n *\n * 1. {@link chatToolDefinitions} — the SDK-native tool DEFINITIONS the route's\n * chat branch declares in `streamText`, deliberately WITHOUT `execute`, so the\n * SDK forwards every call to the client (the route stays a zero-data-access\n * proxy). Plain `{ description, inputSchema }` objects with zod schemas —\n * structurally the SDK's `FunctionTool`, with no SDK import (bundle discipline).\n * 2. {@link ChatToolReaders} — the operations-backed read interface the studio\n * binds client-side (search / list / get). Reads only — the engine never gains\n * a write path; apply is a separate, human-gated draft write.\n * 3. {@link createChatToolExecutor} — the client executor map `useChat`'s\n * `onToolCall` dispatches into. Readers pass through; the terminal tools run\n * the deterministic engines (`applyContentWithShape` / `translateDocument` /\n * `buildUpdateProposal`) and return a COMPACT proposal summary as the tool\n * output — the full proposal goes to the review UI via\n * `onProposal(toolCallId, …)`, never to the model.\n *\n * EC-378: `updateFields` is the edit-flow terminal tool — the model authors\n * per-field changes directly (it has `getDocument` output + the conversation as\n * context); the executor reads the CURRENT document, builds a validated update\n * proposal (`buildUpdateProposal`), and hands it to the review sink. Its target\n * (and `getDocument`'s) may be omitted to mean the document currently open in\n * the editor — resolved via the {@link ChatToolExecutorOptions.currentDocument}\n * seam ({@link resolveDocumentTarget}); the context block the panel injects is\n * ADVISORY, the resolution here is what makes \"this document\" deterministic.\n *\n * The EC-199 planner enum/schema (`plannerSchema` / `parsePlannerAction`) retired\n * with the hand-rolled orchestrator (EC-334 slice 2).\n */\nimport { z } from 'zod'\nimport { resolveDocumentTitle } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n LocaleConfig,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport { applyContentWithShape } from './apply-content'\nimport { describeComponentProps } from './chat-context'\nimport { assetCandidatesOf, relationCandidatesOf } from './leash'\nimport type { SearchedAsset, SearchedDocument } from './leash'\nimport { translateDocument } from './translate-document'\nimport type { TranslateSkip } from './translate-document'\nimport { buildUpdateProposal } from './update-fields'\nimport type { UpdateFieldChange } from './update-fields'\nimport { componentIdsOf, toWriterDocument } from './writer-form'\nimport { aiProvenance } from './provenance'\nimport type { ChatProposal } from './chat-state'\nimport type { AiProvider, ResolvedKnowledge, WriterLeash } from './types'\n\n/** A document the model may reference as a relation target (from a `searchDocuments` read). */\nexport type DocumentSearchResult = SearchedDocument\n\n/**\n * An asset the model may reference (from a `listAssets` read). EC-588: it carries the\n * two facts a field's `accept` is judged on, so each asset position's candidates can be\n * filtered to what that position takes — and the model can see what each asset is.\n */\nexport type AssetSearchResult = SearchedAsset\n\n/**\n * The client-side, operations-backed readers the executor calls. The studio binds\n * these to the user's authenticated operations client; tests bind an in-memory fake.\n * Reads only — there is no write tool (apply is a separate, human-gated draft write).\n */\nexport interface ChatToolReaders {\n searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<DocumentSearchResult[]>\n listAssets(input: { query?: string; limit?: number }): Promise<AssetSearchResult[]>\n /**\n * Fetch a full document (values + localized) — the translate flow and the model's\n * `getDocument` tool. Optional: a studio that only wires create can omit it.\n */\n getDocument?(input: { collection: string; id: string }): Promise<CmsDocument | null>\n /**\n * EC-647 — the revision a document {@link getDocument} returned was read at (the\n * returned value is the token). An update or a translation records it on its proposal:\n * applying the proposal writes AT that revision, so a change made since on one of its\n * positions is refused, never overwritten. Optional: absent, a proposal names no\n * revision and its apply is refused.\n */\n revisionOf?(document: CmsDocument): number | undefined\n}\n\n/** Per-search result cap (protects the wire — results become model context). */\nexport const DEFAULT_SEARCH_LIMIT = 20\n\n// --- SDK-native chat tool definitions (EC-334) --------------------------------------\n\n/**\n * One model-facing tool definition for the route's `streamText` call. Structurally\n * the SDK's `FunctionTool` WITHOUT `execute` (execution is client-side, always) —\n * typed locally so this module needs no SDK import.\n */\nexport interface ChatToolDefinition {\n description: string\n /** Zod input schema (the AI SDK accepts zod schemas as `inputSchema` directly). */\n inputSchema: z.ZodType\n}\n\n/**\n * The tool set the native chat branch declares (EC-334). No `execute` on any entry:\n * the SDK forwards each call to the client, which executes reads against the\n * operations layer with the user's session and posts the result back; the terminal\n * tools (`createDocument` / `translateDocument`) run the deterministic engines\n * client-side and return a compact proposal summary as the tool output. The route\n * itself never executes anything.\n *\n * Collections are NOT enum-leashed here — the route has zero data access, so it has\n * no catalog; the catalog reaches the model through the request `context` (system\n * prompt), and every id a proposal references must come from a tool RESULT\n * (client-validated; `applyContentWithShape` still enum-leashes relation ids).\n */\nexport const chatToolDefinitions = {\n searchDocuments: {\n description:\n 'Search documents in a collection. Use it to find the REAL ids a relation may ' +\n 'reference, or to locate an existing document — never invent an id. Returns ' +\n '{ id, title } summaries.',\n inputSchema: z.object({\n collection: z\n .string()\n .describe('Target collection id (from the catalog in the system context).'),\n query: z.string().optional().describe('Optional search text (title match).'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n listAssets: {\n description:\n 'List or search assets (images, files). Use it to find REAL asset ids — never ' +\n 'invent one. Returns { id, title, contentType, filename } summaries; an asset ' +\n 'field only takes the kinds it accepts.',\n inputSchema: z.object({\n query: z.string().optional().describe('Optional search text.'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n getDocument: {\n description:\n 'Fetch one full document (values + localized values + component ids) by collection and ' +\n 'id. Omit both to read the document currently open in the editor. Rich-text values — ' +\n 'at any depth — are returned as markdown strings where faithfully expressible. ' +\n '`components` lists, for every component on the document, the props you may change ' +\n 'with updateFields and the rules each value must satisfy.',\n inputSchema: z.object({\n collection: z\n .string()\n .optional()\n .describe('Collection id. Omit to target the currently open document.'),\n id: z\n .string()\n .optional()\n .describe(\n 'Document id (from a searchDocuments result). Omit to target the currently open document.',\n ),\n }),\n },\n createDocument: {\n description:\n 'Author a NEW document in a collection as a reviewable draft proposal. Terminal ' +\n 'step of a creation request — call it once you have gathered the real ids you ' +\n 'need. Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Target collection id.'),\n instruction: z.string().describe('What to write, refining the user request.'),\n }),\n },\n updateFields: {\n description:\n 'Change specific fields of an EXISTING document as a reviewable proposal — THE ' +\n 'tool for every edit request (change / fix / remove / replace / rewrite wording, ' +\n 'values, or a page-builder element). Call getDocument first to see the current ' +\n 'values (and component ids), then pass ONLY the fields that change. A component ' +\n 'prop (e.g. a Hero headline) — at any depth: a top-level block, a child inside a ' +\n 'section, a component embedded in rich text — is addressed as field + blockId + ' +\n 'prop. Components are never added, moved or removed by the assistant (that is done ' +\n 'on the canvas). Omit collection and id to target the document currently open in ' +\n 'the editor. A rich-text value takes the FULL new value as a MARKDOWN string ' +\n '(headings, lists, links, bold/italic, blockquotes — no images, code, tables, or HTML).',\n inputSchema: z.object({\n collection: z\n .string()\n .optional()\n .describe('Collection id. Omit to target the currently open document.'),\n id: z\n .string()\n .optional()\n .describe('Document id. Omit to target the currently open document.'),\n changes: z\n .array(\n z.object({\n field: z\n .string()\n .describe(\n 'Field name from the collection schema. The catalog in the system context ' +\n 'lists every field with its type and the rules its value must satisfy.',\n ),\n locale: z\n .string()\n .optional()\n .describe(\n \"Locale of a LOCALIZED field (defaults to the editor's working locale).\",\n ),\n blockId: z\n .string()\n .optional()\n .describe(\n 'To change a component prop: the component id (from getDocument) — any depth.',\n ),\n prop: z\n .string()\n .optional()\n .describe('With blockId: the component prop to change (from getDocument `components`).'),\n value: z\n .unknown()\n .optional()\n .describe(\n 'The new value (a rich-text field takes a markdown string). null clears the ' +\n \"field/prop. It MUST satisfy that field's rules as listed in the catalog \" +\n '(length bounds, format, allowed values, date range…); the studio validates ' +\n 'the merged document and rejects the proposal with the failing rules if it ' +\n 'does not. Where the catalog says further rules apply, keep the value ' +\n 'conventional and plausible.',\n ),\n }),\n )\n .min(1)\n .describe('The field changes — only what changes, never the whole document.'),\n }),\n },\n translateDocument: {\n description:\n 'Fill the EMPTY locale values of an existing document (search for it first to ' +\n 'get its id). Only for translation requests — never for edits (use updateFields ' +\n 'to change existing content). Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Collection id.'),\n id: z.string().describe('Document id (from a searchDocuments result).'),\n locale: z.string().optional().describe('Target locale (defaults to the active one).'),\n }),\n },\n} satisfies Record<string, ChatToolDefinition>\n\n// --- Client executor map (EC-334) ----------------------------------------------------\n\n/** One forwarded tool call, as `useChat`'s `onToolCall` receives it. */\nexport interface ChatToolCall {\n toolCallId: string\n toolName: string\n input: unknown\n}\n\n/** The coordinates of the document currently open in the editor (EC-378 seam). */\nexport interface CurrentDocumentRef {\n collection: string\n id: string\n}\n\n/**\n * Resolve a tool call's target document from its (optional) input coordinates\n * and the current-document seam (EC-378). Deterministic:\n *\n * - both given → use them verbatim;\n * - both omitted → the currently open document (error when none is open);\n * - `collection` given with `id` omitted → the open document ONLY when the\n * collections match — a named collection must never silently cross onto a\n * different open document.\n *\n * Pure — tested directly; `getDocument` and `updateFields` share it.\n */\nexport function resolveDocumentTarget(\n input: { collection?: string; id?: string },\n current: CurrentDocumentRef | null | undefined,\n): { ok: true; ref: CurrentDocumentRef } | { ok: false; errorText: string } {\n if (input.collection !== undefined && input.id !== undefined) {\n return { ok: true, ref: { collection: input.collection, id: input.id } }\n }\n if (!current) {\n return {\n ok: false,\n errorText:\n 'No target document — pass collection and id, or ask the user to open the document in the editor.',\n }\n }\n if (input.collection !== undefined && input.collection !== current.collection) {\n return {\n ok: false,\n errorText: `The open document is in collection \"${current.collection}\", not \"${input.collection}\" — pass the document id explicitly.`,\n }\n }\n return { ok: true, ref: { collection: current.collection, id: input.id ?? current.id } }\n}\n\n/**\n * A tool execution outcome: an `output` posted back as the tool result, or an\n * `errorText` posted as an `output-error` part (the model sees the failure and\n * can react — never a thrown exception into the stream).\n */\nexport type ChatToolOutcome = { ok: true; output: unknown } | { ok: false; errorText: string }\n\n/**\n * The per-conversation candidate store: every `searchDocuments` result is recorded\n * per collection, every `listAssets` result into one flat library pool (EC-381), and\n * the terminal tools may only reference the ids gathered here. The store IS the\n * {@link WriterLeash} the engines ask per position (EC-593): a relation by its target\n * collection, an asset by its declaration's `accept` (EC-588) — so a nested relation, a\n * component's asset prop and a top-level field are leashed by the same two questions\n * (the create enum + drop, the update loud refusal). Held by the panel per\n * conversation — a new conversation (EC-380 clear) starts an empty store.\n */\nexport interface ChatCandidateStore extends WriterLeash {\n record(collection: string, results: readonly DocumentSearchResult[]): void\n /** Record every `listAssets` result into the flat library pool (EC-381). */\n recordAssets(results: readonly AssetSearchResult[]): void\n}\n\nexport function createChatCandidateStore(): ChatCandidateStore {\n const searched = new Map<string, Map<string, DocumentSearchResult>>()\n const searchedAssets = new Map<string, AssetSearchResult>()\n return {\n record(collection, results) {\n const byId = searched.get(collection) ?? new Map<string, DocumentSearchResult>()\n for (const result of results) byId.set(result.id, result)\n searched.set(collection, byId)\n },\n recordAssets(results) {\n for (const result of results) searchedAssets.set(result.id, result)\n },\n relationCandidates(target) {\n return relationCandidatesOf(searched.get(target)?.values() ?? [])\n },\n // EC-588 (A4): a position's enum is the pool filtered by ITS `accept` — an image\n // field is never offered a PDF. The validator re-run at apply is the guarantee\n // (`findAsset` checks the record); this keeps the model from spending its repair\n // budget on a mismatch the leash can rule out up front.\n assetCandidates(field) {\n return assetCandidatesOf(field, searchedAssets.values())\n },\n }\n}\n\nexport interface ChatToolExecutorOptions {\n /** The (route) provider the terminal engines proxy their model calls through. */\n provider: AiProvider\n registry: CollectionRegistry\n /** The collections the assistant may target (unknown ids fail loud). */\n collections: readonly CollectionDef[]\n /** Operations-backed readers (client-side, user's session). */\n readers: ChatToolReaders\n /** Mint a fresh document id for a new draft (studio: the CMS store's minter). */\n mintDocumentId: (collectionId: string) => string\n /** Per-conversation relation-candidate store (see {@link createChatCandidateStore}). */\n candidates: ChatCandidateStore\n /**\n * Full proposal sink, keyed by `toolCallId` — the review UI's entry point.\n * The tool OUTPUT stays a compact summary; the patch never reaches the model.\n */\n onProposal: (toolCallId: string, proposal: ChatProposal) => void\n /**\n * The document currently open in the editor (EC-378 seam) — a thunk read at\n * EXECUTION time, so \"this document\" resolves against what is open NOW.\n * `getDocument` / `updateFields` fall back to it when the model omits the\n * target (see {@link resolveDocumentTarget}).\n */\n currentDocument?: () => CurrentDocumentRef | null | undefined\n /** Current knowledge snapshot (thunk — the body thunk refreshes it per request). */\n knowledge?: () => ResolvedKnowledge | undefined\n /** Target locale for localized fields. */\n locale?: string\n /** Locale config — required for `translateDocument`. */\n localeConfig?: LocaleConfig\n /**\n * THE validation option bag (EC-497) — the CMS session's\n * `gateValidateOptions(...)`, forwarded whole to every engine below. EC-473\n * made the assistant's gate the editor's gate; passing one bag instead of five\n * keys makes it stay that way, because a key can no longer be dropped by being\n * forgotten at one of the three call sites this replaced. Its `lookupManifest` is\n * also how the writer-form converter and the read form reach component props\n * (EC-593) — the props the validator judges, no second component source.\n */\n validateOptions?: ValidateDocumentOptions\n /** Max repair attempts inside `applyContentWithShape`. */\n maxRepairAttempts?: number\n /** Per-search result cap (default {@link DEFAULT_SEARCH_LIMIT}). */\n searchLimit?: number\n}\n\n/** The executor `useChat`'s `onToolCall` dispatches into. */\nexport interface ChatToolExecutor {\n execute(call: ChatToolCall): Promise<ChatToolOutcome>\n}\n\n/** A translate skip as one model-facing phrase: `menu[1].label (de): the provider returned no text`. */\nexport function describeTranslateSkip(skip: TranslateSkip): string {\n const where = skip.at.reduce<string>(\n (out, key) => (typeof key === 'number' ? `${out}[${key}]` : `${out}.${key}`),\n skip.field,\n )\n const component = skip.component ? ` in ${skip.component.componentId} \"${skip.component.nodeId}\"` : ''\n const why =\n skip.reason === 'unreadable'\n ? 'the stored value is not readable as its type'\n : skip.reason === 'not-returned'\n ? 'the provider returned no text'\n : 'the translation did not keep its formatting, links or embeds, so the original was kept'\n return `${where}${component} (${skip.locale}): ${why}`\n}\n\nfunction issueSummary(issues: readonly CmsValidationIssue[]): string {\n return issues\n .slice(0, 5)\n .map((issue) => issue.message)\n .join('; ')\n}\n\n/**\n * The `getDocument` output (EC-379 → EC-593): the document in the form the model reads\n * — the ONE converter's read side (`toWriterDocument`), so rich text is a markdown\n * string at EVERY depth where the engine's loss-guarded inverse can express it\n * faithfully (a top-level field, an object sub-field, a repeater item, a component's\n * rich-text prop), and keeps its stored `{ version: 2, content }` value otherwise (embeds,\n * internal `ref` links, out-of-subset marks), so nothing the model later echoes back can\n * silently lose structure. It used to project TOP-LEVEL rich text only (SHAPES #29: a\n * nested value read as v2 while every writer was told markdown).\n *\n * `components` is the catalog's prop half (RULES F3d): for every component on the\n * document, the props `updateFields` may change and the rules each value must satisfy,\n * read off the same declarations the validator judges (`lookupManifest`). Applies to\n * the TOOL OUTPUT only; the proposal/apply paths always read the raw stored document.\n */\nexport function modelFacingDocument(\n document: CmsDocument,\n collection: CollectionDef,\n validateOptions: ValidateDocumentOptions = {},\n): CmsDocument & { components?: Record<string, string[]> } {\n const lookupManifest = validateOptions.lookupManifest\n const read = toWriterDocument(collection, document, lookupManifest ? { lookupManifest } : {})\n if (!lookupManifest) return read\n const ids = componentIdsOf(collection, document, lookupManifest)\n if (ids.length === 0) return read\n return {\n ...read,\n components: Object.fromEntries(ids.map((id) => [id, describeComponentProps(lookupManifest(id) ?? {})])),\n }\n}\n\n/**\n * Build the client executor map. Every entry validates its input against\n * {@link chatToolDefinitions}' zod schema (the route validates UIMessages only\n * structurally — deep input validation is the client's), executes with the\n * user's session, and returns a JSON-safe outcome. EC-378's `updateFields`\n * lands as one more case in this dispatch.\n */\nexport function createChatToolExecutor(options: ChatToolExecutorOptions): ChatToolExecutor {\n const searchLimit = options.searchLimit ?? DEFAULT_SEARCH_LIMIT\n\n /**\n * EC-497 — the ONE bag every engine below is handed, assembled in exactly one\n * place instead of at each of the three former call sites.\n *\n * The executor's own `localeConfig` is a FLOOR, never an override: the session's\n * bag wins wherever it speaks, but a bag that omits the project's locales must\n * not be able to make the gate locale-blind — a localized bound would then go\n * unchecked, which is precisely the class of hole this task closed.\n */\n const validateOptions: ValidateDocumentOptions = {\n ...(options.localeConfig ? { localeConfig: options.localeConfig } : {}),\n ...(options.validateOptions ?? {}),\n }\n\n function collectionById(id: string): CollectionDef | undefined {\n return options.collections.find((c) => c.id === id)\n }\n\n async function searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<ChatToolOutcome> {\n if (!collectionById(input.collection)) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.searchDocuments({\n collection: input.collection,\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n options.candidates.record(input.collection, results)\n return { ok: true, output: results }\n }\n\n async function listAssets(input: { query?: string; limit?: number }): Promise<ChatToolOutcome> {\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.listAssets({\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n // EC-381 — leash asset fields to what the model actually searched, exactly as\n // searchDocuments feeds the relation store.\n options.candidates.recordAssets(results)\n return { ok: true, output: results }\n }\n\n async function getDocument(input: {\n collection?: string\n id?: string\n }): Promise<ChatToolOutcome> {\n if (!options.readers.getDocument) {\n return { ok: false, errorText: 'Reading documents is not available here.' }\n }\n const target = resolveDocumentTarget(input, options.currentDocument?.())\n if (!target.ok) return { ok: false, errorText: target.errorText }\n const document = await options.readers.getDocument(target.ref)\n if (!document) {\n return {\n ok: false,\n errorText: `Document \"${target.ref.collection}/${target.ref.id}\" was not found.`,\n }\n }\n // EC-379/EC-593: the model reads (and re-authors) every value in its writer form.\n const collection = collectionById(target.ref.collection)\n return { ok: true, output: collection ? modelFacingDocument(document, collection, validateOptions) : document }\n }\n\n /** EC-378 — the edit-flow terminal tool: current doc + model-authored changes → validated proposal. */\n async function updateFields(\n toolCallId: string,\n input: { collection?: string; id?: string; changes: UpdateFieldChange[] },\n ): Promise<ChatToolOutcome> {\n if (!options.readers.getDocument) {\n return { ok: false, errorText: 'Reading documents is not available here.' }\n }\n const target = resolveDocumentTarget(input, options.currentDocument?.())\n if (!target.ok) return { ok: false, errorText: target.errorText }\n const collection = collectionById(target.ref.collection)\n if (!collection) {\n return {\n ok: false,\n errorText: `Unknown collection \"${target.ref.collection}\" — use a collection id from the catalog.`,\n }\n }\n const document = await options.readers.getDocument(target.ref)\n if (!document) {\n return {\n ok: false,\n errorText: `Document \"${target.ref.collection}/${target.ref.id}\" was not found.`,\n }\n }\n const result = buildUpdateProposal({\n registry: options.registry,\n collection,\n document,\n changes: input.changes,\n // EC-381 → EC-593: the store IS the leash, asked per position.\n leash: options.candidates,\n ...(options.locale ? { locale: options.locale } : {}),\n validateOptions,\n })\n if (!result.ok) {\n return {\n ok: false,\n errorText: `The proposed changes did not pass validation: ${issueSummary(result.issues)}`,\n }\n }\n if (result.kind === 'no-change') {\n return {\n ok: true,\n output: {\n status: 'no-change',\n note: 'The requested change matches the current values — there is nothing to update.',\n },\n }\n }\n const revision = options.readers.revisionOf?.(document)\n options.onProposal(toolCallId, {\n origin: 'update',\n collection: collection.id,\n documentId: document.id,\n patch: result.patch,\n patches: result.patches,\n ...(revision !== undefined ? { revision } : {}),\n provenance: aiProvenance(options.provider),\n attempts: 1,\n issues: result.issues,\n before: result.before,\n })\n // Compact summary only — the full patch goes to the review UI, not the model.\n const titleValues = {\n ...result.patch.values,\n ...(options.locale ? result.patch.localized?.[options.locale] : {}),\n }\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId: document.id,\n title: resolveDocumentTitle(collection, titleValues, document.id),\n changedFields: result.changedFields,\n note: 'Update proposal created; the editor reviews and applies it in the studio. Summarize the change briefly — do not repeat the content.',\n },\n }\n }\n\n async function createDocument(\n toolCallId: string,\n input: { collection: string; instruction: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const documentId = options.mintDocumentId(collection.id)\n const knowledge = options.knowledge?.()\n const result = await applyContentWithShape({\n provider: options.provider,\n registry: options.registry,\n collection,\n documentId,\n instruction: input.instruction,\n ...(knowledge ? { knowledge } : {}),\n // EC-381 → EC-593: relation and asset positions — at every depth — are leashed\n // to what was searched (the store IS the leash).\n leash: options.candidates,\n ...(options.locale ? { locale: options.locale } : {}),\n validateOptions,\n ...(options.maxRepairAttempts !== undefined\n ? { maxRepairAttempts: options.maxRepairAttempts }\n : {}),\n })\n if (!result.ok) {\n return {\n ok: false,\n errorText: `The drafted ${collection.id} did not pass validation: ${issueSummary(result.issues)}`,\n }\n }\n options.onProposal(toolCallId, {\n origin: 'create',\n collection: collection.id,\n documentId,\n patch: result.patch,\n provenance: result.provenance,\n attempts: result.attempts,\n issues: result.issues,\n })\n // Compact summary only — the full patch goes to the review UI, not the model.\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId,\n title: resolveDocumentTitle(collection, result.patch.values, documentId),\n note: 'Draft proposal created; the editor reviews and applies it in the studio. Summarize briefly — do not repeat the content.',\n },\n }\n }\n\n async function translate(\n toolCallId: string,\n input: { collection: string; id: string; locale?: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n if (!options.readers.getDocument || !options.localeConfig) {\n return { ok: false, errorText: 'Translation is not available here.' }\n }\n const document = await options.readers.getDocument({\n collection: input.collection,\n id: input.id,\n })\n if (!document) {\n return { ok: false, errorText: `Document \"${input.collection}/${input.id}\" was not found.` }\n }\n const knowledge = options.knowledge?.()\n const result = await translateDocument({\n provider: options.provider,\n collection,\n document,\n localeConfig: options.localeConfig,\n ...(input.locale ? { targetLocales: [input.locale] } : {}),\n ...(knowledge ? { knowledge } : {}),\n // EC-497: the engine gates its own output; both callers hand it the session\n // registry + THE bag so its verdict is the editor's verdict.\n registry: options.registry,\n validateOptions,\n })\n // EC-593 (ratified 4e): what could not be translated is REPORTED — to the model\n // (it tells the user) and on the proposal the editor reviews — never skipped silently.\n const skipped = result.skipped.map(describeTranslateSkip)\n if (result.total === 0 && skipped.length === 0) {\n return {\n ok: true,\n output: {\n status: 'nothing-to-translate',\n note: 'Every locale value is already filled — there is nothing to translate.',\n },\n }\n }\n if (result.translated === 0) {\n return {\n ok: false,\n errorText:\n skipped.length > 0\n ? `The translation did not produce any content. Not translated: ${skipped.slice(0, 5).join('; ')}`\n : 'The translation did not produce any content.',\n }\n }\n // EC-473 established that a translated draft is validated before it is proposed\n // (this path once proposed unvalidated content). EC-497 moved the gate INTO the\n // engine so the detail-editor's header action — the other caller — inherits it\n // instead of writing model output straight to the document. Only errors the\n // translation INTRODUCED block it; pre-existing brokenness is not the\n // assistant's doing.\n if (result.introducedErrors.length > 0) {\n return {\n ok: false,\n errorText: `The translation did not pass validation: ${issueSummary(result.introducedErrors)}`,\n }\n }\n const revision = options.readers.revisionOf?.(document)\n options.onProposal(toolCallId, {\n origin: 'translate',\n collection: collection.id,\n documentId: document.id,\n patch: {\n collection: collection.id,\n id: document.id,\n values: result.document.values,\n ...(result.document.localized ? { localized: result.document.localized } : {}),\n },\n patches: result.patches,\n ...(revision !== undefined ? { revision } : {}),\n provenance: result.provenance,\n attempts: 1,\n // Warnings ride onto the proposal like every other path's (EC-496 renders them).\n issues: [...result.issues],\n ...(result.skipped.length > 0 ? { skipped: [...result.skipped] } : {}),\n before: {\n values: document.values,\n ...(document.localized ? { localized: document.localized } : {}),\n },\n })\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId: document.id,\n translatedUnits: result.translated,\n ...(skipped.length > 0 ? { notTranslated: skipped } : {}),\n note:\n skipped.length > 0\n ? 'Translation proposal created; the editor reviews and applies it in the studio. Tell the user which positions were NOT translated (notTranslated).'\n : 'Translation proposal created; the editor reviews and applies it in the studio.',\n },\n }\n }\n\n return {\n async execute(call: ChatToolCall): Promise<ChatToolOutcome> {\n const definition = (chatToolDefinitions as Record<string, ChatToolDefinition>)[call.toolName]\n if (!definition) {\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n const parsed = definition.inputSchema.safeParse(call.input)\n if (!parsed.success) {\n return { ok: false, errorText: `Invalid ${call.toolName} input: ${parsed.error.message}` }\n }\n try {\n switch (call.toolName) {\n case 'searchDocuments':\n return await searchDocuments(parsed.data as { collection: string; query?: string; limit?: number })\n case 'listAssets':\n return await listAssets(parsed.data as { query?: string; limit?: number })\n case 'getDocument':\n return await getDocument(parsed.data as { collection?: string; id?: string })\n case 'createDocument':\n return await createDocument(\n call.toolCallId,\n parsed.data as { collection: string; instruction: string },\n )\n case 'updateFields':\n return await updateFields(\n call.toolCallId,\n parsed.data as { collection?: string; id?: string; changes: UpdateFieldChange[] },\n )\n case 'translateDocument':\n return await translate(\n call.toolCallId,\n parsed.data as { collection: string; id: string; locale?: string },\n )\n default:\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n } catch (error) {\n return {\n ok: false,\n errorText: `The ${call.toolName} step failed: ${error instanceof Error ? error.message : 'unknown error'}`,\n }\n }\n },\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, STATE_FIELD, UPDATED_AT_FIELD, URL_FIELD,
|
|
3
|
-
import type { CmsDocument, CollectionDef, ConfigView, FieldDef, FilterClause, Locale, LocaleConfig, LocalizedString,
|
|
2
|
+
import { configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, STATE_FIELD, UPDATED_AT_FIELD, URL_FIELD, sortSchema } from '@elytracms/core/cms-core';
|
|
3
|
+
import type { CmsDocument, CollectionDef, ConfigView, FieldDef, FilterClause, Locale, LocaleConfig, LocalizedString, Sort } from '@elytracms/core/cms-core';
|
|
4
4
|
import type { FilterOperator, FilterScalar } from '@elytracms/core/content';
|
|
5
5
|
/**
|
|
6
6
|
* The pure table-view model for the CMS collection table (EC-169).
|
|
@@ -18,8 +18,8 @@ import type { FilterOperator, FilterScalar } from '@elytracms/core/content';
|
|
|
18
18
|
* "show me drafts → bulk publish" working set and still speaks only the
|
|
19
19
|
* closed vocabulary (`eq`/`in`).
|
|
20
20
|
*/
|
|
21
|
-
export { configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, STATE_FIELD, UPDATED_AT_FIELD, URL_FIELD,
|
|
22
|
-
export type { ConfigView, FilterClause,
|
|
21
|
+
export { configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, sortSchema, STATE_FIELD, UPDATED_AT_FIELD, URL_FIELD, };
|
|
22
|
+
export type { ConfigView, FilterClause, Sort };
|
|
23
23
|
export declare const tableViewStateSchema: z.ZodObject<{
|
|
24
24
|
filters: z.ZodArray<z.ZodObject<{
|
|
25
25
|
field: z.ZodString;
|
|
@@ -39,11 +39,11 @@ export declare const tableViewStateSchema: z.ZodObject<{
|
|
|
39
39
|
}, z.core.$strip>>;
|
|
40
40
|
sort: z.ZodNullable<z.ZodObject<{
|
|
41
41
|
field: z.ZodString;
|
|
42
|
-
|
|
42
|
+
direction: z.ZodDefault<z.ZodEnum<{
|
|
43
43
|
asc: "asc";
|
|
44
44
|
desc: "desc";
|
|
45
|
-
}
|
|
46
|
-
}, z.core.$
|
|
45
|
+
}>>;
|
|
46
|
+
}, z.core.$strict>>;
|
|
47
47
|
columns: z.ZodArray<z.ZodString>;
|
|
48
48
|
hidden: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
49
49
|
}, z.core.$strip>;
|
|
@@ -187,13 +187,20 @@ export type IsPublished = (doc: CmsDocument) => boolean;
|
|
|
187
187
|
* relation membership all behave the same on the table as on the live site).
|
|
188
188
|
*/
|
|
189
189
|
export declare function clauseMatches(collection: CollectionDef, doc: CmsDocument, localeConfig: LocaleConfig, locale: Locale, clause: FilterClause, isPublished?: IsPublished): boolean;
|
|
190
|
+
/**
|
|
191
|
+
* The sort a column header click leads to (EC-169): a new column sorts ascending, the
|
|
192
|
+
* active one flips to descending, then clears. Reads `direction`, which every parsed
|
|
193
|
+
* sort carries — THE sort shape normalises an omitted one to `'asc'` (EC-660), so a
|
|
194
|
+
* config view declared `{ field }` flips on its first click instead of clearing.
|
|
195
|
+
*/
|
|
196
|
+
export declare function nextHeaderSort(prev: Sort | null, field: string): Sort | null;
|
|
190
197
|
/**
|
|
191
198
|
* Sort documents by one column in the canonical deterministic order
|
|
192
199
|
* (`compareListEntries`: typed value order, id-ascending tiebreak). Unlike the
|
|
193
200
|
* content accessors, the *table* may sort any rendered column — sorting is a
|
|
194
201
|
* presentation concern here; the `filterable` flag governs filters.
|
|
195
202
|
*/
|
|
196
|
-
export declare function sortViewDocuments(collection: CollectionDef, docs: readonly CmsDocument[], localeConfig: LocaleConfig, locale: Locale, sort:
|
|
203
|
+
export declare function sortViewDocuments(collection: CollectionDef, docs: readonly CmsDocument[], localeConfig: LocaleConfig, locale: Locale, sort: Sort | null, isPublished?: IsPublished, meta?: PseudoColumnMeta): CmsDocument[];
|
|
197
204
|
/** The filtered + sorted documents of a view, plus any clause issues. */
|
|
198
205
|
export interface AppliedViewState {
|
|
199
206
|
docs: CmsDocument[];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { canonicalDateValue, configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, resolveField, resolveLabel, STATE_FIELD, titleFieldOf, UPDATED_AT_FIELD, URL_FIELD,
|
|
2
|
+
import { canonicalDateValue, configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, resolveField, resolveLabel, STATE_FIELD, titleFieldOf, UPDATED_AT_FIELD, URL_FIELD, sortSchema, } from '@elytracms/core/cms-core';
|
|
3
3
|
import { localizedLabel, translate } from '../i18n/index.js';
|
|
4
4
|
import { contentQueryErrorMessage } from '../persona/labels.js';
|
|
5
5
|
import { compareListEntries, sortScalarOf, filterableFields, matchesFieldValue, validateWhere, } from '@elytracms/core/content';
|
|
@@ -22,12 +22,15 @@ import { compareListEntries, sortScalarOf, filterableFields, matchesFieldValue,
|
|
|
22
22
|
// --- Schemas (single source of truth — persisted view records reuse these) ----
|
|
23
23
|
// EC-622: the authoring shape of a view and the reserved `$` keys are declared ONCE, in
|
|
24
24
|
// cms-core (`collection-views.ts`), where the config gate judges every declared view —
|
|
25
|
-
// re-exported here unchanged, so this module's public names stay what they were.
|
|
26
|
-
|
|
25
|
+
// re-exported here unchanged, so this module's public names stay what they were. EC-660:
|
|
26
|
+
// a view's sort is THE sort shape (cms-core `list-query.ts`: `{ field, direction }`, a
|
|
27
|
+
// listing's and `listDocuments`' too), re-exported as `sortSchema` / `Sort` — the views'
|
|
28
|
+
// own `dir`-spelled schema is gone.
|
|
29
|
+
export { configViewSchema, filterClauseSchema, filterScalarSchema, isPseudoColumn, PUBLISHED_AT_FIELD, sortSchema, STATE_FIELD, UPDATED_AT_FIELD, URL_FIELD, };
|
|
27
30
|
export const tableViewStateSchema = z.object({
|
|
28
31
|
/** AND-only list of conditions (no OR, no nesting — vision AD-3). */
|
|
29
32
|
filters: z.array(filterClauseSchema),
|
|
30
|
-
sort:
|
|
33
|
+
sort: sortSchema.nullable(),
|
|
31
34
|
/**
|
|
32
35
|
* The canonical column order (field names) — EVERY column, visible or not
|
|
33
36
|
* (EC-213). Order is independent of visibility: hiding then re-showing a
|
|
@@ -338,6 +341,17 @@ export function clauseMatches(collection, doc, localeConfig, locale, clause, isP
|
|
|
338
341
|
// EC-586: the field def makes a `date` compare as an instant — delivery's exact rule.
|
|
339
342
|
return matchesFieldValue(value, condition, collection.fields.find((f) => f.name === clause.field));
|
|
340
343
|
}
|
|
344
|
+
/**
|
|
345
|
+
* The sort a column header click leads to (EC-169): a new column sorts ascending, the
|
|
346
|
+
* active one flips to descending, then clears. Reads `direction`, which every parsed
|
|
347
|
+
* sort carries — THE sort shape normalises an omitted one to `'asc'` (EC-660), so a
|
|
348
|
+
* config view declared `{ field }` flips on its first click instead of clearing.
|
|
349
|
+
*/
|
|
350
|
+
export function nextHeaderSort(prev, field) {
|
|
351
|
+
if (prev?.field !== field)
|
|
352
|
+
return { field, direction: 'asc' };
|
|
353
|
+
return prev.direction === 'asc' ? { field, direction: 'desc' } : null;
|
|
354
|
+
}
|
|
341
355
|
/**
|
|
342
356
|
* Sort documents by one column in the canonical deterministic order
|
|
343
357
|
* (`compareListEntries`: typed value order, id-ascending tiebreak). Unlike the
|
|
@@ -351,7 +365,7 @@ export function sortViewDocuments(collection, docs, localeConfig, locale, sort,
|
|
|
351
365
|
doc.id,
|
|
352
366
|
scalarOf(collection, doc, sort.field, localeConfig, locale, isPublished, meta),
|
|
353
367
|
]));
|
|
354
|
-
return [...docs].sort((a, b) => compareListEntries({ id: a.id, sortValue: positions.get(a.id) ?? null }, { id: b.id, sortValue: positions.get(b.id) ?? null }, sort.
|
|
368
|
+
return [...docs].sort((a, b) => compareListEntries({ id: a.id, sortValue: positions.get(a.id) ?? null }, { id: b.id, sortValue: positions.get(b.id) ?? null }, sort.direction));
|
|
355
369
|
}
|
|
356
370
|
/**
|
|
357
371
|
* Apply a view state to a document list: validate clauses, AND-match the valid
|