@elytracms/studio 0.0.94 → 0.0.96
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/asset-alt-migration.test.ts +2 -2
- package/convex/asset-meta-patch.test.ts +218 -0
- package/convex/asset-replace-delete-race.test.ts +127 -0
- package/convex/assets.ts +27 -2
- package/convex/cms.ts +124 -8
- package/convex/delivery-redirects.test.ts +167 -0
- package/convex/delivery.ts +15 -5
- package/convex/rail-write-parity.test.ts +6 -6
- package/convex/redirects.ts +1 -1
- package/convex/schema.ts +6 -0
- package/convex/strict-reference-race.test.ts +139 -0
- package/dist/addon.d.ts +1 -1
- package/dist/addon.js.map +1 -1
- 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 +29 -11
- package/dist/components/assets/asset-detail.js.map +1 -1
- package/dist/components/assets/asset-locale.d.ts +16 -0
- package/dist/components/assets/asset-locale.js +30 -0
- package/dist/components/assets/asset-locale.js.map +1 -0
- 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 +13 -0
- package/dist/components/assets/asset-meta-label.js +17 -0
- package/dist/components/assets/asset-meta-label.js.map +1 -0
- package/dist/components/assets/asset-metadata.d.ts +89 -15
- package/dist/components/assets/asset-metadata.js +123 -11
- 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 +19 -3
- package/dist/components/assets/asset-search.js.map +1 -1
- package/dist/components/assets/asset-thumb.js +6 -2
- package/dist/components/assets/asset-thumb.js.map +1 -1
- package/dist/components/assets/assets-collection-view-source.d.ts +25 -9
- package/dist/components/assets/assets-collection-view-source.js +80 -26
- package/dist/components/assets/assets-collection-view-source.js.map +1 -1
- package/dist/components/assets/assets-store.js +17 -4
- package/dist/components/assets/assets-store.js.map +1 -1
- package/dist/components/builder/builder-store.d.ts +21 -0
- package/dist/components/builder/builder-store.js +22 -0
- package/dist/components/builder/builder-store.js.map +1 -1
- package/dist/components/builder/canvas-commit-boundary.d.ts +22 -0
- package/dist/components/builder/canvas-commit-boundary.js +27 -0
- package/dist/components/builder/canvas-commit-boundary.js.map +1 -0
- package/dist/components/builder/canvas-rebase.d.ts +101 -0
- package/dist/components/builder/canvas-rebase.js +179 -0
- package/dist/components/builder/canvas-rebase.js.map +1 -0
- package/dist/components/builder/canvas-render-context.d.ts +6 -3
- package/dist/components/builder/canvas-render-context.js +17 -8
- package/dist/components/builder/canvas-render-context.js.map +1 -1
- package/dist/components/builder/composition-field-editor.d.ts +26 -2
- package/dist/components/builder/composition-field-editor.js +46 -27
- package/dist/components/builder/composition-field-editor.js.map +1 -1
- package/dist/components/builder/node-factory.js +15 -3
- package/dist/components/builder/node-factory.js.map +1 -1
- package/dist/components/builder/property-inspector.js +3 -1
- package/dist/components/builder/property-inspector.js.map +1 -1
- package/dist/components/builder/run-inspector.js +10 -6
- package/dist/components/builder/run-inspector.js.map +1 -1
- package/dist/components/cms/asset-field.d.ts +5 -2
- package/dist/components/cms/asset-field.js +34 -17
- package/dist/components/cms/asset-field.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 +6 -2
- package/dist/components/cms/asset-picker.js.map +1 -1
- package/dist/components/cms/canvas-commit.d.ts +62 -0
- package/dist/components/cms/canvas-commit.js +39 -0
- package/dist/components/cms/canvas-commit.js.map +1 -0
- package/dist/components/cms/cms-store.d.ts +21 -8
- package/dist/components/cms/cms-store.js +19 -10
- package/dist/components/cms/cms-store.js.map +1 -1
- package/dist/components/cms/collection-table.js +27 -18
- package/dist/components/cms/collection-table.js.map +1 -1
- package/dist/components/cms/commit-policy.d.ts +6 -2
- package/dist/components/cms/commit-policy.js +1 -1
- package/dist/components/cms/commit-policy.js.map +1 -1
- package/dist/components/cms/detail-editor.js +12 -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 +121 -5
- package/dist/components/cms/use-document-draft.js +197 -54
- package/dist/components/cms/use-document-draft.js.map +1 -1
- package/dist/components/cms/use-live-url.d.ts +6 -1
- package/dist/components/cms/use-live-url.js +12 -9
- package/dist/components/cms/use-live-url.js.map +1 -1
- package/dist/components/collection-view/cms-collection-view-source.js +11 -5
- 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/components/deployment-setup-gate.js +10 -1
- package/dist/components/deployment-setup-gate.js.map +1 -1
- package/dist/components/records/record-lens.js +3 -8
- package/dist/components/records/record-lens.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/assets/upload.d.ts +25 -7
- package/dist/lib/assets/upload.js +30 -21
- package/dist/lib/assets/upload.js.map +1 -1
- package/dist/lib/cms/published-documents.d.ts +24 -6
- package/dist/lib/cms/published-documents.js +39 -6
- package/dist/lib/cms/published-documents.js.map +1 -1
- package/dist/lib/cms-views/view-model.d.ts +25 -105
- package/dist/lib/cms-views/view-model.js +36 -103
- 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 +21 -8
- 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 +20 -4
- package/dist/lib/i18n/messages.de.js.map +1 -1
- package/dist/lib/i18n/messages.en.d.ts +16 -1
- package/dist/lib/i18n/messages.en.js +22 -5
- package/dist/lib/i18n/messages.en.js.map +1 -1
- package/dist/lib/operations/cms-persistence.d.ts +80 -35
- package/dist/lib/operations/cms-persistence.js +348 -85
- package/dist/lib/operations/cms-persistence.js.map +1 -1
- package/dist/lib/operations/config-manifest-lookup.d.ts +1 -1
- package/dist/lib/operations/config-manifest-lookup.js +3 -3
- package/dist/lib/operations/config-manifest-lookup.js.map +1 -1
- package/dist/lib/persistence/convex-adapter.js +54 -8
- package/dist/lib/persistence/convex-adapter.js.map +1 -1
- package/dist/lib/persistence/deployment-readiness.js +14 -11
- package/dist/lib/persistence/deployment-readiness.js.map +1 -1
- package/dist/lib/persona/labels.js +2 -0
- package/dist/lib/persona/labels.js.map +1 -1
- package/dist/lib/query/index.d.ts +2 -2
- package/dist/lib/query/index.js +1 -1
- package/dist/lib/query/index.js.map +1 -1
- package/dist/lib/query/operations-query.d.ts +26 -0
- package/dist/lib/query/operations-query.js +12 -0
- package/dist/lib/query/operations-query.js.map +1 -1
- package/dist/lib/registry/index.js +2 -2
- package/dist/lib/registry/index.js.map +1 -1
- package/dist/lib/registry/preview.d.ts +10 -0
- package/dist/lib/registry/preview.js +13 -4
- package/dist/lib/registry/preview.js.map +1 -1
- package/dist/lib/routes/route-issues.js +6 -3
- package/dist/lib/routes/route-issues.js.map +1 -1
- package/dist/lib/workspace/workspace-source.js +6 -7
- package/dist/lib/workspace/workspace-source.js.map +1 -1
- package/dist/previews/entry-node.d.ts +14 -0
- package/dist/previews/entry-node.js +22 -0
- package/dist/previews/entry-node.js.map +1 -0
- package/dist/previews/harness.js +2 -16
- package/dist/previews/harness.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deployment-setup-gate.js","sourceRoot":"","sources":["../../src/components/deployment-setup-gate.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEjE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAA;AAC1G,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,4BAA4B,EAC5B,oBAAoB,GACrB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAA;AAO5F;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAAE,QAAQ,EAA2B;IACvE,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,oBAAoB,EAAE,EAAE,EAAE,CAAC,CAAA;IACxD,iFAAiF;IACjF,kFAAkF;IAClF,MAAM,iBAAiB,GAAG,OAAO,CAAC,GAAG,EAAE;QACrC,MAAM,EAAE,GAAG,mBAAmB,EAAE,CAAA;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AC,QAAG,KAAC,IAAI,IAAC,SAAS,EAAC,WAAW,YAAE,KAAK,CAAC,GAAG,GAAQ,IACxF,CACR,CAAC,CAAC,CAAC,IAAI,IACJ,CACP,CAAA;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,EAAE,KAAK,EAA6B;IACpD,OAAO,CACL,eAAK,IAAI,EAAC,UAAU,EAAC,SAAS,EAAC,8DAA8D,aAC3F,MAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,IAAI,QAAC,SAAS,EAAC,kBAAkB,kBAC7C,KAAK,CAAC,EAAE,SACL,EACP,KAAC,IAAI,IAAC,IAAI,EAAC,IAAI,YAAE,KAAK,CAAC,MAAM,GAAQ,EACpC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CACX,MAAC,IAAI,IAAC,IAAI,EAAC,IAAI,EAAC,IAAI,EAAC,OAAO,EAAC,SAAS,EAAC,MAAM,aAC1C,SAAS,CAAC,gCAAgC,CAAC,QAAG,KAAC,IAAI,IAAC,SAAS,EAAC,WAAW,YAAE,KAAK,CAAC,GAAG,GAAQ,IACxF,CACR,CAAC,CAAC,CAAC,IAAI,IACJ,CACP,CAAA;AACH,CAAC;AAED,SAAS,eAAe,CAAC,EAAE,QAAQ,EAA2B;IAC5D,OAAO,cAAK,SAAS,EAAC,qDAAqD,YAAE,QAAQ,GAAO,CAAA;AAC9F,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport { Loader2 } from 'lucide-react'\nimport { Button, Card, CardContent, CardHeader, CardTitle, Code, Stack, Text } from '@elytracms/studio/ui'\nimport {\n resolveBackendConfig,\n selectPersistenceAdapter,\n studioDeploymentReadiness,\n} from '../lib/persistence'\nimport {\n getWorkspaceState,\n resolveDeploymentAi,\n resolveDeploymentCollections,\n resolveDeploymentUrl,\n} from '../lib/workspace'\nimport { translate, useHydrated, useT } from '../lib/i18n'\nimport { probeDeployedFunctionsVersion } from '@elytracms/core/export-sync/deployment-ready'\nimport type {\n DeploymentReadinessReport,\n FunctionsVersionProbe,\n ReadinessCheck,\n} from '@elytracms/core/export-sync/deployment-ready'\n\n/**\n * Deployment-setup boot gate (EC-258) — the single readiness surface that\n * supersedes the separate `BackendGate` (missing `VITE_CONVEX_URL` / unreachable)\n * and `WorkspaceGate` (invalid config) screens by composing the shared\n * `checkDeploymentReady` contract. It renders ONE deterministic \"Deployment setup\"\n * screen listing each failing precondition with its copy-pasteable fix, instead of\n * letting the app boot into a misleading downstream error (most painfully the\n * Konditorei JWT-key footgun). All checks passing → children render untouched.\n *\n * Runs before auth and any adapter is constructed (it is the thing that keeps\n * `selectAuthAdapter`/`selectPersistenceAdapter` from throwing on a misconfigured\n * backend). Convex mode probes reachability once on the client (`adapter.status()`)\n * with a retry; playground and unconfigured resolve synchronously. SSR renders the\n * deterministic \"checking\" state. Auth-signing-keys is reported as `unknown` at boot\n * (the JWKS endpoint is CORS-blocked from the browser — EC-257's honest sign-in error\n * is the browser's actionable surface; `elytra doctor` probes it from node), and the\n * per-user bucket stays `unknown` (this gate runs pre-auth), so neither ever blocks boot.\n */\nexport function DeploymentSetupGate({ children }: { children: ReactNode }) {\n const config = useMemo(() => resolveBackendConfig(), [])\n // EC-399: a configured (and not disabled) `defineStudio({ ai })` block means the\n // AI route exists — its provider-key expectation joins the deployment-env checks.\n const aiRouteConfigured = useMemo(() => {\n const ai = resolveDeploymentAi()\n return Boolean(ai && ai.enabled !== false)\n }, [])\n\n const staticReport = useCallback(\n (): DeploymentReadinessReport =>\n studioDeploymentReadiness({\n backend: config,\n workspace: getWorkspaceState(),\n collections: resolveDeploymentCollections(),\n aiRouteConfigured,\n }),\n [config, aiRouteConfigured],\n )\n\n const [state, setState] = useState<GateState>(() =>\n config.kind === 'convex' ? { phase: 'checking' } : { phase: 'resolved', report: staticReport() },\n )\n\n const check = useCallback(() => {\n if (config.kind !== 'convex') {\n setState({ phase: 'resolved', report: staticReport() })\n return\n }\n const effectiveUrl = resolveDeploymentUrl(config.url)\n const resolve = (\n reachable: { available: boolean; detail?: string },\n functionsVersion: FunctionsVersionProbe,\n ) =>\n setState({\n phase: 'resolved',\n report: studioDeploymentReadiness({\n backend: config,\n effectiveUrl,\n workspace: getWorkspaceState(),\n collections: resolveDeploymentCollections(),\n reachable,\n functionsVersion,\n aiRouteConfigured,\n }),\n })\n setState({ phase: 'checking' })\n // EC-552: the version handshake probes in parallel with the reachability check —\n // same deployment URL, one extra public query. The probe never rejects (network\n // failures resolve to an honest `unknown`), so awaiting it in both paths is safe.\n const versionProbe = probeDeployedFunctionsVersion(effectiveUrl)\n void selectPersistenceAdapter()\n .then((adapter) => adapter.status())\n .then(async (status) =>\n resolve(\n { available: status.available, ...(status.detail ? { detail: status.detail } : {}) },\n await versionProbe,\n ),\n )\n .catch(async (error: unknown) =>\n resolve(\n { available: false, detail: error instanceof Error ? error.message : String(error) },\n await versionProbe,\n ),\n )\n }, [config, staticReport, aiRouteConfigured])\n\n useEffect(() => {\n if (config.kind === 'convex') check()\n }, [config.kind, check])\n\n if (state.phase === 'checking') return <DeploymentChecking />\n if (blockingFailures(state.report).length > 0) {\n return (\n <DeploymentSetupScreen\n report={state.report}\n onRetry={config.kind === 'convex' ? check : undefined}\n />\n )\n }\n return <>{children}</>\n}\n\ntype GateState = { phase: 'checking' } | { phase: 'resolved'; report: DeploymentReadinessReport }\n\n/**\n * The checks that BLOCK boot: a failed deployment-, deployment-env-, or app-level\n * precondition. The per-user bucket (\"not a member\") is not a boot blocker — it is\n * surfaced post-auth (\"ask an admin\"), and at boot it is `unknown` (pre-auth) anyway.\n * Deployment-env checks are `unknown` in the browser today (nothing gathered — EC-399),\n * so they never block in practice; `warn` findings never block anywhere.\n */\nfunction blockingFailures(report: DeploymentReadinessReport): ReadinessCheck[] {\n return report.checks.filter(\n (c) =>\n c.status === 'fail' &&\n (c.bucket === 'deployment' || c.bucket === 'deployment-env' || c.bucket === 'app'),\n )\n}\n\n/**\n * Deterministic boot state while the backend probe is in flight — and, in a\n * CONNECTED build, the body of the prerendered shell itself.\n *\n * **EC-525.** EC-523 removed the last localized string from the shell and proved it\n * against the built artefact — but against the *playground* build, which is the demo's\n * default and the one nobody deploys. Every real studio is connected, so\n * `config.kind === 'convex'` seeds `{ phase: 'checking' }` and *this* is what a\n * production cold load actually bakes: `Checking deployment…`, in the build machine's\n * locale, shown to every visitor whatever theirs is. The class was not closed until\n * both builds satisfied it.\n *\n * Same shape as `SessionLoading` (`router/root.tsx`), for the same reasons, which are\n * written out there: a build-time prerender has no request and therefore no locale, so\n * the shell shows a spinner and an EMPTY `role=\"status\"` region, and `useHydrated`\n * fills it in the visitor's real language once hydration lands. No `aria-label` — that\n * bakes the wrong-language string somewhere a screen-reader user cannot see it flip —\n * and no `aria-busy`, which would suppress the announcement this shape exists to make.\n *\n * Exported so the connected shell's pre-hydration markup is pinnable with\n * `renderToStaticMarkup` — same reason `SessionLoading` is. The built artefact is the\n * real proof; the pin is what fails when someone puts a string back.\n */\nexport function DeploymentChecking() {\n const hydrated = useHydrated()\n const t = useT()\n return (\n <BootScreenFrame>\n <div role=\"status\">\n <Loader2 className=\"size-6 animate-spin text-muted-foreground\" aria-hidden=\"true\" />\n {hydrated ? <span className=\"sr-only\">{t('shell.deploymentSetup.checking')}</span> : null}\n </div>\n </BootScreenFrame>\n )\n}\n\n/**\n * The unified \"Deployment setup\" screen (EC-258): every failing check + its exact\n * fix. Pure/presentational so it is fixture-reproducible and static-render testable.\n */\nexport function DeploymentSetupScreen({\n report,\n onRetry,\n}: {\n report: DeploymentReadinessReport\n onRetry?: () => void\n}) {\n const failures = report.checks.filter((c) => c.status === 'fail')\n const envChecks = report.checks.filter((c) => c.bucket === 'deployment-env')\n return (\n <BootScreenFrame>\n <Card className=\"max-w-2xl border-destructive/40\">\n <CardHeader>\n <CardTitle>{translate('shell.deploymentSetup.title')}</CardTitle>\n </CardHeader>\n <CardContent>\n <Stack gap=\"3\">\n <Text size=\"sm\" tone=\"muted\">\n {translate('shell.deploymentSetup.description')}\n </Text>\n <Stack gap=\"2\" role=\"list\" aria-label={translate('shell.deploymentSetup.issuesLabel')}>\n {failures.map((check) => (\n <CheckRow key={check.id} check={check} />\n ))}\n </Stack>\n {envChecks.length > 0 ? <ExpectedEnvSection checks={envChecks} /> : null}\n {onRetry ? (\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry} className=\"self-start\">\n {translate('shell.deploymentSetup.retry')}\n </Button>\n ) : null}\n </Stack>\n </CardContent>\n </Card>\n </BootScreenFrame>\n )\n}\n\n/**\n * The expected-env facts (EC-399) — the SAME contract `elytra doctor` checks, so the\n * studio and CLI tell one story. Presence only: each row is a var name + set/missing/\n * unknown status text; values never exist in the report. In the browser the presence\n * sources aren't readable pre-auth, so rows typically read `unknown` and point at\n * `elytra doctor` — which is exactly the honest answer.\n */\nfunction ExpectedEnvSection({ checks }: { checks: ReadinessCheck[] }) {\n return (\n <Stack gap=\"2\">\n <Text size=\"sm\" className=\"font-medium\">\n {translate('shell.deploymentSetup.envSection')}\n </Text>\n <Text size=\"xs\" tone=\"muted\">\n {translate('shell.deploymentSetup.envSectionHint')}\n </Text>\n <Stack gap=\"1\" role=\"list\" aria-label={translate('shell.deploymentSetup.envSection')}>\n {checks.map((check) => (\n <EnvCheckRow key={check.id} check={check} />\n ))}\n </Stack>\n </Stack>\n )\n}\n\nconst ENV_STATUS_GLYPH: Record<ReadinessCheck['status'], string> = {\n ok: '✓',\n warn: '!',\n fail: '✗',\n unknown: '?',\n}\n\nfunction EnvCheckRow({ check }: { check: ReadinessCheck }) {\n const failing = check.status === 'fail'\n return (\n <div\n role=\"listitem\"\n className={`rounded-md border p-2 ${failing ? 'border-destructive/30 bg-destructive/5' : 'border-border bg-muted/30'}`}\n >\n <Text size=\"xs\" mono className={failing ? 'text-destructive' : undefined}>\n {ENV_STATUS_GLYPH[check.status]} [{check.id}]\n </Text>\n <Text size=\"xs\" tone=\"muted\">\n {check.detail}\n </Text>\n {check.fix && (check.status === 'fail' || check.status === 'warn') ? (\n <Text size=\"xs\" tone=\"muted\" className=\"mt-1\">\n {translate('shell.deploymentSetup.fixLabel')}: <Code className=\"break-all\">{check.fix}</Code>\n </Text>\n ) : null}\n </div>\n )\n}\n\nfunction CheckRow({ check }: { check: ReadinessCheck }) {\n return (\n <div role=\"listitem\" className=\"rounded-md border border-destructive/30 bg-destructive/5 p-2\">\n <Text size=\"xs\" mono className=\"text-destructive\">\n [{check.id}]\n </Text>\n <Text size=\"sm\">{check.detail}</Text>\n {check.fix ? (\n <Text size=\"xs\" tone=\"muted\" className=\"mt-1\">\n {translate('shell.deploymentSetup.fixLabel')}: <Code className=\"break-all\">{check.fix}</Code>\n </Text>\n ) : null}\n </div>\n )\n}\n\nfunction BootScreenFrame({ children }: { children: ReactNode }) {\n return <div className=\"grid min-h-dvh place-items-center bg-background p-6\">{children}</div>\n}\n"]}
|
|
1
|
+
{"version":3,"file":"deployment-setup-gate.js","sourceRoot":"","sources":["../../src/components/deployment-setup-gate.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAEjE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAA;AAC1G,OAAO,EACL,oBAAoB,EACpB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EACnB,4BAA4B,EAC5B,oBAAoB,GACrB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAC1D,OAAO,EAAE,6BAA6B,EAAE,MAAM,8CAA8C,CAAA;AAO5F;;;;;;;;;;;;;;;;;G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AiC;IAC/D,OAAO,CACL,KAAC,KAAK,IAAC,GAAG,EAAC,GAAG,EAAC,IAAI,EAAC,MAAM,gBAAa,SAAS,CAAC,iCAAiC,CAAC,EAAE,SAAS,EAAC,MAAM,YAClG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAC5B,KAAC,IAAI,IAAa,IAAI,EAAC,UAAU,EAAC,IAAI,EAAC,IAAI,EAAC,IAAI,QAAC,SAAS,EAAC,aAAa,YACrE,KAAK,IADG,KAAK,CAET,CACR,CAAC,GACI,CACT,CAAA;AACH,CAAC;AAED,SAAS,eAAe,CAAC,EAAE,QAAQ,EAA2B;IAC5D,OAAO,cAAK,SAAS,EAAC,qDAAqD,YAAE,QAAQ,GAAO,CAAA;AAC9F,CAAC","sourcesContent":["import { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { ReactNode } from 'react'\nimport { Loader2 } from 'lucide-react'\nimport { Button, Card, CardContent, CardHeader, CardTitle, Code, Stack, Text } from '@elytracms/studio/ui'\nimport {\n resolveBackendConfig,\n selectPersistenceAdapter,\n studioDeploymentReadiness,\n} from '../lib/persistence'\nimport {\n getWorkspaceState,\n resolveDeploymentAi,\n resolveDeploymentCollections,\n resolveDeploymentUrl,\n} from '../lib/workspace'\nimport { translate, useHydrated, useT } from '../lib/i18n'\nimport { probeDeployedFunctionsVersion } from '@elytracms/core/export-sync/deployment-ready'\nimport type {\n DeploymentReadinessReport,\n FunctionsVersionProbe,\n ReadinessCheck,\n} from '@elytracms/core/export-sync/deployment-ready'\n\n/**\n * Deployment-setup boot gate (EC-258) — the single readiness surface that\n * supersedes the separate `BackendGate` (missing `VITE_CONVEX_URL` / unreachable)\n * and `WorkspaceGate` (invalid config) screens by composing the shared\n * `checkDeploymentReady` contract. It renders ONE deterministic \"Deployment setup\"\n * screen listing each failing precondition with its copy-pasteable fix, instead of\n * letting the app boot into a misleading downstream error (most painfully the\n * Konditorei JWT-key footgun). All checks passing → children render untouched.\n *\n * Runs before auth and any adapter is constructed (it is the thing that keeps\n * `selectAuthAdapter`/`selectPersistenceAdapter` from throwing on a misconfigured\n * backend). Convex mode probes reachability once on the client (`adapter.status()`)\n * with a retry; playground and unconfigured resolve synchronously. SSR renders the\n * deterministic \"checking\" state. Auth-signing-keys is reported as `unknown` at boot\n * (the JWKS endpoint is CORS-blocked from the browser — EC-257's honest sign-in error\n * is the browser's actionable surface; `elytra doctor` probes it from node), and the\n * per-user bucket stays `unknown` (this gate runs pre-auth), so neither ever blocks boot.\n */\nexport function DeploymentSetupGate({ children }: { children: ReactNode }) {\n const config = useMemo(() => resolveBackendConfig(), [])\n // EC-399: a configured (and not disabled) `defineStudio({ ai })` block means the\n // AI route exists — its provider-key expectation joins the deployment-env checks.\n const aiRouteConfigured = useMemo(() => {\n const ai = resolveDeploymentAi()\n return Boolean(ai && ai.enabled !== false)\n }, [])\n\n const staticReport = useCallback(\n (): DeploymentReadinessReport =>\n studioDeploymentReadiness({\n backend: config,\n workspace: getWorkspaceState(),\n collections: resolveDeploymentCollections(),\n aiRouteConfigured,\n }),\n [config, aiRouteConfigured],\n )\n\n const [state, setState] = useState<GateState>(() =>\n config.kind === 'convex' ? { phase: 'checking' } : { phase: 'resolved', report: staticReport() },\n )\n\n const check = useCallback(() => {\n if (config.kind !== 'convex') {\n setState({ phase: 'resolved', report: staticReport() })\n return\n }\n const effectiveUrl = resolveDeploymentUrl(config.url)\n const resolve = (\n reachable: { available: boolean; detail?: string },\n functionsVersion: FunctionsVersionProbe,\n ) =>\n setState({\n phase: 'resolved',\n report: studioDeploymentReadiness({\n backend: config,\n effectiveUrl,\n workspace: getWorkspaceState(),\n collections: resolveDeploymentCollections(),\n reachable,\n functionsVersion,\n aiRouteConfigured,\n }),\n })\n setState({ phase: 'checking' })\n // EC-552: the version handshake probes in parallel with the reachability check —\n // same deployment URL, one extra public query. The probe never rejects (network\n // failures resolve to an honest `unknown`), so awaiting it in both paths is safe.\n const versionProbe = probeDeployedFunctionsVersion(effectiveUrl)\n void selectPersistenceAdapter()\n .then((adapter) => adapter.status())\n .then(async (status) =>\n resolve(\n { available: status.available, ...(status.detail ? { detail: status.detail } : {}) },\n await versionProbe,\n ),\n )\n .catch(async (error: unknown) =>\n resolve(\n { available: false, detail: error instanceof Error ? error.message : String(error) },\n await versionProbe,\n ),\n )\n }, [config, staticReport, aiRouteConfigured])\n\n useEffect(() => {\n if (config.kind === 'convex') check()\n }, [config.kind, check])\n\n if (state.phase === 'checking') return <DeploymentChecking />\n if (blockingFailures(state.report).length > 0) {\n return (\n <DeploymentSetupScreen\n report={state.report}\n onRetry={config.kind === 'convex' ? check : undefined}\n />\n )\n }\n return <>{children}</>\n}\n\ntype GateState = { phase: 'checking' } | { phase: 'resolved'; report: DeploymentReadinessReport }\n\n/**\n * The checks that BLOCK boot: a failed deployment-, deployment-env-, or app-level\n * precondition. The per-user bucket (\"not a member\") is not a boot blocker — it is\n * surfaced post-auth (\"ask an admin\"), and at boot it is `unknown` (pre-auth) anyway.\n * Deployment-env checks are `unknown` in the browser today (nothing gathered — EC-399),\n * so they never block in practice; `warn` findings never block anywhere.\n */\nfunction blockingFailures(report: DeploymentReadinessReport): ReadinessCheck[] {\n return report.checks.filter(\n (c) =>\n c.status === 'fail' &&\n (c.bucket === 'deployment' || c.bucket === 'deployment-env' || c.bucket === 'app'),\n )\n}\n\n/**\n * Deterministic boot state while the backend probe is in flight — and, in a\n * CONNECTED build, the body of the prerendered shell itself.\n *\n * **EC-525.** EC-523 removed the last localized string from the shell and proved it\n * against the built artefact — but against the *playground* build, which is the demo's\n * default and the one nobody deploys. Every real studio is connected, so\n * `config.kind === 'convex'` seeds `{ phase: 'checking' }` and *this* is what a\n * production cold load actually bakes: `Checking deployment…`, in the build machine's\n * locale, shown to every visitor whatever theirs is. The class was not closed until\n * both builds satisfied it.\n *\n * Same shape as `SessionLoading` (`router/root.tsx`), for the same reasons, which are\n * written out there: a build-time prerender has no request and therefore no locale, so\n * the shell shows a spinner and an EMPTY `role=\"status\"` region, and `useHydrated`\n * fills it in the visitor's real language once hydration lands. No `aria-label` — that\n * bakes the wrong-language string somewhere a screen-reader user cannot see it flip —\n * and no `aria-busy`, which would suppress the announcement this shape exists to make.\n *\n * Exported so the connected shell's pre-hydration markup is pinnable with\n * `renderToStaticMarkup` — same reason `SessionLoading` is. The built artefact is the\n * real proof; the pin is what fails when someone puts a string back.\n */\nexport function DeploymentChecking() {\n const hydrated = useHydrated()\n const t = useT()\n return (\n <BootScreenFrame>\n <div role=\"status\">\n <Loader2 className=\"size-6 animate-spin text-muted-foreground\" aria-hidden=\"true\" />\n {hydrated ? <span className=\"sr-only\">{t('shell.deploymentSetup.checking')}</span> : null}\n </div>\n </BootScreenFrame>\n )\n}\n\n/**\n * The unified \"Deployment setup\" screen (EC-258): every failing check + its exact\n * fix. Pure/presentational so it is fixture-reproducible and static-render testable.\n */\nexport function DeploymentSetupScreen({\n report,\n onRetry,\n}: {\n report: DeploymentReadinessReport\n onRetry?: () => void\n}) {\n const failures = report.checks.filter((c) => c.status === 'fail')\n const envChecks = report.checks.filter((c) => c.bucket === 'deployment-env')\n return (\n <BootScreenFrame>\n <Card className=\"max-w-2xl border-destructive/40\">\n <CardHeader>\n <CardTitle>{translate('shell.deploymentSetup.title')}</CardTitle>\n </CardHeader>\n <CardContent>\n <Stack gap=\"3\">\n <Text size=\"sm\" tone=\"muted\">\n {translate('shell.deploymentSetup.description')}\n </Text>\n <Stack gap=\"2\" role=\"list\" aria-label={translate('shell.deploymentSetup.issuesLabel')}>\n {failures.map((check) => (\n <CheckRow key={check.id} check={check} />\n ))}\n </Stack>\n {envChecks.length > 0 ? <ExpectedEnvSection checks={envChecks} /> : null}\n {onRetry ? (\n <Button variant=\"outline\" size=\"sm\" onClick={onRetry} className=\"self-start\">\n {translate('shell.deploymentSetup.retry')}\n </Button>\n ) : null}\n </Stack>\n </CardContent>\n </Card>\n </BootScreenFrame>\n )\n}\n\n/**\n * The expected-env facts (EC-399) — the SAME contract `elytra doctor` checks, so the\n * studio and CLI tell one story. Presence only: each row is a var name + set/missing/\n * unknown status text; values never exist in the report. In the browser the presence\n * sources aren't readable pre-auth, so rows typically read `unknown` and point at\n * `elytra doctor` — which is exactly the honest answer.\n */\nfunction ExpectedEnvSection({ checks }: { checks: ReadinessCheck[] }) {\n return (\n <Stack gap=\"2\">\n <Text size=\"sm\" className=\"font-medium\">\n {translate('shell.deploymentSetup.envSection')}\n </Text>\n <Text size=\"xs\" tone=\"muted\">\n {translate('shell.deploymentSetup.envSectionHint')}\n </Text>\n <Stack gap=\"1\" role=\"list\" aria-label={translate('shell.deploymentSetup.envSection')}>\n {checks.map((check) => (\n <EnvCheckRow key={check.id} check={check} />\n ))}\n </Stack>\n </Stack>\n )\n}\n\nconst ENV_STATUS_GLYPH: Record<ReadinessCheck['status'], string> = {\n ok: '✓',\n warn: '!',\n fail: '✗',\n unknown: '?',\n}\n\nfunction EnvCheckRow({ check }: { check: ReadinessCheck }) {\n const failing = check.status === 'fail'\n return (\n <div\n role=\"listitem\"\n className={`rounded-md border p-2 ${failing ? 'border-destructive/30 bg-destructive/5' : 'border-border bg-muted/30'}`}\n >\n <Text size=\"xs\" mono className={failing ? 'text-destructive' : undefined}>\n {ENV_STATUS_GLYPH[check.status]} [{check.id}]\n </Text>\n <Text size=\"xs\" tone=\"muted\">\n {check.detail}\n </Text>\n {check.fix && (check.status === 'fail' || check.status === 'warn') ? (\n <Text size=\"xs\" tone=\"muted\" className=\"mt-1\">\n {translate('shell.deploymentSetup.fixLabel')}: <Code className=\"break-all\">{check.fix}</Code>\n </Text>\n ) : null}\n </div>\n )\n}\n\nfunction CheckRow({ check }: { check: ReadinessCheck }) {\n return (\n <div role=\"listitem\" className=\"rounded-md border border-destructive/30 bg-destructive/5 p-2\">\n <Text size=\"xs\" mono className=\"text-destructive\">\n [{check.id}]\n </Text>\n <Text size=\"sm\">{check.detail}</Text>\n {check.issues && check.issues.length > 0 ? <CheckIssueList issues={check.issues} /> : null}\n {check.fix ? (\n <Text size=\"xs\" tone=\"muted\" className=\"mt-1\">\n {translate('shell.deploymentSetup.fixLabel')}: <Code className=\"break-all\">{check.fix}</Code>\n </Text>\n ) : null}\n </div>\n )\n}\n\n/**\n * EC-626 — the located issues behind a failing check, one line each, exactly as\n * `elytra doctor` prints them (core's `formatConfigIssue`, applied in the shared\n * contract): `config-valid` lists every config issue instead of a count. English, like\n * the check's `detail` — they name keys and paths in the developer's own config.\n */\nfunction CheckIssueList({ issues }: { issues: readonly string[] }) {\n return (\n <Stack gap=\"1\" role=\"list\" aria-label={translate('shell.workspaceGate.issuesLabel')} className=\"mt-1\">\n {issues.map((issue, index) => (\n <Text key={index} role=\"listitem\" size=\"xs\" mono className=\"break-words\">\n {issue}\n </Text>\n ))}\n </Stack>\n )\n}\n\nfunction BootScreenFrame({ children }: { children: ReactNode }) {\n return <div className=\"grid min-h-dvh place-items-center bg-background p-6\">{children}</div>\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { collectionDefSchema, semanticValueEqual } from '@elytracms/core/cms-core';
|
|
2
|
+
import { metaPatchBetween } from '@elytracms/core/persistence';
|
|
2
3
|
import { metaBagProjection } from '../rail-view-source.js';
|
|
3
4
|
/**
|
|
4
5
|
* EC-616 — the projections between a record kind and the portable list/edit surfaces
|
|
@@ -92,14 +93,8 @@ export function lensDocumentToRecordWrite(kind, doc, base) {
|
|
|
92
93
|
// A cleared optional column is `null` on the wire (EC-577: clear), never a silent absence.
|
|
93
94
|
write[column] = value === undefined ? (isRequiredText(field) ? '' : null) : columnWriteValue(field, value);
|
|
94
95
|
}
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
const metaPatch = {};
|
|
98
|
-
for (const key of new Set([...Object.keys(meta), ...Object.keys(baseMeta)])) {
|
|
99
|
-
if (semanticValueEqual(meta[key], baseMeta[key]))
|
|
100
|
-
continue;
|
|
101
|
-
metaPatch[key] = meta[key] === undefined ? null : meta[key];
|
|
102
|
-
}
|
|
96
|
+
// The one per-key diff (core `metaPatchBetween`), shared with the asset editors (EC-634).
|
|
97
|
+
const metaPatch = metaPatchBetween(metaBagProjection(before, columns), metaBagProjection(values, columns));
|
|
103
98
|
if (Object.keys(metaPatch).length > 0)
|
|
104
99
|
write.metaPatch = metaPatch;
|
|
105
100
|
return write;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"record-lens.js","sourceRoot":"","sources":["../../../src/components/records/record-lens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAGlF,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAEvD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,iFAAiF;AACjF,MAAM,UAAU,iBAAiB,CAAC,IAAmB;IACnD,OAAO,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;AAC1C,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB,CAA0B,IAAO,EAAE,KAAuB;IAC5F,MAAM,MAAM,GAAG,KAAgC,CAAA;IAC/C,MAAM,OAAO,GAA4B,EAAE,CAAA;IAC3C,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7C,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,SAAS;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;IACpE,CAAC;IACD,OAAO;QACL,UAAU,EAAE,IAAI,CAAC,IAAI;QACrB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACrB,MAAM,EAAE,EAAE,GAAG,CAAE,MAAM,CAAC,IAA4C,IAAI,EAAE,CAAC,EAAE,GAAG,OAAO,EAAE;KACxF,CAAA;AACH,CAAC;AAYD,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAQ,KAAuC,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msDocument, CollectionDef, FieldDef } from '@elytracms/core/cms-core'\nimport type { AnyRecordKind, RecordEntryOf, RecordWriteOf } from '@elytracms/core/persistence'\nimport { metaBagProjection } from '../rail-view-source'\n\n/**\n * EC-616 — the projections between a record kind and the portable list/edit surfaces\n * (AD-19): a record rail edits a record as a LENS document (`{ collection, id, values }`)\n * over a `CollectionDef`. Pure — no React — so the mapping that decides what a save\n * writes is unit-testable on its own (it is the one place the write is derived from the\n * edited lens; a slip here silently corrupts a record).\n *\n * - **Read** ({@link recordToLensDocument}): the stored `meta` bag spread FIRST, then\n * the kind's columns — a canonical column always wins over a same-named meta key\n * (RESIDUE-3c: spread last, a stored `meta.to` displayed as the redirect's target and a\n * re-save wrote it into the canonical `to`).\n * - **Write** ({@link lensDocumentToRecordWrite}): every lens value keyed by a column is\n * that column; every other key round-trips through the open `meta` bag (EC-311 Tier 2\n * — a mount's additive field). A column the document does not carry is left out, so the\n * stored value is kept (EC-577: a create default applies once, in the adapter's\n * transaction — never restated here). A REQUIRED text column is always sent (`''` when\n * blank): the editor owns it, and an empty one is refused visibly by the write's\n * validation rather than kept silently. `meta` is omitted when no additive value exists,\n * so a rail with no additive fields never touches the bag.\n */\n\n/** The kind's columns (its declared fields; `meta` is the bag, not a column). */\nexport function recordColumnNames(kind: AnyRecordKind): ReadonlySet<string> {\n return new Set(Object.keys(kind.fields))\n}\n\n/** A stored record as the lens document the portable surfaces edit. */\nexport function recordToLensDocument<K extends AnyRecordKind>(kind: K, entry: RecordEntryOf<K>): CmsDocument {\n const record = entry as Record<string, unknown>\n const columns: Record<string, unknown> = {}\n for (const column of recordColumnNames(kind)) {\n if (record[column] !== undefined) columns[column] = record[column]\n }\n return {\n collection: kind.kind,\n id: String(record.id),\n values: { ...((record.meta as Record<string, unknown> | undefined) ?? {}), ...columns },\n }\n}\n\n/**\n * A column's zod definition, read through `_zod.def` rather than `instanceof`: a kind is\n * declared in whichever package owns it (an addon), whose `zod` may be a different copy\n * than this one — `instanceof` across copies is silently false.\n */\ninterface ZodDefView {\n type: string\n innerType?: { _zod: { def: ZodDefView } }\n entries?: Record<string, unknown>\n}\nfunction defOf(field: unknown): ZodDefView {\n return (field as { _zod: { def: ZodDefView } })._zod.def\n}\n\n/** Is this column a required text column (no default, not optional)? */\nfunction isRequiredText(field: unknown): boolean {\n return defOf(field).type === 'string'\n}\n\n/** The column's own definition, below any optional/default/nullable wrapper. */\nfunction unwrapped(field: unknown): ZodDefView {\n let def = defOf(field)\n while ((def.type === 'optional' || def.type === 'default' || def.type === 'nullable') && def.innerType) {\n def = def.innerType._zod.def\n }\n return def\n}\n\n/** A lens value as the write sends it for one column (a required text column is always a string). */\nfunction columnWriteValue(field: unknown, value: unknown): unknown {\n return isRequiredText(field) ? (typeof value === 'string' ? value : '') : value\n}\n\n/**\n * An edited lens document as the record write (see the module header).\n *\n * **With `base`** — the lens document of the record as the editor OPENED it — the write\n * carries only what the editor changed (EC-616, the multi-session baseline): a column whose\n * value differs from the base, and the changed `meta` keys as a per-key `metaPatch` (a key the\n * editor removed is `null`). Every other column is ABSENT, so the EC-577 rule keeps the stored\n * value — a column another writer changed after the editor opened the record survives the\n * editor's save. With nothing changed the write is just the id (a no-op edit).\n *\n * **Without `base`** (a record the editor is creating) the write is whole, as it always was.\n */\nexport function lensDocumentToRecordWrite<K extends AnyRecordKind>(\n kind: K,\n doc: CmsDocument,\n base?: CmsDocument,\n): RecordWriteOf<K> {\n const values = doc.values ?? {}\n const write: Record<string, unknown> = { id: doc.id }\n const columns = recordColumnNames(kind)\n if (!base) {\n for (const [column, field] of Object.entries(kind.fields)) {\n const value = columnWriteValue(field, values[column])\n if (value !== undefined) write[column] = value\n }\n const meta = metaBagProjection(values, columns)\n if (Object.keys(meta).length > 0) write.meta = meta\n return write as RecordWriteOf<K>\n }\n const before = base.values ?? {}\n for (const [column, field] of Object.entries(kind.fields)) {\n const value = values[column]\n if (semanticValueEqual(value, before[column])) continue\n // A cleared optional column is `null` on the wire (EC-577: clear), never a silent absence.\n write[column] = value === undefined ? (isRequiredText(field) ? '' : null) : columnWriteValue(field, value)\n }\n const meta = metaBagProjection(values, columns)\n const baseMeta = metaBagProjection(before, columns)\n const metaPatch: Record<string, unknown> = {}\n for (const key of new Set([...Object.keys(meta), ...Object.keys(baseMeta)])) {\n if (semanticValueEqual(meta[key], baseMeta[key])) continue\n metaPatch[key] = meta[key] === undefined ? null : meta[key]\n }\n if (Object.keys(metaPatch).length > 0) write.metaPatch = metaPatch\n return write as RecordWriteOf<K>\n}\n\n/** The lens field type a column edits as (unwrapping optional/default); `undefined` = not lens-editable. */\nfunction lensFieldType(field: unknown): FieldDef['type'] | undefined {\n switch (unwrapped(field).type) {\n case 'string':\n return 'text'\n case 'boolean':\n return 'boolean'\n case 'number':\n return 'number'\n case 'enum':\n return 'select'\n default:\n return undefined\n }\n}\n\nfunction humanize(name: string): string {\n const spaced = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\n/**\n * The DEFAULT lens of a kind: one field per column whose type the portable form edits\n * (text, boolean, number, select — derived from the column's zod type), labelled from its\n * name. A column of another shape (an object, a list) is not in the lens: the rail never\n * writes it, so the stored value is kept on every save (EC-577). A mount refines the lens\n * by name through `nav.rail(kind, { fields })` (EC-311 — the same override mechanism the\n * built-in rails use), or passes its own `schema`.\n */\nexport function recordLensDef(kind: AnyRecordKind, options: { label?: string; titleField?: string } = {}): CollectionDef {\n const fields: Record<string, unknown>[] = []\n for (const [name, field] of Object.entries(kind.fields)) {\n const type = lensFieldType(field)\n if (!type) continue\n const entry: Record<string, unknown> = { name, type, form: { label: humanize(name) } }\n if (type === 'select') {\n entry.options = Object.values(unwrapped(field).entries ?? {}).map((value) => ({ value: String(value), label: String(value) }))\n }\n fields.push(entry)\n }\n const titleField = options.titleField ?? fields.find((field) => field.type === 'text')?.name\n return collectionDefSchema.parse({\n id: kind.kind,\n // A record kind is not a CMS `kind`; 'document' just satisfies the lens schema.\n kind: 'document',\n ...(titleField ? { titleField } : {}),\n form: { label: options.label ?? humanize(kind.module) },\n fields,\n })\n}\n"]}
|
|
1
|
+
{"version":3,"file":"record-lens.js","sourceRoot":"","sources":["../../../src/components/records/record-lens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAA;AAElF,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAA;AAEvD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,iFAAiF;AACjF,MAAM,UAAU,iBAAiB,CAAC,IAAmB;IACnD,OAAO,IAAI,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAA;AAC1C,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,oBAAoB,CAA0B,IAAO,EAAE,KAAuB;IAC5F,MAAM,MAAM,GAAG,KAAgC,CAAA;IAC/C,MAAM,OAAO,GAA4B,EAAE,CAAA;IAC3C,KAAK,MAAM,MAAM,IAAI,iBAAiB,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7C,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,SAAS;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,CAAA;IACpE,CAAC;IACD,OAAO;QACL,UAAU,EAAE,IAAI,CAAC,IAAI;QACrB,EAAE,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QACrB,MAAM,EAAE,EAAE,GAAG,CAAE,MAAM,CAAC,IAA4C,IAAI,EAAE,CAAC,EAAE,GAAG,OAAO,EAAE;KACxF,CAAA;AACH,CAAC;AAYD,SAAS,KAAK,CAAC,KAAc;IAC3B,OAAQ,KAAuC,CAAC,IAAI,CAAC,GAAG,CAAA;AAC1D,CAAC;AAED,wEAAwE;AACxE,SAAS,cA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C,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;QAChI,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;IACpB,CAAC;IACD,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,EAAE,IAAI,CAAA;IAC5F,OAAO,mBAAmB,CAAC,KAAK,CAAC;QAC/B,EAAE,EAAE,IAAI,CAAC,IAAI;QACb,gFAAgF;QAChF,IAAI,EAAE,UAAU;QAChB,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACrC,IAAI,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;QACvD,MAAM;KACP,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import { collectionDefSchema, semanticValueEqual } from '@elytracms/core/cms-core'\nimport type { CmsDocument, CollectionDef, FieldDef } from '@elytracms/core/cms-core'\nimport { metaPatchBetween } from '@elytracms/core/persistence'\nimport type { AnyRecordKind, RecordEntryOf, RecordWriteOf } from '@elytracms/core/persistence'\nimport { metaBagProjection } from '../rail-view-source'\n\n/**\n * EC-616 — the projections between a record kind and the portable list/edit surfaces\n * (AD-19): a record rail edits a record as a LENS document (`{ collection, id, values }`)\n * over a `CollectionDef`. Pure — no React — so the mapping that decides what a save\n * writes is unit-testable on its own (it is the one place the write is derived from the\n * edited lens; a slip here silently corrupts a record).\n *\n * - **Read** ({@link recordToLensDocument}): the stored `meta` bag spread FIRST, then\n * the kind's columns — a canonical column always wins over a same-named meta key\n * (RESIDUE-3c: spread last, a stored `meta.to` displayed as the redirect's target and a\n * re-save wrote it into the canonical `to`).\n * - **Write** ({@link lensDocumentToRecordWrite}): every lens value keyed by a column is\n * that column; every other key round-trips through the open `meta` bag (EC-311 Tier 2\n * — a mount's additive field). A column the document does not carry is left out, so the\n * stored value is kept (EC-577: a create default applies once, in the adapter's\n * transaction — never restated here). A REQUIRED text column is always sent (`''` when\n * blank): the editor owns it, and an empty one is refused visibly by the write's\n * validation rather than kept silently. `meta` is omitted when no additive value exists,\n * so a rail with no additive fields never touches the bag.\n */\n\n/** The kind's columns (its declared fields; `meta` is the bag, not a column). */\nexport function recordColumnNames(kind: AnyRecordKind): ReadonlySet<string> {\n return new Set(Object.keys(kind.fields))\n}\n\n/** A stored record as the lens document the portable surfaces edit. */\nexport function recordToLensDocument<K extends AnyRecordKind>(kind: K, entry: RecordEntryOf<K>): CmsDocument {\n const record = entry as Record<string, unknown>\n const columns: Record<string, unknown> = {}\n for (const column of recordColumnNames(kind)) {\n if (record[column] !== undefined) columns[column] = record[column]\n }\n return {\n collection: kind.kind,\n id: String(record.id),\n values: { ...((record.meta as Record<string, unknown> | undefined) ?? {}), ...columns },\n }\n}\n\n/**\n * A column's zod definition, read through `_zod.def` rather than `instanceof`: a kind is\n * declared in whichever package owns it (an addon), whose `zod` may be a different copy\n * than this one — `instanceof` across copies is silently false.\n */\ninterface ZodDefView {\n type: string\n innerType?: { _zod: { def: ZodDefView } }\n entries?: Record<string, unknown>\n}\nfunction defOf(field: unknown): ZodDefView {\n return (field as { _zod: { def: ZodDefView } })._zod.def\n}\n\n/** Is this column a required text column (no default, not optional)? */\nfunction isRequiredText(field: unknown): boolean {\n return defOf(field).type === 'string'\n}\n\n/** The column's own definition, below any optional/default/nullable wrapper. */\nfunction unwrapped(field: unknown): ZodDefView {\n let def = defOf(field)\n while ((def.type === 'optional' || def.type === 'default' || def.type === 'nullable') && def.innerType) {\n def = def.innerType._zod.def\n }\n return def\n}\n\n/** A lens value as the write sends it for one column (a required text column is always a string). */\nfunction columnWriteValue(field: unknown, value: unknown): unknown {\n return isRequiredText(field) ? (typeof value === 'string' ? value : '') : value\n}\n\n/**\n * An edited lens document as the record write (see the module header).\n *\n * **With `base`** — the lens document of the record as the editor OPENED it — the write\n * carries only what the editor changed (EC-616, the multi-session baseline): a column whose\n * value differs from the base, and the changed `meta` keys as a per-key `metaPatch` (a key the\n * editor removed is `null`). Every other column is ABSENT, so the EC-577 rule keeps the stored\n * value — a column another writer changed after the editor opened the record survives the\n * editor's save. With nothing changed the write is just the id (a no-op edit).\n *\n * **Without `base`** (a record the editor is creating) the write is whole, as it always was.\n */\nexport function lensDocumentToRecordWrite<K extends AnyRecordKind>(\n kind: K,\n doc: CmsDocument,\n base?: CmsDocument,\n): RecordWriteOf<K> {\n const values = doc.values ?? {}\n const write: Record<string, unknown> = { id: doc.id }\n const columns = recordColumnNames(kind)\n if (!base) {\n for (const [column, field] of Object.entries(kind.fields)) {\n const value = columnWriteValue(field, values[column])\n if (value !== undefined) write[column] = value\n }\n const meta = metaBagProjection(values, columns)\n if (Object.keys(meta).length > 0) write.meta = meta\n return write as RecordWriteOf<K>\n }\n const before = base.values ?? {}\n for (const [column, field] of Object.entries(kind.fields)) {\n const value = values[column]\n if (semanticValueEqual(value, before[column])) continue\n // A cleared optional column is `null` on the wire (EC-577: clear), never a silent absence.\n write[column] = value === undefined ? (isRequiredText(field) ? '' : null) : columnWriteValue(field, value)\n }\n // The one per-key diff (core `metaPatchBetween`), shared with the asset editors (EC-634).\n const metaPatch = metaPatchBetween(metaBagProjection(before, columns), metaBagProjection(values, columns))\n if (Object.keys(metaPatch).length > 0) write.metaPatch = metaPatch\n return write as RecordWriteOf<K>\n}\n\n/** The lens field type a column edits as (unwrapping optional/default); `undefined` = not lens-editable. */\nfunction lensFieldType(field: unknown): FieldDef['type'] | undefined {\n switch (unwrapped(field).type) {\n case 'string':\n return 'text'\n case 'boolean':\n return 'boolean'\n case 'number':\n return 'number'\n case 'enum':\n return 'select'\n default:\n return undefined\n }\n}\n\nfunction humanize(name: string): string {\n const spaced = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\n/**\n * The DEFAULT lens of a kind: one field per column whose type the portable form edits\n * (text, boolean, number, select — derived from the column's zod type), labelled from its\n * name. A column of another shape (an object, a list) is not in the lens: the rail never\n * writes it, so the stored value is kept on every save (EC-577). A mount refines the lens\n * by name through `nav.rail(kind, { fields })` (EC-311 — the same override mechanism the\n * built-in rails use), or passes its own `schema`.\n */\nexport function recordLensDef(kind: AnyRecordKind, options: { label?: string; titleField?: string } = {}): CollectionDef {\n const fields: Record<string, unknown>[] = []\n for (const [name, field] of Object.entries(kind.fields)) {\n const type = lensFieldType(field)\n if (!type) continue\n const entry: Record<string, unknown> = { name, type, form: { label: humanize(name) } }\n if (type === 'select') {\n entry.options = Object.values(unwrapped(field).entries ?? {}).map((value) => ({ value: String(value), label: String(value) }))\n }\n fields.push(entry)\n }\n const titleField = options.titleField ?? fields.find((field) => field.type === 'text')?.name\n return collectionDefSchema.parse({\n id: kind.kind,\n // A record kind is not a CMS `kind`; 'document' just satisfies the lens schema.\n kind: 'document',\n ...(titleField ? { titleField } : {}),\n form: { label: options.label ?? humanize(kind.module) },\n fields,\n })\n}\n"]}
|
|
@@ -54,6 +54,13 @@ export interface ChatProposal {
|
|
|
54
54
|
* revert any change made since the proposal was built. Absent for a create.
|
|
55
55
|
*/
|
|
56
56
|
patches?: readonly DocumentPatch[];
|
|
57
|
+
/**
|
|
58
|
+
* EC-647 — for an update or a translation: the revision of the read the proposal was
|
|
59
|
+
* built from. Applying it writes {@link patches} AT this revision, so a position changed
|
|
60
|
+
* since (by anyone else) is refused on that field, never overwritten. Absent → the apply
|
|
61
|
+
* names no revision and is refused.
|
|
62
|
+
*/
|
|
63
|
+
revision?: number;
|
|
57
64
|
/**
|
|
58
65
|
* EC-593 (ratified 4e) — for a translation: every text position it could NOT
|
|
59
66
|
* translate, shown on the card the editor reviews (never a silent skip).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat-state.js","sourceRoot":"","sources":["../../../src/lib/ai/chat-state.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"chat-state.js","sourceRoot":"","sources":["../../../src/lib/ai/chat-state.ts"],"names":[],"mappings":"AAmFA,MAAM,CAAC,MAAM,sBAAsB,GAAoB;IACrD,SAAS,EAAE,EAAE;IACb,KAAK,EAAE,IAAI;CACZ,CAAA;AAWD,SAAS,UAAU,CACjB,KAAsB,EACtB,UAAkB,EAClB,MAA8B;IAE9B,MAAM,QAAQ,GAAG,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,CAAA;IAC5C,mEAAmE;IACnE,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,SAAS;QAAE,OAAO,KAAK,CAAA;IAC5D,OAAO;QACL,GAAG,KAAK;QACR,SAAS,EAAE,EAAE,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,QAAQ,EAAE,MAAM,EAAE,EAAE;KACzE,CAAA;AACH,CAAC;AAED,MAAM,UAAU,iBAAiB,CAC/B,KAAsB,EACtB,MAAwB;IAExB,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,SAAS;YACZ,OAAO;gBACL,GAAG,KAAK;gBACR,SAAS,EAAE;oBACT,GAAG,KAAK,CAAC,SAAS;oBAClB,CAAC,MAAM,CAAC,UAAU,CAAC,EAAE,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,EAAE,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE;iBACtF;aACF,CAAA;QACH,KAAK,OAAO;YACV,OAAO,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,CAAC,CAAA;QACxD,KAAK,QAAQ;YACX,OAAO,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;QACzD,KAAK,MAAM;YACT,OAAO,KAAK,CAAC,KAAK,KAAK,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,OAAO,EAAE,CAAA;QACrF,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,CAAA;QACjE,KAAK,OAAO;YACV,OAAO,sBAAsB,CAAA;QAC/B;YACE,OAAO,KAAK,CAAA;IAChB,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAC/B,KAAmB,EACnB,MAA0E;IAE1E,OAAO;QACL,MAAM,EAAE;YACN,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,MAAM,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE;YAC5B,GAAG,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC9D;QACD,KAAK,EAAE;YACL,UAAU,EAAE,KAAK,CAAC,UAAU;YAC5B,EAAE,EAAE,KAAK,CAAC,EAAE;YACZ,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3D;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * The chat panel's proposal-review state (EC-199, reshaped by EC-334).\n *\n * `useChat` (the AI SDK) owns the conversation: messages, streaming text, tool\n * parts, busy-status. This reducer keeps ONLY what the SDK does not own:\n *\n * - the proposal review map — the FULL proposals the terminal tools\n * (`createDocument` / `translateDocument`) produce, keyed by `toolCallId`\n * (the model receives only a compact summary as the tool output; the editor\n * reviews the real patch here), each `pending` → `applied` | `rejected`;\n * - the last blocking error (route/provider/step-cap failure), surfaced as a\n * visible note and cleared on the next submit.\n *\n * EC-380 (`clear`): a new conversation resets this state entirely — pending\n * proposals are discarded with REJECT semantics (they were never applied and\n * nothing half-applied survives; an applied draft already lives in the CMS and\n * is untouched). The panel pairs the dispatch with a fresh `useChat` id.\n *\n * House testing pattern (AGENTS.md): the panel's behaviour lives in this\n * deterministic reducer, tested directly; the React component is a thin shell.\n */\nimport type { CmsDocument, CmsValidationIssue, DocumentPatch, FieldValues } from '@elytracms/core/cms-core'\nimport type { AiProvenance, ContentPatch } from './types'\nimport type { TranslateSkip } from './translate-document'\n\n/**\n * A proposal's kind: fresh authoring, a fill-empty translation of an existing\n * doc, or an EC-378 field update of an existing doc (old → new diff).\n */\nexport type ProposalOrigin = 'create' | 'translate' | 'update'\n\n/**\n * The full proposal payload a terminal tool hands to the review UI (via\n * `onProposal` on the executor — see `tools.ts`). The model never sees this;\n * it gets a compact summary as the tool output.\n */\nexport interface ChatProposal {\n origin: ProposalOrigin\n collection: string\n documentId: string\n patch: ContentPatch\n provenance: AiProvenance\n /** Generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues on the accepted content (warnings). */\n issues: CmsValidationIssue[]\n /** For a translation/update: the existing document values the diff renders \"before\". */\n before?: { values?: FieldValues; localized?: Record<string, FieldValues> }\n /**\n * EC-595 A2 — for an update or a translation: the positions it changes, as patches\n * (a field's bucket, a block prop by node id). Applying the proposal persists exactly\n * these through `documents.patch` — never the merged whole document, which would\n * revert any change made since the proposal was built. Absent for a create.\n */\n patches?: readonly DocumentPatch[]\n /**\n * EC-647 — for an update or a translation: the revision of the read the proposal was\n * built from. Applying it writes {@link patches} AT this revision, so a position changed\n * since (by anyone else) is refused on that field, never overwritten. Absent → the apply\n * names no revision and is refused.\n */\n revision?: number\n /**\n * EC-593 (ratified 4e) — for a translation: every text position it could NOT\n * translate, shown on the card the editor reviews (never a silent skip).\n */\n skipped?: readonly TranslateSkip[]\n}\n\n/** A proposal under review: {@link ChatProposal} + its review status. */\nexport interface ProposalReview extends ChatProposal {\n /** The tool call that produced it (`toolCallId`) — the review key. */\n id: string\n status: 'pending' | 'applied' | 'rejected'\n}\n\nexport interface ChatReviewState {\n /** Proposals keyed by `toolCallId`. */\n proposals: Record<string, ProposalReview>\n /** Last blocking error (route/provider/step-cap), surfaced then cleared on submit. */\n error: string | null\n}\n\nexport const initialChatReviewState: ChatReviewState = {\n proposals: {},\n error: null,\n}\n\nexport type ChatReviewAction =\n | { type: 'propose'; toolCallId: string; proposal: ChatProposal }\n | { type: 'apply'; toolCallId: string }\n | { type: 'reject'; toolCallId: string }\n | { type: 'fail'; message: string }\n | { type: 'clear-error' }\n /** EC-380: new conversation — full reset; pending proposals discarded (reject semantics). */\n | { type: 'clear' }\n\nfunction transition(\n state: ChatReviewState,\n toolCallId: string,\n status: 'applied' | 'rejected',\n): ChatReviewState {\n const existing = state.proposals[toolCallId]\n // Only a PENDING proposal transitions — apply/reject are one-shot.\n if (!existing || existing.status !== 'pending') return state\n return {\n ...state,\n proposals: { ...state.proposals, [toolCallId]: { ...existing, status } },\n }\n}\n\nexport function chatReviewReducer(\n state: ChatReviewState,\n action: ChatReviewAction,\n): ChatReviewState {\n switch (action.type) {\n case 'propose':\n return {\n ...state,\n proposals: {\n ...state.proposals,\n [action.toolCallId]: { ...action.proposal, id: action.toolCallId, status: 'pending' },\n },\n }\n case 'apply':\n return transition(state, action.toolCallId, 'applied')\n case 'reject':\n return transition(state, action.toolCallId, 'rejected')\n case 'fail':\n return state.error === action.message ? state : { ...state, error: action.message }\n case 'clear-error':\n return state.error === null ? state : { ...state, error: null }\n case 'clear':\n return initialChatReviewState\n default:\n return state\n }\n}\n\n/**\n * Turn a proposal patch into the before/after document pair the EC-317 diff\n * engine (`diffDocuments`) compares. For a fresh document `before` is empty\n * (the whole proposal reads as \"added\"); for a translation pass the existing\n * document's values. Pure — the reviewable diff is a straight\n * `diffDocuments(collection, before, after)`.\n */\nexport function proposalDocuments(\n patch: ContentPatch,\n before?: { values?: FieldValues; localized?: Record<string, FieldValues> },\n): { before: CmsDocument; after: CmsDocument } {\n return {\n before: {\n collection: patch.collection,\n id: patch.id,\n values: before?.values ?? {},\n ...(before?.localized ? { localized: before.localized } : {}),\n },\n after: {\n collection: patch.collection,\n id: patch.id,\n values: patch.values,\n ...(patch.localized ? { localized: patch.localized } : {}),\n },\n }\n}\n"]}
|
package/dist/lib/ai/tools.d.ts
CHANGED
|
@@ -68,6 +68,14 @@ export interface ChatToolReaders {
|
|
|
68
68
|
collection: string;
|
|
69
69
|
id: string;
|
|
70
70
|
}): Promise<CmsDocument | null>;
|
|
71
|
+
/**
|
|
72
|
+
* EC-647 — the revision a document {@link getDocument} returned was read at (the
|
|
73
|
+
* returned value is the token). An update or a translation records it on its proposal:
|
|
74
|
+
* applying the proposal writes AT that revision, so a change made since on one of its
|
|
75
|
+
* positions is refused, never overwritten. Optional: absent, a proposal names no
|
|
76
|
+
* revision and its apply is refused.
|
|
77
|
+
*/
|
|
78
|
+
revisionOf?(document: CmsDocument): number | undefined;
|
|
71
79
|
}
|
|
72
80
|
/** Per-search result cap (protects the wire — results become model context). */
|
|
73
81
|
export declare const DEFAULT_SEARCH_LIMIT = 20;
|
package/dist/lib/ai/tools.js
CHANGED
|
@@ -381,12 +381,14 @@ export function createChatToolExecutor(options) {
|
|
|
381
381
|
},
|
|
382
382
|
};
|
|
383
383
|
}
|
|
384
|
+
const revision = options.readers.revisionOf?.(document);
|
|
384
385
|
options.onProposal(toolCallId, {
|
|
385
386
|
origin: 'update',
|
|
386
387
|
collection: collection.id,
|
|
387
388
|
documentId: document.id,
|
|
388
389
|
patch: result.patch,
|
|
389
390
|
patches: result.patches,
|
|
391
|
+
...(revision !== undefined ? { revision } : {}),
|
|
390
392
|
provenance: aiProvenance(options.provider),
|
|
391
393
|
attempts: 1,
|
|
392
394
|
issues: result.issues,
|
|
@@ -519,6 +521,7 @@ export function createChatToolExecutor(options) {
|
|
|
519
521
|
errorText: `The translation did not pass validation: ${issueSummary(result.introducedErrors)}`,
|
|
520
522
|
};
|
|
521
523
|
}
|
|
524
|
+
const revision = options.readers.revisionOf?.(document);
|
|
522
525
|
options.onProposal(toolCallId, {
|
|
523
526
|
origin: 'translate',
|
|
524
527
|
collection: collection.id,
|
|
@@ -530,6 +533,7 @@ export function createChatToolExecutor(options) {
|
|
|
530
533
|
...(result.document.localized ? { localized: result.document.localized } : {}),
|
|
531
534
|
},
|
|
532
535
|
patches: result.patches,
|
|
536
|
+
...(revision !== undefined ? { revision } : {}),
|
|
533
537
|
provenance: result.provenance,
|
|
534
538
|
attempts: 1,
|
|
535
539
|
// Warnings ride onto the proposal like every other path's (EC-496 renders them).
|
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;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;AAiC3C,gFAAgF;AAChF,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,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AAM,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,CAA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AO,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"]}
|