blockout-editor 0.0.0-stage → 0.2.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/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "blockout-editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Blockout's editor in your app's dev page: pick anything, change its spacing, type, colour and layout against your own tokens, and send it to Claude Code to write into your code.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "author": "Yash Gidwani (https://github.com/ux-yash)",
7
+ "keywords": [
8
+ "figma",
9
+ "design",
10
+ "editor",
11
+ "claude-code",
12
+ "design-tokens",
13
+ "devtools"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./index.d.ts",
19
+ "default": "./index.js"
20
+ },
21
+ "./react": {
22
+ "types": "./react.d.ts",
23
+ "default": "./react.js"
24
+ },
25
+ "./next": {
26
+ "types": "./server/next.d.ts",
27
+ "default": "./server/next.js"
28
+ },
29
+ "./vite": {
30
+ "types": "./server/vite.d.ts",
31
+ "default": "./server/vite.js"
32
+ },
33
+ "./bundle": "./blockout-editor.js"
34
+ },
35
+ "bin": {
36
+ "blockout-editor": "server/cli.js"
37
+ },
38
+ "files": [
39
+ "index.js",
40
+ "index.d.ts",
41
+ "react.js",
42
+ "react.d.ts",
43
+ "engine.js",
44
+ "server",
45
+ "README.md",
46
+ "NOTICE.md",
47
+ "LICENSE",
48
+ "blockout-editor.js"
49
+ ],
50
+ "peerDependencies": {
51
+ "react": ">=18"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "react": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "engines": {
59
+ "node": ">=18"
60
+ },
61
+ "scripts": {
62
+ "test": "node --test test/notes.test.mjs test/bundle.test.mjs",
63
+ "build": "node scripts/bundle.mjs"
64
+ }
65
+ }
package/react.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { EditorOptions } from "./index.js";
2
+ /** Blockout's editor in a React app's dev page: render once, beside the app. Renders nothing; does nothing in production. */
3
+ export function BlockoutEditor(props: EditorOptions): null;
4
+ export default BlockoutEditor;
package/react.js ADDED
@@ -0,0 +1,21 @@
1
+ "use client";
2
+
3
+ /*
4
+ * <BlockoutEditor />: Blockout's editor in a React app's dev page. Render it once, beside the app (Next.js: in the root
5
+ * layout; Vite: next to <App />). It renders nothing, and in a production build it does nothing.
6
+ */
7
+ import { useEffect } from "react";
8
+ import { startEditor } from "./index.js";
9
+
10
+ /** @param {{ blockout?: string, notesApi?: string, open?: boolean }} props */
11
+ export function BlockoutEditor(props) {
12
+ useEffect(() => {
13
+ if (process.env.NODE_ENV === "production") return;
14
+ return startEditor(props);
15
+ // Started once; its options are read then.
16
+ // eslint-disable-next-line react-hooks/exhaustive-deps
17
+ }, []);
18
+ return null;
19
+ }
20
+
21
+ export default BlockoutEditor;
@@ -0,0 +1,334 @@
1
+ /*
2
+ * The editor's Claude chat: the dev server runs the person's own Claude Code (`claude -p`) in the project's folder, so
3
+ * what they change and comment on in the dev page goes straight to Claude, which writes it into the code; the dev
4
+ * server's hot reload shows it. Each chat is one Claude Code session, resumed message to message (`--resume`), so
5
+ * Claude remembers the thread and its own edits; when the session can't be resumed, the chat's last exchanges go ahead
6
+ * of the message instead.
7
+ *
8
+ * Chats are kept in .notes/blockout-chats.json beside the notes:
9
+ * { "chats": [ { "id", "title", "createdAt", "updatedAt", "sessionId",
10
+ * "messages": [ { "id", "at", "from": "you", "text", "comments": [ { "n", "label", "text" } ], "changed" }
11
+ * | { "id", "at", "from": "claude", "status": "running" | "done" | "failed" | "stopped",
12
+ * "steps": [ { "at", "kind", "text", "done", "failed" } ], "said", "reply", "error",
13
+ * "endedAt" } ] } ] }
14
+ *
15
+ * Claude may read, search and edit the project's files, run commands (Bash), and use the person's skills, with their
16
+ * own settings and CLAUDE.md. Only the dev server runs it, and only for the app's own page on this computer's own
17
+ * address (claudeRefusal): a page another site serves can't start it, by a rebound DNS name either.
18
+ */
19
+ import { spawn } from "node:child_process";
20
+ import { randomUUID } from "node:crypto";
21
+ import { promises as fs, realpathSync } from "node:fs";
22
+ import path from "node:path";
23
+ import { createInterface } from "node:readline";
24
+
25
+ /** Claude Code's tools a run may use without asking: there is no one to ask in `-p`. */
26
+ export const TOOLS = ["Read", "Edit", "MultiEdit", "Write", "Glob", "Grep", "Bash", "Skill", "TodoWrite"];
27
+
28
+ const SYSTEM = [
29
+ "You are working from Blockout's editor, which runs in this project's dev page. Each message is what the person changed or commented on there, for you to make in the code.",
30
+ "Make each change in the project's source, the way the project writes things: its tokens, classes and components, not inline styles. When an element is a shared component, say whether your change reaches every use of it or only this one.",
31
+ "The dev server reloads the page as you save, so there is no need to start it.",
32
+ "Before each step, say what you are about to do in one short sentence. End with one or two lines on what you changed.",
33
+ ].join(" ");
34
+
35
+ /** A run that goes quiet for this long is stopped. */
36
+ const RUN_LIMIT_MS = 15 * 60 * 1000;
37
+ const MAX_CHATS = 50;
38
+ const MAX_MESSAGES = 200;
39
+ /** How much of the chat goes ahead of a message when its session can't be resumed. */
40
+ const MEMORY = 10;
41
+
42
+ const str = (v, max) => (typeof v === "string" ? v.slice(0, max) : "");
43
+
44
+ // Kept on globalThis: a dev server reloads its route modules as files change (Claude's own edits among them), and a
45
+ // run must outlive that.
46
+ const shared = (globalThis.__blockoutEditorClaude ??= { stores: new Map(), runs: new Map() });
47
+
48
+ /** The chats of the project in `dir`'s parent folder, read once and kept in memory, written on each change. */
49
+ export function createChats({ dir = path.join(process.cwd(), ".notes"), cwd = path.dirname(dir), bin = process.env.BLOCKOUT_CLAUDE || "claude" } = {}) {
50
+ const file = path.join(dir, "blockout-chats.json");
51
+ const known = shared.stores.get(file);
52
+ if (known) return known;
53
+ let all = null;
54
+ let writing = Promise.resolve();
55
+ const load = async () => {
56
+ if (all) return all;
57
+ try {
58
+ const read = JSON.parse(await fs.readFile(file, "utf8"));
59
+ all = Array.isArray(read?.chats) ? read : { chats: [] };
60
+ } catch {
61
+ all = { chats: [] };
62
+ }
63
+ // A run the server lost (it restarted) is over.
64
+ for (const chat of all.chats) for (const m of chat.messages) if (m.status === "running" && !shared.runs.has(chat.id)) Object.assign(m, { status: "failed", error: "The dev server restarted during this run." });
65
+ return all;
66
+ };
67
+ // One write at a time, each whole: written aside, then moved into place.
68
+ const save = () => {
69
+ writing = writing.then(async () => {
70
+ await fs.mkdir(dir, { recursive: true });
71
+ const tmp = `${file}.${process.pid}.tmp`;
72
+ await fs.writeFile(tmp, `${JSON.stringify(all, null, 2)}\n`);
73
+ await fs.rename(tmp, file);
74
+ }).catch(() => {});
75
+ return writing;
76
+ };
77
+ // Its real path: Claude Code names files by it (on a Mac, /var is /private/var).
78
+ let real = cwd;
79
+ try {
80
+ real = realpathSync(cwd);
81
+ } catch {}
82
+ const store = { file, cwd: real, bin, load, save, running: (id) => shared.runs.has(id) };
83
+ shared.stores.set(file, store);
84
+ return store;
85
+ }
86
+
87
+ /** Each chat in a line, newest first, for the chat list. */
88
+ export async function listChats(store) {
89
+ const { chats } = await store.load();
90
+ return [...chats]
91
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
92
+ .map((c) => ({ id: c.id, title: c.title, updatedAt: c.updatedAt, messages: c.messages.length, running: store.running(c.id) }));
93
+ }
94
+
95
+ export async function getChat(store, id) {
96
+ const { chats } = await store.load();
97
+ return chats.find((c) => c.id === id) ?? null;
98
+ }
99
+
100
+ /**
101
+ * Sends a message: `prompt` is what Claude gets (the change request the panel wrote), `shown` what the chat shows of
102
+ * it. A new chat without `chatId`. One run at a time in a project: Claude edits the same files.
103
+ */
104
+ export async function sendMessage(store, { chatId, prompt, shown }) {
105
+ const all = await store.load();
106
+ const text = str(prompt, 60000).trim();
107
+ if (!text) return { status: 400, body: { error: "Nothing to send." } };
108
+ if (shared.runs.size) return { status: 409, body: { error: "Claude is still on the last message. Wait for it, or stop it." } };
109
+ let chat = chatId ? all.chats.find((c) => c.id === chatId) : null;
110
+ if (chatId && !chat) return { status: 404, body: { error: "There's no chat with that id." } };
111
+ const now = new Date().toISOString();
112
+ const you = {
113
+ id: randomUUID(),
114
+ at: now,
115
+ from: "you",
116
+ text: str(shown?.text, 4000).trim(),
117
+ comments: (Array.isArray(shown?.comments) ? shown.comments.slice(0, 50) : []).map((c, i) => ({
118
+ n: Number.isInteger(c?.n) ? c.n : i + 1,
119
+ label: str(c?.label, 200),
120
+ text: str(c?.text, 2000),
121
+ })),
122
+ changed: Number.isInteger(shown?.changed) ? shown.changed : 0,
123
+ };
124
+ if (!chat) {
125
+ chat = { id: randomUUID(), title: titleOf(you), createdAt: now, updatedAt: now, sessionId: null, messages: [] };
126
+ all.chats.push(chat);
127
+ all.chats.sort((a, b) => a.updatedAt.localeCompare(b.updatedAt));
128
+ while (all.chats.length > MAX_CHATS) all.chats.shift();
129
+ }
130
+ const reply = { id: randomUUID(), at: now, from: "claude", status: "running", steps: [], said: "", reply: "", error: "" };
131
+ const history = memoryOf(chat);
132
+ chat.messages.push(you, reply);
133
+ chat.messages.splice(0, Math.max(0, chat.messages.length - MAX_MESSAGES));
134
+ chat.updatedAt = now;
135
+ await store.save();
136
+ run(store, chat, reply, text, history);
137
+ return { status: 201, body: { chat } };
138
+ }
139
+
140
+ /** Stops the chat's run, if one is out. */
141
+ export async function stopRun(store, chatId) {
142
+ const live = shared.runs.get(chatId);
143
+ if (!live) return { status: 404, body: { error: "Nothing is running in that chat." } };
144
+ live.stopped = true;
145
+ live.child.kill("SIGTERM");
146
+ return { status: 200, body: {} };
147
+ }
148
+
149
+ function titleOf(you) {
150
+ const words = you.text || you.comments[0]?.text || (you.changed ? `${you.changed} design ${you.changed === 1 ? "change" : "changes"}` : "Design changes");
151
+ const line = words.replace(/\s+/g, " ").trim();
152
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line;
153
+ }
154
+
155
+ /** The chat so far, for a run whose session can't be resumed. */
156
+ function memoryOf(chat) {
157
+ const lines = [];
158
+ for (const m of chat.messages.slice(-MEMORY * 2)) {
159
+ if (m.from === "you") lines.push(`The person: ${m.text || "(design changes and comments)"}${m.comments?.length ? ` [${m.comments.length} comments]` : ""}`);
160
+ else if (m.reply || m.said) lines.push(`You: ${(m.reply || m.said).slice(0, 1500)}`);
161
+ }
162
+ return lines.length ? `This chat so far, for context (your earlier session isn't available):\n${lines.join("\n")}\n\nNow:\n` : "";
163
+ }
164
+
165
+ /** Claude Code's arguments for a run. */
166
+ export function argsFor(resume) {
167
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits", "--allowedTools", TOOLS.join(","), "--append-system-prompt", SYSTEM];
168
+ return resume ? [...args, "--resume", resume] : args;
169
+ }
170
+
171
+ function run(store, chat, msg, prompt, history, resume = chat.sessionId) {
172
+ const live = { child: null, stopped: false, sawInit: false };
173
+ shared.runs.set(chat.id, live);
174
+ let ended = false;
175
+ let saveTimer = null;
176
+ const saveSoon = () => {
177
+ saveTimer ??= setTimeout(() => {
178
+ saveTimer = null;
179
+ void store.save();
180
+ }, 2000);
181
+ };
182
+ const child = spawn(store.bin, argsFor(resume), { cwd: store.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
183
+ live.child = child;
184
+ let quiet = setTimeout(() => child.kill("SIGTERM"), RUN_LIMIT_MS);
185
+ let stderr = "";
186
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
187
+ const finish = (fields) => {
188
+ if (ended) return;
189
+ ended = true;
190
+ clearTimeout(quiet);
191
+ clearTimeout(saveTimer);
192
+ shared.runs.delete(chat.id);
193
+ for (const s of msg.steps) if (!s.done) s.done = Date.now();
194
+ Object.assign(msg, fields, { endedAt: new Date().toISOString() });
195
+ chat.updatedAt = msg.endedAt;
196
+ void store.save();
197
+ };
198
+ child.on("error", (err) =>
199
+ finish({
200
+ status: "failed",
201
+ error: err.code === "ENOENT" ? "Claude Code isn't on this dev server's PATH. Start the dev server from a terminal where `claude` works." : String(err.message),
202
+ code: err.code === "ENOENT" ? "no-claude" : undefined,
203
+ }),
204
+ );
205
+ child.stdin.on("error", () => {});
206
+ child.stdin.end(resume ? prompt : history + prompt);
207
+ createInterface({ input: child.stdout }).on("line", (line) => {
208
+ clearTimeout(quiet);
209
+ quiet = setTimeout(() => child.kill("SIGTERM"), RUN_LIMIT_MS);
210
+ let event;
211
+ try {
212
+ event = JSON.parse(line);
213
+ } catch {
214
+ return;
215
+ }
216
+ if (event.type === "system" && event.subtype === "init") {
217
+ live.sawInit = true;
218
+ if (event.session_id) chat.sessionId = event.session_id;
219
+ }
220
+ if (read(event, msg, store.cwd)) saveSoon();
221
+ });
222
+ child.on("close", (code) => {
223
+ if (ended) return;
224
+ // The session wasn't there (another computer, or Claude Code cleared it): once more, fresh, with the chat so far.
225
+ if (resume && !live.sawInit && !live.stopped) {
226
+ clearTimeout(quiet);
227
+ shared.runs.delete(chat.id);
228
+ chat.sessionId = null;
229
+ ended = true;
230
+ return run(store, chat, msg, prompt, history, null);
231
+ }
232
+ if (live.stopped) return finish({ status: "stopped" });
233
+ if (msg.status === "running") finish(code === 0 ? { status: "done" } : { status: "failed", error: msg.error || stderr.trim().split("\n").pop() || `Claude Code stopped (${code}).` });
234
+ else finish({});
235
+ });
236
+ }
237
+
238
+ /** Puts one line of Claude Code's stream into the message; true when it changed something. */
239
+ export function read(event, msg, cwd) {
240
+ if (event.type === "assistant") {
241
+ let changed = false;
242
+ for (const block of event.message?.content ?? []) {
243
+ if (block.type === "text" && block.text?.trim()) {
244
+ msg.said = block.text.trim().slice(0, 4000);
245
+ changed = true;
246
+ }
247
+ if (block.type === "tool_use") {
248
+ msg.steps.push({ id: block.id, at: Date.now(), ...stepOf(block.name, block.input ?? {}, cwd) });
249
+ msg.steps.splice(0, Math.max(0, msg.steps.length - 200));
250
+ changed = true;
251
+ }
252
+ }
253
+ return changed;
254
+ }
255
+ if (event.type === "user") {
256
+ let changed = false;
257
+ for (const block of event.message?.content ?? []) {
258
+ if (block.type !== "tool_result") continue;
259
+ const step = msg.steps.find((s) => s.id === block.tool_use_id);
260
+ if (!step) continue;
261
+ step.done = Date.now();
262
+ if (block.is_error) step.failed = str(typeof block.content === "string" ? block.content : block.content?.[0]?.text, 200) || "It didn't work.";
263
+ changed = true;
264
+ }
265
+ return changed;
266
+ }
267
+ if (event.type === "result") {
268
+ msg.reply = str(event.result, 8000).trim();
269
+ if (event.is_error) Object.assign(msg, { status: "failed", error: msg.reply || "Claude Code stopped with an error." });
270
+ else msg.status = "done";
271
+ return true;
272
+ }
273
+ return false;
274
+ }
275
+
276
+ /** A tool call as the chat says it. */
277
+ export function stepOf(name, input, cwd) {
278
+ const file = (p) => (typeof p === "string" ? path.relative(cwd, p) || p : "a file");
279
+ const quote = (s) => `“${str(s, 60)}”`;
280
+ switch (name) {
281
+ case "Read":
282
+ return { kind: "read", text: `Read ${file(input.file_path)}` };
283
+ case "Edit":
284
+ case "MultiEdit":
285
+ return { kind: "edit", text: `Edited ${file(input.file_path)}` };
286
+ case "Write":
287
+ return { kind: "edit", text: `Wrote ${file(input.file_path)}` };
288
+ case "Grep":
289
+ return { kind: "find", text: `Searched for ${quote(input.pattern)}` };
290
+ case "Glob":
291
+ return { kind: "find", text: `Looked for ${str(input.pattern, 80)}` };
292
+ case "Bash":
293
+ return { kind: "run", text: str(input.description, 100) || `Ran ${str(input.command, 80)}` };
294
+ case "Skill":
295
+ return { kind: "skill", text: `Used the ${str(input.skill || input.command || input.name, 60) || "a"} skill` };
296
+ case "TodoWrite":
297
+ return { kind: "plan", text: "Planned the steps" };
298
+ default:
299
+ return { kind: "tool", text: `Used ${str(name, 60)}` };
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Claude may start only from the app's own page on this computer's own address. The notes route's own check
305
+ * (same-origin) passes a rebound DNS name, whose page and route share the attacker's host: this one also wants the
306
+ * host to be this computer. Returns why not, or null.
307
+ */
308
+ export function claudeRefusal(get) {
309
+ const host = get("host") || "";
310
+ let name = "";
311
+ try {
312
+ name = new URL(`http://${host}`).hostname;
313
+ } catch {
314
+ name = "";
315
+ }
316
+ const local = name === "localhost" || name === "127.0.0.1" || name === "[::1]" || name.endsWith(".localhost");
317
+ if (!local) return "Claude runs only from the dev page on this computer's own address (localhost or 127.0.0.1).";
318
+ if (get("sec-fetch-site") !== "same-origin") return "Only this app's own pages can talk to Claude.";
319
+ return null;
320
+ }
321
+
322
+ /** One request to the route's Claude ops (`?claude=`): answers { status, body }. */
323
+ export async function handleClaude(store, method, url, body) {
324
+ const params = new URL(url, "http://localhost").searchParams;
325
+ const op = params.get("claude");
326
+ if (method === "GET" && op === "chats") return { status: 200, body: { chats: await listChats(store) } };
327
+ if (method === "GET" && op === "chat") {
328
+ const chat = await getChat(store, params.get("id") || "");
329
+ return chat ? { status: 200, body: { chat, running: store.running(chat.id) } } : { status: 404, body: { error: "There's no chat with that id." } };
330
+ }
331
+ if (method === "POST" && op === "send") return sendMessage(store, { chatId: str(body?.chatId, 100) || null, prompt: body?.prompt, shown: body?.shown });
332
+ if (method === "POST" && op === "stop") return stopRun(store, str(body?.chatId, 100));
333
+ return { status: 400, body: { error: "Ask for chats, chat, send or stop." } };
334
+ }
package/server/cli.js ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // blockout-editor mcp [--dir path/to/.notes]: the notes' MCP server (mcp.js), over stdio.
3
+ import { readFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { runMcp } from "./mcp.js";
6
+
7
+ const args = process.argv.slice(2);
8
+ if (args[0] === "mcp") {
9
+ const at = args.indexOf("--dir");
10
+ const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
11
+ await runMcp({ version, ...(at !== -1 && args[at + 1] ? { dir: path.resolve(args[at + 1]) } : {}) });
12
+ } else {
13
+ process.stdout.write("Usage: blockout-editor mcp [--dir path/to/.notes]\n An MCP server for the notes Blockout's editor saves in this app.\n");
14
+ process.exit(args.length ? 1 : 0);
15
+ }
package/server/mcp.js ADDED
@@ -0,0 +1,97 @@
1
+ /*
2
+ * An MCP server over stdio for the notes Blockout's editor saves (store.js), so Claude Code (or any MCP client) can
3
+ * read them, answer each and mark it resolved without being told where the file is:
4
+ * claude mcp add blockout-editor -- npx blockout-editor mcp
5
+ * Run from the app's folder, or pass --dir to point at its .notes.
6
+ */
7
+ import { createInterface } from "node:readline";
8
+ import { createStore } from "./store.js";
9
+
10
+ /** A note as Claude Code reads it: what to change, where, and what was changed on the page. */
11
+ export function noteText(n) {
12
+ const lines = [`Note ${n.id} (${n.status}) on ${n.page || "the page"}${n.width ? `, window ${n.width}px wide` : ""}`];
13
+ if (n.text) lines.push(` Asks: ${n.text}`);
14
+ if (n.element) {
15
+ lines.push(` About: ${n.element.label}${n.element.text ? ` ("${n.element.text}")` : ""}`);
16
+ if (n.element.components?.length) lines.push(` in: ${n.element.components.join(" < ")}`);
17
+ if (n.element.path) lines.push(` at: ${n.element.path}`);
18
+ }
19
+ if (n.changes?.length) {
20
+ lines.push(" Changed on the page (make these in the code, with the project's own tokens and classes):");
21
+ for (const c of n.changes) {
22
+ lines.push(` ${c.label}${c.components?.length ? ` in ${c.components.join(" < ")}` : ""}${c.path ? ` at ${c.path}` : ""}`);
23
+ for (const p of c.props) lines.push(` ${p.prop}: ${p.from ?? "(not set)"} → ${p.to ?? "(removed)"}`);
24
+ if (c.text) lines.push(` text: "${c.text.from}" → "${c.text.to}"`);
25
+ if (c.removed) lines.push(" deleted from the page");
26
+ }
27
+ }
28
+ for (const r of n.replies ?? []) lines.push(` Reply: ${r.text}`);
29
+ return lines.join("\n");
30
+ }
31
+
32
+ const TOOLS = [
33
+ {
34
+ name: "list_notes",
35
+ description:
36
+ "The notes left with Blockout's editor on this app's pages: what to change, on which element (its CSS path and React components), and the style, text and layer changes made live on the page, to write into the code with the project's own tokens and classes (not inline styles), keeping the app consistent: when the element shares a component, class or pattern with others, decide whether the change is for all of them or this one, and say which.",
37
+ inputSchema: { type: "object", properties: { status: { type: "string", enum: ["open", "resolved", "all"], description: "Default open." } } },
38
+ },
39
+ {
40
+ name: "reply_to_note",
41
+ description: "Answers a note, in one line: what was done, or why not.",
42
+ inputSchema: { type: "object", properties: { id: { type: "string" }, text: { type: "string" } }, required: ["id", "text"] },
43
+ },
44
+ {
45
+ name: "resolve_note",
46
+ description: "Marks a note done, with a one-line reply saying what changed.",
47
+ inputSchema: { type: "object", properties: { id: { type: "string" }, reply: { type: "string" } }, required: ["id"] },
48
+ },
49
+ ];
50
+
51
+ export async function runMcp({ dir, version = "0.0.0", input = process.stdin, output = process.stdout } = {}) {
52
+ const store = createStore(dir ? { dir } : undefined);
53
+ const write = (msg) => output.write(`${JSON.stringify(msg)}\n`);
54
+ const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...(isError ? { isError: true } : {}) });
55
+ const call = async (name, args) => {
56
+ if (name === "list_notes") {
57
+ const notes = await store.list(args.status || "open");
58
+ return text(notes.length ? notes.map(noteText).join("\n\n") : `No ${args.status === "all" ? "" : `${args.status || "open"} `}notes.`);
59
+ }
60
+ if (name === "reply_to_note") {
61
+ const note = await store.update(String(args.id ?? ""), { reply: String(args.text ?? "") });
62
+ return note ? text(`Replied to ${note.id}.`) : text("There's no note with that id.", true);
63
+ }
64
+ if (name === "resolve_note") {
65
+ const note = await store.update(String(args.id ?? ""), { status: "resolved", reply: typeof args.reply === "string" ? args.reply : undefined });
66
+ return note ? text(`Resolved ${note.id}.`) : text("There's no note with that id.", true);
67
+ }
68
+ return text(`There's no tool called ${name}.`, true);
69
+ };
70
+ for await (const line of createInterface({ input })) {
71
+ if (!line.trim()) continue;
72
+ let msg;
73
+ try {
74
+ msg = JSON.parse(line);
75
+ } catch {
76
+ write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } });
77
+ continue;
78
+ }
79
+ // Notifications (initialized, cancelled) want no answer.
80
+ if (msg.id === undefined || msg.id === null) continue;
81
+ try {
82
+ let result;
83
+ if (msg.method === "initialize")
84
+ result = { protocolVersion: msg.params?.protocolVersion || "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "blockout-editor", version } };
85
+ else if (msg.method === "ping") result = {};
86
+ else if (msg.method === "tools/list") result = { tools: TOOLS };
87
+ else if (msg.method === "tools/call") result = await call(msg.params?.name, msg.params?.arguments || {});
88
+ else {
89
+ write({ jsonrpc: "2.0", id: msg.id, error: { code: -32601, message: `No method ${msg.method}` } });
90
+ continue;
91
+ }
92
+ write({ jsonrpc: "2.0", id: msg.id, result });
93
+ } catch (err) {
94
+ write({ jsonrpc: "2.0", id: msg.id, error: { code: -32603, message: String(err?.message || err) } });
95
+ }
96
+ }
97
+ }
@@ -0,0 +1,5 @@
1
+ type Handler = (request: Request) => Promise<Response>;
2
+ export const GET: Handler;
3
+ export const POST: Handler;
4
+ export const PATCH: Handler;
5
+ export const DELETE: Handler;
package/server/next.js ADDED
@@ -0,0 +1,32 @@
1
+ /*
2
+ * The notes route for a Next.js app (App Router). Add app/api/blockout-notes/route.js with:
3
+ * export { GET, POST, PATCH, DELETE } from "blockout-editor/next";
4
+ * It works on the dev server only: in production every method answers 404. With ?claude= it is the editor's Claude
5
+ * chat (claude.js).
6
+ */
7
+ import { claudeRefusal, createChats, handleClaude } from "./claude.js";
8
+ import { createStore, handle, refusal } from "./store.js";
9
+
10
+ const store = createStore();
11
+ const chats = createChats();
12
+
13
+ async function respond(request) {
14
+ if (process.env.NODE_ENV !== "development") return Response.json({ error: "Blockout's editor notes only work on the dev server." }, { status: 404 });
15
+ const no = refusal((name) => request.headers.get(name));
16
+ if (no) return Response.json({ error: no }, { status: 403 });
17
+ if (Number(request.headers.get("content-length") || 0) > 1 << 20) return Response.json({ error: "That's too much for one note." }, { status: 413 });
18
+ const body = request.method === "GET" || request.method === "DELETE" ? null : await request.json().catch(() => null);
19
+ if (new URL(request.url).searchParams.has("claude")) {
20
+ const not = claudeRefusal((name) => request.headers.get(name));
21
+ if (not) return Response.json({ error: not }, { status: 403 });
22
+ const { status, body: out } = await handleClaude(chats, request.method, request.url, body);
23
+ return Response.json(out, { status });
24
+ }
25
+ const { status, body: out } = await handle(store, request.method, request.url, body);
26
+ return Response.json(out, { status });
27
+ }
28
+
29
+ export const GET = respond;
30
+ export const POST = respond;
31
+ export const PATCH = respond;
32
+ export const DELETE = respond;