repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(super): add browser mockup tool

76f745dd8951a2e1cc277b5a56660e23db0d34bb

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (17)

CHANGELOG.md

Modified
54 54 tasks as success `✓`, idle widgets as warning, and errors as error
55 55 - Block unresolved `__LEAK_*__` placeholders in mutating tool calls outside the
56 56 leaks extension
57 +- Add the super `mockup` tool for browser-based visual-option feedback with a
58 + minimal title/question/options/multi schema, fragment-only validation, blocking
59 + browser submit, selectable cards, annotations/global notes tabs, Accept/Iterate
60 + actions, and per-card pin notes
61 +- Update brainstorming to delegate visual feedback to `mockup` and retire the
62 + brainstorming visual companion scripts
58 64 ## 0.0.3

extensions/super/README.md

Modified
21 21 - `push-task` stores a focused task prompt for isolated execution.
22 22 - `prompt`: task prompt to store.
23 23 - `inherit_context`: marks the task as inheriting context.
24 +- `mockup` opens HTML-fragment mockup options in a browser and blocks until browser feedback returns.
25 + - `title`: browser page title.
26 + - `question`: visual question for the human.
27 + - `options`: one to four `{ id, label, description?, html }` fragments.
28 + - `multi`: allow multiple selected options.
25 30 Hooks:
46 51 when there is no task work left.
47 52 If `/auto` starts with no pending tasks, it notifies that there is nothing to
48 53 run.
54 +`mockup` serves content from memory on `127.0.0.1` and stores no project files.
55 +It rejects full HTML documents in `options[].html` with an agent-facing fix message.
56 +It returns `action`, `selected`, `notes`, and `annotations`.
49 57 It also ships the `skills/super` skill set through the root package resources.

extensions/super/__tests__/mockup.test.ts

