@perkyzz/emvb 0.9.0 → 1.0.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 +1 -1
- package/package.json +2 -2
- package/src/admin/agents-api.ts +45 -0
- package/src/admin/editor/A11yCopilot.tsx +1 -1
- package/src/admin/editor/Editor.tsx +297 -248
- package/src/admin/editor/Timeline.tsx +2 -1
- package/src/admin/editor/TopBar.tsx +4 -2
- package/src/admin/editor/canvas/CanvasFrame.tsx +2 -2
- package/src/admin/editor/canvas/DeviceBar.tsx +17 -9
- package/src/admin/editor/canvas/canvas-scale.ts +2 -2
- package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
- package/src/admin/editor/co-design.ts +190 -0
- package/src/admin/editor/dnd/new-element.ts +26 -4
- package/src/admin/editor/editor-chrome.tsx +3 -3
- package/src/admin/editor/editor-commands.ts +8 -3
- package/src/admin/editor/element-chrome.ts +3 -1
- package/src/admin/editor/extension-manifests.ts +20 -0
- package/src/admin/editor/extensions/ExtensionPanels.tsx +26 -0
- package/src/admin/editor/extensions-context.tsx +27 -0
- package/src/admin/editor/feature-css.ts +17 -0
- package/src/admin/editor/palette-items.ts +2 -2
- package/src/admin/editor/panels/AddPanel.tsx +31 -1
- package/src/admin/editor/panels/AgentRequestBox.tsx +116 -0
- package/src/admin/editor/panels/ClassesSection.tsx +9 -6
- package/src/admin/editor/panels/CoDesignPanel.tsx +170 -0
- package/src/admin/editor/panels/ColorControl.tsx +2 -2
- package/src/admin/editor/panels/ElementPanel.tsx +49 -14
- package/src/admin/editor/panels/LanguagesSection.tsx +152 -0
- package/src/admin/editor/panels/LayersPanel.tsx +10 -6
- package/src/admin/editor/panels/LeftPanel.tsx +33 -5
- package/src/admin/editor/panels/PageSettings.tsx +4 -0
- package/src/admin/editor/panels/SettingsPanel.tsx +21 -2
- package/src/admin/editor/panels/SiteStylesDrawer.tsx +7 -7
- package/src/admin/editor/panels/settings/BackgroundControls.tsx +72 -15
- package/src/admin/editor/panels/settings/BackgroundFill.tsx +8 -6
- package/src/admin/editor/panels/settings/BoxControl.tsx +5 -5
- package/src/admin/editor/panels/settings/EffectsControls.tsx +104 -9
- package/src/admin/editor/panels/settings/FieldControl.tsx +9 -3
- package/src/admin/editor/panels/settings/IconControls.tsx +14 -11
- package/src/admin/editor/panels/settings/LengthRow.tsx +27 -16
- package/src/admin/editor/panels/settings/LoopControl.tsx +269 -0
- package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
- package/src/admin/editor/panels/settings/MotionControl.tsx +12 -11
- package/src/admin/editor/panels/settings/QueryStyleRows.tsx +7 -4
- package/src/admin/editor/panels/settings/StyleRow.tsx +113 -13
- package/src/admin/editor/panels/settings/TextMarksControl.tsx +247 -0
- package/src/admin/editor/panels/settings/VariableBinding.tsx +2 -2
- package/src/admin/editor/panels/settings/background-mode.ts +14 -11
- package/src/admin/editor/panels/settings/box-link-name.ts +1 -1
- package/src/admin/editor/panels/settings/box-sides.ts +22 -14
- package/src/admin/editor/panels/settings/heading-warning.ts +5 -1
- package/src/admin/editor/panels/settings/length-units.ts +53 -1
- package/src/admin/editor/panels/settings/query-style.ts +3 -3
- package/src/admin/editor/panels/settings/style-sections.ts +51 -10
- package/src/admin/editor/panels/style-target.ts +9 -7
- package/src/admin/editor/presence.ts +60 -0
- package/src/admin/editor/store.ts +6 -2
- package/src/admin/editor/useCoDesign.ts +177 -0
- package/src/admin/editor/useEditorCommands.ts +4 -4
- package/src/admin/editor/useExtensions.ts +45 -0
- package/src/admin/editor/useNodeActions.ts +15 -6
- package/src/admin/editor/useProposals.ts +81 -0
- package/src/admin/languages-api.ts +61 -0
- package/src/admin/pages/AgentSetup.tsx +148 -0
- package/src/admin/pages/AgentsPage.tsx +9 -26
- package/src/admin/pages/CreateDialog.tsx +15 -0
- package/src/admin/pages/ImportButton.tsx +18 -0
- package/src/admin/pages/ImportElementorDialog.tsx +669 -0
- package/src/admin/pages/ImportPageLinks.tsx +86 -0
- package/src/admin/pages/PageList.tsx +15 -1
- package/src/admin/pages/ThemePartList.tsx +15 -1
- package/src/admin/pages/section-head.tsx +27 -0
- package/src/admin/proposals-api.ts +91 -0
- package/src/admin/ui.ts +39 -2
- package/src/astro/content-port.ts +14 -1
- package/src/astro/resolve-theme.ts +14 -1
- package/src/astro/resolve.ts +89 -2
- package/src/constants.ts +1 -1
- package/src/core/a11y/audit.ts +44 -14
- package/src/core/arrange.ts +5 -1
- package/src/core/bounded-array.ts +31 -0
- package/src/core/clipboard.ts +9 -0
- package/src/core/contract.ts +285 -0
- package/src/core/css/generate.ts +89 -20
- package/src/core/css/trace.ts +18 -9
- package/src/core/css-keywords.ts +51 -1
- package/src/core/design/cascade.ts +12 -9
- package/src/core/design/classes.ts +4 -5
- package/src/core/design/devices.ts +13 -13
- package/src/core/design/states.ts +5 -3
- package/src/core/design/transfer.ts +5 -0
- package/src/core/design/variables.ts +17 -4
- package/src/core/elements/dynamic-elements.ts +3 -3
- package/src/core/elements/index.ts +73 -9
- package/src/core/extensions/define.ts +13 -0
- package/src/core/extensions/index.ts +41 -0
- package/src/core/extensions/namespace.ts +82 -0
- package/src/core/extensions/normalize.ts +141 -0
- package/src/core/extensions/placeholder.ts +41 -0
- package/src/core/extensions/registry.ts +94 -0
- package/src/core/extensions/render-ext.ts +118 -0
- package/src/core/extensions/safe-nodes.ts +93 -0
- package/src/core/extensions/schema.ts +112 -0
- package/src/core/extensions/types.ts +159 -0
- package/src/core/forms/binding.ts +1 -1
- package/src/core/history/diff.ts +1 -1
- package/src/core/import/elementor/atomic.ts +1595 -0
- package/src/core/import/elementor/classes.ts +127 -0
- package/src/core/import/elementor/context.ts +429 -0
- package/src/core/import/elementor/counter-steps.ts +72 -0
- package/src/core/import/elementor/css.ts +445 -0
- package/src/core/import/elementor/html.ts +500 -0
- package/src/core/import/elementor/index.ts +949 -0
- package/src/core/import/elementor/inline-marks.ts +81 -0
- package/src/core/import/elementor/snapshots.ts +48 -0
- package/src/core/import/elementor/style.ts +409 -0
- package/src/core/import/elementor/values.ts +241 -0
- package/src/core/import/elementor/widgets.ts +1897 -0
- package/src/core/index.ts +82 -0
- package/src/core/json-schema.ts +107 -0
- package/src/core/limits.ts +19 -0
- package/src/core/migrate/index.ts +6 -1
- package/src/core/migrate/v18.ts +222 -0
- package/src/core/perf/meter.ts +5 -5
- package/src/core/proposals-safety.ts +102 -0
- package/src/core/proposals.ts +357 -0
- package/src/core/recipes/index.ts +2 -2
- package/src/core/render/extras.ts +3 -3
- package/src/core/render/index.ts +140 -20
- package/src/core/render/loop.ts +1 -1
- package/src/core/render/section.ts +4 -4
- package/src/core/render/vnode.ts +1 -1
- package/src/core/sanitize/css.ts +125 -10
- package/src/core/sanitize/motion.ts +116 -0
- package/src/core/saved-sections.ts +6 -0
- package/src/core/schema/descriptors.ts +3 -1
- package/src/core/schema/design.ts +2 -1
- package/src/core/schema/layout.ts +82 -14
- package/src/core/schema/style.ts +251 -114
- package/src/core/text-marks.ts +227 -0
- package/src/core/theme/dynamic.ts +9 -4
- package/src/core/theme/float.ts +1 -0
- package/src/core/theme/popup-rules.ts +17 -1
- package/src/core/translatable.ts +34 -0
- package/src/core/validate.ts +13 -1
- package/src/index.ts +24 -0
- package/src/mcp/errors.ts +3 -1
- package/src/mcp/ports.ts +67 -0
- package/src/mcp/prompts.ts +1 -11
- package/src/mcp/proposals.ts +281 -0
- package/src/mcp/read.ts +10 -9
- package/src/mcp/tools.ts +71 -3
- package/src/mcp/write.ts +66 -11
- package/src/server/agent-settings.ts +5 -1
- package/src/server/mcp-routes.ts +15 -0
- package/src/server/plugin.ts +35 -2
- package/src/server/presence.ts +78 -0
- package/src/server/proposals.ts +261 -0
- package/src/server/requests.ts +196 -0
- package/src/server/tools-served.ts +45 -0
package/src/server/plugin.ts
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import {
|
|
2
|
+
proposalCreateRoute,
|
|
3
|
+
proposalGetRoute,
|
|
4
|
+
proposalsRoute,
|
|
5
|
+
proposalAcceptedRoute,
|
|
6
|
+
proposalWithdrawRoute,
|
|
7
|
+
} from "./proposals.ts";
|
|
8
|
+
import { presenceRoute } from "./presence.ts";
|
|
9
|
+
import { requestCancelRoute, requestCreateRoute, requestsRoute } from "./requests.ts";
|
|
1
10
|
import { definePlugin } from "emdash";
|
|
2
11
|
import { ADMIN_ENTRY, PLUGIN_ID, PLUGIN_VERSION } from "../constants.ts";
|
|
3
12
|
import {
|
|
@@ -23,14 +32,20 @@ import {
|
|
|
23
32
|
} from "./agent-settings.ts";
|
|
24
33
|
import { canvasStyleUrls } from "../core/canvas-styles.ts";
|
|
25
34
|
import { canvasCollectionSlugs } from "../core/canvas-collections.ts";
|
|
35
|
+
import { manifestsFromOptions } from "../core/extensions/index.ts";
|
|
26
36
|
import { TOOLS } from "../mcp/tools.ts";
|
|
27
37
|
import { mcpRoutes, mcpToolConfig } from "./mcp-routes.ts";
|
|
28
38
|
|
|
29
39
|
export function createPlugin(
|
|
30
|
-
options: {
|
|
40
|
+
options: {
|
|
41
|
+
canvasStyles?: unknown;
|
|
42
|
+
canvasCollections?: unknown;
|
|
43
|
+
extensions?: unknown;
|
|
44
|
+
} = {},
|
|
31
45
|
) {
|
|
32
46
|
const canvasStyles = canvasStyleUrls(options.canvasStyles);
|
|
33
47
|
const canvasCollections = canvasCollectionSlugs(options.canvasCollections);
|
|
48
|
+
const extensions = manifestsFromOptions(options.extensions);
|
|
34
49
|
return definePlugin({
|
|
35
50
|
id: PLUGIN_ID,
|
|
36
51
|
version: PLUGIN_VERSION,
|
|
@@ -52,6 +67,9 @@ export function createPlugin(
|
|
|
52
67
|
designhistory: { indexes: ["at"] },
|
|
53
68
|
// W-875 (D-060): saved sections, by name, per site.
|
|
54
69
|
emvb_saved_sections: { indexes: ["updatedAt"] },
|
|
70
|
+
emvb_proposals: { indexes: ["createdAt"] },
|
|
71
|
+
// W-931: prompt relay requests for bring-your-own agents.
|
|
72
|
+
emvb_requests: { indexes: ["createdAt"] },
|
|
55
73
|
},
|
|
56
74
|
hooks: {
|
|
57
75
|
"content:beforeSave": {
|
|
@@ -82,13 +100,28 @@ export function createPlugin(
|
|
|
82
100
|
handler: async () => ({ ok: true, plugin: PLUGIN_ID, version: PLUGIN_VERSION }),
|
|
83
101
|
},
|
|
84
102
|
// W-327: what the editor needs from the host's `emvb()` options.
|
|
85
|
-
"editor/config": {
|
|
103
|
+
"editor/config": {
|
|
104
|
+
handler: async () => ({
|
|
105
|
+
canvasStyles,
|
|
106
|
+
canvasCollections,
|
|
107
|
+
extensions,
|
|
108
|
+
}),
|
|
109
|
+
},
|
|
86
110
|
design: designRoute,
|
|
87
111
|
"design/draft": designDraftRoute,
|
|
88
112
|
"design/save": designSaveRoute,
|
|
89
113
|
"design/publish": designPublishRoute,
|
|
90
114
|
icons: iconsRoute,
|
|
91
115
|
"saved-sections": savedSectionsRoute,
|
|
116
|
+
proposals: proposalsRoute,
|
|
117
|
+
"proposals/get": proposalGetRoute,
|
|
118
|
+
"proposals/create": proposalCreateRoute,
|
|
119
|
+
"proposals/withdraw": proposalWithdrawRoute,
|
|
120
|
+
"proposals/accepted": proposalAcceptedRoute,
|
|
121
|
+
presence: presenceRoute,
|
|
122
|
+
requests: requestsRoute,
|
|
123
|
+
"requests/create": requestCreateRoute,
|
|
124
|
+
"requests/cancel": requestCancelRoute,
|
|
92
125
|
"saved-sections/get": savedSectionGetRoute,
|
|
93
126
|
"saved-sections/save": savedSectionSaveRoute,
|
|
94
127
|
"saved-sections/rename": savedSectionRenameRoute,
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { PluginRoute, RouteContext } from "emdash";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { isRecord } from "../core/record.ts";
|
|
4
|
+
import { ProposalTarget } from "../core/proposals.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* W-929 (D-064): which pages are open in the EmVB editor right now. EmVB's editor is a plugin page,
|
|
8
|
+
* so it holds no EmDash edit lock, and plugin content writes skip that lock anyway. The editor
|
|
9
|
+
* renews a short lease here instead; agent writes to a page with a live lease are refused and
|
|
10
|
+
* pointed at propose_changes, so the person editing reviews them.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** A closed tab frees the page within this long. The editor renews at a third of it. */
|
|
14
|
+
export const PRESENCE_LEASE_MS = 90_000;
|
|
15
|
+
const MAX_HOLDERS = 20;
|
|
16
|
+
|
|
17
|
+
type Holders = Record<string, number>;
|
|
18
|
+
type Kv = {
|
|
19
|
+
get<T>(key: string): Promise<T | null>;
|
|
20
|
+
set(key: string, value: unknown): Promise<void>;
|
|
21
|
+
delete(key: string): Promise<boolean>;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const keyOf = (target: z.infer<typeof ProposalTarget>) =>
|
|
25
|
+
`presence:${target.collection}:${target.id}`;
|
|
26
|
+
|
|
27
|
+
function live(raw: unknown, now: number): Holders {
|
|
28
|
+
if (!isRecord(raw)) return {};
|
|
29
|
+
const out: Holders = {};
|
|
30
|
+
for (const [user, until] of Object.entries(raw)) {
|
|
31
|
+
if (typeof until === "number" && until > now && until <= now + PRESENCE_LEASE_MS)
|
|
32
|
+
out[user] = until;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Renews (open) or ends (closed) `userId`'s lease on a page. */
|
|
38
|
+
export async function setPresence(
|
|
39
|
+
kv: Kv,
|
|
40
|
+
target: z.infer<typeof ProposalTarget>,
|
|
41
|
+
userId: string,
|
|
42
|
+
open: boolean,
|
|
43
|
+
now = Date.now(),
|
|
44
|
+
): Promise<void> {
|
|
45
|
+
const key = keyOf(target);
|
|
46
|
+
const holders = live(await kv.get<unknown>(key), now);
|
|
47
|
+
if (open) holders[userId] = now + PRESENCE_LEASE_MS;
|
|
48
|
+
else delete holders[userId];
|
|
49
|
+
const kept = Object.entries(holders)
|
|
50
|
+
.toSorted(([, a], [, b]) => b - a)
|
|
51
|
+
.slice(0, MAX_HOLDERS);
|
|
52
|
+
if (kept.length === 0) await kv.delete(key);
|
|
53
|
+
else await kv.set(key, Object.fromEntries(kept));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** True while someone has the page open in the EmVB editor. */
|
|
57
|
+
export async function isOpenInEditor(
|
|
58
|
+
kv: Kv,
|
|
59
|
+
target: z.infer<typeof ProposalTarget>,
|
|
60
|
+
now = Date.now(),
|
|
61
|
+
): Promise<boolean> {
|
|
62
|
+
return Object.keys(live(await kv.get<unknown>(keyOf(target)), now)).length > 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const PresenceInput = z.strictObject({ target: ProposalTarget, open: z.boolean() });
|
|
66
|
+
|
|
67
|
+
/** The editor's heartbeat: `open: true` every PRESENCE_LEASE_MS / 3, `open: false` on close. */
|
|
68
|
+
export const presenceRoute: PluginRoute<z.infer<typeof PresenceInput>> = {
|
|
69
|
+
permission: "content:edit_any",
|
|
70
|
+
input: PresenceInput,
|
|
71
|
+
handler: async (ctx: RouteContext<z.infer<typeof PresenceInput>>) => {
|
|
72
|
+
const userId = ctx.user?.id;
|
|
73
|
+
if (userId) {
|
|
74
|
+
await setPresence(ctx.kv as unknown as Kv, ctx.input.target, userId, ctx.input.open);
|
|
75
|
+
}
|
|
76
|
+
return { leaseMs: PRESENCE_LEASE_MS };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
|
|
4
|
+
import { MAX_PENDING_PER_PAGE, MAX_PROPOSAL_OPS, MAX_PROPOSALS } from "../core/limits.ts";
|
|
5
|
+
import {
|
|
6
|
+
applyProposal,
|
|
7
|
+
ProposalTarget,
|
|
8
|
+
readProposal,
|
|
9
|
+
type Proposal,
|
|
10
|
+
type ProposalBase,
|
|
11
|
+
type ProposalRecord,
|
|
12
|
+
type ProposalRefusal,
|
|
13
|
+
} from "../core/proposals.ts";
|
|
14
|
+
import { isRecord } from "../core/record.ts";
|
|
15
|
+
import type { ProposalsPort } from "../mcp/ports.ts";
|
|
16
|
+
import { queued } from "../mcp/queue.ts";
|
|
17
|
+
import { agentLog, appendAgentLog } from "./agent-settings.ts";
|
|
18
|
+
import { readDesign } from "./design-routes.ts";
|
|
19
|
+
|
|
20
|
+
const COLLECTION = "emvb_proposals";
|
|
21
|
+
const ID = /^[0-9a-f]{16}$/;
|
|
22
|
+
type ProposalStore = {
|
|
23
|
+
get(id: string): Promise<unknown>;
|
|
24
|
+
put(id: string, data: ProposalRecord): Promise<void>;
|
|
25
|
+
delete(id: string): Promise<boolean>;
|
|
26
|
+
query(options: { orderBy: Record<string, "asc" | "desc">; limit: number }): Promise<{
|
|
27
|
+
items: { id: string; data: unknown }[];
|
|
28
|
+
hasMore: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function readRecord(raw: unknown): { ok: true; record: ProposalRecord } | ProposalRefusal {
|
|
33
|
+
if (
|
|
34
|
+
!isRecord(raw) ||
|
|
35
|
+
typeof raw.createdAt !== "string" ||
|
|
36
|
+
!Number.isFinite(Date.parse(raw.createdAt))
|
|
37
|
+
) {
|
|
38
|
+
return { ok: false, code: "INVALID_PROPOSAL", reason: "Damaged proposal record." };
|
|
39
|
+
}
|
|
40
|
+
const read = readProposal(raw.proposal);
|
|
41
|
+
return read.ok
|
|
42
|
+
? { ok: true, record: { proposal: read.proposal, createdAt: raw.createdAt } }
|
|
43
|
+
: read;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Same per-isolate write queue as saved sections. Content/design are read-only dependencies. */
|
|
47
|
+
export function proposalsPort(
|
|
48
|
+
store: ProposalStore,
|
|
49
|
+
readBase: (target: Proposal["target"]) => Promise<ProposalBase | null>,
|
|
50
|
+
): ProposalsPort {
|
|
51
|
+
const all = () => store.query({ orderBy: { createdAt: "desc" }, limit: MAX_PROPOSALS });
|
|
52
|
+
const get: ProposalsPort["get"] = async (id) => {
|
|
53
|
+
if (!ID.test(id)) return null;
|
|
54
|
+
const raw = await store.get(id);
|
|
55
|
+
if (raw === undefined || raw === null) return null;
|
|
56
|
+
const read = readRecord(raw);
|
|
57
|
+
return read.ok ? { ...read, id } : read;
|
|
58
|
+
};
|
|
59
|
+
return {
|
|
60
|
+
get,
|
|
61
|
+
async list(target) {
|
|
62
|
+
const items: { id: string; record: ProposalRecord }[] = [];
|
|
63
|
+
for (const row of (await all()).items) {
|
|
64
|
+
const read = readRecord(row.data);
|
|
65
|
+
if (
|
|
66
|
+
read.ok &&
|
|
67
|
+
read.record.proposal.target.collection === target.collection &&
|
|
68
|
+
read.record.proposal.target.id === target.id
|
|
69
|
+
)
|
|
70
|
+
items.push({ id: row.id, record: read.record });
|
|
71
|
+
}
|
|
72
|
+
return items;
|
|
73
|
+
},
|
|
74
|
+
create: (raw) =>
|
|
75
|
+
queued("proposals", async () => {
|
|
76
|
+
const read = readProposal(raw);
|
|
77
|
+
if (!read.ok) return read;
|
|
78
|
+
const base = await readBase(read.proposal.target);
|
|
79
|
+
if (!base)
|
|
80
|
+
return { ok: false, code: "NOT_FOUND", reason: "No target page with a readable layout." };
|
|
81
|
+
const applied = applyProposal(base, read.proposal);
|
|
82
|
+
if (!applied.ok) return applied;
|
|
83
|
+
const page = await all();
|
|
84
|
+
const forPage = page.items.filter((row) => {
|
|
85
|
+
const target =
|
|
86
|
+
isRecord(row.data) && isRecord(row.data.proposal)
|
|
87
|
+
? row.data.proposal.target
|
|
88
|
+
: undefined;
|
|
89
|
+
return (
|
|
90
|
+
isRecord(target) &&
|
|
91
|
+
target.collection === read.proposal.target.collection &&
|
|
92
|
+
target.id === read.proposal.target.id
|
|
93
|
+
);
|
|
94
|
+
}).length;
|
|
95
|
+
if (forPage >= MAX_PENDING_PER_PAGE)
|
|
96
|
+
return {
|
|
97
|
+
ok: false,
|
|
98
|
+
code: "PROPOSALS_FULL",
|
|
99
|
+
reason: `This page already has ${MAX_PENDING_PER_PAGE} proposals waiting for review. Withdraw one, or wait until the person editing reviews them.`,
|
|
100
|
+
};
|
|
101
|
+
if (page.hasMore || page.items.length >= MAX_PROPOSALS)
|
|
102
|
+
return {
|
|
103
|
+
ok: false,
|
|
104
|
+
code: "PROPOSALS_FULL",
|
|
105
|
+
reason: `At most ${MAX_PROPOSALS} proposals are kept. Withdraw an old one and try again.`,
|
|
106
|
+
};
|
|
107
|
+
const latest = await readBase(read.proposal.target);
|
|
108
|
+
if (!latest)
|
|
109
|
+
return {
|
|
110
|
+
ok: false,
|
|
111
|
+
code: "NOT_FOUND",
|
|
112
|
+
reason: "The target page is no longer available.",
|
|
113
|
+
};
|
|
114
|
+
const rechecked = applyProposal(latest, read.proposal);
|
|
115
|
+
if (!rechecked.ok) return rechecked;
|
|
116
|
+
const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
|
|
117
|
+
const record = { proposal: read.proposal, createdAt: new Date().toISOString() };
|
|
118
|
+
await store.put(id, record);
|
|
119
|
+
return { ok: true, id, record };
|
|
120
|
+
}),
|
|
121
|
+
withdraw: (id) => queued("proposals", async () => ID.test(id) && (await store.delete(id))),
|
|
122
|
+
async base(target) {
|
|
123
|
+
const found = await readBase(target);
|
|
124
|
+
return found ? { revision: found.revision, designRevision: found.designRevision } : null;
|
|
125
|
+
},
|
|
126
|
+
async prepare(id, selected) {
|
|
127
|
+
const read = await get(id);
|
|
128
|
+
if (!read || !read.ok) return read;
|
|
129
|
+
const base = await readBase(read.record.proposal.target);
|
|
130
|
+
if (!base)
|
|
131
|
+
return { ok: false, code: "NOT_FOUND", reason: "The target page is no longer available." };
|
|
132
|
+
return applyProposal(base, read.record.proposal, selected);
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function proposalPortOf(ctx: RouteContext<unknown>): ProposalsPort {
|
|
138
|
+
return proposalsPort(ctx.storage[COLLECTION] as unknown as ProposalStore, async (target) => {
|
|
139
|
+
const found = await ctx.content?.getVersioned?.(target.collection, target.id);
|
|
140
|
+
if (!found) return null;
|
|
141
|
+
let layout: unknown = found.item.data["layout"];
|
|
142
|
+
if (typeof layout === "string") {
|
|
143
|
+
try {
|
|
144
|
+
layout = JSON.parse(layout);
|
|
145
|
+
} catch {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
|
|
150
|
+
const published = await readDesign(ctx, DESIGN_KEY);
|
|
151
|
+
const styles = draft.status === "empty" ? published : draft;
|
|
152
|
+
return {
|
|
153
|
+
revision: found["_rev"],
|
|
154
|
+
layout,
|
|
155
|
+
design: styles.status === "unreadable" ? null : styles.design,
|
|
156
|
+
designRevision: styles.revision,
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function unwrap<T extends { ok: boolean }>(result: T | null): Extract<T, { ok: true }> {
|
|
162
|
+
if (!result) throw new PluginRouteError("NOT_FOUND", "No such proposal.", 404);
|
|
163
|
+
if (!result.ok) {
|
|
164
|
+
const refusal = result as unknown as ProposalRefusal;
|
|
165
|
+
throw new PluginRouteError(
|
|
166
|
+
refusal.code,
|
|
167
|
+
refusal.reason,
|
|
168
|
+
refusal.code === "STALE_BASE" || refusal.code === "PROPOSALS_FULL"
|
|
169
|
+
? 409
|
|
170
|
+
: refusal.code === "NOT_FOUND"
|
|
171
|
+
? 404
|
|
172
|
+
: 422,
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
return result as Extract<T, { ok: true }>;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Plugin-local editor transport, not a public API. Agents use the MCP tools (W-929).
|
|
179
|
+
export const proposalsRoute: PluginRoute<z.infer<typeof ProposalTarget>> = {
|
|
180
|
+
permission: "content:edit_any",
|
|
181
|
+
input: ProposalTarget,
|
|
182
|
+
handler: async (ctx) => ({ items: await proposalPortOf(ctx).list(ctx.input) }),
|
|
183
|
+
};
|
|
184
|
+
const IdInput = z.strictObject({ id: z.string().regex(ID) });
|
|
185
|
+
export const proposalGetRoute: PluginRoute<z.infer<typeof IdInput>> = {
|
|
186
|
+
permission: "content:edit_any",
|
|
187
|
+
input: IdInput,
|
|
188
|
+
handler: async (ctx) => unwrap(await proposalPortOf(ctx).get(ctx.input.id)),
|
|
189
|
+
};
|
|
190
|
+
const CreateInput = z.strictObject({ proposal: z.unknown() });
|
|
191
|
+
export const proposalCreateRoute: PluginRoute<z.infer<typeof CreateInput>> = {
|
|
192
|
+
permission: "content:edit_any",
|
|
193
|
+
input: CreateInput,
|
|
194
|
+
handler: async (ctx) => unwrap(await proposalPortOf(ctx).create(ctx.input.proposal)),
|
|
195
|
+
};
|
|
196
|
+
const WithdrawInput = IdInput.extend({
|
|
197
|
+
/** W-933: the person's review, when the editor closes a proposal it decided. */
|
|
198
|
+
decision: z
|
|
199
|
+
.strictObject({
|
|
200
|
+
accepted: z.number().int().min(0).max(MAX_PROPOSAL_OPS),
|
|
201
|
+
rejected: z.number().int().min(0).max(MAX_PROPOSAL_OPS),
|
|
202
|
+
})
|
|
203
|
+
.optional(),
|
|
204
|
+
});
|
|
205
|
+
export const proposalWithdrawRoute: PluginRoute<z.infer<typeof WithdrawInput>> = {
|
|
206
|
+
permission: "content:edit_any",
|
|
207
|
+
input: WithdrawInput,
|
|
208
|
+
handler: async (ctx) => {
|
|
209
|
+
const port = proposalPortOf(ctx);
|
|
210
|
+
const found = await port.get(ctx.input.id);
|
|
211
|
+
if (!(await port.withdraw(ctx.input.id)))
|
|
212
|
+
throw new PluginRouteError("NOT_FOUND", "No such proposal.", 404);
|
|
213
|
+
const decision = ctx.input.decision;
|
|
214
|
+
if (decision && found?.ok) {
|
|
215
|
+
await appendAgentLog(agentLog(ctx as never), {
|
|
216
|
+
target: "page",
|
|
217
|
+
tool: "review_proposal",
|
|
218
|
+
pageId: found.record.proposal.target.id,
|
|
219
|
+
proposalId: ctx.input.id,
|
|
220
|
+
changes: found.record.proposal.ops.length,
|
|
221
|
+
summary: `Reviewed a proposal: ${decision.accepted} accepted, ${decision.rejected} rejected`,
|
|
222
|
+
userId: ctx.user?.id ?? null,
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
return { id: ctx.input.id };
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const AcceptedInput = z.strictObject({
|
|
230
|
+
target: ProposalTarget,
|
|
231
|
+
accepted: z.number().int().min(1).max(MAX_PROPOSAL_OPS),
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* W-930: after Save draft, the editor notes that the new version holds changes accepted from an
|
|
236
|
+
* agent proposal. The version itself is a normal save by the person; the log entry only labels it
|
|
237
|
+
* "Via agent" in the timeline. The newest revision is read here, never taken from the browser.
|
|
238
|
+
*/
|
|
239
|
+
export const proposalAcceptedRoute: PluginRoute<z.infer<typeof AcceptedInput>> = {
|
|
240
|
+
permission: "content:edit_any",
|
|
241
|
+
input: AcceptedInput,
|
|
242
|
+
handler: async (ctx) => {
|
|
243
|
+
const { target, accepted } = ctx.input;
|
|
244
|
+
const content = ctx.content as unknown as {
|
|
245
|
+
listRevisions?(c: string, id: string, o: { limit?: number }): Promise<{ id: string }[]>;
|
|
246
|
+
};
|
|
247
|
+
const [latest] = content.listRevisions
|
|
248
|
+
? await content.listRevisions(target.collection, target.id, { limit: 1 })
|
|
249
|
+
: [];
|
|
250
|
+
if (!latest) throw new PluginRouteError("NOT_FOUND", "No saved version to label.", 404);
|
|
251
|
+
await appendAgentLog(agentLog(ctx as never), {
|
|
252
|
+
target: "page",
|
|
253
|
+
tool: "accept_proposal",
|
|
254
|
+
pageId: target.id,
|
|
255
|
+
revisionId: latest.id,
|
|
256
|
+
summary: `Saved ${accepted} ${accepted === 1 ? "change" : "changes"} accepted from an agent proposal`,
|
|
257
|
+
userId: ctx.user?.id ?? null,
|
|
258
|
+
});
|
|
259
|
+
return { revisionId: latest.id };
|
|
260
|
+
},
|
|
261
|
+
};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { MAX_OPEN_REQUESTS_PER_PAGE, MAX_REQUEST_PROMPT } from "../core/limits.ts";
|
|
4
|
+
import { ProposalTarget } from "../core/proposals.ts";
|
|
5
|
+
import { isRecord } from "../core/record.ts";
|
|
6
|
+
import type { AgentRequest, RequestsPort } from "../mcp/ports.ts";
|
|
7
|
+
import { queued } from "../mcp/queue.ts";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* W-931 prompt relay (D-063: bring-your-own agent). A person writes a request in the editor's
|
|
11
|
+
* Agent tab; their own agent reads it with get_requests and answers with propose_changes. Nothing
|
|
12
|
+
* here calls a model or holds a key. Requests are the person's words for their agent: they are
|
|
13
|
+
* shown back as plain text and never reach a page.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const COLLECTION = "emvb_requests";
|
|
17
|
+
const ID = /^[0-9a-f]{16}$/;
|
|
18
|
+
/** Requests older than this are no longer offered to agents. */
|
|
19
|
+
const REQUEST_TTL_MS = 24 * 3_600_000;
|
|
20
|
+
const SEEN_KEY = "relay:seen";
|
|
21
|
+
|
|
22
|
+
type Target = z.infer<typeof ProposalTarget>;
|
|
23
|
+
type Stored = {
|
|
24
|
+
target: Target;
|
|
25
|
+
prompt: string;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
userId: string | null;
|
|
28
|
+
status: "open" | "answered";
|
|
29
|
+
proposalId?: string;
|
|
30
|
+
answeredAt?: string;
|
|
31
|
+
};
|
|
32
|
+
type Store = {
|
|
33
|
+
get(id: string): Promise<unknown>;
|
|
34
|
+
put(id: string, data: Stored): Promise<void>;
|
|
35
|
+
delete(id: string): Promise<boolean>;
|
|
36
|
+
query(options: { orderBy: Record<string, "asc" | "desc">; limit: number }): Promise<{
|
|
37
|
+
items: { id: string; data: unknown }[];
|
|
38
|
+
}>;
|
|
39
|
+
};
|
|
40
|
+
type Kv = {
|
|
41
|
+
get<T>(key: string): Promise<T | null>;
|
|
42
|
+
set(key: string, value: unknown): Promise<void>;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function read(raw: unknown): Stored | null {
|
|
46
|
+
if (!isRecord(raw) || !isRecord(raw.target)) return null;
|
|
47
|
+
const target = ProposalTarget.safeParse(raw.target);
|
|
48
|
+
if (
|
|
49
|
+
!target.success ||
|
|
50
|
+
typeof raw.prompt !== "string" ||
|
|
51
|
+
typeof raw.createdAt !== "string" ||
|
|
52
|
+
(raw.status !== "open" && raw.status !== "answered")
|
|
53
|
+
)
|
|
54
|
+
return null;
|
|
55
|
+
return raw as Stored;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const toRequest = (id: string, s: Stored): AgentRequest => ({
|
|
59
|
+
id,
|
|
60
|
+
target: s.target,
|
|
61
|
+
prompt: s.prompt,
|
|
62
|
+
createdAt: s.createdAt,
|
|
63
|
+
status: s.status,
|
|
64
|
+
...(s.proposalId ? { proposalId: s.proposalId } : {}),
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/** Two requests in the same millisecond kept no order; times only move forward in one process. */
|
|
68
|
+
let lastCreatedMs = 0;
|
|
69
|
+
const nextCreatedAt = (nowMs: number) => {
|
|
70
|
+
// A tie (or a slightly earlier clock) moves one millisecond on; a clock far behind is kept.
|
|
71
|
+
lastCreatedMs =
|
|
72
|
+
nowMs > lastCreatedMs || lastCreatedMs - nowMs >= 1000 ? nowMs : lastCreatedMs + 1;
|
|
73
|
+
return new Date(lastCreatedMs).toISOString();
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const sameTarget = (a: Target, b: Target) => a.collection === b.collection && a.id === b.id;
|
|
77
|
+
|
|
78
|
+
/** Same per-isolate write queue pattern as proposals; `now` is injectable for tests. */
|
|
79
|
+
export function requestsPort(store: Store, kv: Kv, now: () => number = Date.now): RequestsPort {
|
|
80
|
+
const all = async () => {
|
|
81
|
+
const rows = await store.query({ orderBy: { createdAt: "desc" }, limit: 200 });
|
|
82
|
+
const out: { id: string; stored: Stored }[] = [];
|
|
83
|
+
for (const row of rows.items) {
|
|
84
|
+
const stored = read(row.data);
|
|
85
|
+
if (stored) out.push({ id: row.id, stored });
|
|
86
|
+
}
|
|
87
|
+
return out;
|
|
88
|
+
};
|
|
89
|
+
const live = (s: Stored) => now() - Date.parse(s.createdAt) < REQUEST_TTL_MS;
|
|
90
|
+
return {
|
|
91
|
+
async list(target) {
|
|
92
|
+
return (await all())
|
|
93
|
+
.filter((r) => sameTarget(r.stored.target, target))
|
|
94
|
+
.map((r) => toRequest(r.id, r.stored));
|
|
95
|
+
},
|
|
96
|
+
async open(target) {
|
|
97
|
+
return (await all())
|
|
98
|
+
.filter((r) => r.stored.status === "open" && live(r.stored))
|
|
99
|
+
.filter((r) => !target || sameTarget(r.stored.target, target))
|
|
100
|
+
.map((r) => toRequest(r.id, r.stored))
|
|
101
|
+
.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
102
|
+
},
|
|
103
|
+
create: (target, prompt, userId) =>
|
|
104
|
+
queued("requests", async () => {
|
|
105
|
+
const text = prompt.trim();
|
|
106
|
+
if (!text) return { ok: false as const, reason: "Write what you'd like the agent to do." };
|
|
107
|
+
if (text.length > MAX_REQUEST_PROMPT)
|
|
108
|
+
return {
|
|
109
|
+
ok: false as const,
|
|
110
|
+
reason: `Keep a request under ${MAX_REQUEST_PROMPT} characters.`,
|
|
111
|
+
};
|
|
112
|
+
const open = (await all()).filter(
|
|
113
|
+
(r) =>
|
|
114
|
+
r.stored.status === "open" && live(r.stored) && sameTarget(r.stored.target, target),
|
|
115
|
+
);
|
|
116
|
+
if (open.length >= MAX_OPEN_REQUESTS_PER_PAGE)
|
|
117
|
+
return {
|
|
118
|
+
ok: false as const,
|
|
119
|
+
reason: `This page already has ${MAX_OPEN_REQUESTS_PER_PAGE} requests waiting. Cancel one or wait for an answer.`,
|
|
120
|
+
};
|
|
121
|
+
const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
|
|
122
|
+
const stored: Stored = {
|
|
123
|
+
target,
|
|
124
|
+
prompt: text,
|
|
125
|
+
createdAt: nextCreatedAt(now()),
|
|
126
|
+
userId,
|
|
127
|
+
status: "open",
|
|
128
|
+
};
|
|
129
|
+
await store.put(id, stored);
|
|
130
|
+
return { ok: true as const, request: toRequest(id, stored) };
|
|
131
|
+
}),
|
|
132
|
+
cancel: (id) => queued("requests", async () => ID.test(id) && (await store.delete(id))),
|
|
133
|
+
answer: (id, target, proposalId) =>
|
|
134
|
+
queued("requests", async () => {
|
|
135
|
+
if (!ID.test(id)) return false;
|
|
136
|
+
const stored = read(await store.get(id));
|
|
137
|
+
if (!stored || stored.status !== "open" || !sameTarget(stored.target, target)) return false;
|
|
138
|
+
await store.put(id, {
|
|
139
|
+
...stored,
|
|
140
|
+
status: "answered",
|
|
141
|
+
proposalId,
|
|
142
|
+
answeredAt: new Date(now()).toISOString(),
|
|
143
|
+
});
|
|
144
|
+
return true;
|
|
145
|
+
}),
|
|
146
|
+
async seen() {
|
|
147
|
+
await kv.set(SEEN_KEY, new Date(now()).toISOString());
|
|
148
|
+
},
|
|
149
|
+
async lastSeen() {
|
|
150
|
+
const at = await kv.get<unknown>(SEEN_KEY);
|
|
151
|
+
return typeof at === "string" && Number.isFinite(Date.parse(at)) ? at : null;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const requestsPortOf = (ctx: RouteContext<unknown>): RequestsPort =>
|
|
157
|
+
requestsPort(ctx.storage[COLLECTION] as unknown as Store, ctx.kv as unknown as Kv);
|
|
158
|
+
|
|
159
|
+
/** The editor's list: this page's requests and when an agent last checked for requests. */
|
|
160
|
+
export const requestsRoute: PluginRoute<z.infer<typeof ProposalTarget>> = {
|
|
161
|
+
permission: "content:edit_any",
|
|
162
|
+
input: ProposalTarget,
|
|
163
|
+
handler: async (ctx) => {
|
|
164
|
+
const port = requestsPortOf(ctx);
|
|
165
|
+
return { items: await port.list(ctx.input), agentSeenAt: await port.lastSeen() };
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const CreateInput = z.strictObject({
|
|
170
|
+
target: ProposalTarget,
|
|
171
|
+
prompt: z.string().max(MAX_REQUEST_PROMPT * 2),
|
|
172
|
+
});
|
|
173
|
+
export const requestCreateRoute: PluginRoute<z.infer<typeof CreateInput>> = {
|
|
174
|
+
permission: "content:edit_any",
|
|
175
|
+
input: CreateInput,
|
|
176
|
+
handler: async (ctx) => {
|
|
177
|
+
const made = await requestsPortOf(ctx).create(
|
|
178
|
+
ctx.input.target,
|
|
179
|
+
ctx.input.prompt,
|
|
180
|
+
ctx.user?.id ?? null,
|
|
181
|
+
);
|
|
182
|
+
if (!made.ok) throw new PluginRouteError("INVALID_REQUEST", made.reason, 422);
|
|
183
|
+
return { request: made.request };
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const IdInput = z.strictObject({ id: z.string().regex(ID) });
|
|
188
|
+
export const requestCancelRoute: PluginRoute<z.infer<typeof IdInput>> = {
|
|
189
|
+
permission: "content:edit_any",
|
|
190
|
+
input: IdInput,
|
|
191
|
+
handler: async (ctx) => {
|
|
192
|
+
if (!(await requestsPortOf(ctx).cancel(ctx.input.id)))
|
|
193
|
+
throw new PluginRouteError("NOT_FOUND", "No such request.", 404);
|
|
194
|
+
return { id: ctx.input.id };
|
|
195
|
+
},
|
|
196
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ToolDef } from "../mcp/tools.ts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* W-932: EmDash approves a plugin's MCP tools as a snapshot of the tool list and hides them again
|
|
5
|
+
* when the list changes (an EmVB update), without saying so to the plugin. EmVB notes which tool
|
|
6
|
+
* list EmDash last actually served, so the AI agents page can tell "working on this version" from
|
|
7
|
+
* "approved, but maybe for an older list".
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const KEY = "mcp:served";
|
|
11
|
+
type Kv = {
|
|
12
|
+
get<T>(key: string): Promise<T | null>;
|
|
13
|
+
set(key: string, value: unknown): Promise<void>;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** FNV-1a over what EmDash's consent covers: names, descriptions and the destructive flag. */
|
|
17
|
+
export function toolListFingerprint(tools: readonly ToolDef[]): string {
|
|
18
|
+
let hash = 0x811c9dc5;
|
|
19
|
+
const text = tools
|
|
20
|
+
.map((t) => `${t.name}\u0000${t.description}\u0000${t.destructive}`)
|
|
21
|
+
.join("\u0001");
|
|
22
|
+
for (let i = 0; i < text.length; i++) {
|
|
23
|
+
hash ^= text.charCodeAt(i);
|
|
24
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
25
|
+
}
|
|
26
|
+
return `${tools.length}-${hash.toString(16)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Called when EmDash's own MCP endpoint ran an EmVB tool; writes only when the list changed. */
|
|
30
|
+
export async function noteServed(kv: Kv, fingerprint: string): Promise<void> {
|
|
31
|
+
if ((await kv.get<string>(KEY)) !== fingerprint) await kv.set(KEY, fingerprint);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function servedCurrent(kv: Kv, fingerprint: string): Promise<boolean> {
|
|
35
|
+
return (await kv.get<string>(KEY)) === fingerprint;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** EmDash's MCP endpoint, as opposed to calling the plugin route `mcp/<tool>` directly. */
|
|
39
|
+
export const viaEmDashMcp = (request: Request): boolean => {
|
|
40
|
+
try {
|
|
41
|
+
return new URL(request.url).pathname === "/_emdash/api/mcp";
|
|
42
|
+
} catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
};
|