@perkyzz/emvb 0.4.0 → 0.5.0
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/README.md +19 -3
- package/package.json +4 -3
- package/src/admin/agents-api.ts +39 -0
- package/src/admin/editor/CommandPalette.tsx +43 -2
- package/src/admin/editor/Editor.tsx +27 -0
- package/src/admin/editor/Timeline.tsx +108 -6
- package/src/admin/editor/editor-css.ts +4 -0
- package/src/admin/editor/feature-css.ts +22 -3
- package/src/admin/editor/palette.ts +6 -2
- package/src/admin/editor/panels/ColorControl.tsx +19 -8
- package/src/admin/editor/panels/ElementPanel.tsx +1 -1
- package/src/admin/editor/panels/TokenScales.tsx +4 -2
- package/src/admin/editor/panels/color-space.ts +12 -1
- package/src/admin/editor/panels/settings/AdvancedFields.tsx +84 -28
- package/src/admin/editor/panels/settings/AudienceEditor.tsx +42 -4
- package/src/admin/editor/panels/settings/DraftTextField.tsx +38 -9
- package/src/admin/editor/panels/settings/FieldControl.tsx +6 -0
- package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
- package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
- package/src/admin/editor/panels/settings/MediaPicker.tsx +2 -3
- package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
- package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
- package/src/admin/editor/panels/settings/link-rules.ts +19 -0
- package/src/admin/editor/panels/settings/number-input.ts +11 -0
- package/src/admin/editor/panels/settings/query-style.ts +65 -0
- package/src/admin/editor/panels/variable-values.ts +4 -2
- package/src/admin/editor/remote-change.ts +67 -0
- package/src/admin/index.tsx +3 -1
- package/src/admin/media-api.ts +20 -0
- package/src/admin/pages/AgentsPage.tsx +274 -0
- package/src/admin/ui.ts +28 -0
- package/src/astro/floats/runtime.ts +10 -0
- package/src/astro/popups/runtime.ts +15 -0
- package/src/astro/tabs/runtime.ts +60 -1
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +202 -26
- package/src/core/arrange.ts +11 -3
- package/src/core/css/generate.ts +9 -1
- package/src/core/elements/form-elements.ts +19 -3
- package/src/core/elements/index.ts +39 -11
- package/src/core/render/dynamic-post.ts +21 -5
- package/src/core/render/form.ts +12 -5
- package/src/core/render/index.ts +50 -11
- package/src/core/render/pagination.ts +21 -2
- package/src/core/sanitize/embed-url.ts +7 -1
- package/src/core/sanitize/href.ts +13 -1
- package/src/core/schema/descriptors.ts +4 -1
- package/src/core/schema/layout.ts +10 -3
- package/src/core/share/link.ts +4 -1
- package/src/core/theme/dynamic.ts +12 -7
- package/src/mcp/errors.ts +44 -0
- package/src/mcp/index.ts +4 -0
- package/src/mcp/ports.ts +78 -0
- package/src/mcp/prompts.ts +76 -0
- package/src/mcp/publish.ts +60 -0
- package/src/mcp/queue.ts +19 -0
- package/src/mcp/rate-limit.ts +80 -0
- package/src/mcp/read.ts +419 -0
- package/src/mcp/refs.ts +84 -0
- package/src/mcp/settings.ts +18 -0
- package/src/mcp/tools.ts +265 -0
- package/src/mcp/write.ts +582 -0
- package/src/server/agent-settings.ts +134 -0
- package/src/server/design-routes.ts +71 -17
- package/src/server/icon-routes.ts +5 -1
- package/src/server/mcp-routes.ts +265 -0
- package/src/server/plugin.ts +32 -2
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PluginRouteError,
|
|
3
|
+
type ContentPolicyDecision,
|
|
4
|
+
type ContentPolicyEvent,
|
|
5
|
+
type PluginContext,
|
|
6
|
+
type PluginRoute,
|
|
7
|
+
} from "emdash";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../constants.ts";
|
|
10
|
+
import { AgentSettings, DEFAULT_AGENT_SETTINGS } from "../mcp/settings.ts";
|
|
11
|
+
|
|
12
|
+
/** Plugin KV key of the agent settings (plan § 4, D-055). */
|
|
13
|
+
const AGENT_SETTINGS_KEY = "agent-settings";
|
|
14
|
+
|
|
15
|
+
/** The agent settings and their revision. Missing or damaged settings read as the safe defaults. */
|
|
16
|
+
export async function readAgentSettings(
|
|
17
|
+
ctx: Pick<PluginContext, "kv">,
|
|
18
|
+
): Promise<{ settings: AgentSettings; revision: string | null }> {
|
|
19
|
+
const stored = await ctx.kv.getVersioned<unknown>(AGENT_SETTINGS_KEY);
|
|
20
|
+
if (!stored) return { settings: DEFAULT_AGENT_SETTINGS, revision: null };
|
|
21
|
+
const parsed = AgentSettings.safeParse(stored.value);
|
|
22
|
+
return {
|
|
23
|
+
settings: parsed.success ? parsed.data : DEFAULT_AGENT_SETTINGS,
|
|
24
|
+
revision: stored.revision,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type LogQuery = {
|
|
29
|
+
query(o: {
|
|
30
|
+
where?: Record<string, unknown>;
|
|
31
|
+
orderBy: Record<string, "asc" | "desc">;
|
|
32
|
+
limit: number;
|
|
33
|
+
}): Promise<{
|
|
34
|
+
items: { id: string; data: unknown }[];
|
|
35
|
+
}>;
|
|
36
|
+
put(id: string, data: unknown): Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
const agentLog = (ctx: PluginContext) => ctx.storage["agentlog"] as unknown as LogQuery;
|
|
39
|
+
|
|
40
|
+
/** Agents tab: the settings, the MCP endpoint and the last 50 agent changes. Admins only. */
|
|
41
|
+
export const agentsRoute: PluginRoute = {
|
|
42
|
+
permission: "plugins:manage",
|
|
43
|
+
handler: async (ctx) => {
|
|
44
|
+
const { settings, revision } = await readAgentSettings(ctx);
|
|
45
|
+
const log = await agentLog(ctx).query({ orderBy: { at: "desc" }, limit: 50 });
|
|
46
|
+
return {
|
|
47
|
+
settings,
|
|
48
|
+
revision,
|
|
49
|
+
endpoint: new URL("/_emdash/api/mcp", ctx.request.url).toString(),
|
|
50
|
+
activity: log.items.map((item) => Object.assign({ id: item.id }, item.data as object)),
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const PageAgentsInput = z.object({ pageId: z.string().min(1).max(128) });
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* W-460: the page's versions an agent saved, for the Timeline's Agent badge and filter. Editors
|
|
59
|
+
* can read this (it carries no settings); the full activity list stays admin-only.
|
|
60
|
+
*/
|
|
61
|
+
export const pageAgentVersionsRoute: PluginRoute<z.infer<typeof PageAgentsInput>> = {
|
|
62
|
+
permission: "content:edit_any",
|
|
63
|
+
input: PageAgentsInput,
|
|
64
|
+
handler: async (ctx) => {
|
|
65
|
+
const log = await agentLog(ctx).query({
|
|
66
|
+
where: { pageId: ctx.input.pageId },
|
|
67
|
+
orderBy: { at: "desc" },
|
|
68
|
+
limit: 100,
|
|
69
|
+
});
|
|
70
|
+
const versions = log.items
|
|
71
|
+
.map(
|
|
72
|
+
(item) => item.data as { revisionId?: string; tool: string; summary: string; at: string },
|
|
73
|
+
)
|
|
74
|
+
.filter((entry) => entry.revisionId)
|
|
75
|
+
.map((entry) => ({
|
|
76
|
+
revisionId: entry.revisionId as string,
|
|
77
|
+
tool: entry.tool,
|
|
78
|
+
summary: entry.summary,
|
|
79
|
+
at: entry.at,
|
|
80
|
+
}));
|
|
81
|
+
return { versions };
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const SaveInput = z.object({ settings: AgentSettings, revision: z.string().nullable() });
|
|
86
|
+
|
|
87
|
+
/** Saves the agent settings (compare-and-set). Admins only; no MCP tool can reach this. */
|
|
88
|
+
export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
|
|
89
|
+
permission: "plugins:manage",
|
|
90
|
+
input: SaveInput,
|
|
91
|
+
handler: async (ctx) => {
|
|
92
|
+
const write = await ctx.kv.compareAndSet(
|
|
93
|
+
AGENT_SETTINGS_KEY,
|
|
94
|
+
ctx.input.revision,
|
|
95
|
+
ctx.input.settings,
|
|
96
|
+
);
|
|
97
|
+
if (!write.applied) {
|
|
98
|
+
throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
|
|
99
|
+
}
|
|
100
|
+
const at = new Date().toISOString();
|
|
101
|
+
const s = ctx.input.settings;
|
|
102
|
+
await agentLog(ctx).put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
|
|
103
|
+
at,
|
|
104
|
+
target: "settings",
|
|
105
|
+
tool: "settings",
|
|
106
|
+
userId: ctx.user?.id ?? null,
|
|
107
|
+
summary: `Agent settings: access ${s.mcpEnabled ? "on" : "off"}, publish pages ${s.publishPages ? "on" : "off"}, publish styles ${s.publishStyles ? "on" : "off"}`,
|
|
108
|
+
});
|
|
109
|
+
return { revision: write.revision };
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const OWNED = new Set([PAGES_COLLECTION, THEME_PARTS_COLLECTION]);
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* D-055: refuse publishing EmVB content through EmDash's own MCP tools (e.g. `content_publish`)
|
|
117
|
+
* unless the admin let agents publish pages. Our `publish_page` tool publishes with a plugin
|
|
118
|
+
* origin after its own settings check.
|
|
119
|
+
*/
|
|
120
|
+
export async function beforePublish(
|
|
121
|
+
event: ContentPolicyEvent,
|
|
122
|
+
ctx: PluginContext,
|
|
123
|
+
): Promise<ContentPolicyDecision> {
|
|
124
|
+
if (!OWNED.has(event.collection)) return undefined;
|
|
125
|
+
const source = event.origin.source === "mcp" || event.actor?.source === "mcp";
|
|
126
|
+
if (!source) return undefined;
|
|
127
|
+
const { settings } = await readAgentSettings(ctx);
|
|
128
|
+
if (settings.mcpEnabled && settings.publishPages) return undefined;
|
|
129
|
+
return {
|
|
130
|
+
cancel: true,
|
|
131
|
+
reason:
|
|
132
|
+
"Agents may not publish EmVB pages on this site. An admin can allow it in Pages VisualBuilder → AI agents.",
|
|
133
|
+
};
|
|
134
|
+
}
|
|
@@ -27,7 +27,10 @@ type DesignResponse = {
|
|
|
27
27
|
status: "ok" | "empty" | "unreadable";
|
|
28
28
|
};
|
|
29
29
|
|
|
30
|
-
const readDesign = async (
|
|
30
|
+
export const readDesign = async (
|
|
31
|
+
ctx: RouteContext<unknown>,
|
|
32
|
+
key: string,
|
|
33
|
+
): Promise<DesignResponse> => {
|
|
31
34
|
const current = await store(ctx).getVersioned(key);
|
|
32
35
|
if (!current) return { design: emptyDesign(), revision: null, status: "empty" };
|
|
33
36
|
const result = validateDesign(current.value);
|
|
@@ -88,20 +91,62 @@ export const designSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
|
|
|
88
91
|
const summary = summarizeIssues(result.issues);
|
|
89
92
|
throw new PluginRouteError("INVALID_DESIGN", `The design system is invalid. ${summary}`, 422);
|
|
90
93
|
}
|
|
91
|
-
const write = await
|
|
92
|
-
|
|
93
|
-
ctx.input.revision,
|
|
94
|
-
result.design,
|
|
95
|
-
);
|
|
96
|
-
if (!write.applied) {
|
|
94
|
+
const write = await writeDesignDraft(ctx, result.design, ctx.input.revision, "editor");
|
|
95
|
+
if (!write) {
|
|
97
96
|
throw PluginRouteError.conflict(
|
|
98
97
|
"The design system was changed somewhere else. Reload it and try again.",
|
|
99
98
|
);
|
|
100
99
|
}
|
|
101
|
-
return { revision: write
|
|
100
|
+
return { revision: write };
|
|
102
101
|
},
|
|
103
102
|
};
|
|
104
103
|
|
|
104
|
+
/** Keep the last 50 style drafts and publishes (D-057), newest first by key. */
|
|
105
|
+
const DESIGN_HISTORY_LIMIT = 50;
|
|
106
|
+
|
|
107
|
+
type HistoryStore = {
|
|
108
|
+
put(id: string, data: unknown): Promise<void>;
|
|
109
|
+
query(o: { orderBy: Record<string, "asc" | "desc">; limit: number; cursor?: string }): Promise<{
|
|
110
|
+
items: { id: string; data: unknown }[];
|
|
111
|
+
}>;
|
|
112
|
+
deleteMany(ids: string[]): Promise<number>;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** Records a style draft or publish in the design history, then trims it to the limit. */
|
|
116
|
+
async function recordDesign(
|
|
117
|
+
ctx: RouteContext<unknown>,
|
|
118
|
+
design: DesignSystem,
|
|
119
|
+
kind: "draft" | "publish",
|
|
120
|
+
by: "editor" | "agent",
|
|
121
|
+
) {
|
|
122
|
+
const history = ctx.storage["designhistory"] as unknown as HistoryStore | undefined;
|
|
123
|
+
if (!history) return;
|
|
124
|
+
const at = new Date().toISOString();
|
|
125
|
+
await history.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
|
|
126
|
+
at,
|
|
127
|
+
kind,
|
|
128
|
+
by,
|
|
129
|
+
userId: ctx.user?.id ?? null,
|
|
130
|
+
design,
|
|
131
|
+
});
|
|
132
|
+
const old = await history.query({ orderBy: { at: "desc" }, limit: 100 });
|
|
133
|
+
const extra = old.items.slice(DESIGN_HISTORY_LIMIT).map((item) => item.id);
|
|
134
|
+
if (extra.length > 0) await history.deleteMany(extra);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Compare-and-set of the style draft, recorded in the history. The new revision, or null on conflict. */
|
|
138
|
+
export async function writeDesignDraft(
|
|
139
|
+
ctx: RouteContext<unknown>,
|
|
140
|
+
design: DesignSystem,
|
|
141
|
+
expectedRevision: string | null,
|
|
142
|
+
by: "editor" | "agent",
|
|
143
|
+
): Promise<string | null> {
|
|
144
|
+
const write = await store(ctx).compareAndSet(DESIGN_DRAFT_KEY, expectedRevision, design);
|
|
145
|
+
if (!write.applied) return null;
|
|
146
|
+
await recordDesign(ctx, design, "draft", by);
|
|
147
|
+
return write.revision;
|
|
148
|
+
}
|
|
149
|
+
|
|
105
150
|
const PublishInput = z.object({ publishedRevision: z.string().nullable() });
|
|
106
151
|
|
|
107
152
|
/** Copies the style draft onto the published design. Pages are not republished (W-100). */
|
|
@@ -109,20 +154,29 @@ export const designPublishRoute: PluginRoute<z.infer<typeof PublishInput>> = {
|
|
|
109
154
|
permission: "content:edit_any",
|
|
110
155
|
input: PublishInput,
|
|
111
156
|
handler: async (ctx) => {
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
157
|
+
const result = await publishDesignDraft(ctx, ctx.input.publishedRevision, "editor");
|
|
158
|
+
if (result === "no-draft") {
|
|
114
159
|
throw new PluginRouteError("NO_STYLE_DRAFT", "There are no style changes to publish.", 409);
|
|
115
160
|
}
|
|
116
|
-
|
|
117
|
-
DESIGN_KEY,
|
|
118
|
-
ctx.input.publishedRevision,
|
|
119
|
-
draft.design,
|
|
120
|
-
);
|
|
121
|
-
if (!write.applied) {
|
|
161
|
+
if (result === "conflict") {
|
|
122
162
|
throw PluginRouteError.conflict(
|
|
123
163
|
"Site styles were published somewhere else. Reload the editor and try again.",
|
|
124
164
|
);
|
|
125
165
|
}
|
|
126
|
-
return { revision:
|
|
166
|
+
return { revision: result.revision };
|
|
127
167
|
},
|
|
128
168
|
};
|
|
169
|
+
|
|
170
|
+
/** Copies the style draft onto the published design (compare-and-set) and records it. */
|
|
171
|
+
export async function publishDesignDraft(
|
|
172
|
+
ctx: RouteContext<unknown>,
|
|
173
|
+
expectedPublishedRevision: string | null,
|
|
174
|
+
by: "editor" | "agent",
|
|
175
|
+
): Promise<"no-draft" | "conflict" | { revision: string }> {
|
|
176
|
+
const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
|
|
177
|
+
if (draft.status !== "ok") return "no-draft";
|
|
178
|
+
const write = await store(ctx).compareAndSet(DESIGN_KEY, expectedPublishedRevision, draft.design);
|
|
179
|
+
if (!write.applied) return "conflict";
|
|
180
|
+
await recordDesign(ctx, draft.design, "publish", by);
|
|
181
|
+
return { revision: write.revision };
|
|
182
|
+
}
|
|
@@ -111,8 +111,12 @@ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
|
|
|
111
111
|
const current = await store(ctx).get(ctx.input.id);
|
|
112
112
|
if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
|
|
113
113
|
const name = uploadName(ctx.input.name);
|
|
114
|
+
// W-390: answer with the same checked markup the list sends; a row that fails the
|
|
115
|
+
// allowlist is not renamed or echoed back.
|
|
116
|
+
const item = publicUploadedIcon(ctx.input.id, { ...current, name });
|
|
117
|
+
if (!item) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
|
|
114
118
|
await store(ctx).put(ctx.input.id, { ...current, name });
|
|
115
|
-
return { item
|
|
119
|
+
return { item };
|
|
116
120
|
},
|
|
117
121
|
};
|
|
118
122
|
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
|
|
2
|
+
import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
|
|
3
|
+
import { McpToolError } from "../mcp/errors.ts";
|
|
4
|
+
import type { EmvbPorts, PageRecord, PageSummary } from "../mcp/ports.ts";
|
|
5
|
+
import { callerKey, hitRateLimit, type RateStore } from "../mcp/rate-limit.ts";
|
|
6
|
+
import { runTool, type ToolDef } from "../mcp/tools.ts";
|
|
7
|
+
import { publishDesignDraft, readDesign, writeDesignDraft } from "./design-routes.ts";
|
|
8
|
+
import { readAgentSettings } from "./agent-settings.ts";
|
|
9
|
+
|
|
10
|
+
type Item = {
|
|
11
|
+
id: string;
|
|
12
|
+
slug: string | null;
|
|
13
|
+
status: string;
|
|
14
|
+
data: Record<string, unknown>;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
publishedAt: string | null;
|
|
17
|
+
draftRevisionId?: string | null;
|
|
18
|
+
liveRevisionId?: string | null;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
type Content = {
|
|
22
|
+
list(
|
|
23
|
+
c: string,
|
|
24
|
+
o: { limit?: number; cursor?: string },
|
|
25
|
+
): Promise<{
|
|
26
|
+
items: Item[];
|
|
27
|
+
cursor?: string;
|
|
28
|
+
hasMore: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
getVersioned?(c: string, id: string): Promise<{ item: Item; _rev: string } | null>;
|
|
31
|
+
listRevisions?(
|
|
32
|
+
c: string,
|
|
33
|
+
id: string,
|
|
34
|
+
o: { limit?: number },
|
|
35
|
+
): Promise<{ id: string; createdAt: string; authorId?: string | null }[]>;
|
|
36
|
+
getRevision?(
|
|
37
|
+
c: string,
|
|
38
|
+
id: string,
|
|
39
|
+
revisionId: string,
|
|
40
|
+
): Promise<{ data: Record<string, unknown> } | null>;
|
|
41
|
+
update(c: string, id: string, data: Record<string, unknown>): Promise<Item>;
|
|
42
|
+
create(c: string, data: Record<string, unknown>): Promise<Item>;
|
|
43
|
+
publish?(c: string, id: string, o: { _rev: string }): Promise<unknown>;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
type LogStore = { put(id: string, data: unknown): Promise<void> };
|
|
47
|
+
|
|
48
|
+
const parseJson = (raw: unknown) => {
|
|
49
|
+
if (typeof raw !== "string") return raw;
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(raw) as unknown;
|
|
52
|
+
} catch {
|
|
53
|
+
return raw;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const summary = (item: Item): PageSummary => ({
|
|
58
|
+
id: item.id,
|
|
59
|
+
title: typeof item.data["title"] === "string" ? item.data["title"] : "Untitled page",
|
|
60
|
+
slug: item.slug ?? "",
|
|
61
|
+
status: item.status,
|
|
62
|
+
hasDraft: Boolean(item.draftRevisionId && item.draftRevisionId !== item.liveRevisionId),
|
|
63
|
+
updatedAt: item.updatedAt,
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
/** The tool core's ports on a plugin route (D-053, R1 save path). */
|
|
67
|
+
function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
|
|
68
|
+
const content = ctx.content as unknown as Content | undefined;
|
|
69
|
+
if (!content) throw new McpToolError("FORBIDDEN", "EmVB has no content access on this site.");
|
|
70
|
+
const versioned = (id: string) =>
|
|
71
|
+
content.getVersioned ? content.getVersioned(PAGES_COLLECTION, id) : Promise.resolve(null);
|
|
72
|
+
return {
|
|
73
|
+
caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
|
|
74
|
+
async rateLimit(cls) {
|
|
75
|
+
await hitRateLimit(
|
|
76
|
+
ctx.kv as unknown as RateStore,
|
|
77
|
+
await callerKey(ctx.request, ctx.user?.id ?? null),
|
|
78
|
+
cls,
|
|
79
|
+
);
|
|
80
|
+
},
|
|
81
|
+
async listPages({ cursor, limit }) {
|
|
82
|
+
let result: Awaited<ReturnType<Content["list"]>>;
|
|
83
|
+
try {
|
|
84
|
+
result = await content.list(PAGES_COLLECTION, { limit, ...(cursor ? { cursor } : {}) });
|
|
85
|
+
} catch (error) {
|
|
86
|
+
// W-474: a cursor the agent made up or truncated was an INTERNAL_ERROR.
|
|
87
|
+
if (cursor && /cursor/i.test(String((error as Error)?.message ?? error))) {
|
|
88
|
+
throw new McpToolError(
|
|
89
|
+
"INVALID_INPUT",
|
|
90
|
+
"That cursor isn't valid. Pass nextCursor exactly as list_pages returned it, or leave it out to start again.",
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
pages: result.items.map(summary),
|
|
97
|
+
...(result.hasMore && result.cursor ? { nextCursor: result.cursor } : {}),
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
async getPage(id): Promise<PageRecord | null> {
|
|
101
|
+
const found = content.getVersioned ? await content.getVersioned(PAGES_COLLECTION, id) : null;
|
|
102
|
+
if (!found) return null;
|
|
103
|
+
return {
|
|
104
|
+
...summary(found.item),
|
|
105
|
+
layout: parseJson(found.item.data["layout"]),
|
|
106
|
+
rev: found["_rev"],
|
|
107
|
+
};
|
|
108
|
+
},
|
|
109
|
+
async listRevisions(id, limit) {
|
|
110
|
+
const list = content.listRevisions
|
|
111
|
+
? await content.listRevisions(PAGES_COLLECTION, id, { limit })
|
|
112
|
+
: [];
|
|
113
|
+
return list.map((r) => ({ id: r.id, createdAt: r.createdAt, authorId: r.authorId ?? null }));
|
|
114
|
+
},
|
|
115
|
+
async getRevisionData(id, revisionId) {
|
|
116
|
+
const revision = content.getRevision
|
|
117
|
+
? await content.getRevision(PAGES_COLLECTION, id, revisionId)
|
|
118
|
+
: null;
|
|
119
|
+
return revision?.data ?? null;
|
|
120
|
+
},
|
|
121
|
+
async savePage(id, patch, expectedRev) {
|
|
122
|
+
const current = await versioned(id);
|
|
123
|
+
if (!current) throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
|
|
124
|
+
if (current["_rev"] !== expectedRev) {
|
|
125
|
+
throw new McpToolError("CONFLICT", "The page changed since it was read.", {
|
|
126
|
+
rev: current["_rev"],
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
await content.update(PAGES_COLLECTION, id, {
|
|
130
|
+
...(patch.layout ? { layout: patch.layout } : {}),
|
|
131
|
+
...(patch.title ? { title: patch.title } : {}),
|
|
132
|
+
});
|
|
133
|
+
const after = await versioned(id);
|
|
134
|
+
return {
|
|
135
|
+
rev: after?.["_rev"] ?? "",
|
|
136
|
+
...(after?.item.draftRevisionId ? { revisionId: after.item.draftRevisionId } : {}),
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
async createPage({ title, layout }) {
|
|
140
|
+
// Plugins can't choose a slug on create; EmDash derives it from the title.
|
|
141
|
+
const item = await content.create(PAGES_COLLECTION, { title, layout });
|
|
142
|
+
const after = await versioned(item.id);
|
|
143
|
+
return { id: item.id, slug: String(item.slug ?? ""), rev: after?.["_rev"] ?? "" };
|
|
144
|
+
},
|
|
145
|
+
async saveDesign(design, expectedRevision) {
|
|
146
|
+
const written = await writeDesignDraft(ctx, design, expectedRevision, "agent");
|
|
147
|
+
if (!written) throw new McpToolError("CONFLICT", "Site styles changed since they were read.");
|
|
148
|
+
return { revision: written };
|
|
149
|
+
},
|
|
150
|
+
async log(entry) {
|
|
151
|
+
const at = new Date().toISOString();
|
|
152
|
+
const store = ctx.storage["agentlog"] as unknown as LogStore;
|
|
153
|
+
await store.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
|
|
154
|
+
...entry,
|
|
155
|
+
at,
|
|
156
|
+
userId: ctx.user?.id ?? null,
|
|
157
|
+
client: (ctx.request.headers.get("user-agent") ?? "").slice(0, 120),
|
|
158
|
+
});
|
|
159
|
+
},
|
|
160
|
+
settings: async () => (await readAgentSettings(ctx)).settings,
|
|
161
|
+
async publishPage(id, expectedRev) {
|
|
162
|
+
if (!content.publish)
|
|
163
|
+
throw new McpToolError("FORBIDDEN", "This site can't publish from plugins.");
|
|
164
|
+
try {
|
|
165
|
+
await content.publish(PAGES_COLLECTION, id, { _rev: expectedRev });
|
|
166
|
+
} catch (error) {
|
|
167
|
+
const code = (error as { code?: string }).code ?? "";
|
|
168
|
+
if (/CONFLICT|REV/i.test(code)) {
|
|
169
|
+
throw new McpToolError(
|
|
170
|
+
"CONFLICT",
|
|
171
|
+
"The page changed since you read it. Call get_layout again.",
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
if (/NOT_FOUND/i.test(code))
|
|
175
|
+
throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
const after = await versioned(id);
|
|
179
|
+
return { rev: after?.["_rev"] ?? "" };
|
|
180
|
+
},
|
|
181
|
+
async publishDesign(expectedPublishedRevision) {
|
|
182
|
+
const result = await publishDesignDraft(ctx, expectedPublishedRevision, "agent");
|
|
183
|
+
if (result === "no-draft")
|
|
184
|
+
throw new McpToolError("REFUSED", "There are no style changes to publish.");
|
|
185
|
+
if (result === "conflict") {
|
|
186
|
+
throw new McpToolError(
|
|
187
|
+
"CONFLICT",
|
|
188
|
+
"Site styles were published somewhere else. Call get_site_styles again.",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
return { revision: result.revision };
|
|
192
|
+
},
|
|
193
|
+
async getDesign() {
|
|
194
|
+
const published = await readDesign(ctx, DESIGN_KEY);
|
|
195
|
+
const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
|
|
196
|
+
if (draft.status !== "ok") {
|
|
197
|
+
return {
|
|
198
|
+
design: published.design,
|
|
199
|
+
revision: draft.revision,
|
|
200
|
+
publishedRevision: published.revision,
|
|
201
|
+
unpublished: false,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
return {
|
|
205
|
+
design: draft.design,
|
|
206
|
+
revision: draft.revision,
|
|
207
|
+
publishedRevision: published.revision,
|
|
208
|
+
unpublished: JSON.stringify(draft.design) !== JSON.stringify(published.design),
|
|
209
|
+
};
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** W-474: before "Set up EmVB" there is no `emvb_pages` table, and every page tool was an INTERNAL_ERROR. */
|
|
215
|
+
export const NOT_SET_UP_MESSAGE =
|
|
216
|
+
'EmVB isn\'t set up on this site yet. Ask an admin to open Pages VisualBuilder in the EmDash admin and click "Set up EmVB", then try again.';
|
|
217
|
+
|
|
218
|
+
export const isNotSetUp = (error: unknown) =>
|
|
219
|
+
/no such table:?\s*\W?ec_emvb_|relation "?ec_emvb_\w+"? does not exist|collection "?emvb_(pages|theme_parts)"? (not found|does not exist)/i.test(
|
|
220
|
+
String((error as Error)?.message ?? error),
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
/** Routes `mcp/<tool>`: editors and above (D-056), POST JSON, one per tool (R1 D-054). */
|
|
224
|
+
export function mcpRoutes(tools: readonly ToolDef[]): Record<string, PluginRoute> {
|
|
225
|
+
return Object.fromEntries(
|
|
226
|
+
tools.map((tool) => [
|
|
227
|
+
`mcp/${tool.name}`,
|
|
228
|
+
{
|
|
229
|
+
permission: "content:edit_any",
|
|
230
|
+
input: tool.input,
|
|
231
|
+
handler: async (ctx: RouteContext<unknown>) => {
|
|
232
|
+
try {
|
|
233
|
+
return await runTool(tool, pluginPorts(ctx), ctx.input);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error instanceof McpToolError) {
|
|
236
|
+
throw new PluginRouteError(error.code, error.message, error.status, error.details);
|
|
237
|
+
}
|
|
238
|
+
if (isNotSetUp(error)) {
|
|
239
|
+
throw new PluginRouteError("NOT_SET_UP", NOT_SET_UP_MESSAGE, 409);
|
|
240
|
+
}
|
|
241
|
+
throw error;
|
|
242
|
+
}
|
|
243
|
+
},
|
|
244
|
+
} satisfies PluginRoute,
|
|
245
|
+
]),
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** `definePlugin({ mcp })`: EmDash lists these on /_emdash/api/mcp as `emvb__<name>`. */
|
|
250
|
+
export function mcpToolConfig(tools: readonly ToolDef[]) {
|
|
251
|
+
return {
|
|
252
|
+
tools: Object.fromEntries(
|
|
253
|
+
tools.map((tool) => [
|
|
254
|
+
tool.name,
|
|
255
|
+
{
|
|
256
|
+
description: tool.description,
|
|
257
|
+
route: `mcp/${tool.name}`,
|
|
258
|
+
input: tool.input,
|
|
259
|
+
output: tool.output,
|
|
260
|
+
destructive: tool.destructive,
|
|
261
|
+
},
|
|
262
|
+
]),
|
|
263
|
+
),
|
|
264
|
+
};
|
|
265
|
+
}
|
package/src/server/plugin.ts
CHANGED
|
@@ -8,24 +8,47 @@ import {
|
|
|
8
8
|
} from "./design-routes.ts";
|
|
9
9
|
import { iconDeleteRoute, iconRenameRoute, iconUploadRoute, iconsRoute } from "./icon-routes.ts";
|
|
10
10
|
import { beforeSave } from "./hooks.ts";
|
|
11
|
+
import {
|
|
12
|
+
agentsRoute,
|
|
13
|
+
agentsSaveRoute,
|
|
14
|
+
beforePublish,
|
|
15
|
+
pageAgentVersionsRoute,
|
|
16
|
+
} from "./agent-settings.ts";
|
|
11
17
|
import { canvasStyleUrls } from "../core/canvas-styles.ts";
|
|
18
|
+
import { TOOLS } from "../mcp/tools.ts";
|
|
19
|
+
import { mcpRoutes, mcpToolConfig } from "./mcp-routes.ts";
|
|
12
20
|
|
|
13
21
|
export function createPlugin(options: { canvasStyles?: unknown } = {}) {
|
|
14
22
|
const canvasStyles = canvasStyleUrls(options.canvasStyles);
|
|
15
23
|
return definePlugin({
|
|
16
24
|
id: PLUGIN_ID,
|
|
17
25
|
version: PLUGIN_VERSION,
|
|
18
|
-
capabilities: [
|
|
26
|
+
capabilities: [
|
|
27
|
+
"content:read",
|
|
28
|
+
"content:write",
|
|
29
|
+
"content:publish",
|
|
30
|
+
"content:revisions:read",
|
|
31
|
+
"hooks.content-policy:register",
|
|
32
|
+
],
|
|
19
33
|
// W-239: uploaded SVG icons (EmDash's media library refuses SVG by default).
|
|
20
|
-
storage: {
|
|
34
|
+
storage: {
|
|
35
|
+
design: { indexes: [] },
|
|
36
|
+
icons: { indexes: ["uploadedAt"] },
|
|
37
|
+
// D-057: agent changes and the site styles history.
|
|
38
|
+
agentlog: { indexes: ["at", "pageId"] },
|
|
39
|
+
designhistory: { indexes: ["at"] },
|
|
40
|
+
},
|
|
21
41
|
hooks: {
|
|
22
42
|
"content:beforeSave": { handler: beforeSave, errorPolicy: "abort" },
|
|
43
|
+
// D-055: EmDash's own MCP tools can't publish EmVB pages unless the admin allowed it.
|
|
44
|
+
"content:beforePublish": { handler: beforePublish },
|
|
23
45
|
},
|
|
24
46
|
admin: {
|
|
25
47
|
entry: ADMIN_ENTRY,
|
|
26
48
|
pages: [
|
|
27
49
|
{ path: "/pages", label: "Pages VisualBuilder", icon: "layout" },
|
|
28
50
|
{ path: "/theme", label: "Theme Builder", icon: "layout" },
|
|
51
|
+
{ path: "/agents", label: "AI agents", icon: "layout" },
|
|
29
52
|
],
|
|
30
53
|
fieldWidgets: [{ name: "layout", label: "EmVB page (read-only)", fieldTypes: ["json"] }],
|
|
31
54
|
},
|
|
@@ -44,6 +67,13 @@ export function createPlugin(options: { canvasStyles?: unknown } = {}) {
|
|
|
44
67
|
"icons/upload": iconUploadRoute,
|
|
45
68
|
"icons/rename": iconRenameRoute,
|
|
46
69
|
"icons/delete": iconDeleteRoute,
|
|
70
|
+
// W-463: the Agents tab (admins only).
|
|
71
|
+
agents: agentsRoute,
|
|
72
|
+
"agents/save": agentsSaveRoute,
|
|
73
|
+
"agents/page": pageAgentVersionsRoute,
|
|
74
|
+
// R1 D-054: EmDash's /_emdash/api/mcp lists these as emvb__<tool> (EmDash 1.2+, mcp: true).
|
|
75
|
+
...mcpRoutes(TOOLS),
|
|
47
76
|
},
|
|
77
|
+
mcp: mcpToolConfig(TOOLS),
|
|
48
78
|
});
|
|
49
79
|
}
|