Added
new file mode 100644
1 +import assert from "node:assert";
2 +import { describe, it } from "vitest";
3 +import {
4 + MOCKUP_FULL_DOCUMENT_ERROR,
5 + type MockupRequest,
6 + renderMockupPage,
7 + startMockupServer,
8 + validateMockupRequest,
9 +} from "../mockup.ts";
11 +const baseRequest: MockupRequest = {
12 + title: "Pick layout",
13 + question: "Which option works?",
14 + options: [
15 + {
16 + id: "a",
17 + label: "A",
18 + description: "First direction",
19 + html: "<section><h3>A</h3><script>window.allowed = true;</script></section>",
20 + },
21 + ],
22 +};
24 +describe("mockup validation", () => {
25 + it("rejects full HTML documents with an agent-facing fix", () => {
26 + for (const html of [
27 + "<!doctype html><html></html>",
28 + "<!-- built elsewhere --><html><body>full</body></html>",
29 + ]) {
30 + assert.throws(
31 + () =>
32 + validateMockupRequest({
33 + ...baseRequest,
34 + options: [{ id: "full", label: "Full", html }],
35 + }),
36 + (error) => {
37 + assert.ok(error instanceof Error);
38 + assert.strictEqual(
39 + error.message,
40 + MOCKUP_FULL_DOCUMENT_ERROR("options[0].html"),
41 + );
42 + return true;
43 + },
44 + );
45 + }
46 + });
48 + it("allows scripts and styles inside HTML fragments", () => {
49 + const request = validateMockupRequest({
50 + ...baseRequest,
51 + options: [
52 + {
53 + ...baseRequest.options[0],
54 + html: '<section><style>.x::before{content:"<html"}</style><script>const tag = "<body";</script></section>',
55 + },
56 + ],
57 + });
58 + assert.match(
59 + request.options[0].html,
60 + /<style>\.x::before\{content:"<html"\}<\/style>/,
61 + );
62 + assert.match(
63 + request.options[0].html,
64 + /<script>const tag = "<body";<\/script>/,
65 + );
66 + });
68 + it("rejects parameters outside the minimal public schema", () => {
69 + assert.throws(
70 + () => validateMockupRequest({ ...baseRequest, timeout_ms: 1000 }),
71 + /timeout_ms is not a supported mockup parameter/,
72 + );
73 + });
74 +});
76 +describe("mockup page", () => {
77 + it("renders fragments inside selectable cards with checkbox controls", () => {
78 + const html = renderMockupPage(baseRequest, "tok");
79 + assert.match(html, /type="checkbox"/);
80 + assert.match(html, /data-option-id="a"/);
81 + assert.match(
82 + html,
83 + /<section><h3>A<\/h3><script>window\.allowed = true;<\/script><\/section>/,
84 + );
85 + assert.match(html, /Pin note/);
86 + assert.match(html, /pin-bubble/);
87 + assert.match(html, /Delete pin/);
88 + });
90 + it("keeps accept and iterate actions in the feedback drawer header", () => {
91 + const html = renderMockupPage(baseRequest, "tok");
92 + const topbar = html.slice(
93 + html.indexOf('<header class="topbar">'),
94 + html.indexOf('<main class="stage"'),
95 + );
96 + const drawerHead = html.slice(
97 + html.indexOf('<div class="drawer-head">'),
98 + html.indexOf('<div id="annotations-panel"'),
99 + );
100 + assert.doesNotMatch(topbar, /id="iterate"|id="accept"/);
101 + assert.match(drawerHead, /id="iterate"/);
102 + assert.match(drawerHead, /id="accept"/);
103 + assert.match(html, /\.drawer-head \{[^}]*grid-row:1/);
104 + assert.match(html, /\.panel \{[^}]*grid-row:2/);
105 + assert.match(html, /#global-notes \{[^}]*height:100%/);
106 + });
107 +});
109 +describe("mockup server", () => {
110 + it("rejects multiple submitted selections unless multi is enabled", async () => {
111 + const server = await startMockupServer(
113 + ...baseRequest,
114 + options: [
115 + ...baseRequest.options,
116 + { id: "b", label: "B", html: "<section>B</section>" },
117 + ],
118 + },
119 + { openBrowser: false },
120 + );
121 + try {
122 + const res = await fetch(new URL("/api/submit", server.url), {
123 + method: "POST",
124 + headers: {
125 + Authorization: `Bearer ${server.token}`,
126 + "Content-Type": "application/json",
127 + },
128 + body: JSON.stringify({
129 + action: "accept",
130 + selected: ["a", "b"],
131 + notes: "",
132 + annotations: [],
133 + }),
134 + });
135 + assert.strictEqual(res.status, 400);
136 + assert.match(await res.text(), /selected must contain at most one item/);
137 + } finally {
138 + server.result.catch(() => undefined);
139 + server.close("test");
141 + });
143 + it("blocks until browser submits action, selection, notes, and annotations", async () => {
144 + const server = await startMockupServer(baseRequest, { openBrowser: false });
145 + try {
146 + assert.match(server.url, /[?&]k=/);
147 + assert.doesNotMatch(server.url, /token=|key=/);
148 + const posted = fetch(new URL("/api/submit", server.url), {
149 + method: "POST",
150 + headers: {
151 + Authorization: `Bearer ${server.token}`,
152 + "Content-Type": "application/json",
153 + },
154 + body: JSON.stringify({
155 + action: "iterate",
156 + selected: ["a"],
157 + notes: "keep A, denser drawer",
158 + annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
159 + }),
160 + });
161 + const res = await posted;
162 + assert.strictEqual(await res.text(), '{"ok":true}');
163 + const result = await server.result;
164 + assert.deepStrictEqual(result, {
165 + action: "iterate",
166 + selected: ["a"],
167 + notes: "keep A, denser drawer",
168 + annotations: [{ optionId: "a", x: 0.25, y: 0.5, note: "tighten" }],
169 + });
170 + } finally {
171 + server.result.catch(() => undefined);
172 + server.close("test");
174 + });
175 +});

extensions/super/__tests__/super.test.ts

Modified
1075 1075 // ── Registration ─────────────────────────────────────────────────
1077 1077 describe("registration", () => {
1078 - it("registers the push-task tool and all five task commands", () => {
1078 + it("registers the push-task tool, mockup tool, and all five task commands", () => {
1079 1079 const registered: Array<{
1080 1080 type: string;
1081 1081 name: string;
1111 1111 description:
1112 1112 "Store a task prompt for a user-started navigation branch.",
1115 + type: "tool",
1116 + name: "mockup",
1117 + description:
1118 + "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.",
1119 + },
1115 1121 type: "command",
1116 1122 name: "start-task",

extensions/super/index.ts

Modified
13 13 import { Box, Text } from "@earendil-works/pi-tui";
15 15 import { Type } from "typebox";
16 +import { createMockupTool } from "./mockup.js";
17 18 export default function registerTaskCommands(pi: ExtensionAPI): void {
18 19 pi.registerTool(createPushTaskTool(pi));
20 + pi.registerTool(createMockupTool());
19 21 pi.registerCommand("start-task", createStartTaskCommand(pi));
20 22 pi.registerCommand("discard-task", createDiscardTaskCommand(pi));
21 23 pi.registerCommand("finish-task", createFinishTaskCommand(pi));

extensions/super/mockup.ts

Added
new file mode 100644
1 +import { spawn } from "node:child_process";
2 +import { randomUUID } from "node:crypto";
3 +import {
4 + createServer,
5 + type IncomingMessage,
6 + type Server,
7 + type ServerResponse,
8 +} from "node:http";
9 +import {
10 + defineTool,
11 + keyHint,
12 + type ToolDefinition,
13 +} from "@earendil-works/pi-coding-agent";
14 +import { Text } from "@earendil-works/pi-tui";
15 +import { Type } from "typebox";
17 +export type MockupOption = {
18 + id: string;
19 + label: string;
20 + description?: string;
21 + html: string;
22 +};
24 +export type MockupRequest = {
25 + title: string;
26 + question: string;
27 + options: MockupOption[];
28 + multi?: boolean;
29 +};
31 +export type MockupResult = {
32 + action: "accept" | "iterate";
33 + selected: string[];
34 + notes: string;
35 + annotations: Array<{ optionId: string; x: number; y: number; note: string }>;
36 +};
38 +export type MockupServer = {
39 + id: string;
40 + url: string;
41 + token: string;
42 + result: Promise<MockupResult>;
43 + close(reason: string): void;
44 +};
46 +const COOKIE = "pi_mockup_session";
47 +const BODY_LIMIT = 1_000_000;
48 +const DEFAULT_TIMEOUT_MS = 3_600_000;
49 +const ID_RE = /^[a-zA-Z0-9._-]+$/;
51 +export const MOCKUP_DESCRIPTION =
52 + "Show HTML-fragment mockup options in a browser and return selected options, notes, annotations, and accept/iterate action.";
54 +export function MOCKUP_FULL_DOCUMENT_ERROR(path: string): string {
55 + return `${path} must be an HTML fragment, not a full document. Remove <!doctype>, <html>, <head>, <body>; keep only content for the card.`;
58 +export function createMockupTool(): ToolDefinition {
59 + return defineTool({
60 + name: "mockup",
61 + label: "Mockup",
62 + description: MOCKUP_DESCRIPTION,
63 + promptSnippet: MOCKUP_DESCRIPTION,
64 + promptGuidelines: [
65 + "Use mockup for visual UI/layout/style choices when seeing options beats reading descriptions.",
66 + "Pass only HTML fragments in options[].html; never pass <!doctype>, <html>, <head>, or <body>.",
67 + "Create 1-4 options. One option is valid for review of a single screen.",
68 + "The tool owns browser communication, selection, notes, annotations, Accept, and Iterate. Do not ask the user to repeat browser feedback in chat.",
69 + "After an iterate result, revise the fragments and call mockup again. After accept, continue the design unless notes require another iteration.",
70 + ],
71 + parameters: mockupParameters,
72 + renderCall(args, theme, context) {
73 + const title = theme.fg("toolTitle", theme.bold("mockup"));
74 + const optionCount = Array.isArray(args.options) ? args.options.length : 0;
75 + const lines = [
76 + title,
77 + theme.fg(
78 + "dim",
79 + `${args.title ?? "untitled"} · ${optionCount} option${optionCount === 1 ? "" : "s"}`,
80 + ),
81 + ];
82 + if (context.expanded && Array.isArray(args.options)) {
83 + for (const option of args.options) {
84 + if (option && typeof option === "object" && "id" in option) {
85 + lines.push(theme.fg("muted", `- ${String(option.id)}`));
86 + }
87 + }
88 + } else {
89 + lines.push(theme.fg("muted", keyHint("app.tools.expand", "to expand")));
90 + }
91 + return new Text(lines.join("\n"), 0, 0);
92 + },
93 + renderResult(result, theme, context) {
94 + const details = result.details as Partial<MockupResult> | undefined;
95 + if (!details) return new Text("", 0, 0);
96 + const summary = `${details.action ?? "submitted"} · ${(details.selected ?? []).join(", ") || "none"} · ${(details.annotations ?? []).length} annotation${(details.annotations ?? []).length === 1 ? "" : "s"}`;
97 + if (!context.expanded) return new Text(theme.fg("dim", summary), 0, 0);
98 + return new Text(
99 + [
100 + theme.fg("dim", summary),
101 + details.notes ? `notes: ${details.notes}` : "notes: ",
102 + ].join("\n"),
103 + 0,
104 + );
105 + },
106 + async execute(_toolCallId, params, signal, _onUpdate, ctx) {
107 + const request = validateMockupRequest(params);
108 + const server = await startMockupServer(request, {
109 + openBrowser: process.env.PI_MOCKUP_NO_OPEN !== "1",
110 + });
111 + if (ctx.hasUI) {
112 + ctx.ui.notify(`Mockup open: ${server.url}`, "info");
114 + try {
115 + const result = await abortable(server.result, signal, () =>
116 + server.close("aborted"),
117 + );
118 + return {
119 + content: [
121 + type: "text" as const,
122 + text: JSON.stringify(result),
123 + },
124 + ],
125 + details: result,
126 + };
127 + } finally {
128 + server.close("done");
130 + },
131 + });
134 +export function validateMockupRequest(value: unknown): MockupRequest {
135 + if (!isRecord(value)) throw new Error("mockup args must be an object");
136 + assertKnownKeys(value, new Set(["title", "question", "options", "multi"]));
137 + const title = requiredString(value.title, "title").trim();
138 + const question = requiredString(value.question, "question").trim();
139 + if (!title) throw new Error("title must not be empty");
140 + if (!question) throw new Error("question must not be empty");
141 + if (!Array.isArray(value.options))
142 + throw new Error("options must be an array");
143 + if (value.options.length < 1)
144 + throw new Error("options must contain at least one item");
145 + if (value.options.length > 4)
146 + throw new Error(
147 + "options must contain at most four items; split large comparisons into multiple mockup calls.",
148 + );
149 + const ids = new Set<string>();
150 + const options = value.options.map((raw, index) => {
151 + if (!isRecord(raw)) throw new Error(`options[${index}] must be an object`);
152 + const id = requiredString(raw.id, `options[${index}].id`).trim();
153 + if (!ID_RE.test(id))
154 + throw new Error(
155 + `options[${index}].id must contain only letters, numbers, dot, underscore, or dash`,
156 + );
157 + if (ids.has(id))
158 + throw new Error(`options[${index}].id duplicates a previous option id`);
159 + ids.add(id);
160 + const label = requiredString(raw.label, `options[${index}].label`).trim();
161 + if (!label) throw new Error(`options[${index}].label must not be empty`);
162 + const html = requiredString(raw.html, `options[${index}].html`);
163 + if (isFullDocument(html))
164 + throw new Error(MOCKUP_FULL_DOCUMENT_ERROR(`options[${index}].html`));
165 + const description = optionalString(
166 + raw.description,
167 + `options[${index}].description`,
168 + )?.trim();
169 + return { id, label, html, ...(description && { description }) };
170 + });
171 + return {
172 + title,
173 + question,
174 + options,
175 + multi: value.multi === true,
176 + };
179 +export async function startMockupServer(
180 + request: MockupRequest,
181 + options: { openBrowser?: boolean } = {},
182 +): Promise<MockupServer> {
183 + const normalized = validateMockupRequest(request);
184 + const browserKey = `${randomUUID()}-${randomUUID()}`;
185 + const id = randomUUID();
186 + let server!: Server;
187 + let finished = false;
188 + let timeout: NodeJS.Timeout | undefined;
189 + let resolveResult!: (result: MockupResult) => void;
190 + let rejectResult!: (error: Error) => void;
191 + const result = new Promise<MockupResult>((resolve, reject) => {
192 + resolveResult = resolve;
193 + rejectResult = reject;
194 + });
196 + const finish = (result: MockupResult) => {
197 + if (finished) return;
198 + finished = true;
199 + if (timeout) clearTimeout(timeout);
200 + server.close();
201 + resolveResult(result);
202 + };
203 + const fail = (error: Error) => {
204 + if (finished) return;
205 + finished = true;
206 + if (timeout) clearTimeout(timeout);
207 + server.close();
208 + rejectResult(error);
209 + };
211 + server = createServer(
212 + (req, res) =>
213 + void dispatch(req, res, {
214 + request: normalized,
215 + ["token"]: browserKey,
216 + finish,
217 + }),
218 + );
219 + await listen(server);
220 + const address = server.address();
221 + if (!address || typeof address === "string")
222 + throw new Error("Failed to bind mockup server");
223 + const url = `http://127.0.0.1:${address.port}/?k=${browserKey}`;
224 + timeout = setTimeout(
225 + () => fail(new Error("mockup timed out waiting for browser Submit")),
226 + DEFAULT_TIMEOUT_MS,
227 + );
228 + timeout.unref();
229 + if (options.openBrowser) void openBrowser(url);
230 + return {
231 + id,
232 + url,
233 + ["token"]: browserKey,
234 + result,
235 + close(reason: string) {
236 + if (finished) return;
237 + finished = true;
238 + if (timeout) clearTimeout(timeout);
239 + server.close();
240 + rejectResult(new Error(`mockup closed: ${reason}`));
241 + },
242 + };
245 +export function renderMockupPage(
246 + request: MockupRequest,
247 + browserKey: string,
248 +): string {
249 + const options = request.options
250 + .map((option) => renderOption(option))
251 + .join("\n");
252 + return `<!doctype html>
253 +<html lang="en">
254 +<head>
255 +<meta charset="utf-8">
256 +<meta name="viewport" content="width=device-width, initial-scale=1">
257 +<title>${esc(request.title)}</title>
258 +<style>${FRAME_CSS}</style>
259 +</head>
260 +<body data-multi="${request.multi ? "true" : "false"}">
261 +<header class="topbar">
262 + <div>
263 + <div class="eyebrow">Pi mockup ${request.multi ? "· multi-select" : ""}</div>
264 + <h1>${esc(request.title)}</h1>
265 + <p>${esc(request.question)}</p>
266 + </div>
267 +</header>
268 +<main class="stage" id="options">${options}</main>
269 +<section class="drawer" aria-label="Feedback drawer">
270 + <div class="drawer-head">
271 + <div class="tabs" role="tablist">
272 + <button class="tab active" type="button" data-tab="annotations">Annotations <span id="annotation-count">0</span></button>
273 + <button class="tab" type="button" data-tab="global">Global notes</button>
274 + </div>
275 + <div id="selection-summary" class="selection-summary">No option selected</div>
276 + <div class="drawer-actions">
277 + <button id="iterate" type="button" class="secondary">Iterate</button>
278 + <button id="accept" type="button">Accept</button>
279 + </div>
280 + </div>
281 + <div id="annotations-panel" class="panel active"></div>
282 + <div id="global-panel" class="panel"><textarea id="global-notes" placeholder="what you like · what sucks · what to change"></textarea></div>
283 +</section>
284 +<script>window.__MOCKUP_TOKEN__ = ${JSON.stringify(browserKey)};</script>
285 +<script>${CLIENT_JS}</script>
286 +</body>
287 +</html>`;
290 +function renderOption(option: MockupOption): string {
291 + return `<article class="option-card" data-option-id="${esc(option.id)}">
292 +<header class="option-head">
293 + <label><input type="checkbox" data-select-option="${esc(option.id)}"> <strong>${esc(option.label)}</strong></label>
294 + <button type="button" class="pin-toggle" data-pin-option="${esc(option.id)}" hidden>Pin note</button>
295 +</header>
296 +${option.description ? `<p class="option-description">${esc(option.description)}</p>` : ""}
297 +<div class="fragment" data-fragment="${esc(option.id)}">${option.html}</div>
298 +</article>`;
301 +type Ctx = {
302 + request: MockupRequest;
303 + token: string;
304 + finish(result: MockupResult): void;
307 +async function dispatch(req: IncomingMessage, res: ServerResponse, ctx: Ctx) {
308 + try {
309 + const url = new URL(req.url ?? "/", "http://127.0.0.1");
310 + if (req.method === "GET" && url.pathname === "/") {
311 + if (url.searchParams.get("k") !== ctx.token)
312 + return json(res, 401, { error: "unauthorized" });
313 + res.setHeader(
314 + "Set-Cookie",
315 + `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`,
316 + );
317 + return html(res, 200, renderMockupPage(ctx.request, ctx.token));
319 + if (!authorized(req, ctx.token))
320 + return json(res, 401, { error: "unauthorized" });
321 + if (req.method === "POST" && url.pathname === "/api/submit") {
322 + const result = parseResult(JSON.parse(await readBody(req)), ctx.request);
323 + json(res, 200, { ok: true });
324 + ctx.finish(result);
325 + return;
327 + json(res, 404, { error: "not found" });
328 + } catch (error) {
329 + json(res, 400, {
330 + error: error instanceof Error ? error.message : String(error),
331 + });
335 +function parseResult(value: unknown, request: MockupRequest): MockupResult {
336 + if (!isRecord(value)) throw new Error("submit body must be an object");
337 + const action = enumString(
338 + value.action,
339 + new Set(["accept", "iterate"]),
340 + "action",
341 + );
342 + if (!Array.isArray(value.selected))
343 + throw new Error("selected must be an array");
344 + const optionIds = new Set(request.options.map((o) => o.id));
345 + const selected = value.selected.map((v, i) => {
346 + const id = requiredString(v, `selected[${i}]`);
347 + if (!optionIds.has(id))
348 + throw new Error(`selected[${i}] must match an option id`);
349 + return id;
350 + });
351 + if (!request.multi && selected.length > 1)
352 + throw new Error(
353 + "selected must contain at most one item unless multi is true",
354 + );
355 + const notes = optionalString(value.notes, "notes")?.trim() ?? "";
356 + if (!Array.isArray(value.annotations))
357 + throw new Error("annotations must be an array");
358 + const annotations = value.annotations.map((raw, index) =>
359 + parseAnnotation(raw, index, optionIds),
360 + );
361 + return { action, selected, notes, annotations };
364 +function parseAnnotation(
365 + value: unknown,
366 + index: number,
367 + optionIds: Set<string>,
368 +): MockupResult["annotations"][number] {
369 + if (!isRecord(value))
370 + throw new Error(`annotations[${index}] must be an object`);
371 + const optionId = requiredString(
372 + value.optionId,
373 + `annotations[${index}].optionId`,
374 + );
375 + if (!optionIds.has(optionId))
376 + throw new Error(`annotations[${index}].optionId must match an option id`);
377 + const x = unitNumber(value.x, `annotations[${index}].x`);
378 + const y = unitNumber(value.y, `annotations[${index}].y`);
379 + const note = requiredString(value.note, `annotations[${index}].note`).trim();
380 + if (!note) throw new Error(`annotations[${index}].note must not be empty`);
381 + return { optionId, x, y, note };
384 +function isFullDocument(html: string): boolean {
385 + const stripped = html.replaceAll(
386 + /<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi,
387 + "",
388 + );
389 + return /<!doctype\b|<\s*\/?\s*(html|head|body)\b/i.test(stripped);
392 +function authorized(req: IncomingMessage, browserKey: string): boolean {
393 + return (
394 + req.headers.authorization === `Bearer ${browserKey}` ||
395 + (req.headers.cookie ?? "")
396 + .split(/;\s*/)
397 + .some((cookie) => cookie === `${COOKIE}=${browserKey}`)
398 + );
401 +async function readBody(req: IncomingMessage): Promise<string> {
402 + let body = "";
403 + for await (const chunk of req) {
404 + body += String(chunk);
405 + if (Buffer.byteLength(body, "utf8") > BODY_LIMIT)
406 + throw new Error("request body too large");
408 + return body;
411 +function html(res: ServerResponse, status: number, body: string): void {
412 + res.statusCode = status;
413 + res.setHeader("Content-Type", "text/html; charset=utf-8");
414 + res.setHeader("Cache-Control", "no-store");
415 + res.end(body);
418 +function json(res: ServerResponse, status: number, body: unknown): void {
419 + res.statusCode = status;
420 + res.setHeader("Content-Type", "application/json; charset=utf-8");
421 + res.end(JSON.stringify(body));
424 +function listen(server: Server): Promise<void> {
425 + return new Promise((resolve, reject) => {
426 + server.once("error", reject);
427 + server.listen(0, "127.0.0.1", () => {
428 + server.off("error", reject);
429 + resolve();
430 + });
431 + });
434 +async function openBrowser(url: string): Promise<void> {
435 + if (process.env.NODE_ENV === "test" || process.env.VITEST) return;
436 + const candidates = openerCandidates(url);
437 + for (const candidate of candidates) {
438 + if (await trySpawn(candidate.command, candidate.args)) return;
442 +function openerCandidates(
443 + url: string,
444 +): Array<{ command: string; args: string[] }> {
445 + if (process.env.TERMUX_VERSION)
446 + return [{ command: "termux-open-url", args: [url] }];
447 + if (process.platform === "darwin") return [{ command: "open", args: [url] }];
448 + if (process.platform === "win32")
449 + return [{ command: "cmd.exe", args: ["/c", "start", "", url] }];
450 + return [
451 + { command: "xdg-open", args: [url] },
452 + { command: "wslview", args: [url] },
453 + { command: "gio", args: ["open", url] },
454 + ];
457 +function trySpawn(command: string, args: string[]): Promise<boolean> {
458 + return new Promise((resolve) => {
459 + const child = spawn(command, args, { detached: true, stdio: "ignore" });
460 + let settled = false;
461 + const done = (ok: boolean) => {
462 + if (settled) return;
463 + settled = true;
464 + resolve(ok);
465 + };
466 + child.once("error", () => done(false));
467 + child.once("spawn", () => {
468 + child.unref();
469 + done(true);
470 + });
471 + setTimeout(() => done(false), 1500).unref();
472 + });
475 +function abortable<T>(
476 + promise: Promise<T>,
477 + signal: AbortSignal | undefined,
478 + abort: () => void,
479 +): Promise<T> {
480 + if (!signal) return promise;
481 + if (signal.aborted) {
482 + abort();
483 + return Promise.reject(new Error("mockup aborted"));
485 + return new Promise((resolve, reject) => {
486 + const onAbort = () => {
487 + abort();
488 + reject(new Error("mockup aborted"));
489 + };
490 + signal.addEventListener("abort", onAbort, { once: true });
491 + promise
492 + .then(resolve, reject)
493 + .finally(() => signal.removeEventListener("abort", onAbort));
494 + });
497 +function requiredString(value: unknown, name: string): string {
498 + if (typeof value !== "string") throw new Error(`${name} must be a string`);
499 + return value;
502 +function optionalString(value: unknown, name: string): string | undefined {
503 + if (value === undefined) return undefined;
504 + return requiredString(value, name);
507 +function unitNumber(value: unknown, name: string): number {
508 + if (
509 + typeof value !== "number" ||
510 + !Number.isFinite(value) ||
511 + value < 0 ||
512 + value > 1
514 + throw new Error(`${name} must be a number between 0 and 1`);
515 + return value;
518 +function enumString<T extends string>(
519 + value: unknown,
520 + choices: ReadonlySet<T>,
521 + name: string,
522 +): T {
523 + if (typeof value === "string" && choices.has(value as T)) return value as T;
524 + throw new Error(`invalid ${name}`);
527 +function isRecord(value: unknown): value is Record<string, unknown> {
528 + return !!value && typeof value === "object" && !Array.isArray(value);
531 +function assertKnownKeys(
532 + value: Record<string, unknown>,
533 + allowed: ReadonlySet<string>,
534 +): void {
535 + for (const key of Object.keys(value)) {
536 + if (!allowed.has(key))
537 + throw new Error(`${key} is not a supported mockup parameter`);
541 +function esc(value: string): string {
542 + return value
543 + .replaceAll("&", "&amp;")
544 + .replaceAll("<", "&lt;")
545 + .replaceAll(">", "&gt;")
546 + .replaceAll('"', "&quot;")
547 + .replaceAll("'", "&#39;");
550 +const mockupParameters = Type.Object({
551 + title: Type.String({
552 + description: "Short browser page title for this visual decision.",
553 + }),
554 + question: Type.String({
555 + description: "The exact visual question the human should answer.",
556 + }),
557 + options: Type.Array(
558 + Type.Object({
559 + id: Type.String({
560 + description:
561 + "Stable option id. Letters, numbers, dot, underscore, dash only.",
562 + }),
563 + label: Type.String({ description: "Human-visible option label." }),
564 + description: Type.Optional(
565 + Type.String({
566 + description: "One short sentence explaining the option.",
567 + }),
568 + ),
569 + html: Type.String({
570 + description:
571 + "HTML fragment for this mockup option. Do not include <!doctype>, <html>, <head>, or <body>. Scripts are allowed.",
572 + }),
573 + }),
575 + minItems: 1,
576 + maxItems: 4,
577 + description:
578 + "One to four mockup options. One option is valid for reviewing a single screen.",
579 + },
580 + ),
581 + multi: Type.Optional(
582 + Type.Boolean({
583 + default: false,
584 + description: "Allow selecting multiple options.",
585 + }),
586 + ),
587 +});
589 +const FRAME_CSS = String.raw`
590 +:root { color-scheme: dark light; --bg:#101010; --panel:#181818; --text:#ededed; --muted:#9a9a9a; --line:#ededed; --soft:#2a2a2a; --accent:#d86dd8; --bad:#ff6b6b; font:14px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace; }
591 +@media (prefers-color-scheme: light) { :root { --bg:#f4f0f4; --panel:#fff; --text:#151515; --muted:#666; --line:#151515; --soft:#e4dfe4; --accent:#a900a9; } }
592 +* { box-sizing:border-box; }
593 +body { margin:0; min-height:100vh; display:grid; grid-template-rows:auto 1fr minmax(170px, 30vh); background:var(--bg); color:var(--text); }
594 +button,input,textarea { font:inherit; }
595 +button { border:2px solid var(--line); background:var(--text); color:var(--bg); padding:.55rem .8rem; font-weight:900; cursor:pointer; }
596 +button.secondary { background:var(--panel); color:var(--text); }
597 +button:focus-visible,input:focus-visible,textarea:focus-visible { outline:3px solid var(--accent); outline-offset:2px; }
598 +.topbar { border-bottom:2px solid var(--line); background:var(--panel); padding:1rem; }
599 +h1 { margin:0; font-size:1.15rem; text-transform:uppercase; letter-spacing:.04em; }
600 +p { margin:.25rem 0 0; color:var(--muted); }
601 +.eyebrow { color:var(--accent); font-weight:900; text-transform:uppercase; font-size:.72rem; }
602 +.drawer-actions { display:flex; gap:.6rem; }
603 +.stage { padding:1rem; display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:1rem; overflow:auto; }
604 +.option-card { border:2px solid var(--line); background:var(--panel); display:grid; grid-template-rows:auto auto 1fr; min-height:280px; position:relative; }
605 +.option-card.selected { border-color:var(--accent); box-shadow:6px 6px 0 color-mix(in srgb, var(--accent), transparent 55%); }
606 +.option-head { border-bottom:2px solid var(--line); padding:.7rem; display:flex; justify-content:space-between; gap:.7rem; align-items:center; }
607 +.option-head label { display:flex; align-items:center; gap:.55rem; cursor:pointer; }
608 +.option-head input { width:1.1rem; height:1.1rem; accent-color:var(--accent); }
609 +.pin-toggle[aria-pressed="true"] { background:var(--accent); color:white; border-color:var(--accent); }
610 +.option-description { padding:0 .7rem .7rem; margin:.55rem 0 0; }
611 +.fragment { min-height:180px; padding:1rem; position:relative; overflow:auto; }
612 +.pin { position:absolute; width:24px; height:24px; border:2px solid var(--accent); background:var(--bg); color:var(--accent); border-radius:50%; display:grid; place-items:center; font-weight:900; transform:translate(-50%,-50%); z-index:5; }
613 +.pin-bubble { position:absolute; z-index:8; width:min(320px, calc(100% - 1rem)); border:2px solid var(--accent); background:var(--panel); padding:.6rem; display:grid; gap:.45rem; box-shadow:5px 5px 0 color-mix(in srgb, var(--accent), transparent 45%); }
614 +.pin-bubble textarea { width:100%; min-height:4rem; border:1px solid var(--line); background:var(--bg); color:var(--text); padding:.4rem; }
615 +.pin-bubble .bubble-actions { display:flex; gap:.45rem; justify-content:flex-end; }
616 +.drawer { border-top:2px solid var(--line); background:var(--panel); padding:.75rem; display:grid; grid-template-rows:auto minmax(0, 1fr); gap:.6rem; min-height:0; }
617 +.drawer-head { grid-row:1; display:flex; align-items:center; justify-content:space-between; gap:1rem; position:relative; z-index:2; }
618 +.tabs { display:flex; gap:.45rem; }
619 +.tab { background:var(--panel); color:var(--text); padding:.4rem .65rem; }
620 +.tab.active { background:var(--text); color:var(--bg); }
621 +.selection-summary { color:var(--muted); }
622 +.panel { grid-row:2; display:none; min-height:0; overflow:auto; position:relative; z-index:1; }
623 +.panel.active { display:block; }
624 +#global-notes { width:100%; height:100%; min-height:0; resize:none; border:2px solid var(--line); background:var(--bg); color:var(--text); padding:.7rem; }
625 +.annotation-row { display:grid; grid-template-columns:max-content 1fr max-content; gap:.6rem; align-items:center; border:1px solid var(--soft); padding:.45rem; margin-bottom:.45rem; }
626 +.annotation-row textarea { width:100%; min-height:2.5rem; border:1px solid var(--line); background:var(--bg); color:var(--text); padding:.35rem; }
627 +.empty { color:var(--muted); padding:.7rem; border:1px dashed var(--soft); }
630 +const CLIENT_JS = String.raw`
631 +const multi = document.body.dataset.multi === "true";
632 +const selected = new Set();
633 +const annotations = [];
634 +let armed = null;
635 +const $ = (s, r = document) => r.querySelector(s);
636 +const $$ = (s, r = document) => [...r.querySelectorAll(s)];
637 +function sync() {
638 + closeBubble();
639 + $$(".option-card").forEach(card => {
640 + const id = card.dataset.optionId;
641 + const is = selected.has(id);
642 + card.classList.toggle("selected", is);
643 + $("input", card).checked = is;
644 + const pin = $(".pin-toggle", card);
645 + pin.hidden = !is;
646 + pin.setAttribute("aria-pressed", String(armed === id));
647 + });
648 + $("#selection-summary").textContent = selected.size ? "Selected: " + [...selected].join(", ") : "No option selected";
649 + $("#annotation-count").textContent = String(annotations.length);
650 + renderAnnotations();
652 +function select(id) {
653 + if (!multi) selected.clear();
654 + if (multi && selected.has(id)) selected.delete(id); else selected.add(id);
655 + if (!selected.has(armed)) armed = null;
656 + sync();
658 +function addPin(id, event) {
659 + const frag = event.currentTarget;
660 + const rect = frag.getBoundingClientRect();
661 + const pin = { optionId:id, x:(event.clientX - rect.left) / rect.width, y:(event.clientY - rect.top) / rect.height, note:"" };
662 + annotations.push(pin);
663 + sync();
664 + showBubble(annotations.indexOf(pin));
666 +function closeBubble() {
667 + const bubble = $(".pin-bubble");
668 + if (bubble) bubble.remove();
670 +function showBubble(index) {
671 + closeBubble();
672 + const a = annotations[index];
673 + if (!a) return;
674 + const frag = $("[data-fragment=\"" + CSS.escape(a.optionId) + "\"]");
675 + if (!frag) return;
676 + const bubble = document.createElement("div");
677 + bubble.className = "pin-bubble";
678 + bubble.style.left = Math.min(82, Math.max(2, a.x * 100)) + "%";
679 + bubble.style.top = Math.min(82, Math.max(2, a.y * 100)) + "%";
680 + bubble.innerHTML = '<textarea aria-label="Pin note" placeholder="note for this spot"></textarea><div class="bubble-actions"><button type="button" class="secondary" data-close>Close</button><button type="button" data-delete>Delete pin</button></div>';
681 + const text = $("textarea", bubble);
682 + text.value = a.note;
683 + text.addEventListener("input", () => { a.note = text.value; renderAnnotations(false); });
684 + $("[data-close]", bubble).addEventListener("click", closeBubble);
685 + $("[data-delete]", bubble).addEventListener("click", () => { annotations.splice(index, 1); sync(); });
686 + frag.append(bubble);
687 + text.focus();
689 +function renderPins() {
690 + $$(".pin").forEach(p => p.remove());
691 + annotations.forEach((a, i) => {
692 + const frag = $("[data-fragment=\"" + CSS.escape(a.optionId) + "\"]");
693 + if (!frag) return;
694 + const button = document.createElement("button");
695 + button.type = "button";
696 + button.className = "pin";
697 + button.textContent = String(i + 1);
698 + button.style.left = (a.x * 100) + "%";
699 + button.style.top = (a.y * 100) + "%";
700 + button.addEventListener("click", e => {
701 + e.stopPropagation();
702 + showBubble(i);
703 + });
704 + frag.append(button);
705 + });
707 +function renderAnnotations(redrawPins = true) {
708 + if (redrawPins) renderPins();
709 + const panel = $("#annotations-panel");
710 + panel.replaceChildren();
711 + if (!annotations.length) {
712 + const empty = document.createElement("div");
713 + empty.className = "empty";
714 + empty.textContent = "No annotations. Select an option, press Pin note, then click inside its mockup.";
715 + panel.append(empty);
716 + return;
718 + annotations.forEach((a, i) => {
719 + const row = document.createElement("div");
720 + row.className = "annotation-row";
721 + row.innerHTML = "<strong>" + (i + 1) + " · " + a.optionId + "</strong><textarea></textarea><button type=\"button\" class=\"secondary\">Delete</button>";
722 + const text = $("textarea", row);
723 + text.value = a.note;
724 + text.addEventListener("input", () => { a.note = text.value; });
725 + $("button", row).addEventListener("click", () => { annotations.splice(i, 1); sync(); });
726 + panel.append(row);
727 + });
729 +$$(".option-card").forEach(card => {
730 + const id = card.dataset.optionId;
731 + $("input", card).addEventListener("click", e => { e.stopPropagation(); select(id); });
732 + $(".option-head", card).addEventListener("click", e => { if (e.target.tagName !== "BUTTON") select(id); });
733 + $(".pin-toggle", card).addEventListener("click", e => { e.stopPropagation(); armed = armed === id ? null : id; sync(); });
734 + $(".fragment", card).addEventListener("click", e => { if (armed === id) addPin(id, e); else select(id); });
735 +});
736 +$$(".tab").forEach(tab => tab.addEventListener("click", () => {
737 + $$(".tab").forEach(t => t.classList.toggle("active", t === tab));
738 + $$(".panel").forEach(p => p.classList.remove("active"));
739 + $("#" + tab.dataset.tab + "-panel").classList.add("active");
740 +}));
741 +async function submit(action) {
742 + const res = await fetch("/api/submit", { method:"POST", headers:{ Authorization:"Bearer " + window.__MOCKUP_TOKEN__, "Content-Type":"application/json" }, body:JSON.stringify({ action, selected:[...selected], notes:$("#global-notes").value.trim(), annotations:annotations.filter(a => a.note.trim()) }) });
743 + if (!res.ok) alert(await res.text()); else document.body.innerHTML = '<main style="padding:2rem"><h1>Sent to Pi</h1><p>You can close this tab.</p></main>';
745 +$("#accept").addEventListener("click", () => submit("accept"));
746 +$("#iterate").addEventListener("click", () => submit("iterate"));
747 +sync();

package.json

Modified
11 11 "lint": "biome ci . && ruff format --check . && ruff check . && markdownlint-cli2",
12 12 "test": "vitest run",
13 13 "test:watch": "vitest",
14 - "test:brainstorming": "node --test skills/super/brainstorming/scripts/companion.test.mjs",
15 14 "typecheck": "tsc --noEmit"
17 16 "devDependencies": {

skills/super/brainstorming/SKILL.md

Modified
166 166 - **Browser required** if options involve UI nouns that can be shown: editor, terminal, drawer, panel, rail, tab, toolbar, omnibox, composer, command palette, transcript, file view, diff view, action card, chip, sidebar, navigation, layout, placement, density, style.
167 167 - **Terminal allowed** only for abstract intent/scope/success metrics or non-visual implementation boundaries.
169 -Do not ask terminal A/B/C text for visual placement/control questions. Create a rough mockup and use `ask-screen` / `ask-choice` instead. Rough and immediate beats perfect and delayed.
169 +Do not ask terminal A/B/C text for visual placement/control questions. Create a rough mockup and use `mockup` instead. Rough and immediate beats perfect and delayed.
171 171 If the user says "show me", "visual", "mockup", "let me see it", or similar while discussing UI, immediately produce a browser mockup for the current question. Do not respond by asking another terminal question.
173 173 A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is conceptual — use the terminal. "Should the inspector live as a right rail, middle split, or overlay?" is visual placement — use the browser. "Composer model: unified input vs stacked inputs vs palette" is visual/control presentation — use the browser.
175 -If they agree to the companion, read the sibling guide in this skill directory before proceeding:
176 -`skills/super/brainstorming/visual-companion.md`
175 +If they agree to the companion, use the `mockup` tool for visual questions.
178 -For the first browser visual choice, prefer `open-choice` or `open-screen` so the browser opens and the agent waits for the click in the same tool call. If auto-open is unavailable, use `start-choice` or `start-screen` so the first browser load has real content. Never start an empty companion and promise "next question there".
177 +The `mockup` tool is the only browser bridge.
178 +It owns browser opening, selection, notes, annotations, Accept, Iterate, and returning browser feedback to the agent.
179 +Do not run companion scripts, write browser state files, ask the user to repeat clicks in chat, or manage browser communication manually.
181 +Use `mockup` with one to four `options`.
182 +One option is valid for reviewing a single screen.
183 +Each option supplies an HTML fragment only:
185 +```json
187 + "title": "Layout direction",
188 + "question": "Which layout feels right?",
189 + "options": [
191 + "id": "right-rail",
192 + "label": "Right rail",
193 + "description": "Inspector stays beside the work.",
194 + "html": "<div class=\"mockup\">...</div>"
198 +```
200 +Never pass a full HTML document.
201 +Do not include `<!doctype>`, `<html>`, `<head>`, or `<body>` in `options[].html`.
202 +Scripts inside fragments are allowed.
204 +Read the tool result as the user's browser feedback:
206 +```json
208 + "action": "iterate",
209 + "selected": ["right-rail"],
210 + "notes": "keep this, make the drawer denser",
211 + "annotations": [
212 + { "optionId": "right-rail", "x": 0.4, "y": 0.2, "note": "too loud" }
215 +```
217 +If `action` is `iterate`, revise the fragments and call `mockup` again.
218 +If `action` is `accept`, continue the brainstorming flow unless notes or annotations clearly require another visual iteration.

skills/super/brainstorming/scripts/companion.mjs

Deleted
deleted file mode 100755
1 -#!/usr/bin/env node
2 -import { spawn } from "node:child_process";
3 -import fs from "node:fs";
4 -import os from "node:os";
5 -import path from "node:path";
6 -import { pathToFileURL } from "node:url";
7 -import { startServer } from "./start-server.mjs";
8 -import { stop } from "./stop-server.mjs";
10 -const registryFile = path.join(
11 - os.homedir(),
12 - ".local",
13 - "state",
14 - "pi",
15 - "brainstorm-companion",
16 - "servers.jsonl",
17 -);
19 -const helpText = `Usage: companion.mjs <command> [args]
21 -Commands:
22 - start-choice --project-dir DIR --name NAME --title TITLE --option choice|title|description
23 - start-screen --project-dir DIR --name NAME (--html HTML | --html-file FILE)
24 - open-choice --project-dir DIR --name NAME --title TITLE --option choice|title|description [--timeout-ms MS<=3600000]
25 - open-screen --project-dir DIR --name NAME (--html HTML | --html-file FILE) [--timeout-ms MS<=3600000]
26 - stop SESSION_DIR
27 - cleanup
28 - write-screen SESSION_DIR --name NAME (--html HTML | --html-file FILE)
29 - choice-screen SESSION_DIR --name NAME --title TITLE [--subtitle TEXT] --option choice|title|description [--multi]
30 - ask-choice SESSION_DIR --name NAME --title TITLE [--subtitle TEXT] --option choice|title|description [--timeout-ms MS<=3600000]
31 - ask-screen SESSION_DIR --name NAME (--html HTML | --html-file FILE) [--timeout-ms MS<=3600000]
32 - waiting-screen SESSION_DIR --name NAME
33 - events SESSION_DIR [--clear]
34 - listen --project-dir DIR [--clear] [--timeout-ms MS<=3600000]
35 - wait-choice SESSION_DIR [--timeout-ms MS<=3600000]
36 -`;
38 -function die(message) {
39 - console.log(JSON.stringify({ error: message }));
40 - process.exit(1);
43 -function help() {
44 - console.log(helpText);
47 -function parseFlags(argv) {
48 - const flags = { _: [] };
49 - for (let i = 0; i < argv.length; i++) {
50 - const arg = argv[i];
51 - if (!arg.startsWith("--")) flags._.push(arg);
52 - else if (arg === "--clear" || arg === "--multi") flags[arg.slice(2)] = true;
53 - else {
54 - const key = arg.slice(2);
55 - const value = argv[++i];
56 - if (value === undefined) die(`Missing value for ${arg}`);
57 - if (flags[key] === undefined) flags[key] = value;
58 - else if (Array.isArray(flags[key])) flags[key].push(value);
59 - else flags[key] = [flags[key], value];
60 - }
61 - }
62 - return flags;
65 -function sessionPaths(sessionDir) {
66 - if (!sessionDir) die("Missing session_dir");
67 - const contentDir = path.join(sessionDir, "content");
68 - const stateDir = path.join(sessionDir, "state");
69 - return {
70 - sessionDir,
71 - contentDir,
72 - stateDir,
73 - eventsFile: path.join(stateDir, "events"),
74 - };
77 -function latestSession(projectDir) {
78 - if (!projectDir) die("Missing --project-dir");
79 - const root = path.join(projectDir, ".super", "brainstorm");
80 - if (!fs.existsSync(root)) die("No brainstorm sessions found");
81 - const sessions = fs
82 - .readdirSync(root, { withFileTypes: true })
83 - .filter((entry) => entry.isDirectory())
84 - .map((entry) => path.join(root, entry.name))
85 - .filter((sessionDir) =>
86 - fs.existsSync(path.join(sessionDir, "state", "server-info")),
87 - )
88 - .map((sessionDir) => ({
89 - sessionDir,
90 - mtime: fs.statSync(path.join(sessionDir, "state", "server-info")).mtimeMs,
91 - }))
92 - .sort((a, b) => b.mtime - a.mtime);
93 - if (sessions.length === 0) die("No running brainstorm session found");
94 - return sessions[0].sessionDir;
97 -function requireAlive(paths) {
98 - if (!fs.existsSync(path.join(paths.stateDir, "server-info")))
99 - die("Brainstorm server is not running; start it first.");
102 -function screenName(name) {
103 - const base = name || `screen-${Date.now()}`;
104 - if (!/^[a-zA-Z0-9._-]+$/.test(base))
105 - die(
106 - "Screen name must contain only letters, numbers, dot, underscore, or dash.",
107 - );
108 - return base.endsWith(".html") ? base.slice(0, -5) : base;
111 -function uniqueScreenPath(contentDir, name) {
112 - const base = screenName(name);
113 - let candidate = path.join(contentDir, `${base}.html`);
114 - for (let i = 2; fs.existsSync(candidate); i++)
115 - candidate = path.join(contentDir, `${base}-${i}.html`);
116 - return candidate;
119 -function escapeHtml(value) {
120 - return String(value)
121 - .replaceAll("&", "&amp;")
122 - .replaceAll("<", "&lt;")
123 - .replaceAll(">", "&gt;")
124 - .replaceAll('"', "&quot;")
125 - .replaceAll("'", "&#39;");
128 -function parseOption(value) {
129 - const [choice, title, description = ""] = String(value).split("|");
130 - if (!choice || !title)
131 - die(`Invalid --option ${value}; expected choice|title|description`);
132 - return { choice, title, description };
135 -function htmlFromFlags(flags) {
136 - if (flags.html !== undefined) return flags.html;
137 - if (flags["html-file"] !== undefined)
138 - return fs.readFileSync(flags["html-file"], "utf8");
139 - die("Missing --html or --html-file");
142 -function timeoutMs(flags) {
143 - const value = Number(flags["timeout-ms"] ?? 600_000);
144 - if (!Number.isFinite(value) || value <= 0)
145 - die("--timeout-ms must be a positive number");
146 - if (value > 3_600_000) die("--timeout-ms max is 3600000ms");
147 - return value;
150 -function renderChoiceScreen({ title, subtitle = "", options, multi = false }) {
151 - if (!title) die("Missing --title");
152 - if (options.length === 0) die("At least one --option is required");
153 - const attrs = multi ? " data-multiselect" : "";
154 - const body = options
155 - .map((option, index) => {
156 - const letter = String.fromCharCode(65 + index);
157 - const id = `option-${escapeHtml(option.choice)}`;
158 - return ` <div id="${id}" class="option" data-choice="${escapeHtml(option.choice)}" onclick="toggleSelect(this)">\n <div class="letter">${letter}</div>\n <div class="content">\n <h3>${escapeHtml(option.title)}</h3>\n <p>${escapeHtml(option.description)}</p>\n </div>\n </div>`;
159 - })
160 - .join("\n");
162 - return `<h2>${escapeHtml(title)}</h2>\n${subtitle ? `<p class="subtitle">${escapeHtml(subtitle)}</p>\n` : ""}\n<div class="options"${attrs}>\n${body}\n</div>\n`;
165 -function writeScreen(sessionDir, name, html, { quiet = false } = {}) {
166 - const paths = sessionPaths(sessionDir);
167 - requireAlive(paths);
168 - fs.mkdirSync(paths.contentDir, { recursive: true });
169 - fs.rmSync(paths.eventsFile, { force: true });
170 - const file = uniqueScreenPath(paths.contentDir, name);
171 - fs.writeFileSync(file, html);
172 - const result = { status: "screen-written", file };
173 - if (!quiet) console.log(JSON.stringify(result));
174 - return result;
177 -function readEvents(eventsFile) {
178 - if (!fs.existsSync(eventsFile)) return [];
179 - return fs
180 - .readFileSync(eventsFile, "utf8")
181 - .split("\n")
182 - .filter(Boolean)
183 - .map((line) => JSON.parse(line));
186 -function sleep(ms) {
187 - return new Promise((resolve) => setTimeout(resolve, ms));
190 -function isAlive(pid) {
191 - try {
192 - process.kill(pid, 0);
193 - return true;
194 - } catch {
195 - return false;
196 - }
199 -function registryEntries() {
200 - if (!fs.existsSync(registryFile)) return [];
201 - return fs
202 - .readFileSync(registryFile, "utf8")
203 - .split("\n")
204 - .filter(Boolean)
205 - .map((line) => JSON.parse(line));
208 -function writeRegistry(entries) {
209 - fs.mkdirSync(path.dirname(registryFile), { recursive: true });
210 - fs.writeFileSync(
211 - registryFile,
212 - entries.map((entry) => JSON.stringify(entry)).join("\n") +
213 - (entries.length ? "\n" : ""),
214 - );
217 -async function cleanup() {
218 - const kept = [];
219 - const stopped = [];
221 - for (const entry of registryEntries()) {
222 - if (!isAlive(entry.pid)) continue;
223 - if (entry.owner_pid && isAlive(entry.owner_pid)) {
224 - kept.push(entry);
225 - continue;
226 - }
228 - await stop(entry.session_dir);
229 - stopped.push({
230 - session_dir: entry.session_dir,
231 - pid: entry.pid,
232 - reason: "owner_dead",
233 - });
234 - }
236 - writeRegistry(kept);
237 - console.log(JSON.stringify({ stopped, kept }));
240 -async function waitChoiceEvent(sessionDir, timeoutMs) {
241 - const { eventsFile } = sessionPaths(sessionDir);
242 - const deadline = Date.now() + timeoutMs;
243 - while (Date.now() <= deadline) {
244 - const choices = readEvents(eventsFile).filter((event) => event.choice);
245 - if (choices.length > 0) return choices.at(-1);
246 - await sleep(50);
247 - }
248 - die(`Timed out waiting for choice after ${timeoutMs}ms`);
251 -async function listen(projectDir, { clear = false, timeoutMs = 0 } = {}) {
252 - const sessionDir = latestSession(projectDir);
253 - const { eventsFile } = sessionPaths(sessionDir);
254 - const deadline = Date.now() + timeoutMs;
255 - let events = readEvents(eventsFile);
256 - while (events.length === 0 && Date.now() <= deadline) {
257 - await sleep(50);
258 - events = readEvents(eventsFile);
259 - }
260 - if (clear) fs.rmSync(eventsFile, { force: true });
261 - console.log(JSON.stringify({ session_dir: sessionDir, events }));
264 -async function waitChoice(sessionDir, timeoutMs) {
265 - console.log(JSON.stringify(await waitChoiceEvent(sessionDir, timeoutMs)));
268 -function openUrl(url) {
269 - if (process.env.BRAINSTORM_NO_OPEN === "1") return;
270 - const command =
271 - process.env.BRAINSTORM_OPEN_CMD ||
272 - (process.platform === "darwin" ? "open" : "xdg-open");
273 - try {
274 - const child = spawn(command, [url], { detached: true, stdio: "ignore" });
275 - child.unref();
276 - } catch {
277 - // Opening is best-effort. URL remains available in returned JSON for fallback.
278 - }
281 -function splitStartArgs(args) {
282 - const startArgs = [];
283 - const screenArgs = [];
284 - const startFlags = new Set([
285 - "--project-dir",
286 - "--host",
287 - "--url-host",
288 - "--owner-pid",
289 - "--no-browser-timeout-ms",
290 - ]);
291 - for (let i = 0; i < args.length; i++) {
292 - const arg = args[i];
293 - if (startFlags.has(arg)) {
294 - startArgs.push(arg, args[++i] ?? die(`Missing value for ${arg}`));
295 - } else {
296 - screenArgs.push(arg);
297 - }
298 - }
299 - return { startArgs, screenArgs };
302 -async function startWithScreen(args, renderHtml, { wait = false } = {}) {
303 - const { startArgs, screenArgs } = splitStartArgs(args);
304 - const info = await startServer(startArgs);
305 - const sessionDir = path.dirname(info.screen_dir);
306 - const flags = parseFlags(screenArgs);
307 - const written = writeScreen(sessionDir, flags.name, renderHtml(flags), {
308 - quiet: true,
309 - });
310 - const context = {
311 - ...info,
312 - session_dir: sessionDir,
313 - screen_file: written.file,
314 - };
315 - if (!wait) {
316 - console.log(JSON.stringify(context));
317 - return;
318 - }
319 - openUrl(info.url);
320 - const event = await waitChoiceEvent(sessionDir, timeoutMs(flags));
321 - console.log(
322 - JSON.stringify({
323 - ...event,
324 - session_dir: sessionDir,
325 - url: info.url,
326 - screen_file: written.file,
327 - }),
328 - );
331 -async function main(argv = process.argv.slice(2)) {
332 - const [command, ...rest] = argv;
333 - if (
334 - !command ||
335 - command === "--help" ||
336 - command === "-h" ||
337 - command === "help"
338 - ) {
339 - help();
340 - return;
341 - }
343 - if (command === "start")
344 - die(
345 - "Use start-choice or start-screen so the browser never opens to an empty waiting page.",
346 - );
348 - if (command === "start-choice") {
349 - await startWithScreen(rest, (flags) => {
350 - const options = [flags.option ?? []]
351 - .flat()
352 - .filter(Boolean)
353 - .map(parseOption);
354 - return renderChoiceScreen({
355 - title: flags.title,
356 - subtitle: flags.subtitle,
357 - options,
358 - multi: Boolean(flags.multi),
359 - });
360 - });
361 - return;
362 - }
364 - if (command === "start-screen") {
365 - await startWithScreen(rest, htmlFromFlags);
366 - return;
367 - }
369 - if (command === "open-choice") {
370 - await startWithScreen(
371 - rest,
372 - (flags) => {
373 - const options = [flags.option ?? []]
374 - .flat()
375 - .filter(Boolean)
376 - .map(parseOption);
377 - return renderChoiceScreen({
378 - title: flags.title,
379 - subtitle: flags.subtitle,
380 - options,
381 - multi: Boolean(flags.multi),
382 - });
383 - },
384 - { wait: true },
385 - );
386 - return;
387 - }
389 - if (command === "open-screen") {
390 - await startWithScreen(rest, htmlFromFlags, { wait: true });
391 - return;
392 - }
394 - if (command === "stop") {
395 - const result = await stop(rest[0]);
396 - console.log(JSON.stringify(result));
397 - if (result.error) process.exit(1);
398 - return;
399 - }
401 - if (command === "cleanup") {
402 - await cleanup();
403 - return;
404 - }
406 - if (command === "write-screen") {
407 - const [sessionDir, ...args] = rest;
408 - const flags = parseFlags(args);
409 - writeScreen(sessionDir, flags.name, htmlFromFlags(flags));
410 - return;
411 - }
413 - if (command === "choice-screen") {
414 - const [sessionDir, ...args] = rest;
415 - const flags = parseFlags(args);
416 - const options = [flags.option ?? []]
417 - .flat()
418 - .filter(Boolean)
419 - .map(parseOption);
420 - writeScreen(
421 - sessionDir,
422 - flags.name,
423 - renderChoiceScreen({
424 - title: flags.title,
425 - subtitle: flags.subtitle,
426 - options,
427 - multi: Boolean(flags.multi),
428 - }),
429 - );
430 - return;
431 - }
433 - if (command === "waiting-screen") {
434 - const [sessionDir, ...args] = rest;
435 - const flags = parseFlags(args);
436 - writeScreen(
437 - sessionDir,
438 - flags.name,
439 - '<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">\n <p class="subtitle">Continuing in terminal...</p>\n</div>\n',
440 - );
441 - return;
442 - }
444 - if (command === "events") {
445 - const [sessionDir, ...args] = rest;
446 - const flags = parseFlags(args);
447 - const { eventsFile } = sessionPaths(sessionDir);
448 - const events = readEvents(eventsFile);
449 - if (flags.clear) fs.rmSync(eventsFile, { force: true });
450 - console.log(JSON.stringify(events));
451 - return;
452 - }
454 - if (command === "listen") {
455 - const flags = parseFlags(rest);
456 - await listen(flags["project-dir"], {
457 - clear: Boolean(flags.clear),
458 - timeoutMs: flags["timeout-ms"] === undefined ? 0 : timeoutMs(flags),
459 - });
460 - return;
461 - }
463 - if (command === "wait-choice") {
464 - const [sessionDir, ...args] = rest;
465 - const flags = parseFlags(args);
466 - await waitChoice(sessionDir, timeoutMs(flags));
467 - return;
468 - }
470 - if (command === "ask-choice") {
471 - const [sessionDir, ...args] = rest;
472 - const flags = parseFlags(args);
473 - const options = [flags.option ?? []]
474 - .flat()
475 - .filter(Boolean)
476 - .map(parseOption);
477 - writeScreen(
478 - sessionDir,
479 - flags.name,
480 - renderChoiceScreen({
481 - title: flags.title,
482 - subtitle: flags.subtitle,
483 - options,
484 - multi: Boolean(flags.multi),
485 - }),
486 - { quiet: true },
487 - );
488 - await waitChoice(sessionDir, timeoutMs(flags));
489 - return;
490 - }
492 - if (command === "ask-screen") {
493 - const [sessionDir, ...args] = rest;
494 - const flags = parseFlags(args);
495 - writeScreen(sessionDir, flags.name, htmlFromFlags(flags), { quiet: true });
496 - await waitChoice(sessionDir, timeoutMs(flags));
497 - return;
498 - }
500 - die(`Unknown command: ${command}`);
503 -if (
504 - process.argv[1] &&
505 - import.meta.url === pathToFileURL(process.argv[1]).href
506 -) {
507 - main().catch((error) => die(error.message));
510 -export { cleanup, main, parseFlags, readEvents, renderChoiceScreen };

skills/super/brainstorming/scripts/companion.test.mjs

Deleted
deleted file mode 100644
1 -import assert from "node:assert/strict";
2 -import { execFile, spawn } from "node:child_process";
3 -import crypto from "node:crypto";
4 -import fs from "node:fs";
5 -import http from "node:http";
6 -import os from "node:os";
7 -import path from "node:path";
8 -import test from "node:test";
9 -import { promisify } from "node:util";
10 -import { OPCODES } from "./server.mjs";
12 -const execFileAsync = promisify(execFile);
13 -const scriptDir = import.meta.dirname;
15 -async function runNode(script, args = [], options = {}) {
16 - return execFileAsync(
17 - process.execPath,
18 - [path.join(scriptDir, script), ...args],
19 - {
20 - timeout: options.timeout ?? 10_000,
21 - maxBuffer: 1024 * 1024,
22 - env: { ...process.env, ...(options.env ?? {}) },
23 - },
24 - );
27 -function tmpProject() {
28 - return fs.mkdtempSync(path.join(os.tmpdir(), "brainstorm-companion-"));
31 -async function start(projectDir) {
32 - const first = path.join(projectDir, "first.html");
33 - fs.writeFileSync(first, "<h2>Ready</h2>");
34 - const { stdout } = await runNode("companion.mjs", [
35 - "start-screen",
36 - "--project-dir",
37 - projectDir,
38 - "--name",
39 - "ready",
40 - "--html-file",
41 - first,
42 - ]);
43 - const info = JSON.parse(stdout.trim());
44 - return {
45 - ...info,
46 - session_dir: info.session_dir ?? path.dirname(info.screen_dir),
47 - };
50 -async function stop(sessionDir) {
51 - return runNode("companion.mjs", ["stop", sessionDir]).catch(() => {});
54 -async function withSession(fn) {
55 - const projectDir = tmpProject();
56 - let info;
57 - try {
58 - info = await start(projectDir);
59 - await fn(info, projectDir);
60 - } finally {
61 - if (info) await stop(info.session_dir);
62 - fs.rmSync(projectDir, { recursive: true, force: true });
63 - }
66 -function encodeClientTextFrame(value) {
67 - const payload = Buffer.from(JSON.stringify(value));
68 - const header = payload.length < 126 ? Buffer.alloc(2) : Buffer.alloc(4);
69 - header[0] = 0x80 | OPCODES.TEXT;
70 - if (payload.length < 126) header[1] = 0x80 | payload.length;
71 - else {
72 - header[1] = 0x80 | 126;
73 - header.writeUInt16BE(payload.length, 2);
74 - }
75 - const mask = crypto.randomBytes(4);
76 - const masked = Buffer.alloc(payload.length);
77 - for (let i = 0; i < payload.length; i++) masked[i] = payload[i] ^ mask[i % 4];
78 - return Buffer.concat([header, mask, masked]);
81 -function decodeServerTextFrame(buffer) {
82 - if (buffer.length < 2) return null;
83 - const opcode = buffer[0] & 0x0f;
84 - let payloadLen = buffer[1] & 0x7f;
85 - let offset = 2;
86 - if (payloadLen === 126) {
87 - if (buffer.length < 4) return null;
88 - payloadLen = buffer.readUInt16BE(2);
89 - offset = 4;
90 - }
91 - const end = offset + payloadLen;
92 - if (buffer.length < end) return null;
93 - return { opcode, payload: buffer.subarray(offset, end) };
96 -function wsSendText(port, event) {
97 - return new Promise((resolve, reject) => {
98 - const key = crypto.randomBytes(16).toString("base64");
99 - const req = http.request({
100 - port,
101 - host: "localhost",
102 - headers: {
103 - Connection: "Upgrade",
104 - Upgrade: "websocket",
105 - "Sec-WebSocket-Version": "13",
106 - "Sec-WebSocket-Key": key,
107 - },
108 - });
110 - req.on("upgrade", (_res, socket) => {
111 - socket.write(encodeClientTextFrame(event));
112 - setTimeout(() => {
113 - socket.destroy();
114 - resolve();
115 - }, 50).unref();
116 - });
117 - req.on("error", reject);
118 - req.end();
119 - });
122 -function wsListenForReload(port) {
123 - return new Promise((resolve, reject) => {
124 - const key = crypto.randomBytes(16).toString("base64");
125 - const req = http.request({
126 - port,
127 - host: "localhost",
128 - headers: {
129 - Connection: "Upgrade",
130 - Upgrade: "websocket",
131 - "Sec-WebSocket-Version": "13",
132 - "Sec-WebSocket-Key": key,
133 - },
134 - });
136 - req.on("upgrade", (_res, socket) => {
137 - let buffer = Buffer.alloc(0);
138 - socket.on("data", (chunk) => {
139 - buffer = Buffer.concat([buffer, chunk]);
140 - const frame = decodeServerTextFrame(buffer);
141 - if (frame?.opcode === OPCODES.TEXT) {
142 - socket.destroy();
143 - resolve(JSON.parse(frame.payload.toString()));
144 - }
145 - });
146 - });
147 - req.on("error", reject);
148 - setTimeout(
149 - () => reject(new Error("timed out waiting for reload")),
150 - 3000,
151 - ).unref();
152 - req.end();
153 - });
156 -test("visual companion launchers are pure Node scripts", () => {
157 - assert.equal(fs.existsSync(path.join(scriptDir, "companion.mjs")), true);
158 - assert.equal(fs.existsSync(path.join(scriptDir, "start-server.mjs")), true);
159 - assert.equal(fs.existsSync(path.join(scriptDir, "stop-server.mjs")), true);
160 - assert.equal(fs.existsSync(path.join(scriptDir, "start-server.sh")), false);
161 - assert.equal(fs.existsSync(path.join(scriptDir, "stop-server.sh")), false);
162 -});
164 -test("internal start-server CLI is rejected to avoid empty browser sessions", async () => {
165 - await assert.rejects(
166 - runNode("start-server.mjs", ["--project-dir", tmpProject()]),
167 - (error) => {
168 - assert.match(error.stdout, /start-server\.mjs is internal/);
169 - assert.match(error.stdout, /start-choice/);
170 - return true;
171 - },
172 - );
173 -});
175 -test("human-agent workflow: script renders choices, UI event arrives while agent waits", async () => {
176 - await withSession(async (info) => {
177 - await runNode("companion.mjs", [
178 - "choice-screen",
179 - info.session_dir,
180 - "--name",
181 - "approaches",
182 - "--title",
183 - "Which approach?",
184 - "--subtitle",
185 - "Pick one direction",
186 - "--option",
187 - "a|Small|Minimal change",
188 - "--option",
189 - "b|Large|Broad redesign",
190 - ]);
192 - const html = await (await fetch(info.url)).text();
193 - assert.match(html, /Which approach\?/);
194 - assert.match(html, /data-choice="a"/);
195 - assert.match(html, /Minimal change/);
196 - assert.match(html, /window\.toggleSelect = \(el\) => \{/);
198 - const waiting = runNode("companion.mjs", [
199 - "wait-choice",
200 - info.session_dir,
201 - "--timeout-ms",
202 - "3000",
203 - ]);
204 - await wsSendText(info.port, {
205 - type: "click",
206 - choice: "b",
207 - text: "Large",
208 - id: "option-b",
209 - });
210 - const result = JSON.parse((await waiting).stdout.trim());
212 - assert.equal(result.choice, "b");
213 - assert.equal(result.text, "Large");
214 - assert.equal(result.id, "option-b");
215 - });
216 -});
218 -test("companion has help for deterministic workflow commands", async () => {
219 - const { stdout } = await runNode("companion.mjs", ["--help"]);
220 - assert.match(stdout, /start-choice/);
221 - assert.match(stdout, /start-screen/);
222 - assert.match(stdout, /open-choice/);
223 - assert.match(stdout, /open-screen/);
224 - assert.match(stdout, /ask-choice/);
225 - assert.match(stdout, /ask-screen/);
226 - assert.match(stdout, /--html-file/);
227 - assert.match(stdout, /cleanup/);
228 - assert.doesNotMatch(stdout, /\n {2}start --project-dir/);
229 -});
231 -test("companion start without a first screen is rejected", async () => {
232 - await assert.rejects(
233 - runNode("companion.mjs", ["start", "--project-dir", tmpProject()]),
234 - (error) => {
235 - assert.match(error.stdout, /Use start-choice or start-screen/);
236 - return true;
237 - },
238 - );
239 -});
241 -test("start-choice starts server with first browser screen already loaded", async () => {
242 - const projectDir = tmpProject();
243 - let sessionDir;
245 - try {
246 - const { stdout } = await runNode("companion.mjs", [
247 - "start-choice",
248 - "--project-dir",
249 - projectDir,
250 - "--name",
251 - "first-layout",
252 - "--title",
253 - "First visual question",
254 - "--subtitle",
255 - "Browser must not show waiting page",
256 - "--option",
257 - "a|Left rail|Tree on left",
258 - "--option",
259 - "b|Graph first|Session graph center",
260 - ]);
261 - const info = JSON.parse(stdout.trim());
262 - sessionDir = info.session_dir;
264 - assert.equal(info.type, "server-started");
265 - assert.match(info.url, /^http:\/\/localhost:\d+$/);
266 - assert.equal(fs.existsSync(info.screen_file), true);
268 - const html = await (await fetch(info.url)).text();
269 - assert.match(html, /First visual question/);
270 - assert.match(html, /Browser must not show waiting page/);
271 - assert.match(html, /data-choice="b"/);
272 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
273 - } finally {
274 - if (sessionDir) await stop(sessionDir);
275 - fs.rmSync(projectDir, { recursive: true, force: true });
276 - }
277 -});
279 -test("start-screen starts server with first custom HTML screen already loaded", async () => {
280 - const projectDir = tmpProject();
281 - let sessionDir;
283 - try {
284 - const htmlFile = path.join(projectDir, "first.html");
285 - fs.writeFileSync(htmlFile, "<h2>First custom screen</h2>");
286 - const { stdout } = await runNode("companion.mjs", [
287 - "start-screen",
288 - "--project-dir",
289 - projectDir,
290 - "--name",
291 - "first-custom",
292 - "--html-file",
293 - htmlFile,
294 - ]);
295 - const info = JSON.parse(stdout.trim());
296 - sessionDir = info.session_dir;
298 - assert.equal(fs.existsSync(info.screen_file), true);
299 - const html = await (await fetch(info.url)).text();
300 - assert.match(html, /First custom screen/);
301 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
302 - } finally {
303 - if (sessionDir) await stop(sessionDir);
304 - fs.rmSync(projectDir, { recursive: true, force: true });
305 - }
306 -});
308 -test("visual wait commands reject slow timeouts above 30 seconds", async () => {
309 - const projectDir = tmpProject();
310 - let sessionDir;
312 - try {
313 - const first = path.join(projectDir, "first.html");
314 - fs.writeFileSync(first, "<h2>Timeout Cap</h2>");
315 - const { stdout } = await runNode("companion.mjs", [
316 - "start-screen",
317 - "--project-dir",
318 - projectDir,
319 - "--name",
320 - "timeout-cap",
321 - "--html-file",
322 - first,
323 - ]);
324 - sessionDir = JSON.parse(stdout.trim()).session_dir;
326 - await assert.rejects(
327 - runNode("companion.mjs", [
328 - "ask-choice",
329 - sessionDir,
330 - "--name",
331 - "too-slow",
332 - "--title",
333 - "Too slow",
334 - "--option",
335 - "a|A|A",
336 - "--timeout-ms",
337 - "300001",
338 - ]),
339 - (error) => {
340 - assert.match(error.stdout, /--timeout-ms max is 30000ms/);
341 - return true;
342 - },
343 - );
344 - } finally {
345 - if (sessionDir) await stop(sessionDir);
346 - fs.rmSync(projectDir, { recursive: true, force: true });
347 - }
348 -});
350 -test("open-choice starts with first screen, waits, and returns click without terminal reply", async () => {
351 - const projectDir = tmpProject();
352 - let sessionDir;
354 - try {
355 - const asking = runNode(
356 - "companion.mjs",
357 - [
358 - "open-choice",
359 - "--project-dir",
360 - projectDir,
361 - "--name",
362 - "first-open-choice",
363 - "--title",
364 - "Choose first layout",
365 - "--option",
366 - "map|Map|Mission map",
367 - "--option",
368 - "queue|Queue|Decision queue",
369 - "--timeout-ms",
370 - "3000",
371 - ],
372 - { env: { BRAINSTORM_NO_OPEN: "1" } },
373 - );
375 - let info;
376 - for (let i = 0; i < 50; i++) {
377 - const files = fs.globSync(
378 - `${projectDir}/.super/brainstorm/*/state/server-info`,
379 - );
380 - if (files.length) {
381 - info = JSON.parse(fs.readFileSync(files[0], "utf8"));
382 - sessionDir = path.dirname(info.screen_dir);
383 - break;
384 - }
385 - await new Promise((resolve) => setTimeout(resolve, 50));
386 - }
387 - assert.ok(info);
389 - let html = "";
390 - for (let i = 0; i < 50; i++) {
391 - html = await (await fetch(info.url)).text();
392 - if (html.includes("Choose first layout")) break;
393 - await new Promise((resolve) => setTimeout(resolve, 50));
394 - }
395 - assert.match(html, /Choose first layout/);
396 - assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
398 - await wsSendText(info.port, {
399 - type: "click",
400 - choice: "queue",
401 - text: "Queue",
402 - id: "option-queue",
403 - });
404 - const result = JSON.parse((await asking).stdout.trim());
405 - assert.equal(result.choice, "queue");
406 - assert.equal(result.session_dir, sessionDir);
407 - assert.equal(result.url, info.url);
408 - } finally {
409 - if (sessionDir) await stop(sessionDir);
410 - fs.rmSync(projectDir, { recursive: true, force: true });
411 - }
412 -});
414 -test("open-screen starts with first custom screen, waits, and returns click", async () => {
415 - const projectDir = tmpProject();
416 - let sessionDir;
418 - try {
419 - const htmlFile = path.join(projectDir, "open-screen.html");
420 - fs.writeFileSync(
421 - htmlFile,
422 - '<h2>Open custom</h2><div data-choice="x" onclick="toggleSelect(this)">X</div>',
423 - );
424 - const asking = runNode(
425 - "companion.mjs",
426 - [
427 - "open-screen",
428 - "--project-dir",
429 - projectDir,
430 - "--name",
431 - "open-custom",
432 - "--html-file",
433 - htmlFile,
434 - "--timeout-ms",
435 - "3000",
436 - ],
437 - { env: { BRAINSTORM_NO_OPEN: "1" } },
438 - );
440 - let info;
441 - for (let i = 0; i < 50; i++) {
442 - const files = fs.globSync(
443 - `${projectDir}/.super/brainstorm/*/state/server-info`,
444 - );
445 - if (files.length) {
446 - info = JSON.parse(fs.readFileSync(files[0], "utf8"));
447 - sessionDir = path.dirname(info.screen_dir);
448 - break;
449 - }
450 - await new Promise((resolve) => setTimeout(resolve, 50));
451 - }
452 - assert.ok(info);
454 - let html = "";
455 - for (let i = 0; i < 50; i++) {
456 - html = await (await fetch(info.url)).text();
457 - if (html.includes("Open custom")) break;
458 - await new Promise((resolve) => setTimeout(resolve, 50));
459 - }
460 - assert.match(html, /Open custom/);
461 - await wsSendText(info.port, {
462 - type: "click",
463 - choice: "x",
464 - text: "X",
465 - id: null,
466 - });
467 - const result = JSON.parse((await asking).stdout.trim());
468 - assert.equal(result.choice, "x");
469 - } finally {
470 - if (sessionDir) await stop(sessionDir);
471 - fs.rmSync(projectDir, { recursive: true, force: true });
472 - }
473 -});
475 -test("ask-choice writes a choice screen and returns the browser click without terminal reply", async () => {
476 - await withSession(async (info) => {
477 - const asking = runNode("companion.mjs", [
478 - "ask-choice",
479 - info.session_dir,
480 - "--name",
481 - "ask-style",
482 - "--title",
483 - "Pick a mode",
484 - "--subtitle",
485 - "No terminal reply needed",
486 - "--option",
487 - "fast|Fast|Shortest path",
488 - "--option",
489 - "deep|Deep|More detail",
490 - "--timeout-ms",
491 - "3000",
492 - ]);
494 - for (let i = 0; i < 50; i++) {
495 - const html = await (await fetch(info.url)).text();
496 - if (html.includes("Pick a mode") && html.includes('data-choice="deep"'))
497 - break;
498 - await new Promise((resolve) => setTimeout(resolve, 50));
499 - }
501 - await wsSendText(info.port, {
502 - type: "click",
503 - choice: "deep",
504 - text: "Deep",
505 - id: "option-deep",
506 - });
507 - const result = JSON.parse((await asking).stdout.trim());
509 - assert.equal(result.choice, "deep");
510 - assert.equal(result.text, "Deep");
511 - assert.equal(result.id, "option-deep");
512 - });
513 -});
515 -test("ask-screen reads custom HTML from file and returns browser click without shell quoting", async () => {
516 - await withSession(async (info, projectDir) => {
517 - const htmlFile = path.join(projectDir, "mockups.html");
518 - fs.writeFileSync(
519 - htmlFile,
520 - `
521 -<h2>Custom mockups</h2>
522 -<div class="cards">
523 - <div class="card" data-choice="a" onclick="toggleSelect(this)"><div class="card-body"><h3>A</h3><p>Alpha</p></div></div>
524 - <div class="card" data-choice="b" onclick="toggleSelect(this)"><div class="card-body"><h3>B</h3><p>Beta</p></div></div>
525 -</div>
526 -`,
527 - );
529 - const asking = runNode("companion.mjs", [
530 - "ask-screen",
531 - info.session_dir,
532 - "--name",
533 - "custom-mockups",
534 - "--html-file",
535 - htmlFile,
536 - "--timeout-ms",
537 - "3000",
538 - ]);
540 - for (let i = 0; i < 50; i++) {
541 - const html = await (await fetch(info.url)).text();
542 - if (html.includes("Custom mockups") && html.includes('data-choice="b"'))
543 - break;
544 - await new Promise((resolve) => setTimeout(resolve, 50));
545 - }
547 - await wsSendText(info.port, {
548 - type: "click",
549 - choice: "b",
550 - text: "B Beta",
551 - id: null,
552 - });
553 - const result = JSON.parse((await asking).stdout.trim());
554 - assert.equal(result.choice, "b");
555 - assert.equal(result.text, "B Beta");
556 - });
557 -});
559 -test("write-screen reads custom HTML from file", async () => {
560 - await withSession(async (info, projectDir) => {
561 - const htmlFile = path.join(projectDir, "screen.html");
562 - fs.writeFileSync(htmlFile, "<h2>File Screen</h2>");
563 - await runNode("companion.mjs", [
564 - "write-screen",
565 - info.session_dir,
566 - "--name",
567 - "file-screen",
568 - "--html-file",
569 - htmlFile,
570 - ]);
571 - assert.match(await (await fetch(info.url)).text(), /File Screen/);
572 - });
573 -});
575 -test("scripted workflow supports waiting screen, event listing, clearing, and per-screen event reset", async () => {
576 - await withSession(async (info) => {
577 - await runNode("companion.mjs", [
578 - "choice-screen",
579 - info.session_dir,
580 - "--name",
581 - "first",
582 - "--title",
583 - "First?",
584 - "--option",
585 - "a|Alpha|A",
586 - ]);
587 - await wsSendText(info.port, { type: "click", choice: "a", text: "Alpha" });
589 - const listed = JSON.parse(
590 - (
591 - await runNode("companion.mjs", ["events", info.session_dir])
592 - ).stdout.trim(),
593 - );
594 - assert.equal(listed.length, 1);
595 - assert.equal(listed[0].choice, "a");
597 - await runNode("companion.mjs", [
598 - "choice-screen",
599 - info.session_dir,
600 - "--name",
601 - "second",
602 - "--title",
603 - "Second?",
604 - "--option",
605 - "b|Beta|B",
606 - ]);
607 - assert.deepEqual(
608 - JSON.parse(
609 - (
610 - await runNode("companion.mjs", ["events", info.session_dir])
611 - ).stdout.trim(),
612 - ),
613 - [],
614 - );
616 - await wsSendText(info.port, { type: "click", choice: "b", text: "Beta" });
617 - assert.equal(
618 - JSON.parse(
619 - (
620 - await runNode("companion.mjs", [
621 - "events",
622 - info.session_dir,
623 - "--clear",
624 - ])
625 - ).stdout.trim(),
626 - ).length,
627 - 1,
628 - );
629 - assert.deepEqual(
630 - JSON.parse(
631 - (
632 - await runNode("companion.mjs", ["events", info.session_dir])
633 - ).stdout.trim(),
634 - ),
635 - [],
636 - );
638 - await runNode("companion.mjs", [
639 - "waiting-screen",
640 - info.session_dir,
641 - "--name",
642 - "terminal",
643 - ]);
644 - const html = await (await fetch(info.url)).text();
645 - assert.match(html, /Continuing in terminal/);
646 - });
647 -});
649 -test("browser gets reload when agent pushes a new screen", async () => {
650 - await withSession(async (info) => {
651 - const reload = wsListenForReload(info.port);
652 - await runNode("companion.mjs", [
653 - "choice-screen",
654 - info.session_dir,
655 - "--name",
656 - "reload",
657 - "--title",
658 - "Reload?",
659 - "--option",
660 - "y|Yes|Y",
661 - ]);
662 - assert.deepEqual(await reload, { type: "reload" });
663 - });
664 -});
666 -test("server serves wrapped fragments, full documents, and content assets", async () => {
667 - await withSession(async (info) => {
668 - await runNode("companion.mjs", [
669 - "write-screen",
670 - info.session_dir,
671 - "--name",
672 - "fragment",
673 - "--html",
674 - "<h2>Fragment</h2>",
675 - ]);
676 - const fragment = await (await fetch(info.url)).text();
677 - assert.match(fragment, /Super Brainstorming/);
678 - assert.match(fragment, /<h2>Fragment<\/h2>/);
680 - await runNode("companion.mjs", [
681 - "write-screen",
682 - info.session_dir,
683 - "--name",
684 - "full",
685 - "--html",
686 - "<!DOCTYPE html><html><body><main>Full Doc</main></body></html>",
687 - ]);
688 - const full = await (await fetch(info.url)).text();
689 - assert.doesNotMatch(full, /Super Brainstorming/);
690 - assert.match(full, /<main>Full Doc<\/main>/);
691 - assert.match(full, /const WS_URL/);
693 - fs.writeFileSync(path.join(info.screen_dir, "asset.json"), '{"ok":true}');
694 - const asset = await fetch(`${info.url}/files/asset.json`);
695 - assert.equal(asset.headers.get("content-type"), "application/json");
696 - assert.deepEqual(await asset.json(), { ok: true });
697 - });
698 -});
700 -test("cleanup stops servers whose owner pid is gone", async () => {
701 - const projectDir = tmpProject();
702 - let sessionDir;
703 - let owner;
705 - try {
706 - const first = path.join(projectDir, "first.html");
707 - fs.writeFileSync(first, "<h2>Owned</h2>");
708 - owner = spawn(
709 - process.execPath,
710 - ["-e", "console.log(process.pid); setInterval(() => {}, 1000);"],
711 - { stdio: ["ignore", "pipe", "ignore"] },
712 - );
713 - const ownerPid = await new Promise((resolve) =>
714 - owner.stdout.once("data", (chunk) =>
715 - resolve(Number(chunk.toString().trim())),
716 - ),
717 - );
718 - assert.equal(Number.isInteger(ownerPid), true);
720 - const { stdout } = await runNode("companion.mjs", [
721 - "start-screen",
722 - "--project-dir",
723 - projectDir,
724 - "--owner-pid",
725 - String(ownerPid),
726 - "--name",
727 - "owned",
728 - "--html-file",
729 - first,
730 - ]);
731 - const info = JSON.parse(stdout.trim());
732 - sessionDir = info.session_dir;
734 - owner.kill("SIGTERM");
735 - await new Promise((resolve) => owner.once("exit", resolve));
737 - const cleaned = JSON.parse(
738 - (await runNode("companion.mjs", ["cleanup"])).stdout.trim(),
739 - );
740 - assert.equal(cleaned.stopped.length, 1);
741 - assert.equal(cleaned.stopped[0].session_dir, sessionDir);
742 - assert.equal(cleaned.stopped[0].reason, "owner_dead");
743 - assert.equal(
744 - fs.existsSync(path.join(sessionDir, "state", "server.pid")),
745 - false,
746 - );
747 - } finally {
748 - if (owner && owner.exitCode === null) owner.kill("SIGTERM");
749 - if (sessionDir) await stop(sessionDir);
750 - fs.rmSync(projectDir, { recursive: true, force: true });
751 - }
752 -});
754 -test("server exits after browser disconnect timeout", async () => {
755 - const projectDir = tmpProject();
756 - let sessionDir;
758 - try {
759 - const first = path.join(projectDir, "first.html");
760 - fs.writeFileSync(first, "<h2>Disconnect</h2>");
761 - const { stdout } = await runNode("companion.mjs", [
762 - "start-screen",
763 - "--project-dir",
764 - projectDir,
765 - "--no-browser-timeout-ms",
766 - "200",
767 - "--name",
768 - "disconnect",
769 - "--html-file",
770 - first,
771 - ]);
772 - const info = JSON.parse(stdout.trim());
773 - sessionDir = info.session_dir;
775 - await new Promise((resolve, reject) => {
776 - const key = crypto.randomBytes(16).toString("base64");
777 - const req = http.request({
778 - port: info.port,
779 - host: "localhost",
780 - headers: {
781 - Connection: "Upgrade",
782 - Upgrade: "websocket",
783 - "Sec-WebSocket-Version": "13",
784 - "Sec-WebSocket-Key": key,
785 - },
786 - });
787 - req.on("upgrade", (_res, socket) => {
788 - socket.destroy();
789 - resolve();
790 - });
791 - req.on("error", reject);
792 - req.end();
793 - });
795 - const stoppedFile = path.join(sessionDir, "state", "server-stopped");
796 - for (let i = 0; i < 50 && !fs.existsSync(stoppedFile); i++)
797 - await new Promise((resolve) => setTimeout(resolve, 50));
798 - assert.equal(fs.existsSync(stoppedFile), true);
799 - assert.match(fs.readFileSync(stoppedFile, "utf8"), /no browser clients/);
800 - } finally {
801 - if (sessionDir) await stop(sessionDir);
802 - fs.rmSync(projectDir, { recursive: true, force: true });
803 - }
804 -});
806 -test("server module exports websocket helpers without side effects", async () => {
807 - const server = await import("./server.mjs");
808 - assert.deepEqual(Object.keys(server).sort(), [
809 - "OPCODES",
810 - "computeAcceptKey",
811 - "decodeFrame",
812 - "encodeFrame",
813 - ]);
814 -});

skills/super/brainstorming/scripts/frame-template.html

Deleted
deleted file mode 100644
1 -<!DOCTYPE html>
2 -<html lang="en">
3 -<head>
4 - <meta charset="utf-8">
5 - <title>Super Brainstorming</title>
6 - <style>
7 - /*
8 - * BRAINSTORM COMPANION FRAME TEMPLATE
9 - *
10 - * This template provides a consistent frame with:
11 - * - OS-aware light/dark theming
12 - * - Fixed header and selection indicator bar
13 - * - Scrollable main content area
14 - * - CSS helpers for common UI patterns
15 - *
16 - * Content is injected via placeholder comment in #claude-content.
17 - */
19 - * { box-sizing: border-box; margin: 0; padding: 0; }
20 - html, body { height: 100%; overflow: hidden; }
22 - /* ===== THEME VARIABLES ===== */
23 - :root {
24 - --bg-primary: #f5f5f7;
25 - --bg-secondary: #ffffff;
26 - --bg-tertiary: #e5e5e7;
27 - --border: #d1d1d6;
28 - --text-primary: #1d1d1f;
29 - --text-secondary: #86868b;
30 - --text-tertiary: #aeaeb2;
31 - --accent: #0071e3;
32 - --accent-hover: #0077ed;
33 - --success: #34c759;
34 - --warning: #ff9f0a;
35 - --error: #ff3b30;
36 - --selected-bg: #e8f4fd;
37 - --selected-border: #0071e3;
38 - }
40 - @media (prefers-color-scheme: dark) {
41 - :root {
42 - --bg-primary: #1d1d1f;
43 - --bg-secondary: #2d2d2f;
44 - --bg-tertiary: #3d3d3f;
45 - --border: #424245;
46 - --text-primary: #f5f5f7;
47 - --text-secondary: #86868b;
48 - --text-tertiary: #636366;
49 - --accent: #0a84ff;
50 - --accent-hover: #409cff;
51 - --selected-bg: rgba(10, 132, 255, 0.15);
52 - --selected-border: #0a84ff;
53 - }
54 - }
56 - body {
57 - font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif;
58 - background: var(--bg-primary);
59 - color: var(--text-primary);
60 - display: flex;
61 - flex-direction: column;
62 - line-height: 1.5;
63 - }
65 - /* ===== FRAME STRUCTURE ===== */
66 - .header {
67 - background: var(--bg-secondary);
68 - padding: 0.5rem 1.5rem;
69 - display: flex;
70 - justify-content: space-between;
71 - align-items: center;
72 - border-bottom: 1px solid var(--border);
73 - flex-shrink: 0;
74 - }
75 - .header h1 { font-size: 0.85rem; font-weight: 500; color: var(--text-secondary); }
76 - .header .status { font-size: 0.7rem; color: var(--success); display: flex; align-items: center; gap: 0.4rem; }
77 - .header .status::before { content: ''; width: 6px; height: 6px; background: var(--success); border-radius: 50%; }
79 - .main { flex: 1; overflow-y: auto; }
80 - #claude-content { padding: 2rem; min-height: 100%; }
82 - .indicator-bar {
83 - background: var(--bg-secondary);
84 - border-top: 1px solid var(--border);
85 - padding: 0.5rem 1.5rem;
86 - flex-shrink: 0;
87 - text-align: center;
88 - }
89 - .indicator-bar span {
90 - font-size: 0.75rem;
91 - color: var(--text-secondary);
92 - }
93 - .indicator-bar .selected-text {
94 - color: var(--accent);
95 - font-weight: 500;
96 - }
98 - /* ===== TYPOGRAPHY ===== */
99 - h2 { font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; }
100 - h3 { font-size: 1.1rem; font-weight: 600; margin-bottom: 0.25rem; }
101 - .subtitle { color: var(--text-secondary); margin-bottom: 1.5rem; }
102 - .section { margin-bottom: 2rem; }
103 - .label { font-size: 0.7rem; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 0.5rem; }
105 - /* ===== OPTIONS (for A/B/C choices) ===== */
106 - .options { display: flex; flex-direction: column; gap: 0.75rem; }
107 - .option {
108 - background: var(--bg-secondary);
109 - border: 2px solid var(--border);
110 - border-radius: 12px;
111 - padding: 1rem 1.25rem;
112 - cursor: pointer;
113 - transition: all 0.15s ease;
114 - display: flex;
115 - align-items: flex-start;
116 - gap: 1rem;
117 - }
118 - .option:hover { border-color: var(--accent); }
119 - .option.selected { background: var(--selected-bg); border-color: var(--selected-border); }
120 - .option .letter {
121 - background: var(--bg-tertiary);
122 - color: var(--text-secondary);
123 - width: 1.75rem; height: 1.75rem;
124 - border-radius: 6px;
125 - display: flex; align-items: center; justify-content: center;
126 - font-weight: 600; font-size: 0.85rem; flex-shrink: 0;
127 - }
128 - .option.selected .letter { background: var(--accent); color: white; }
129 - .option .content { flex: 1; }
130 - .option .content h3 { font-size: 0.95rem; margin-bottom: 0.15rem; }
131 - .option .content p { color: var(--text-secondary); font-size: 0.85rem; margin: 0; }
133 - /* ===== CARDS (for showing designs/mockups) ===== */
134 - .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 1rem; }
135 - .card {
136 - background: var(--bg-secondary);
137 - border: 1px solid var(--border);
138 - border-radius: 12px;
139 - overflow: hidden;
140 - cursor: pointer;
141 - transition: all 0.15s ease;
142 - }
143 - .card:hover { border-color: var(--accent); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
144 - .card.selected { border-color: var(--selected-border); border-width: 2px; }
145 - .card-image { background: var(--bg-tertiary); aspect-ratio: 16/10; display: flex; align-items: center; justify-content: center; }
146 - .card-body { padding: 1rem; }
147 - .card-body h3 { margin-bottom: 0.25rem; }
148 - .card-body p { color: var(--text-secondary); font-size: 0.85rem; }
150 - /* ===== MOCKUP CONTAINER ===== */
151 - .mockup {
152 - background: var(--bg-secondary);
153 - border: 1px solid var(--border);
154 - border-radius: 12px;
155 - overflow: hidden;
156 - margin-bottom: 1.5rem;
157 - }
158 - .mockup-header {
159 - background: var(--bg-tertiary);
160 - padding: 0.5rem 1rem;
161 - font-size: 0.75rem;
162 - color: var(--text-secondary);
163 - border-bottom: 1px solid var(--border);
164 - }
165 - .mockup-body { padding: 1.5rem; }
167 - /* ===== SPLIT VIEW (side-by-side comparison) ===== */
168 - .split { display: grid; grid-template-columns: 1fr 1fr; gap: 1.5rem; }
169 - @media (max-width: 700px) { .split { grid-template-columns: 1fr; } }
171 - /* ===== PROS/CONS ===== */
172 - .pros-cons { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
173 - .pros, .cons { background: var(--bg-secondary); border-radius: 8px; padding: 1rem; }
174 - .pros h4 { color: var(--success); font-size: 0.85rem; margin-bottom: 0.5rem; }
175 - .cons h4 { color: var(--error); font-size: 0.85rem; margin-bottom: 0.5rem; }
176 - .pros ul, .cons ul { margin-left: 1.25rem; font-size: 0.85rem; color: var(--text-secondary); }
177 - .pros li, .cons li { margin-bottom: 0.25rem; }
179 - /* ===== PLACEHOLDER (for mockup areas) ===== */
180 - .placeholder {
181 - background: var(--bg-tertiary);
182 - border: 2px dashed var(--border);
183 - border-radius: 8px;
184 - padding: 2rem;
185 - text-align: center;
186 - color: var(--text-tertiary);
187 - }
189 - /* ===== INLINE MOCKUP ELEMENTS ===== */
190 - .mock-nav { background: var(--accent); color: white; padding: 0.75rem 1rem; display: flex; gap: 1.5rem; font-size: 0.9rem; }
191 - .mock-sidebar { background: var(--bg-tertiary); padding: 1rem; min-width: 180px; }
192 - .mock-content { padding: 1.5rem; flex: 1; }
193 - .mock-button { background: var(--accent); color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; font-size: 0.85rem; }
194 - .mock-input { background: var(--bg-primary); border: 1px solid var(--border); border-radius: 6px; padding: 0.5rem; width: 100%; }
195 - </style>
196 -</head>
197 -<body>
198 - <div class="header">
199 - <h1>Super Brainstorming</h1>
200 - <div class="status">Connected</div>
201 - </div>
203 - <div class="main">
204 - <div id="claude-content">
205 - <!-- CONTENT -->
206 - </div>
207 - </div>
209 - <div class="indicator-bar">
210 - <span id="indicator-text">Click an option above, then return to the terminal</span>
211 - </div>
213 -</body>
214 -</html>

skills/super/brainstorming/scripts/helper.js

Deleted
deleted file mode 100644
1 -(() => {
2 - const WS_URL = "ws://" + window.location.host;
3 - let ws = null;
4 - let eventQueue = [];
6 - function ensureHumanNotes() {
7 - if (document.getElementById("human-notes")) return;
8 - const bar = document.createElement("div");
9 - bar.id = "human-notes-bar";
10 - bar.innerHTML =
11 - '<div class="human-notes-brand"><span class="human-notes-sigil">N</span><span><b>Nugu notes</b><small>sent with click</small></span></div><textarea id="human-notes" aria-label="Notes to agent" placeholder="what you like · what sucks · what to change"></textarea>';
12 - document.body.appendChild(bar);
13 - const style = document.createElement("style");
14 - style.textContent = `
15 - #human-notes-bar { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); z-index: 2147483647; width: min(960px, calc(100vw - 28px)); display: grid; grid-template-columns: max-content 1fr; gap: 0.9rem; align-items: center; padding: 0.75rem; background: linear-gradient(135deg, rgba(18,18,18,0.98), rgba(34,20,34,0.98)); border: 1px solid #d86dd8; border-radius: 14px; box-shadow: 0 18px 48px rgba(0,0,0,0.55), 0 0 0 1px rgba(216,109,216,0.25) inset; color: #ededed; font: 13px "IBM Plex Sans", system-ui, sans-serif; }
16 - .human-notes-brand { display: grid; grid-template-columns: 34px max-content; gap: 0.65rem; align-items: center; color: #ededed; }
17 - .human-notes-sigil { width: 34px; height: 34px; display: grid; place-items: center; border: 2px solid #d86dd8; color: #d86dd8; background: #121212; font: 900 18px "IBM Plex Mono", monospace; box-shadow: 4px 4px 0 #000; }
18 - .human-notes-brand b { display:block; color:#ededed; font: 800 13px "IBM Plex Mono", monospace; letter-spacing: .04em; text-transform: uppercase; }
19 - .human-notes-brand small { display:block; color:#a8a8a8; font-size: 11px; margin-top: 1px; }
20 - #human-notes { min-height: 2.65rem; max-height: 9rem; resize: vertical; width: 100%; border: 1px solid rgba(216,109,216,0.55); border-radius: 10px; background: #0f0f0f; color: #ededed; caret-color: #d86dd8; padding: 0.62rem 0.75rem; font: 14px "IBM Plex Sans", system-ui, sans-serif; outline: none; }
21 - #human-notes:focus { border-color: #d86dd8; box-shadow: 0 0 0 3px rgba(216,109,216,0.18); }
22 - #human-notes::placeholder { color: #777; }
23 - body { padding-bottom: 6.25rem !important; }
24 - `;
25 - document.head.appendChild(style);
26 - }
28 - function humanNotes() {
29 - return document.getElementById("human-notes")?.value?.trim() || "";
30 - }
32 - function connect() {
33 - ws = new WebSocket(WS_URL);
35 - ws.onopen = () => {
36 - eventQueue.forEach((e) => ws.send(JSON.stringify(e)));
37 - eventQueue = [];
38 - };
40 - ws.onmessage = (msg) => {
41 - const data = JSON.parse(msg.data);
42 - if (data.type === "reload") {
43 - window.location.reload();
44 - }
45 - };
47 - ws.onclose = () => {
48 - setTimeout(connect, 1000);
49 - };
50 - }
52 - function sendEvent(event) {
53 - event.timestamp = Date.now();
54 - event.humanNotes = humanNotes();
55 - if (ws && ws.readyState === WebSocket.OPEN) {
56 - ws.send(JSON.stringify(event));
57 - } else {
58 - eventQueue.push(event);
59 - }
60 - }
62 - ensureHumanNotes();
63 - if (document.readyState === "loading")
64 - document.addEventListener("DOMContentLoaded", ensureHumanNotes);
66 - // Capture clicks on choice elements
67 - document.addEventListener("click", (e) => {
68 - const target = e.target.closest("[data-choice]");
69 - if (!target) return;
71 - sendEvent({
72 - type: "click",
73 - text: target.textContent.trim(),
74 - choice: target.dataset.choice,
75 - id: target.id || null,
76 - });
78 - // Update indicator bar (defer so toggleSelect runs first)
79 - setTimeout(() => {
80 - const indicator = document.getElementById("indicator-text");
81 - if (!indicator) return;
82 - const container = target.closest(".options") || target.closest(".cards");
83 - const selected = container ? container.querySelectorAll(".selected") : [];
84 - if (selected.length === 0) {
85 - indicator.textContent =
86 - "Click an option above, then return to the terminal";
87 - } else if (selected.length === 1) {
88 - const label =
89 - selected[0]
90 - .querySelector("h3, .content h3, .card-body h3")
91 - ?.textContent?.trim() || selected[0].dataset.choice;
92 - indicator.innerHTML =
93 - '<span class="selected-text">' +
94 - label +
95 - " selected</span> — return to terminal to continue";
96 - } else {
97 - indicator.innerHTML =
98 - '<span class="selected-text">' +
99 - selected.length +
100 - " selected</span> — return to terminal to continue";
101 - }
102 - }, 0);
103 - });
105 - // Frame UI: selection tracking
106 - window.selectedChoice = null;
108 - window.toggleSelect = (el) => {
109 - const container = el.closest(".options") || el.closest(".cards");
110 - const multi = container && container.dataset.multiselect !== undefined;
111 - if (container && !multi) {
112 - container
113 - .querySelectorAll(".option, .card")
114 - .forEach((o) => o.classList.remove("selected"));
115 - }
116 - if (multi) {
117 - el.classList.toggle("selected");
118 - } else {
119 - el.classList.add("selected");
120 - }
121 - window.selectedChoice = el.dataset.choice;
122 - };
124 - // Expose API for explicit use
125 - window.brainstorm = {
126 - send: sendEvent,
127 - choice: (value, metadata = {}) =>
128 - sendEvent({ type: "choice", value, ...metadata }),
129 - };
131 - connect();
132 -})();

skills/super/brainstorming/scripts/server.mjs

Deleted
deleted file mode 100644
1 -import crypto from "node:crypto";
2 -import fs from "node:fs";
3 -import http from "node:http";
4 -import path from "node:path";
5 -import { fileURLToPath, pathToFileURL } from "node:url";
7 -const __dirname = path.dirname(fileURLToPath(import.meta.url));
9 -// ========== WebSocket Protocol (RFC 6455) ==========
11 -const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0a };
12 -const WS_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
14 -function computeAcceptKey(clientKey) {
15 - return crypto
16 - .createHash("sha1")
17 - .update(clientKey + WS_MAGIC)
18 - .digest("base64");
21 -function encodeFrame(opcode, payload) {
22 - const fin = 0x80;
23 - const len = payload.length;
24 - let header;
26 - if (len < 126) {
27 - header = Buffer.alloc(2);
28 - header[0] = fin | opcode;
29 - header[1] = len;
30 - } else if (len < 65536) {
31 - header = Buffer.alloc(4);
32 - header[0] = fin | opcode;
33 - header[1] = 126;
34 - header.writeUInt16BE(len, 2);
35 - } else {
36 - header = Buffer.alloc(10);
37 - header[0] = fin | opcode;
38 - header[1] = 127;
39 - header.writeBigUInt64BE(BigInt(len), 2);
40 - }
42 - return Buffer.concat([header, payload]);
45 -function decodeFrame(buffer) {
46 - if (buffer.length < 2) return null;
48 - const secondByte = buffer[1];
49 - const opcode = buffer[0] & 0x0f;
50 - const masked = (secondByte & 0x80) !== 0;
51 - let payloadLen = secondByte & 0x7f;
52 - let offset = 2;
54 - if (!masked) throw new Error("Client frames must be masked");
56 - if (payloadLen === 126) {
57 - if (buffer.length < 4) return null;
58 - payloadLen = buffer.readUInt16BE(2);
59 - offset = 4;
60 - } else if (payloadLen === 127) {
61 - if (buffer.length < 10) return null;
62 - payloadLen = Number(buffer.readBigUInt64BE(2));
63 - offset = 10;
64 - }
66 - const maskOffset = offset;
67 - const dataOffset = offset + 4;
68 - const totalLen = dataOffset + payloadLen;
69 - if (buffer.length < totalLen) return null;
71 - const mask = buffer.slice(maskOffset, dataOffset);
72 - const data = Buffer.alloc(payloadLen);
73 - for (let i = 0; i < payloadLen; i++) {
74 - data[i] = buffer[dataOffset + i] ^ mask[i % 4];
75 - }
77 - return { opcode, payload: data, bytesConsumed: totalLen };
80 -// ========== Configuration ==========
82 -const PORT =
83 - process.env.BRAINSTORM_PORT || 49152 + Math.floor(Math.random() * 16383);
84 -const HOST = process.env.BRAINSTORM_HOST || "127.0.0.1";
85 -const URL_HOST =
86 - process.env.BRAINSTORM_URL_HOST ||
87 - (HOST === "127.0.0.1" ? "localhost" : HOST);
88 -const SESSION_DIR = process.env.BRAINSTORM_DIR || "/tmp/brainstorm";
89 -const CONTENT_DIR = path.join(SESSION_DIR, "content");
90 -const STATE_DIR = path.join(SESSION_DIR, "state");
91 -let ownerPid = process.env.BRAINSTORM_OWNER_PID
92 - ? Number(process.env.BRAINSTORM_OWNER_PID)
93 - : null;
94 -const NO_BROWSER_TIMEOUT_MS = Number(
95 - process.env.BRAINSTORM_NO_BROWSER_TIMEOUT_MS || 60_000,
96 -);
98 -const MIME_TYPES = {
99 - ".html": "text/html",
100 - ".css": "text/css",
101 - ".js": "application/javascript",
102 - ".json": "application/json",
103 - ".png": "image/png",
104 - ".jpg": "image/jpeg",
105 - ".jpeg": "image/jpeg",
106 - ".gif": "image/gif",
107 - ".svg": "image/svg+xml",
108 -};
110 -// ========== Templates and Constants ==========
112 -const WAITING_PAGE = `<!DOCTYPE html>
113 -<html>
114 -<head><meta charset="utf-8"><title>Brainstorm Companion</title>
115 -<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
116 -h1 { color: #333; } p { color: #666; }</style>
117 -</head>
118 -<body><h1>Brainstorm Companion</h1>
119 -<p>Waiting for the agent to push a screen...</p></body></html>`;
121 -const frameTemplate = fs.readFileSync(
122 - path.join(__dirname, "frame-template.html"),
123 - "utf-8",
124 -);
125 -const helperScript = fs.readFileSync(
126 - path.join(__dirname, "helper.js"),
127 - "utf-8",
128 -);
129 -const helperInjection = "<script>\n" + helperScript + "\n</script>";
131 -// ========== Helper Functions ==========
133 -function isFullDocument(html) {
134 - const trimmed = html.trimStart().toLowerCase();
135 - return trimmed.startsWith("<!doctype") || trimmed.startsWith("<html");
138 -function wrapInFrame(content) {
139 - return frameTemplate.replace("<!-- CONTENT -->", content);
142 -function getNewestScreen() {
143 - const files = fs
144 - .readdirSync(CONTENT_DIR)
145 - .filter((f) => f.endsWith(".html"))
146 - .map((f) => {
147 - const fp = path.join(CONTENT_DIR, f);
148 - return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
149 - })
150 - .sort((a, b) => b.mtime - a.mtime);
151 - return files.length > 0 ? files[0].path : null;
154 -// ========== HTTP Request Handler ==========
156 -function handleRequest(req, res) {
157 - touchActivity();
158 - if (req.method === "GET" && req.url === "/") {
159 - const screenFile = getNewestScreen();
160 - let html = screenFile
161 - ? ((raw) => (isFullDocument(raw) ? raw : wrapInFrame(raw)))(
162 - fs.readFileSync(screenFile, "utf-8"),
163 - )
164 - : WAITING_PAGE;
166 - if (html.includes("</body>")) {
167 - html = html.replace("</body>", helperInjection + "\n</body>");
168 - } else {
169 - html += helperInjection;
170 - }
172 - res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
173 - res.end(html);
174 - } else if (req.method === "GET" && req.url.startsWith("/files/")) {
175 - const fileName = req.url.slice(7);
176 - const filePath = path.join(CONTENT_DIR, path.basename(fileName));
177 - if (!fs.existsSync(filePath)) {
178 - res.writeHead(404);
179 - res.end("Not found");
180 - return;
181 - }
182 - const ext = path.extname(filePath).toLowerCase();
183 - const contentType = MIME_TYPES[ext] || "application/octet-stream";
184 - res.writeHead(200, { "Content-Type": contentType });
185 - res.end(fs.readFileSync(filePath));
186 - } else {
187 - res.writeHead(404);
188 - res.end("Not found");
189 - }
192 -// ========== WebSocket Connection Handling ==========
194 -const clients = new Set();
195 -let browserEverConnected = false;
196 -let browserDisconnectedAt = null;
198 -function handleUpgrade(req, socket) {
199 - const key = req.headers["sec-websocket-key"];
200 - if (!key) {
201 - socket.destroy();
202 - return;
203 - }
205 - const accept = computeAcceptKey(key);
206 - socket.write(
207 - "HTTP/1.1 101 Switching Protocols\r\n" +
208 - "Upgrade: websocket\r\n" +
209 - "Connection: Upgrade\r\n" +
210 - "Sec-WebSocket-Accept: " +
211 - accept +
212 - "\r\n\r\n",
213 - );
215 - let buffer = Buffer.alloc(0);
216 - clients.add(socket);
217 - browserEverConnected = true;
218 - browserDisconnectedAt = null;
220 - socket.on("data", (chunk) => {
221 - buffer = Buffer.concat([buffer, chunk]);
222 - while (buffer.length > 0) {
223 - let result;
224 - try {
225 - result = decodeFrame(buffer);
226 - } catch {
227 - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
228 - removeClient();
229 - return;
230 - }
231 - if (!result) break;
232 - buffer = buffer.slice(result.bytesConsumed);
234 - switch (result.opcode) {
235 - case OPCODES.TEXT:
236 - handleMessage(result.payload.toString());
237 - break;
238 - case OPCODES.CLOSE:
239 - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
240 - removeClient();
241 - return;
242 - case OPCODES.PING:
243 - socket.write(encodeFrame(OPCODES.PONG, result.payload));
244 - break;
245 - case OPCODES.PONG:
246 - break;
247 - default: {
248 - const closeBuf = Buffer.alloc(2);
249 - closeBuf.writeUInt16BE(1003);
250 - socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
251 - removeClient();
252 - return;
253 - }
254 - }
255 - }
256 - });
258 - function removeClient() {
259 - clients.delete(socket);
260 - if (browserEverConnected && clients.size === 0)
261 - browserDisconnectedAt = Date.now();
262 - }
264 - socket.on("close", removeClient);
265 - socket.on("end", removeClient);
266 - socket.on("error", removeClient);
269 -function handleMessage(text) {
270 - let event;
271 - try {
272 - event = JSON.parse(text);
273 - } catch (e) {
274 - console.error("Failed to parse WebSocket message:", e.message);
275 - return;
276 - }
277 - touchActivity();
278 - console.log(JSON.stringify({ source: "user-event", ...event }));
279 - if (event.choice) {
280 - const eventsFile = path.join(STATE_DIR, "events");
281 - fs.appendFileSync(eventsFile, JSON.stringify(event) + "\n");
282 - }
285 -function broadcast(msg) {
286 - const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
287 - for (const socket of clients) {
288 - try {
289 - socket.write(frame);
290 - } catch {
291 - clients.delete(socket);
292 - }
293 - }
296 -// ========== Activity Tracking ==========
298 -const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
299 -let lastActivity = Date.now();
301 -function touchActivity() {
302 - lastActivity = Date.now();
305 -// ========== File Watching ==========
307 -const debounceTimers = new Map();
309 -// ========== Server Startup ==========
311 -function startServer() {
312 - if (!fs.existsSync(CONTENT_DIR))
313 - fs.mkdirSync(CONTENT_DIR, { recursive: true });
314 - if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
316 - // Track known files to distinguish new screens from updates.
317 - // macOS fs.watch reports 'rename' for both new files and overwrites,
318 - // so we can't rely on eventType alone.
319 - const knownFiles = new Set(
320 - fs.readdirSync(CONTENT_DIR).filter((f) => f.endsWith(".html")),
321 - );
323 - const server = http.createServer(handleRequest);
324 - server.on("upgrade", handleUpgrade);
326 - const watcher = fs.watch(CONTENT_DIR, (_eventType, filename) => {
327 - if (!filename?.endsWith(".html")) return;
329 - if (debounceTimers.has(filename))
330 - clearTimeout(debounceTimers.get(filename));
331 - debounceTimers.set(
332 - filename,
333 - setTimeout(() => {
334 - debounceTimers.delete(filename);
335 - const filePath = path.join(CONTENT_DIR, filename);
337 - if (!fs.existsSync(filePath)) return; // file was deleted
338 - touchActivity();
340 - if (!knownFiles.has(filename)) {
341 - knownFiles.add(filename);
342 - console.log(JSON.stringify({ type: "screen-added", file: filePath }));
343 - } else {
344 - console.log(
345 - JSON.stringify({ type: "screen-updated", file: filePath }),
346 - );
347 - }
349 - broadcast({ type: "reload" });
350 - }, 100),
351 - );
352 - });
353 - watcher.on("error", (err) => console.error("fs.watch error:", err.message));
355 - function shutdown(reason) {
356 - console.log(JSON.stringify({ type: "server-stopped", reason }));
357 - const infoFile = path.join(STATE_DIR, "server-info");
358 - if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
359 - fs.writeFileSync(
360 - path.join(STATE_DIR, "server-stopped"),
361 - JSON.stringify({ reason, timestamp: Date.now() }) + "\n",
362 - );
363 - watcher.close();
364 - clearInterval(lifecycleCheck);
365 - server.close(() => process.exit(0));
366 - }
368 - function ownerAlive() {
369 - if (!ownerPid) return true;
370 - try {
371 - process.kill(ownerPid, 0);
372 - return true;
373 - } catch (e) {
374 - return e.code === "EPERM";
375 - }
376 - }
378 - // Check every 60s: exit if owner process died or idle for 30 minutes
379 - const lifecycleCheck = setInterval(() => {
380 - if (!ownerAlive()) shutdown("owner process exited");
381 - else if (
382 - browserDisconnectedAt &&
383 - Date.now() - browserDisconnectedAt > NO_BROWSER_TIMEOUT_MS
384 - )
385 - shutdown("no browser clients");
386 - else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS)
387 - shutdown("idle timeout");
388 - }, 100);
389 - lifecycleCheck.unref();
391 - // Validate owner PID at startup. If it's already dead, the PID resolution
392 - // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
393 - // Disable monitoring and rely on the idle timeout instead.
394 - if (ownerPid) {
395 - try {
396 - process.kill(ownerPid, 0);
397 - } catch (e) {
398 - if (e.code !== "EPERM") {
399 - console.log(
400 - JSON.stringify({
401 - type: "owner-pid-invalid",
402 - pid: ownerPid,
403 - reason: "dead at startup",
404 - }),
405 - );
406 - ownerPid = null;
407 - }
408 - }
409 - }
411 - server.listen(PORT, HOST, () => {
412 - const info = JSON.stringify({
413 - type: "server-started",
414 - port: Number(PORT),
415 - host: HOST,
416 - url_host: URL_HOST,
417 - url: "http://" + URL_HOST + ":" + PORT,
418 - screen_dir: CONTENT_DIR,
419 - state_dir: STATE_DIR,
420 - });
421 - console.log(info);
422 - fs.writeFileSync(path.join(STATE_DIR, "server-info"), info + "\n");
423 - });
426 -if (
427 - process.argv[1] &&
428 - import.meta.url === pathToFileURL(process.argv[1]).href
429 -) {
430 - startServer();
433 -export { computeAcceptKey, decodeFrame, encodeFrame, OPCODES };

skills/super/brainstorming/scripts/start-server.mjs

Deleted
deleted file mode 100755
1 -#!/usr/bin/env node
2 -import { spawn } from "node:child_process";
3 -import fs from "node:fs";
4 -import os from "node:os";
5 -import path from "node:path";
6 -import { fileURLToPath, pathToFileURL } from "node:url";
8 -const scriptDir = path.dirname(fileURLToPath(import.meta.url));
10 -const registryFile = path.join(
11 - os.homedir(),
12 - ".local",
13 - "state",
14 - "pi",
15 - "brainstorm-companion",
16 - "servers.jsonl",
17 -);
19 -function usage(error) {
20 - const message = error
21 - ? { error }
22 - : {
23 - usage:
24 - "start-server.mjs [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--owner-pid <pid>] [--no-browser-timeout-ms <ms>]",
25 - };
26 - console.log(JSON.stringify(message));
27 - process.exit(error ? 1 : 0);
30 -function parentPid(pid) {
31 - try {
32 - const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
33 - const afterName = stat
34 - .slice(stat.lastIndexOf(")") + 2)
35 - .trim()
36 - .split(/\s+/);
37 - return Number(afterName[1]);
38 - } catch {
39 - return null;
40 - }
43 -function defaultOwnerPid() {
44 - return parentPid(process.ppid) || process.ppid;
47 -function parseArgs(argv) {
48 - const options = {
49 - projectDir: "",
50 - host: "127.0.0.1",
51 - urlHost: "",
52 - ownerPid: defaultOwnerPid(),
53 - noBrowserTimeoutMs: 60_000,
54 - };
56 - for (let i = 0; i < argv.length; i++) {
57 - const arg = argv[i];
58 - if (arg === "--project-dir")
59 - options.projectDir =
60 - argv[++i] ?? usage("Missing value for --project-dir");
61 - else if (arg === "--host")
62 - options.host = argv[++i] ?? usage("Missing value for --host");
63 - else if (arg === "--url-host")
64 - options.urlHost = argv[++i] ?? usage("Missing value for --url-host");
65 - else if (arg === "--owner-pid")
66 - options.ownerPid = Number(
67 - argv[++i] ?? usage("Missing value for --owner-pid"),
68 - );
69 - else if (arg === "--no-browser-timeout-ms")
70 - options.noBrowserTimeoutMs = Number(
71 - argv[++i] ?? usage("Missing value for --no-browser-timeout-ms"),
72 - );
73 - else if (arg === "--help" || arg === "-h") usage();
74 - else usage(`Unknown argument: ${arg}`);
75 - }
77 - if (!options.urlHost) {
78 - options.urlHost =
79 - options.host === "127.0.0.1" || options.host === "localhost"
80 - ? "localhost"
81 - : options.host;
82 - }
84 - return options;
87 -function sleep(ms) {
88 - return new Promise((resolve) => setTimeout(resolve, ms));
91 -function appendRegistry(entry) {
92 - fs.mkdirSync(path.dirname(registryFile), { recursive: true });
93 - fs.appendFileSync(registryFile, `${JSON.stringify(entry)}\n`);
96 -async function waitForStart(stateDir, child, logFile) {
97 - const infoFile = path.join(stateDir, "server-info");
99 - for (let i = 0; i < 50; i++) {
100 - if (fs.existsSync(infoFile))
101 - return fs.readFileSync(infoFile, "utf8").trim();
102 - if (child.exitCode !== null) break;
103 - await sleep(100);
104 - }
106 - const log = fs.existsSync(logFile)
107 - ? fs.readFileSync(logFile, "utf8").trim()
108 - : "";
109 - const suffix = log ? `: ${log}` : "";
110 - throw new Error(`Server failed to start within 5 seconds${suffix}`);
113 -async function startServer(argv = process.argv.slice(2)) {
114 - const options = parseArgs(argv);
115 - const sessionId = `${process.pid}-${Math.floor(Date.now() / 1000)}`;
116 - const sessionDir = options.projectDir
117 - ? path.join(options.projectDir, ".super", "brainstorm", sessionId)
118 - : path.join(os.tmpdir(), `brainstorm-${sessionId}`);
119 - const contentDir = path.join(sessionDir, "content");
120 - const stateDir = path.join(sessionDir, "state");
121 - const pidFile = path.join(stateDir, "server.pid");
122 - const logFile = path.join(stateDir, "server.log");
124 - fs.mkdirSync(contentDir, { recursive: true });
125 - fs.mkdirSync(stateDir, { recursive: true });
127 - const log = fs.openSync(logFile, "a");
128 - const child = spawn(process.execPath, [path.join(scriptDir, "server.mjs")], {
129 - detached: true,
130 - stdio: ["ignore", log, log],
131 - env: {
132 - ...process.env,
133 - BRAINSTORM_DIR: sessionDir,
134 - BRAINSTORM_HOST: options.host,
135 - BRAINSTORM_URL_HOST: options.urlHost,
136 - BRAINSTORM_OWNER_PID: String(options.ownerPid),
137 - BRAINSTORM_NO_BROWSER_TIMEOUT_MS: String(options.noBrowserTimeoutMs),
138 - },
139 - });
141 - child.unref();
142 - fs.writeFileSync(pidFile, `${child.pid}\n`);
144 - try {
145 - const info = JSON.parse(await waitForStart(stateDir, child, logFile));
146 - fs.writeFileSync(path.join(stateDir, "owner"), `${options.ownerPid}\n`);
147 - appendRegistry({
148 - pid: child.pid,
149 - owner_pid: options.ownerPid,
150 - session_dir: sessionDir,
151 - url: info.url,
152 - started_at: Date.now(),
153 - });
154 - return info;
155 - } finally {
156 - fs.closeSync(log);
157 - }
160 -async function main() {
161 - console.log(
162 - JSON.stringify({
163 - error:
164 - "start-server.mjs is internal. Use companion.mjs start-choice or companion.mjs start-screen.",
165 - }),
166 - );
167 - process.exit(1);
170 -if (
171 - process.argv[1] &&
172 - import.meta.url === pathToFileURL(process.argv[1]).href
173 -) {
174 - main().catch((error) => {
175 - console.log(JSON.stringify({ error: error.message }));
176 - process.exit(1);
177 - });
180 -export { defaultOwnerPid, main, parentPid, parseArgs, startServer };

skills/super/brainstorming/scripts/stop-server.mjs

Deleted
deleted file mode 100755
1 -#!/usr/bin/env node
2 -import fs from "node:fs";
3 -import os from "node:os";
4 -import path from "node:path";
5 -import { pathToFileURL } from "node:url";
7 -function sleep(ms) {
8 - return new Promise((resolve) => setTimeout(resolve, ms));
9 -}
11 -function isAlive(pid) {
12 - try {
13 - process.kill(pid, 0);
14 - return true;
15 - } catch {
16 - return false;
17 - }
18 -}
20 -async function waitUntilDead(pid) {
21 - for (let i = 0; i < 20; i++) {
22 - if (!isAlive(pid)) return true;
23 - await sleep(100);
24 - }
25 - return false;
26 -}
28 -async function stop(sessionDir) {
29 - if (!sessionDir) return { error: "Usage: stop-server.mjs <session_dir>" };
31 - const stateDir = path.join(sessionDir, "state");
32 - const pidFile = path.join(stateDir, "server.pid");
33 - if (!fs.existsSync(pidFile)) return { status: "not_running" };
35 - const pid = Number(fs.readFileSync(pidFile, "utf8").trim());
36 - if (!Number.isInteger(pid) || pid <= 0)
37 - return { status: "failed", error: "invalid pid file" };
39 - if (isAlive(pid)) {
40 - process.kill(pid, "SIGTERM");
41 - if (!(await waitUntilDead(pid))) {
42 - process.kill(pid, "SIGKILL");
43 - await sleep(100);
44 - }
45 - }
47 - if (isAlive(pid)) return { status: "failed", error: "process still running" };
49 - fs.rmSync(pidFile, { force: true });
50 - fs.rmSync(path.join(stateDir, "server.log"), { force: true });
52 - const resolvedSession = path.resolve(sessionDir);
53 - const resolvedTmp = path.resolve(os.tmpdir());
54 - if (resolvedSession.startsWith(resolvedTmp + path.sep)) {
55 - fs.rmSync(sessionDir, { recursive: true, force: true });
56 - }
58 - return { status: "stopped" };
59 -}
61 -async function main(argv = process.argv.slice(2)) {
62 - const result = await stop(argv[0]);
63 - console.log(JSON.stringify(result));
64 - if (result.error) process.exit(1);
65 -}
67 -if (
68 - process.argv[1] &&
69 - import.meta.url === pathToFileURL(process.argv[1]).href
70 -) {
71 - main().catch((error) => {
72 - console.log(JSON.stringify({ status: "failed", error: error.message }));
73 - process.exit(1);
74 - });
75 -}
77 -export { stop };

skills/super/brainstorming/visual-companion.md

Deleted
deleted file mode 100644
1 -# Visual Companion Guide
3 -Browser-based visual brainstorming companion for showing mockups, diagrams, and options.
5 -## When to Use
7 -Decide per-question, not per-session. The test: **would the user understand this better by seeing it than reading it?**
9 -**Use the browser** when the content itself is visual:
11 -- **UI mockups** — wireframes, layouts, navigation structures, component designs
12 -- **Architecture diagrams** — system components, data flow, relationship maps
13 -- **Side-by-side visual comparisons** — comparing two layouts, two color schemes, two design directions
14 -- **Design polish** — when the question is about look and feel, spacing, visual hierarchy
15 -- **Spatial relationships** — state machines, flowcharts, entity relationships rendered as diagrams
17 -**Use the terminal** when the content is text or tabular:
19 -- **Requirements and scope questions** — "what does X mean?", "which features are in scope?"
20 -- **Conceptual A/B/C choices** — picking between approaches described in words
21 -- **Tradeoff lists** — pros/cons, comparison tables
22 -- **Technical decisions** — API design, data modeling, architectural approach selection
23 -- **Clarifying questions** — anything where the answer is words, not a visual preference
25 -A question _about_ a UI topic is not automatically a visual question. "What kind of wizard do you want?" is conceptual — use the terminal. "Which of these wizard layouts feels right?" is visual — use the browser.
27 -## After Visual Mode Starts
29 -After the first browser mockup, visual mode is sticky for UI shape decisions. Do not slide back into terminal questions for visual decisions.
31 -Before every terminal A/B/C question, classify it:
33 -- **Browser required** when options contain UI nouns that can be shown: editor, terminal, drawer, panel, rail, tab, toolbar, omnibox, composer, command palette, transcript, file view, diff view, action card, chip, sidebar, navigation, layout, placement, density, style.
34 -- **Terminal allowed** only for abstract requirements, scope, success metrics, implementation boundaries, or open-ended text that cannot be shown better as a mockup.
36 -Use the browser for questions about:
38 -- placement: right rail vs middle split vs overlay
39 -- layout: columns, panels, navigation, split sizes
40 -- visual hierarchy: what dominates, what is secondary
41 -- component arrangement: what sits near what
42 -- control presentation: unified input vs stacked inputs vs mode toggle vs palette
43 -- terminal behavior: bottom drawer vs right drawer vs inline transcript vs replacement view
44 -- density, spacing, polish, style, color, typography
46 -If the user asks "show me" or similar, stop explaining and create the mockup. Prefer a quick rough screen over a perfect terminal description.
48 -## How It Works
50 -The Node companion script starts the server, writes screens, waits for browser choices, lists/clears events, and pushes the terminal waiting screen. The server watches a directory for HTML files and serves the newest one to the browser. The user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` and read through `companion.mjs`.
52 -**Content fragments vs full documents:** If your HTML file starts with `<!DOCTYPE` or `<html`, the server serves it as-is (just injects the helper script). Otherwise, the server automatically wraps your content in the frame template — adding the header, CSS theme, selection indicator, and all interactive infrastructure. **Write content fragments by default.** Only write full documents when you need complete control over the page.
54 -## Starting a Session
56 -Do not start an empty browser companion. For first visual choices, prefer `open-choice` or `open-screen`: they start the server, load the first screen, open the browser, wait for the click, and return the selected event JSON. Use `start-choice` / `start-screen` only when automatic browser opening is unavailable or you intentionally need a non-blocking display.
58 -```bash
59 -# Start server, load first choice screen, open browser, and wait for click
60 -node scripts/companion.mjs open-choice \
61 - --project-dir /path/to/project \
62 - --name first-layout \
63 - --title "Which layout direction?" \
64 - --option "timeline|Timeline first|Session tree dominates" \
65 - --option "diff|Diff first|Review surface dominates"
67 -# Returns after click: {"type":"click","choice":"timeline","url":"http://localhost:52341",
68 -# "session_dir":"/path/to/project/.super/brainstorm/12345-1706000000",
69 -# "screen_file":".../content/first-layout.html"}
70 -```
72 -For custom first screens, create an HTML file with the Write tool, then:
74 -```bash
75 -node scripts/companion.mjs open-screen \
76 - --project-dir /path/to/project \
77 - --name first-mockup \
78 - --html-file /tmp/first-mockup.html
79 -```
81 -**Thinking time rule:** Do not use short blocking waits for visual decisions that need real thinking time: logo direction, style exploration, layout comparison, subjective polish, multi-option mockups, or anything the user may want to inspect. Blocking commands now default to 10 minutes and allow up to 1 hour, but for open-ended design thinking prefer `write-screen` or `start-screen`, give the URL, and later read clicks with `events`.
83 -**Human notes rule:** Every visual screen includes a human notes textarea. Browser click events include `humanNotes`; use those notes as first-class user feedback, not an afterthought. If the notes contradict the clicked option, ask one clarifying question or iterate toward the notes.
85 -**NON-NEGOTIABLE FIRST ACTION after any visual screen:** before replying, before reading files, before making new mockups, before explaining, run:
87 -```bash
88 -node scripts/companion.mjs listen --project-dir PROJECT --clear
89 -```
91 -This finds the newest project session, so there is no session ID for the agent to remember. Skipping this is a skill violation. Do not use `events SESSION_DIR` unless debugging the companion itself. Treat returned clicks and `humanNotes` as the user's current visual answer unless the terminal message explicitly overrides them. Never ask the user to repeat a clicked choice in chat. If there are no events, proceed from the terminal text.
93 -If `open-choice` / `open-screen` cannot open a browser in the current environment, fall back to `start-choice` / `start-screen`, save `session_dir` from the response, and tell the user to open the URL. Never use `start` alone; it is rejected because the browser would show the waiting page.
95 -**Finding connection info:** The server writes its startup JSON to `$STATE_DIR/server-info`. If you launched the server in the background and didn't capture stdout, read that file to get the URL and port. When using `--project-dir`, check `<project>/.super/brainstorm/` for the session directory.
97 -**Note:** Pass the project root as `--project-dir` so mockups persist in `.super/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.super/` to `.gitignore` if it's not already there.
99 -The launcher is a Node script and starts `server.mjs` in the background. Use the same command on macOS, Linux, and Windows. Prefer `companion.mjs` commands over hand-writing files or reading event files manually. Servers stop automatically when the owning Pi process exits, after browser disconnect timeout, or through `companion.mjs cleanup`.
101 -If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host on `open-choice`, `open-screen`, `start-choice`, or `start-screen`:
103 -```bash
104 -node scripts/companion.mjs open-choice \
105 - --project-dir /path/to/project \
106 - --host 0.0.0.0 \
107 - --url-host localhost \
108 - --name first-layout \
109 - --title "Which layout direction?" \
110 - --option "timeline|Timeline first|Session tree dominates" \
111 - --option "diff|Diff first|Review surface dominates"
112 -```
114 -Use `--url-host` to control what hostname is printed in the returned URL JSON.
116 -Lifecycle controls:
118 -```bash
119 -node scripts/companion.mjs open-choice --project-dir /path/to/project --owner-pid "$PPID" --no-browser-timeout-ms 60000 --name first --title "First question" --option "a|A|A" --option "b|B|B"
120 -node scripts/companion.mjs cleanup
121 -node scripts/companion.mjs stop "$SESSION_DIR"
122 -```
124 -`cleanup` reads the global registry and stops orphaned servers whose owner process is gone. `--no-browser-timeout-ms` stops the server after the browser has connected once and then all browser clients disconnect.
126 -## The Loop
128 -1. **For quick visual choices only, ask and wait in one deterministic command.** It checks the server, writes a fresh filename, clears old events, blocks for the browser click, then prints the selected event JSON. Do not use this path for subjective design thinking; use the thinking time rule above.
130 - ```bash
131 - node scripts/companion.mjs ask-choice "$SESSION_DIR" \
132 - --name layout \
133 - --title "Which layout works better?" \
134 - --subtitle "Consider readability and visual hierarchy" \
135 - --option "single|Single Column|Clean, focused reading experience" \
136 - --option "two|Two Column|Sidebar navigation with main content" \
137 - --timeout-ms 600000
138 - ```
140 - Do not tell the user "reply here after clicking" for normal visual choices. The click itself returns to the agent through the tool result while the turn is active. Use long waits for user-facing visual choices; never rush subjective decisions.
142 -2. **For custom visual choices, write HTML to a file, then ask and wait.** Do not embed large HTML in shell args or heredocs.
144 - ```bash
145 - # First create /tmp/layout-options.html with Write tool.
146 - node scripts/companion.mjs ask-screen "$SESSION_DIR" \
147 - --name layout-custom \
148 - --html-file /tmp/layout-options.html \
149 - --timeout-ms 600000
150 - ```
152 - The HTML must include clickable elements with `data-choice` and `onclick="toggleSelect(this)"`.
154 -3. **For display-only visuals, push a screen and end the turn:**
156 - ```bash
157 - # First create /tmp/custom-screen.html with Write tool.
158 - node scripts/companion.mjs write-screen "$SESSION_DIR" \
159 - --name layout-custom \
160 - --html-file /tmp/custom-screen.html
161 - ```
163 - Remind them of the URL and ask for terminal feedback only when the answer is open-ended text, not a choice.
165 -4. **For existing browser feedback, only use `listen`:**
167 - ```bash
168 - node scripts/companion.mjs listen --project-dir /path/to/project --clear
169 - node scripts/companion.mjs listen --project-dir /path/to/project --timeout-ms 600000 --clear
170 - ```
172 - Required before every response while visual mode is active. Merge browser events with any terminal text if both exist. Terminal text is primary only when it explicitly overrides browser feedback; otherwise browser clicks + `humanNotes` are primary.
174 -5. **Iterate or advance** — if feedback changes current screen, push a new screen name (e.g., `layout-v2`). Only move to the next question when the current step is validated.
176 -6. **Unload when returning to terminal** — when the next step doesn't need the browser, push the deterministic waiting screen:
178 - ```bash
179 - node scripts/companion.mjs waiting-screen "$SESSION_DIR" --name terminal
180 - ```
182 - This prevents the user from staring at a resolved choice while the conversation has moved on.
184 -7. Repeat until done.
186 -## Writing Content Fragments
188 -For custom HTML/CSS mockups, use the `web-ui` skill if available. Keep screens plain HTML/CSS with minimal JS, semantic regions, strong visual hierarchy, and real UI shapes rather than text lists in boxes.
190 -Use `ask-choice` for ordinary A/B/C questions. Use `ask-screen --html-file` for custom clickable mockups. Use `choice-screen` only when you intentionally want to display choices without blocking for a click. Use `write-screen --html-file` only when you need custom display-only markup. Write just the content that goes inside the page. The server wraps it in the frame template automatically (header, theme CSS, selection indicator, and all interactive infrastructure).
192 -**Minimal example:**
194 -```html
195 -<h2>Which layout works better?</h2>
196 -<p class="subtitle">Consider readability and visual hierarchy</p>
198 -<div class="options">
199 - <div class="option" data-choice="a" onclick="toggleSelect(this)">
200 - <div class="letter">A</div>
201 - <div class="content">
202 - <h3>Single Column</h3>
203 - <p>Clean, focused reading experience</p>
204 - </div>
205 - </div>
206 - <div class="option" data-choice="b" onclick="toggleSelect(this)">
207 - <div class="letter">B</div>
208 - <div class="content">
209 - <h3>Two Column</h3>
210 - <p>Sidebar navigation with main content</p>
211 - </div>
212 - </div>
213 -</div>
214 -```
216 -That's it. No `<html>`, no CSS, no `<script>` tags needed. The server provides all of that.
218 -## CSS Classes Available
220 -The frame template provides these CSS classes for your content:
222 -### Options (A/B/C choices)
224 -```html
225 -<div class="options">
226 - <div class="option" data-choice="a" onclick="toggleSelect(this)">
227 - <div class="letter">A</div>
228 - <div class="content">
229 - <h3>Title</h3>
230 - <p>Description</p>
231 - </div>
232 - </div>
233 -</div>
234 -```
236 -**Multi-select:** Add `data-multiselect` to the container to let users select multiple options. Each click toggles the item. The indicator bar shows the count.
238 -```html
239 -<div class="options" data-multiselect>
240 - <!-- same option markup — users can select/deselect multiple -->
241 -</div>
242 -```
244 -### Cards (visual designs)
246 -```html
247 -<div class="cards">
248 - <div class="card" data-choice="design1" onclick="toggleSelect(this)">
249 - <div class="card-image"><!-- mockup content --></div>
250 - <div class="card-body">
251 - <h3>Name</h3>
252 - <p>Description</p>
253 - </div>
254 - </div>
255 -</div>
256 -```
258 -### Mockup container
260 -```html
261 -<div class="mockup">
262 - <div class="mockup-header">Preview: Dashboard Layout</div>
263 - <div class="mockup-body"><!-- your mockup HTML --></div>
264 -</div>
265 -```
267 -### Split view (side-by-side)
269 -```html
270 -<div class="split">
271 - <div class="mockup"><!-- left --></div>
272 - <div class="mockup"><!-- right --></div>
273 -</div>
274 -```
276 -### Pros/Cons
278 -```html
279 -<div class="pros-cons">
280 - <div class="pros">
281 - <h4>Pros</h4>
282 - <ul><li>Benefit</li></ul>
283 - </div>
284 - <div class="cons">
285 - <h4>Cons</h4>
286 - <ul><li>Drawback</li></ul>
287 - </div>
288 -</div>
289 -```
291 -### Mock elements (wireframe building blocks)
293 -```html
294 -<div class="mock-nav">Logo | Home | About | Contact</div>
295 -<div style="display: flex">
296 - <div class="mock-sidebar">Navigation</div>
297 - <div class="mock-content">Main content area</div>
298 -</div>
299 -<button class="mock-button">Action Button</button>
300 -<input class="mock-input" placeholder="Input field">
301 -<div class="placeholder">Placeholder area</div>
302 -```
304 -### Typography and sections
306 -- `h2` — page title
307 -- `h3` — section heading
308 -- `.subtitle` — secondary text below title
309 -- `.section` — content block with bottom margin
310 -- `.label` — small uppercase label text
312 -## Browser Events Format
314 -When the user clicks options in the browser, their interactions are recorded to `$STATE_DIR/events` (one JSON object per line). The file is cleared automatically when you push a new screen.
316 -```jsonl
317 -{"type":"click","choice":"a","text":"Option A - Simple Layout","timestamp":1706000101}
318 -{"type":"click","choice":"c","text":"Option C - Complex Grid","timestamp":1706000108}
319 -{"type":"click","choice":"b","text":"Option B - Hybrid","timestamp":1706000115}
320 -```
322 -The full event stream shows the user's exploration path — they may click multiple options before settling. The last `choice` event is typically the final selection, but the pattern of clicks can reveal hesitation or preferences worth asking about.
324 -If `$STATE_DIR/events` doesn't exist, the user didn't interact with the browser — use only their terminal text.
326 -## Design Tips
328 -- **Scale fidelity to the question** — wireframes for layout, polish for polish questions
329 -- **Explain the question on each page** — "Which layout feels more professional?" not just "Pick one"
330 -- **Iterate before advancing** — if feedback changes current screen, write a new version
331 -- **2-4 options max** per screen
332 -- **Use real content when it matters** — for a photography portfolio, use actual images (Unsplash). Placeholder content obscures design issues.
333 -- **Keep mockups simple** — focus on layout and structure, not pixel-perfect design
335 -## File Naming
337 -- Use semantic names: `platform.html`, `visual-style.html`, `layout.html`
338 -- Never reuse filenames — each screen must be a new file
339 -- For iterations: append version suffix like `layout-v2.html`, `layout-v3.html`
340 -- Server serves newest file by modification time
342 -## Cleaning Up
344 -```bash
345 -node scripts/companion.mjs stop $SESSION_DIR
346 -```
348 -If the session used `--project-dir`, mockup files persist in `.super/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.
350 -## Reference
352 -- Frame template (CSS reference): `scripts/frame-template.html`
353 -- Helper script (client-side): `scripts/helper.js`

skills/web-ui/SKILL.md

Modified
89 89 - architecture-diagram: inline SVG works well for diagrams; no canvas/lib needed.
90 90 - Repo examples:
91 91 - `extensions/diff-review/browser/`: real app shell, semantic panes, theme vars, aria labels, splitters.
92 - - `skills/super/brainstorming/scripts/frame-template.html`: reusable mockup/card/option primitives.
92 + - `extensions/super/mockup.ts`: reusable mockup frame/card/drawer primitives.
93 93 - `pilot-desk/site/index.html`: tight single-file landing page.
94 94 - `pilot-desk/src/main/resources/theme.css`: brutal mono cockpit language.
138 -### Clickable mockup cards
138 +### Clickable cards
140 140 ```html
141 141 <div class="cards">
142 - <button class="card" data-choice="a">
142 + <button class="card" type="button">
143 143 <strong>A · Command Center</strong>
144 144 <span>Transcript → prompt → terminal, one vertical loop.</span>
145 145 </button>
146 146 </div>
149 -Use real `<button>` for choices unless a host helper requires `onclick="toggleSelect(this)"`.
149 +Use real `<button>` for standalone page choices.
150 +For `mockup` tool fragments, do not add card-selection plumbing; the tool frame owns it.
151 152 ### Inline SVG diagram
179 180 - No giant unstructured style soup: group CSS by tokens, base, layout, components, state, responsive.
180 181 - No fragile shell heredocs for large HTML; write files directly.
181 182 - Before final answer, scan for literal `:focus-visible`; add it if missing.
182 -- If used in brainstorming visual companion, include clickable `data-choice` targets and keep labels readable at browser zoom.
183 +- If creating a `mockup` tool fragment for brainstorming, output only the card fragment; the tool owns card selection, notes, annotations, and submit controls.
184 185 ## Common Failures