repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

super: improves brainstorm skill with better live html previews

6b41c8ccc2d9b9ccec0cf4cfc4233cbfbfb6cdc2

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (16)

.pi/prompts/live-extension-test.md

Modified
319 319 This is expected to take time.
320 320 Be thorough.
321 +Thorough ≠ idle.
322 +Waiting is allowed only when tied to observable progress.
324 +## Timeout + Wait Budget
326 +Use short, intelligent, condition-based waits.
327 +Do not choose huge defensive timeouts.
329 +Defaults:
331 +- shell/local commands: 5–15s unless known slow
332 +- Pi startup/readiness: 15s
333 +- UI settle after a keypress: 0.2–1s
334 +- browser navigation/DOM readiness: 10–15s
335 +- ordinary build/test/probe: 30s
336 +- nested model no-progress limit: 60s, then capture evidence and interrupt/escalate
338 +Rules:
340 +- Prefer polling `pane_current_command`, files, session JSONL, process state, DOM state, or network state over sleeping.
341 +- Check progress every 5–10s for long model/tool runs.
342 +- Any timeout >30s must be written in notes with reason, expected progress signal, and stop condition.
343 +- Any timeout >120s needs explicit scenario justification; otherwise it is a harness bug.
344 +- If blocked, fail fast with evidence instead of waiting minutes silently.
322 346 ## Browser UI Testing

CHANGELOG.md

Modified
22 22 - Trim and harden the tmux skill with pane-ID tracking, readiness gates, safe input helpers, polluted-pane quarantine, and bounded stop guidance
23 23 - Remove obsolete tmux agent workflow and tooling migration planning notes
24 24 - Remove stale provider test prompt templates that hardcoded an old `/tmp` findings file
25 +- Stop exporting prompt templates from the goal extension package
26 +- Convert brainstorming visual companion server and launchers from CommonJS/shell scripts to cross-platform ESM `.mjs` Node scripts
27 +- Add deterministic brainstorming companion commands for start/stop, choice screens, custom screens, waiting screens, event listing/clearing, waiting for browser choices, and per-screen event reset
28 +- Add brainstorming `open-choice` and `open-screen` for first visual choices that open the browser and wait for the click in one command
29 +- Reject empty brainstorming visual companion starts and direct `start-server.mjs` CLI use
30 +- Cap brainstorming visual wait timeouts at 30000ms
31 +- Add brainstorming `ask-choice` to write a fresh choice screen, clear old events, wait for browser click, and return the selected event without terminal reply
32 +- Add brainstorming `ask-screen --html-file` for custom clickable mockups that wait for browser choice without shell heredocs or terminal replies
33 +- Add `write-screen --html-file` and `companion.mjs --help` for deterministic brainstorming visual workflows
34 +- Fix brainstorming visual event clearing to avoid delayed server-side races after new screens
35 +- Add brainstorming companion lifecycle cleanup with owner PID tracking, global server registry, orphan cleanup, and browser disconnect timeout
36 +- Shorten the brainstorming browser-visuals consent prompt to a terse opt-in question
37 +- Make brainstorming visual mode sticky after the first browser mockup and require browser mockups for follow-up UI shape, placement, control presentation, composer, and terminal behavior choices
38 +- Point brainstorming visual companion guide references at the explicit skill path
39 +- Add the `web-ui` skill for standalone HTML/CSS UI, visual mockups, dashboards, landing pages, and no-build tools with minimal vanilla JS and no default frameworks
40 +- Harden `web-ui` guidance to require complete standalone HTML documents, representative one-screen first passes, root CSS tokens, mandatory `:focus-visible`, and bounded static slices for complex viewers, traces, and graphs
41 +- Route custom brainstorming HTML/CSS mockups through `web-ui` guidance when available
42 +- Add brainstorming visual companion Node test coverage for the human-agent browser workflow, reloads, events, assets, screen rendering, lifecycle cleanup, help output, file-backed screens, deterministic open commands, timeout caps, and `npm run test:brainstorming`
43 +- Add `mise run clean` for generated caches and scratch artifacts, clearing `.demo/` contents while keeping the directory and removing `node_modules`, `__pycache__`, `.ruff_cache`, and `extensions/diff-review/static/`
26 45 ## 0.0.3

mise.toml

Modified
53 53 description = "Record demo GIFs"
54 54 run = "python3 scripts/demo.py \"$@\""
56 +[tasks.clean]
57 +description = "Remove generated caches and scratch artifacts"
58 +run = '''
59 +mkdir -p .demo
60 +find .demo -mindepth 1 -maxdepth 1 -exec rm -rf {} +
61 +find . -path ./.git -prune -o -path ./.jj -prune -o -type d -name node_modules -prune -exec rm -rf {} +
62 +find . -path ./.git -prune -o -path ./.jj -prune -o -type d -name __pycache__ -prune -exec rm -rf {} +
63 +rm -rf .ruff_cache extensions/diff-review/static
64 +'''
56 66 [tasks.publish]
57 67 description = "Publish after release gate"
58 68 depends = ["ci"]

package.json

Modified
2 2 "scripts": {
3 - "typecheck": "tsc --noEmit"
3 + "typecheck": "tsc --noEmit",
4 + "test:brainstorming": "node --test skills/super/brainstorming/scripts/companion.test.mjs"
5 6 "name": "pi-ext",
6 7 "version": "0.0.3",

skills/super/brainstorming/SKILL.md

Modified
151 151 A browser-based companion for showing mockups, diagrams, and visual options during brainstorming. Available as a tool — not a mode. Accepting the companion means it's available for questions that benefit from visual treatment; it does NOT mean every question goes through the browser.
153 -**Offering the companion:** When you anticipate that upcoming questions will involve visual content (mockups, layouts, diagrams), offer it once for consent:
154 -> "Some of what we're working on might be easier to explain if I can show it to you in a web browser. I can put together mockups, diagrams, comparisons, and other visuals as we go. This feature is still new and can be token-intensive. Want to try it? (Requires opening a local URL)"
153 +**Offering the companion:** When upcoming questions are genuinely visual (mockups, layouts, diagrams), ask once, tersely:
154 +> "Use browser visuals for the visual parts?"
156 156 **This offer MUST be its own message.** Do not combine it with clarifying questions, context summaries, or any other content. The message should contain ONLY the offer above and nothing else. Wait for the user's response before continuing. If they decline, proceed with text-only brainstorming.
160 160 - **Use the browser** for content that IS visual — mockups, wireframes, layout comparisons, architecture diagrams, side-by-side visual designs
161 161 - **Use the terminal** for content that is text — requirements questions, conceptual choices, tradeoff lists, A/B/C/D text options, scope decisions
163 -A question about a UI topic is not automatically a visual question. "What does personality mean in this context?" is a conceptual question — use the terminal. "Which wizard layout works better?" is a visual question — use the browser.
163 +Once a browser session has shown its first mockup, visual mode is sticky for UI shape decisions. Before asking any terminal A/B/C question, classify it:
165 -If they agree to the companion, read the detailed guide before proceeding:
166 -`skills/brainstorming/visual-companion.md`
165 +- **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.
166 +- **Terminal allowed** only for abstract intent/scope/success metrics or non-visual implementation boundaries.
168 +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.
170 +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.
172 +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.
174 +If they agree to the companion, read the sibling guide in this skill directory before proceeding:
175 +`skills/super/brainstorming/visual-companion.md`
177 +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".

skills/super/brainstorming/scripts/companion.mjs

Added
new file mode 100755
1 +#!/usr/bin/env node
2 +import { spawn } from 'node:child_process';
3 +import fs from 'node:fs';
4 +import path from 'node:path';
5 +import { pathToFileURL } from 'node:url';
6 +import os from 'node:os';
7 +import { startServer } from './start-server.mjs';
8 +import { stop } from './stop-server.mjs';
10 +const registryFile = path.join(os.homedir(), '.local', 'state', 'pi', 'brainstorm-companion', 'servers.jsonl');
12 +const helpText = `Usage: companion.mjs <command> [args]
14 +Commands:
15 + start-choice --project-dir DIR --name NAME --title TITLE --option choice|title|description
16 + start-screen --project-dir DIR --name NAME (--html HTML | --html-file FILE)
17 + open-choice --project-dir DIR --name NAME --title TITLE --option choice|title|description [--timeout-ms MS<=30000]
18 + open-screen --project-dir DIR --name NAME (--html HTML | --html-file FILE) [--timeout-ms MS<=30000]
19 + stop SESSION_DIR
20 + cleanup
21 + write-screen SESSION_DIR --name NAME (--html HTML | --html-file FILE)
22 + choice-screen SESSION_DIR --name NAME --title TITLE [--subtitle TEXT] --option choice|title|description [--multi]
23 + ask-choice SESSION_DIR --name NAME --title TITLE [--subtitle TEXT] --option choice|title|description [--timeout-ms MS<=30000]
24 + ask-screen SESSION_DIR --name NAME (--html HTML | --html-file FILE) [--timeout-ms MS<=30000]
25 + waiting-screen SESSION_DIR --name NAME
26 + events SESSION_DIR [--clear]
27 + wait-choice SESSION_DIR [--timeout-ms MS<=30000]
28 +`;
30 +function die(message) {
31 + console.log(JSON.stringify({ error: message }));
32 + process.exit(1);
35 +function help() {
36 + console.log(helpText);
39 +function parseFlags(argv) {
40 + const flags = { _: [] };
41 + for (let i = 0; i < argv.length; i++) {
42 + const arg = argv[i];
43 + if (!arg.startsWith('--')) flags._.push(arg);
44 + else if (arg === '--clear' || arg === '--multi') flags[arg.slice(2)] = true;
45 + else {
46 + const key = arg.slice(2);
47 + const value = argv[++i];
48 + if (value === undefined) die(`Missing value for ${arg}`);
49 + if (flags[key] === undefined) flags[key] = value;
50 + else if (Array.isArray(flags[key])) flags[key].push(value);
51 + else flags[key] = [flags[key], value];
52 + }
53 + }
54 + return flags;
57 +function sessionPaths(sessionDir) {
58 + if (!sessionDir) die('Missing session_dir');
59 + const contentDir = path.join(sessionDir, 'content');
60 + const stateDir = path.join(sessionDir, 'state');
61 + return { sessionDir, contentDir, stateDir, eventsFile: path.join(stateDir, 'events') };
64 +function requireAlive(paths) {
65 + if (!fs.existsSync(path.join(paths.stateDir, 'server-info'))) die('Brainstorm server is not running; start it first.');
68 +function screenName(name) {
69 + const base = name || `screen-${Date.now()}`;
70 + if (!/^[a-zA-Z0-9._-]+$/.test(base)) die('Screen name must contain only letters, numbers, dot, underscore, or dash.');
71 + return base.endsWith('.html') ? base.slice(0, -5) : base;
74 +function uniqueScreenPath(contentDir, name) {
75 + const base = screenName(name);
76 + let candidate = path.join(contentDir, `${base}.html`);
77 + for (let i = 2; fs.existsSync(candidate); i++) candidate = path.join(contentDir, `${base}-${i}.html`);
78 + return candidate;
81 +function escapeHtml(value) {
82 + return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&#39;');
85 +function parseOption(value) {
86 + const [choice, title, description = ''] = String(value).split('|');
87 + if (!choice || !title) die(`Invalid --option ${value}; expected choice|title|description`);
88 + return { choice, title, description };
91 +function htmlFromFlags(flags) {
92 + if (flags.html !== undefined) return flags.html;
93 + if (flags['html-file'] !== undefined) return fs.readFileSync(flags['html-file'], 'utf8');
94 + die('Missing --html or --html-file');
97 +function timeoutMs(flags) {
98 + const value = Number(flags['timeout-ms'] ?? 30_000);
99 + if (!Number.isFinite(value) || value <= 0) die('--timeout-ms must be a positive number');
100 + if (value > 30_000) die('--timeout-ms max is 30000ms');
101 + return value;
104 +function renderChoiceScreen({ title, subtitle = '', options, multi = false }) {
105 + if (!title) die('Missing --title');
106 + if (options.length === 0) die('At least one --option is required');
107 + const attrs = multi ? ' data-multiselect' : '';
108 + const body = options.map((option, index) => {
109 + const letter = String.fromCharCode(65 + index);
110 + const id = `option-${escapeHtml(option.choice)}`;
111 + 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>`;
112 + }).join('\n');
114 + return `<h2>${escapeHtml(title)}</h2>\n${subtitle ? `<p class="subtitle">${escapeHtml(subtitle)}</p>\n` : ''}\n<div class="options"${attrs}>\n${body}\n</div>\n`;
117 +function writeScreen(sessionDir, name, html, { quiet = false } = {}) {
118 + const paths = sessionPaths(sessionDir);
119 + requireAlive(paths);
120 + fs.mkdirSync(paths.contentDir, { recursive: true });
121 + fs.rmSync(paths.eventsFile, { force: true });
122 + const file = uniqueScreenPath(paths.contentDir, name);
123 + fs.writeFileSync(file, html);
124 + const result = { status: 'screen-written', file };
125 + if (!quiet) console.log(JSON.stringify(result));
126 + return result;
129 +function readEvents(eventsFile) {
130 + if (!fs.existsSync(eventsFile)) return [];
131 + return fs.readFileSync(eventsFile, 'utf8')
132 + .split('\n')
133 + .filter(Boolean)
134 + .map(line => JSON.parse(line));
137 +function sleep(ms) {
138 + return new Promise(resolve => setTimeout(resolve, ms));
141 +function isAlive(pid) {
142 + try {
143 + process.kill(pid, 0);
144 + return true;
145 + } catch {
146 + return false;
150 +function registryEntries() {
151 + if (!fs.existsSync(registryFile)) return [];
152 + return fs.readFileSync(registryFile, 'utf8')
153 + .split('\n')
154 + .filter(Boolean)
155 + .map(line => JSON.parse(line));
158 +function writeRegistry(entries) {
159 + fs.mkdirSync(path.dirname(registryFile), { recursive: true });
160 + fs.writeFileSync(registryFile, entries.map(entry => JSON.stringify(entry)).join('\n') + (entries.length ? '\n' : ''));
163 +async function cleanup() {
164 + const kept = [];
165 + const stopped = [];
167 + for (const entry of registryEntries()) {
168 + if (!isAlive(entry.pid)) continue;
169 + if (entry.owner_pid && isAlive(entry.owner_pid)) {
170 + kept.push(entry);
171 + continue;
174 + await stop(entry.session_dir);
175 + stopped.push({ session_dir: entry.session_dir, pid: entry.pid, reason: 'owner_dead' });
178 + writeRegistry(kept);
179 + console.log(JSON.stringify({ stopped, kept }));
182 +async function waitChoiceEvent(sessionDir, timeoutMs) {
183 + const { eventsFile } = sessionPaths(sessionDir);
184 + const deadline = Date.now() + timeoutMs;
185 + while (Date.now() <= deadline) {
186 + const choices = readEvents(eventsFile).filter(event => event.choice);
187 + if (choices.length > 0) return choices.at(-1);
188 + await sleep(50);
190 + die(`Timed out waiting for choice after ${timeoutMs}ms`);
193 +async function waitChoice(sessionDir, timeoutMs) {
194 + console.log(JSON.stringify(await waitChoiceEvent(sessionDir, timeoutMs)));
197 +function openUrl(url) {
198 + if (process.env.BRAINSTORM_NO_OPEN === '1') return;
199 + const command = process.env.BRAINSTORM_OPEN_CMD || (process.platform === 'darwin' ? 'open' : 'xdg-open');
200 + try {
201 + const child = spawn(command, [url], { detached: true, stdio: 'ignore' });
202 + child.unref();
203 + } catch {
204 + // Opening is best-effort. URL remains available in returned JSON for fallback.
208 +function splitStartArgs(args) {
209 + const startArgs = [];
210 + const screenArgs = [];
211 + const startFlags = new Set(['--project-dir', '--host', '--url-host', '--owner-pid', '--no-browser-timeout-ms']);
212 + for (let i = 0; i < args.length; i++) {
213 + const arg = args[i];
214 + if (startFlags.has(arg)) {
215 + startArgs.push(arg, args[++i] ?? die(`Missing value for ${arg}`));
216 + } else {
217 + screenArgs.push(arg);
220 + return { startArgs, screenArgs };
223 +async function startWithScreen(args, renderHtml, { wait = false } = {}) {
224 + const { startArgs, screenArgs } = splitStartArgs(args);
225 + const info = await startServer(startArgs);
226 + const sessionDir = path.dirname(info.screen_dir);
227 + const flags = parseFlags(screenArgs);
228 + const written = writeScreen(sessionDir, flags.name, renderHtml(flags), { quiet: true });
229 + const context = { ...info, session_dir: sessionDir, screen_file: written.file };
230 + if (!wait) {
231 + console.log(JSON.stringify(context));
232 + return;
234 + openUrl(info.url);
235 + const event = await waitChoiceEvent(sessionDir, timeoutMs(flags));
236 + console.log(JSON.stringify({ ...event, session_dir: sessionDir, url: info.url, screen_file: written.file }));
239 +async function main(argv = process.argv.slice(2)) {
240 + const [command, ...rest] = argv;
241 + if (!command || command === '--help' || command === '-h' || command === 'help') {
242 + help();
243 + return;
246 + if (command === 'start') die('Use start-choice or start-screen so the browser never opens to an empty waiting page.');
248 + if (command === 'start-choice') {
249 + await startWithScreen(rest, flags => {
250 + const options = [flags.option ?? []].flat().filter(Boolean).map(parseOption);
251 + return renderChoiceScreen({ title: flags.title, subtitle: flags.subtitle, options, multi: Boolean(flags.multi) });
252 + });
253 + return;
256 + if (command === 'start-screen') {
257 + await startWithScreen(rest, htmlFromFlags);
258 + return;
261 + if (command === 'open-choice') {
262 + await startWithScreen(rest, flags => {
263 + const options = [flags.option ?? []].flat().filter(Boolean).map(parseOption);
264 + return renderChoiceScreen({ title: flags.title, subtitle: flags.subtitle, options, multi: Boolean(flags.multi) });
265 + }, { wait: true });
266 + return;
269 + if (command === 'open-screen') {
270 + await startWithScreen(rest, htmlFromFlags, { wait: true });
271 + return;
274 + if (command === 'stop') {
275 + const result = await stop(rest[0]);
276 + console.log(JSON.stringify(result));
277 + if (result.error) process.exit(1);
278 + return;
281 + if (command === 'cleanup') {
282 + await cleanup();
283 + return;
286 + if (command === 'write-screen') {
287 + const [sessionDir, ...args] = rest;
288 + const flags = parseFlags(args);
289 + writeScreen(sessionDir, flags.name, htmlFromFlags(flags));
290 + return;
293 + if (command === 'choice-screen') {
294 + const [sessionDir, ...args] = rest;
295 + const flags = parseFlags(args);
296 + const options = [flags.option ?? []].flat().filter(Boolean).map(parseOption);
297 + writeScreen(sessionDir, flags.name, renderChoiceScreen({ title: flags.title, subtitle: flags.subtitle, options, multi: Boolean(flags.multi) }));
298 + return;
301 + if (command === 'waiting-screen') {
302 + const [sessionDir, ...args] = rest;
303 + const flags = parseFlags(args);
304 + writeScreen(sessionDir, flags.name, '<div style="display:flex;align-items:center;justify-content:center;min-height:60vh">\n <p class="subtitle">Continuing in terminal...</p>\n</div>\n');
305 + return;
308 + if (command === 'events') {
309 + const [sessionDir, ...args] = rest;
310 + const flags = parseFlags(args);
311 + const { eventsFile } = sessionPaths(sessionDir);
312 + const events = readEvents(eventsFile);
313 + if (flags.clear) fs.rmSync(eventsFile, { force: true });
314 + console.log(JSON.stringify(events));
315 + return;
318 + if (command === 'wait-choice') {
319 + const [sessionDir, ...args] = rest;
320 + const flags = parseFlags(args);
321 + await waitChoice(sessionDir, timeoutMs(flags));
322 + return;
325 + if (command === 'ask-choice') {
326 + const [sessionDir, ...args] = rest;
327 + const flags = parseFlags(args);
328 + const options = [flags.option ?? []].flat().filter(Boolean).map(parseOption);
329 + writeScreen(sessionDir, flags.name, renderChoiceScreen({ title: flags.title, subtitle: flags.subtitle, options, multi: Boolean(flags.multi) }), { quiet: true });
330 + await waitChoice(sessionDir, timeoutMs(flags));
331 + return;
334 + if (command === 'ask-screen') {
335 + const [sessionDir, ...args] = rest;
336 + const flags = parseFlags(args);
337 + writeScreen(sessionDir, flags.name, htmlFromFlags(flags), { quiet: true });
338 + await waitChoice(sessionDir, timeoutMs(flags));
339 + return;
342 + die(`Unknown command: ${command}`);
345 +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
346 + main().catch(error => die(error.message));
349 +export { cleanup, main, parseFlags, renderChoiceScreen, readEvents };

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

Added
new file mode 100644
1 +import assert from 'node:assert/strict';
2 +import crypto from 'node:crypto';
3 +import fs from 'node:fs';
4 +import http from 'node:http';
5 +import os from 'node:os';
6 +import path from 'node:path';
7 +import { execFile, spawn } from 'node:child_process';
8 +import { promisify } from 'node:util';
9 +import test from 'node:test';
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(process.execPath, [path.join(scriptDir, script), ...args], {
17 + timeout: options.timeout ?? 10_000,
18 + maxBuffer: 1024 * 1024,
19 + env: { ...process.env, ...(options.env ?? {}) },
20 + });
23 +function tmpProject() {
24 + return fs.mkdtempSync(path.join(os.tmpdir(), 'brainstorm-companion-'));
27 +async function start(projectDir) {
28 + const first = path.join(projectDir, 'first.html');
29 + fs.writeFileSync(first, '<h2>Ready</h2>');
30 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--name', 'ready', '--html-file', first]);
31 + const info = JSON.parse(stdout.trim());
32 + return { ...info, session_dir: info.session_dir ?? path.dirname(info.screen_dir) };
35 +async function stop(sessionDir) {
36 + return runNode('companion.mjs', ['stop', sessionDir]).catch(() => {});
39 +async function withSession(fn) {
40 + const projectDir = tmpProject();
41 + let info;
42 + try {
43 + info = await start(projectDir);
44 + await fn(info, projectDir);
45 + } finally {
46 + if (info) await stop(info.session_dir);
47 + fs.rmSync(projectDir, { recursive: true, force: true });
48 + }
51 +function encodeClientTextFrame(value) {
52 + const payload = Buffer.from(JSON.stringify(value));
53 + const header = payload.length < 126 ? Buffer.alloc(2) : Buffer.alloc(4);
54 + header[0] = 0x80 | OPCODES.TEXT;
55 + if (payload.length < 126) header[1] = 0x80 | payload.length;
56 + else {
57 + header[1] = 0x80 | 126;
58 + header.writeUInt16BE(payload.length, 2);
59 + }
60 + const mask = crypto.randomBytes(4);
61 + const masked = Buffer.alloc(payload.length);
62 + for (let i = 0; i < payload.length; i++) masked[i] = payload[i] ^ mask[i % 4];
63 + return Buffer.concat([header, mask, masked]);
66 +function decodeServerTextFrame(buffer) {
67 + if (buffer.length < 2) return null;
68 + const opcode = buffer[0] & 0x0F;
69 + let payloadLen = buffer[1] & 0x7F;
70 + let offset = 2;
71 + if (payloadLen === 126) {
72 + if (buffer.length < 4) return null;
73 + payloadLen = buffer.readUInt16BE(2);
74 + offset = 4;
75 + }
76 + const end = offset + payloadLen;
77 + if (buffer.length < end) return null;
78 + return { opcode, payload: buffer.subarray(offset, end) };
81 +function wsSendText(port, event) {
82 + return new Promise((resolve, reject) => {
83 + const key = crypto.randomBytes(16).toString('base64');
84 + const req = http.request({
85 + port,
86 + host: 'localhost',
87 + headers: {
88 + Connection: 'Upgrade',
89 + Upgrade: 'websocket',
90 + 'Sec-WebSocket-Version': '13',
91 + 'Sec-WebSocket-Key': key,
92 + },
93 + });
95 + req.on('upgrade', (_res, socket) => {
96 + socket.write(encodeClientTextFrame(event));
97 + setTimeout(() => {
98 + socket.destroy();
99 + resolve();
100 + }, 50).unref();
101 + });
102 + req.on('error', reject);
103 + req.end();
104 + });
107 +function wsListenForReload(port) {
108 + return new Promise((resolve, reject) => {
109 + const key = crypto.randomBytes(16).toString('base64');
110 + const req = http.request({
111 + port,
112 + host: 'localhost',
113 + headers: {
114 + Connection: 'Upgrade',
115 + Upgrade: 'websocket',
116 + 'Sec-WebSocket-Version': '13',
117 + 'Sec-WebSocket-Key': key,
118 + },
119 + });
121 + req.on('upgrade', (_res, socket) => {
122 + let buffer = Buffer.alloc(0);
123 + socket.on('data', chunk => {
124 + buffer = Buffer.concat([buffer, chunk]);
125 + const frame = decodeServerTextFrame(buffer);
126 + if (frame?.opcode === OPCODES.TEXT) {
127 + socket.destroy();
128 + resolve(JSON.parse(frame.payload.toString()));
130 + });
131 + });
132 + req.on('error', reject);
133 + setTimeout(() => reject(new Error('timed out waiting for reload')), 3000).unref();
134 + req.end();
135 + });
138 +test('visual companion launchers are pure Node scripts', () => {
139 + assert.equal(fs.existsSync(path.join(scriptDir, 'companion.mjs')), true);
140 + assert.equal(fs.existsSync(path.join(scriptDir, 'start-server.mjs')), true);
141 + assert.equal(fs.existsSync(path.join(scriptDir, 'stop-server.mjs')), true);
142 + assert.equal(fs.existsSync(path.join(scriptDir, 'start-server.sh')), false);
143 + assert.equal(fs.existsSync(path.join(scriptDir, 'stop-server.sh')), false);
144 +});
146 +test('internal start-server CLI is rejected to avoid empty browser sessions', async () => {
147 + await assert.rejects(
148 + runNode('start-server.mjs', ['--project-dir', tmpProject()]),
149 + error => {
150 + assert.match(error.stdout, /start-server\.mjs is internal/);
151 + assert.match(error.stdout, /start-choice/);
152 + return true;
153 + },
154 + );
155 +});
157 +test('human-agent workflow: script renders choices, UI event arrives while agent waits', async () => {
158 + await withSession(async info => {
159 + await runNode('companion.mjs', [
160 + 'choice-screen', info.session_dir,
161 + '--name', 'approaches',
162 + '--title', 'Which approach?',
163 + '--subtitle', 'Pick one direction',
164 + '--option', 'a|Small|Minimal change',
165 + '--option', 'b|Large|Broad redesign',
166 + ]);
168 + const html = await (await fetch(info.url)).text();
169 + assert.match(html, /Which approach\?/);
170 + assert.match(html, /data-choice="a"/);
171 + assert.match(html, /Minimal change/);
172 + assert.match(html, /function\(\) \{/);
174 + const waiting = runNode('companion.mjs', ['wait-choice', info.session_dir, '--timeout-ms', '3000']);
175 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'Large', id: 'option-b' });
176 + const result = JSON.parse((await waiting).stdout.trim());
178 + assert.equal(result.choice, 'b');
179 + assert.equal(result.text, 'Large');
180 + assert.equal(result.id, 'option-b');
181 + });
182 +});
184 +test('companion has help for deterministic workflow commands', async () => {
185 + const { stdout } = await runNode('companion.mjs', ['--help']);
186 + assert.match(stdout, /start-choice/);
187 + assert.match(stdout, /start-screen/);
188 + assert.match(stdout, /open-choice/);
189 + assert.match(stdout, /open-screen/);
190 + assert.match(stdout, /ask-choice/);
191 + assert.match(stdout, /ask-screen/);
192 + assert.match(stdout, /--html-file/);
193 + assert.match(stdout, /cleanup/);
194 + assert.doesNotMatch(stdout, /\n start --project-dir/);
195 +});
197 +test('companion start without a first screen is rejected', async () => {
198 + await assert.rejects(
199 + runNode('companion.mjs', ['start', '--project-dir', tmpProject()]),
200 + error => {
201 + assert.match(error.stdout, /Use start-choice or start-screen/);
202 + return true;
203 + },
204 + );
205 +});
207 +test('start-choice starts server with first browser screen already loaded', async () => {
208 + const projectDir = tmpProject();
209 + let sessionDir;
211 + try {
212 + const { stdout } = await runNode('companion.mjs', [
213 + 'start-choice',
214 + '--project-dir', projectDir,
215 + '--name', 'first-layout',
216 + '--title', 'First visual question',
217 + '--subtitle', 'Browser must not show waiting page',
218 + '--option', 'a|Left rail|Tree on left',
219 + '--option', 'b|Graph first|Session graph center',
220 + ]);
221 + const info = JSON.parse(stdout.trim());
222 + sessionDir = info.session_dir;
224 + assert.equal(info.type, 'server-started');
225 + assert.match(info.url, /^http:\/\/localhost:\d+$/);
226 + assert.equal(fs.existsSync(info.screen_file), true);
228 + const html = await (await fetch(info.url)).text();
229 + assert.match(html, /First visual question/);
230 + assert.match(html, /Browser must not show waiting page/);
231 + assert.match(html, /data-choice="b"/);
232 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
233 + } finally {
234 + if (sessionDir) await stop(sessionDir);
235 + fs.rmSync(projectDir, { recursive: true, force: true });
237 +});
239 +test('start-screen starts server with first custom HTML screen already loaded', async () => {
240 + const projectDir = tmpProject();
241 + let sessionDir;
243 + try {
244 + const htmlFile = path.join(projectDir, 'first.html');
245 + fs.writeFileSync(htmlFile, '<h2>First custom screen</h2>');
246 + const { stdout } = await runNode('companion.mjs', [
247 + 'start-screen',
248 + '--project-dir', projectDir,
249 + '--name', 'first-custom',
250 + '--html-file', htmlFile,
251 + ]);
252 + const info = JSON.parse(stdout.trim());
253 + sessionDir = info.session_dir;
255 + assert.equal(fs.existsSync(info.screen_file), true);
256 + const html = await (await fetch(info.url)).text();
257 + assert.match(html, /First custom screen/);
258 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
259 + } finally {
260 + if (sessionDir) await stop(sessionDir);
261 + fs.rmSync(projectDir, { recursive: true, force: true });
263 +});
265 +test('visual wait commands reject slow timeouts above 30 seconds', async () => {
266 + const projectDir = tmpProject();
267 + let sessionDir;
269 + try {
270 + const first = path.join(projectDir, 'first.html');
271 + fs.writeFileSync(first, '<h2>Timeout Cap</h2>');
272 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--name', 'timeout-cap', '--html-file', first]);
273 + sessionDir = JSON.parse(stdout.trim()).session_dir;
275 + await assert.rejects(
276 + runNode('companion.mjs', ['ask-choice', sessionDir, '--name', 'too-slow', '--title', 'Too slow', '--option', 'a|A|A', '--timeout-ms', '300001']),
277 + error => {
278 + assert.match(error.stdout, /--timeout-ms max is 30000ms/);
279 + return true;
280 + },
281 + );
282 + } finally {
283 + if (sessionDir) await stop(sessionDir);
284 + fs.rmSync(projectDir, { recursive: true, force: true });
286 +});
288 +test('open-choice starts with first screen, waits, and returns click without terminal reply', async () => {
289 + const projectDir = tmpProject();
290 + let sessionDir;
292 + try {
293 + const asking = runNode('companion.mjs', [
294 + 'open-choice',
295 + '--project-dir', projectDir,
296 + '--name', 'first-open-choice',
297 + '--title', 'Choose first layout',
298 + '--option', 'map|Map|Mission map',
299 + '--option', 'queue|Queue|Decision queue',
300 + '--timeout-ms', '3000',
301 + ], { env: { BRAINSTORM_NO_OPEN: '1' } });
303 + let info;
304 + for (let i = 0; i < 50; i++) {
305 + const files = fs.globSync(`${projectDir}/.superpowers/brainstorm/*/state/server-info`);
306 + if (files.length) {
307 + info = JSON.parse(fs.readFileSync(files[0], 'utf8'));
308 + sessionDir = path.dirname(info.screen_dir);
309 + break;
311 + await new Promise(resolve => setTimeout(resolve, 50));
313 + assert.ok(info);
315 + let html = '';
316 + for (let i = 0; i < 50; i++) {
317 + html = await (await fetch(info.url)).text();
318 + if (html.includes('Choose first layout')) break;
319 + await new Promise(resolve => setTimeout(resolve, 50));
321 + assert.match(html, /Choose first layout/);
322 + assert.doesNotMatch(html, /Waiting for the agent to push a screen/);
324 + await wsSendText(info.port, { type: 'click', choice: 'queue', text: 'Queue', id: 'option-queue' });
325 + const result = JSON.parse((await asking).stdout.trim());
326 + assert.equal(result.choice, 'queue');
327 + assert.equal(result.session_dir, sessionDir);
328 + assert.equal(result.url, info.url);
329 + } finally {
330 + if (sessionDir) await stop(sessionDir);
331 + fs.rmSync(projectDir, { recursive: true, force: true });
333 +});
335 +test('open-screen starts with first custom screen, waits, and returns click', async () => {
336 + const projectDir = tmpProject();
337 + let sessionDir;
339 + try {
340 + const htmlFile = path.join(projectDir, 'open-screen.html');
341 + fs.writeFileSync(htmlFile, '<h2>Open custom</h2><div data-choice="x" onclick="toggleSelect(this)">X</div>');
342 + const asking = runNode('companion.mjs', [
343 + 'open-screen',
344 + '--project-dir', projectDir,
345 + '--name', 'open-custom',
346 + '--html-file', htmlFile,
347 + '--timeout-ms', '3000',
348 + ], { env: { BRAINSTORM_NO_OPEN: '1' } });
350 + let info;
351 + for (let i = 0; i < 50; i++) {
352 + const files = fs.globSync(`${projectDir}/.superpowers/brainstorm/*/state/server-info`);
353 + if (files.length) {
354 + info = JSON.parse(fs.readFileSync(files[0], 'utf8'));
355 + sessionDir = path.dirname(info.screen_dir);
356 + break;
358 + await new Promise(resolve => setTimeout(resolve, 50));
360 + assert.ok(info);
362 + let html = '';
363 + for (let i = 0; i < 50; i++) {
364 + html = await (await fetch(info.url)).text();
365 + if (html.includes('Open custom')) break;
366 + await new Promise(resolve => setTimeout(resolve, 50));
368 + assert.match(html, /Open custom/);
369 + await wsSendText(info.port, { type: 'click', choice: 'x', text: 'X', id: null });
370 + const result = JSON.parse((await asking).stdout.trim());
371 + assert.equal(result.choice, 'x');
372 + } finally {
373 + if (sessionDir) await stop(sessionDir);
374 + fs.rmSync(projectDir, { recursive: true, force: true });
376 +});
378 +test('ask-choice writes a choice screen and returns the browser click without terminal reply', async () => {
379 + await withSession(async info => {
380 + const asking = runNode('companion.mjs', [
381 + 'ask-choice', info.session_dir,
382 + '--name', 'ask-style',
383 + '--title', 'Pick a mode',
384 + '--subtitle', 'No terminal reply needed',
385 + '--option', 'fast|Fast|Shortest path',
386 + '--option', 'deep|Deep|More detail',
387 + '--timeout-ms', '3000',
388 + ]);
390 + for (let i = 0; i < 50; i++) {
391 + const html = await (await fetch(info.url)).text();
392 + if (html.includes('Pick a mode') && html.includes('data-choice="deep"')) break;
393 + await new Promise(resolve => setTimeout(resolve, 50));
396 + await wsSendText(info.port, { type: 'click', choice: 'deep', text: 'Deep', id: 'option-deep' });
397 + const result = JSON.parse((await asking).stdout.trim());
399 + assert.equal(result.choice, 'deep');
400 + assert.equal(result.text, 'Deep');
401 + assert.equal(result.id, 'option-deep');
402 + });
403 +});
405 +test('ask-screen reads custom HTML from file and returns browser click without shell quoting', async () => {
406 + await withSession(async (info, projectDir) => {
407 + const htmlFile = path.join(projectDir, 'mockups.html');
408 + fs.writeFileSync(htmlFile, `
409 +<h2>Custom mockups</h2>
410 +<div class="cards">
411 + <div class="card" data-choice="a" onclick="toggleSelect(this)"><div class="card-body"><h3>A</h3><p>Alpha</p></div></div>
412 + <div class="card" data-choice="b" onclick="toggleSelect(this)"><div class="card-body"><h3>B</h3><p>Beta</p></div></div>
413 +</div>
414 +`);
416 + const asking = runNode('companion.mjs', [
417 + 'ask-screen', info.session_dir,
418 + '--name', 'custom-mockups',
419 + '--html-file', htmlFile,
420 + '--timeout-ms', '3000',
421 + ]);
423 + for (let i = 0; i < 50; i++) {
424 + const html = await (await fetch(info.url)).text();
425 + if (html.includes('Custom mockups') && html.includes('data-choice="b"')) break;
426 + await new Promise(resolve => setTimeout(resolve, 50));
429 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'B Beta', id: null });
430 + const result = JSON.parse((await asking).stdout.trim());
431 + assert.equal(result.choice, 'b');
432 + assert.equal(result.text, 'B Beta');
433 + });
434 +});
436 +test('write-screen reads custom HTML from file', async () => {
437 + await withSession(async (info, projectDir) => {
438 + const htmlFile = path.join(projectDir, 'screen.html');
439 + fs.writeFileSync(htmlFile, '<h2>File Screen</h2>');
440 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'file-screen', '--html-file', htmlFile]);
441 + assert.match(await (await fetch(info.url)).text(), /File Screen/);
442 + });
443 +});
445 +test('scripted workflow supports waiting screen, event listing, clearing, and per-screen event reset', async () => {
446 + await withSession(async info => {
447 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'first', '--title', 'First?', '--option', 'a|Alpha|A']);
448 + await wsSendText(info.port, { type: 'click', choice: 'a', text: 'Alpha' });
450 + const listed = JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim());
451 + assert.equal(listed.length, 1);
452 + assert.equal(listed[0].choice, 'a');
454 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'second', '--title', 'Second?', '--option', 'b|Beta|B']);
455 + assert.deepEqual(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim()), []);
457 + await wsSendText(info.port, { type: 'click', choice: 'b', text: 'Beta' });
458 + assert.equal(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir, '--clear'])).stdout.trim()).length, 1);
459 + assert.deepEqual(JSON.parse((await runNode('companion.mjs', ['events', info.session_dir])).stdout.trim()), []);
461 + await runNode('companion.mjs', ['waiting-screen', info.session_dir, '--name', 'terminal']);
462 + const html = await (await fetch(info.url)).text();
463 + assert.match(html, /Continuing in terminal/);
464 + });
465 +});
467 +test('browser gets reload when agent pushes a new screen', async () => {
468 + await withSession(async info => {
469 + const reload = wsListenForReload(info.port);
470 + await runNode('companion.mjs', ['choice-screen', info.session_dir, '--name', 'reload', '--title', 'Reload?', '--option', 'y|Yes|Y']);
471 + assert.deepEqual(await reload, { type: 'reload' });
472 + });
473 +});
475 +test('server serves wrapped fragments, full documents, and content assets', async () => {
476 + await withSession(async info => {
477 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'fragment', '--html', '<h2>Fragment</h2>']);
478 + const fragment = await (await fetch(info.url)).text();
479 + assert.match(fragment, /Superpowers Brainstorming/);
480 + assert.match(fragment, /<h2>Fragment<\/h2>/);
482 + await runNode('companion.mjs', ['write-screen', info.session_dir, '--name', 'full', '--html', '<!DOCTYPE html><html><body><main>Full Doc</main></body></html>']);
483 + const full = await (await fetch(info.url)).text();
484 + assert.doesNotMatch(full, /Superpowers Brainstorming/);
485 + assert.match(full, /<main>Full Doc<\/main>/);
486 + assert.match(full, /const WS_URL/);
488 + fs.writeFileSync(path.join(info.screen_dir, 'asset.json'), '{"ok":true}');
489 + const asset = await fetch(`${info.url}/files/asset.json`);
490 + assert.equal(asset.headers.get('content-type'), 'application/json');
491 + assert.deepEqual(await asset.json(), { ok: true });
492 + });
493 +});
495 +test('cleanup stops servers whose owner pid is gone', async () => {
496 + const projectDir = tmpProject();
497 + let sessionDir;
498 + let owner;
500 + try {
501 + const first = path.join(projectDir, 'first.html');
502 + fs.writeFileSync(first, '<h2>Owned</h2>');
503 + owner = spawn(process.execPath, ['-e', 'console.log(process.pid); setInterval(() => {}, 1000);'], { stdio: ['ignore', 'pipe', 'ignore'] });
504 + const ownerPid = await new Promise(resolve => owner.stdout.once('data', chunk => resolve(Number(chunk.toString().trim()))));
505 + assert.equal(Number.isInteger(ownerPid), true);
507 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--owner-pid', String(ownerPid), '--name', 'owned', '--html-file', first]);
508 + const info = JSON.parse(stdout.trim());
509 + sessionDir = info.session_dir;
511 + owner.kill('SIGTERM');
512 + await new Promise(resolve => owner.once('exit', resolve));
514 + const cleaned = JSON.parse((await runNode('companion.mjs', ['cleanup'])).stdout.trim());
515 + assert.equal(cleaned.stopped.length, 1);
516 + assert.equal(cleaned.stopped[0].session_dir, sessionDir);
517 + assert.equal(cleaned.stopped[0].reason, 'owner_dead');
518 + assert.equal(fs.existsSync(path.join(sessionDir, 'state', 'server.pid')), false);
519 + } finally {
520 + if (owner && owner.exitCode === null) owner.kill('SIGTERM');
521 + if (sessionDir) await stop(sessionDir);
522 + fs.rmSync(projectDir, { recursive: true, force: true });
524 +});
526 +test('server exits after browser disconnect timeout', async () => {
527 + const projectDir = tmpProject();
528 + let sessionDir;
530 + try {
531 + const first = path.join(projectDir, 'first.html');
532 + fs.writeFileSync(first, '<h2>Disconnect</h2>');
533 + const { stdout } = await runNode('companion.mjs', ['start-screen', '--project-dir', projectDir, '--no-browser-timeout-ms', '200', '--name', 'disconnect', '--html-file', first]);
534 + const info = JSON.parse(stdout.trim());
535 + sessionDir = info.session_dir;
537 + await new Promise((resolve, reject) => {
538 + const key = crypto.randomBytes(16).toString('base64');
539 + const req = http.request({
540 + port: info.port,
541 + host: 'localhost',
542 + headers: {
543 + Connection: 'Upgrade',
544 + Upgrade: 'websocket',
545 + 'Sec-WebSocket-Version': '13',
546 + 'Sec-WebSocket-Key': key,
547 + },
548 + });
549 + req.on('upgrade', (_res, socket) => {
550 + socket.destroy();
551 + resolve();
552 + });
553 + req.on('error', reject);
554 + req.end();
555 + });
557 + const stoppedFile = path.join(sessionDir, 'state', 'server-stopped');
558 + for (let i = 0; i < 50 && !fs.existsSync(stoppedFile); i++) await new Promise(resolve => setTimeout(resolve, 50));
559 + assert.equal(fs.existsSync(stoppedFile), true);
560 + assert.match(fs.readFileSync(stoppedFile, 'utf8'), /no browser clients/);
561 + } finally {
562 + if (sessionDir) await stop(sessionDir);
563 + fs.rmSync(projectDir, { recursive: true, force: true });
565 +});
567 +test('server module exports websocket helpers without side effects', async () => {
568 + const server = await import('./server.mjs');
569 + assert.deepEqual(Object.keys(server).sort(), ['OPCODES', 'computeAcceptKey', 'decodeFrame', 'encodeFrame']);
570 +});

skills/super/brainstorming/scripts/server.cjs

Deleted
deleted file mode 100644
1 -const crypto = require('crypto');
2 -const http = require('http');
3 -const fs = require('fs');
4 -const path = require('path');
6 -// ========== WebSocket Protocol (RFC 6455) ==========
8 -const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
9 -const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
11 -function computeAcceptKey(clientKey) {
12 - return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
15 -function encodeFrame(opcode, payload) {
16 - const fin = 0x80;
17 - const len = payload.length;
18 - let header;
20 - if (len < 126) {
21 - header = Buffer.alloc(2);
22 - header[0] = fin | opcode;
23 - header[1] = len;
24 - } else if (len < 65536) {
25 - header = Buffer.alloc(4);
26 - header[0] = fin | opcode;
27 - header[1] = 126;
28 - header.writeUInt16BE(len, 2);
29 - } else {
30 - header = Buffer.alloc(10);
31 - header[0] = fin | opcode;
32 - header[1] = 127;
33 - header.writeBigUInt64BE(BigInt(len), 2);
34 - }
36 - return Buffer.concat([header, payload]);
39 -function decodeFrame(buffer) {
40 - if (buffer.length < 2) return null;
42 - const secondByte = buffer[1];
43 - const opcode = buffer[0] & 0x0F;
44 - const masked = (secondByte & 0x80) !== 0;
45 - let payloadLen = secondByte & 0x7F;
46 - let offset = 2;
48 - if (!masked) throw new Error('Client frames must be masked');
50 - if (payloadLen === 126) {
51 - if (buffer.length < 4) return null;
52 - payloadLen = buffer.readUInt16BE(2);
53 - offset = 4;
54 - } else if (payloadLen === 127) {
55 - if (buffer.length < 10) return null;
56 - payloadLen = Number(buffer.readBigUInt64BE(2));
57 - offset = 10;
58 - }
60 - const maskOffset = offset;
61 - const dataOffset = offset + 4;
62 - const totalLen = dataOffset + payloadLen;
63 - if (buffer.length < totalLen) return null;
65 - const mask = buffer.slice(maskOffset, dataOffset);
66 - const data = Buffer.alloc(payloadLen);
67 - for (let i = 0; i < payloadLen; i++) {
68 - data[i] = buffer[dataOffset + i] ^ mask[i % 4];
69 - }
71 - return { opcode, payload: data, bytesConsumed: totalLen };
74 -// ========== Configuration ==========
76 -const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
77 -const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
78 -const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
79 -const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
80 -const CONTENT_DIR = path.join(SESSION_DIR, 'content');
81 -const STATE_DIR = path.join(SESSION_DIR, 'state');
82 -let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
84 -const MIME_TYPES = {
85 - '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
86 - '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
87 - '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
88 -};
90 -// ========== Templates and Constants ==========
92 -const WAITING_PAGE = `<!DOCTYPE html>
93 -<html>
94 -<head><meta charset="utf-8"><title>Brainstorm Companion</title>
95 -<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
96 -h1 { color: #333; } p { color: #666; }</style>
97 -</head>
98 -<body><h1>Brainstorm Companion</h1>
99 -<p>Waiting for the agent to push a screen...</p></body></html>`;
101 -const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
102 -const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
103 -const helperInjection = '<script>\n' + helperScript + '\n</script>';
105 -// ========== Helper Functions ==========
107 -function isFullDocument(html) {
108 - const trimmed = html.trimStart().toLowerCase();
109 - return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
112 -function wrapInFrame(content) {
113 - return frameTemplate.replace('<!-- CONTENT -->', content);
116 -function getNewestScreen() {
117 - const files = fs.readdirSync(CONTENT_DIR)
118 - .filter(f => f.endsWith('.html'))
119 - .map(f => {
120 - const fp = path.join(CONTENT_DIR, f);
121 - return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
122 - })
123 - .sort((a, b) => b.mtime - a.mtime);
124 - return files.length > 0 ? files[0].path : null;
127 -// ========== HTTP Request Handler ==========
129 -function handleRequest(req, res) {
130 - touchActivity();
131 - if (req.method === 'GET' && req.url === '/') {
132 - const screenFile = getNewestScreen();
133 - let html = screenFile
134 - ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
135 - : WAITING_PAGE;
137 - if (html.includes('</body>')) {
138 - html = html.replace('</body>', helperInjection + '\n</body>');
139 - } else {
140 - html += helperInjection;
141 - }
143 - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
144 - res.end(html);
145 - } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
146 - const fileName = req.url.slice(7);
147 - const filePath = path.join(CONTENT_DIR, path.basename(fileName));
148 - if (!fs.existsSync(filePath)) {
149 - res.writeHead(404);
150 - res.end('Not found');
151 - return;
152 - }
153 - const ext = path.extname(filePath).toLowerCase();
154 - const contentType = MIME_TYPES[ext] || 'application/octet-stream';
155 - res.writeHead(200, { 'Content-Type': contentType });
156 - res.end(fs.readFileSync(filePath));
157 - } else {
158 - res.writeHead(404);
159 - res.end('Not found');
160 - }
163 -// ========== WebSocket Connection Handling ==========
165 -const clients = new Set();
167 -function handleUpgrade(req, socket) {
168 - const key = req.headers['sec-websocket-key'];
169 - if (!key) { socket.destroy(); return; }
171 - const accept = computeAcceptKey(key);
172 - socket.write(
173 - 'HTTP/1.1 101 Switching Protocols\r\n' +
174 - 'Upgrade: websocket\r\n' +
175 - 'Connection: Upgrade\r\n' +
176 - 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
177 - );
179 - let buffer = Buffer.alloc(0);
180 - clients.add(socket);
182 - socket.on('data', (chunk) => {
183 - buffer = Buffer.concat([buffer, chunk]);
184 - while (buffer.length > 0) {
185 - let result;
186 - try {
187 - result = decodeFrame(buffer);
188 - } catch (e) {
189 - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
190 - clients.delete(socket);
191 - return;
192 - }
193 - if (!result) break;
194 - buffer = buffer.slice(result.bytesConsumed);
196 - switch (result.opcode) {
197 - case OPCODES.TEXT:
198 - handleMessage(result.payload.toString());
199 - break;
200 - case OPCODES.CLOSE:
201 - socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
202 - clients.delete(socket);
203 - return;
204 - case OPCODES.PING:
205 - socket.write(encodeFrame(OPCODES.PONG, result.payload));
206 - break;
207 - case OPCODES.PONG:
208 - break;
209 - default: {
210 - const closeBuf = Buffer.alloc(2);
211 - closeBuf.writeUInt16BE(1003);
212 - socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
213 - clients.delete(socket);
214 - return;
215 - }
216 - }
217 - }
218 - });
220 - socket.on('close', () => clients.delete(socket));
221 - socket.on('error', () => clients.delete(socket));
224 -function handleMessage(text) {
225 - let event;
226 - try {
227 - event = JSON.parse(text);
228 - } catch (e) {
229 - console.error('Failed to parse WebSocket message:', e.message);
230 - return;
231 - }
232 - touchActivity();
233 - console.log(JSON.stringify({ source: 'user-event', ...event }));
234 - if (event.choice) {
235 - const eventsFile = path.join(STATE_DIR, 'events');
236 - fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
237 - }
240 -function broadcast(msg) {
241 - const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
242 - for (const socket of clients) {
243 - try { socket.write(frame); } catch (e) { clients.delete(socket); }
244 - }
247 -// ========== Activity Tracking ==========
249 -const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
250 -let lastActivity = Date.now();
252 -function touchActivity() {
253 - lastActivity = Date.now();
256 -// ========== File Watching ==========
258 -const debounceTimers = new Map();
260 -// ========== Server Startup ==========
262 -function startServer() {
263 - if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
264 - if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
266 - // Track known files to distinguish new screens from updates.
267 - // macOS fs.watch reports 'rename' for both new files and overwrites,
268 - // so we can't rely on eventType alone.
269 - const knownFiles = new Set(
270 - fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
271 - );
273 - const server = http.createServer(handleRequest);
274 - server.on('upgrade', handleUpgrade);
276 - const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
277 - if (!filename || !filename.endsWith('.html')) return;
279 - if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
280 - debounceTimers.set(filename, setTimeout(() => {
281 - debounceTimers.delete(filename);
282 - const filePath = path.join(CONTENT_DIR, filename);
284 - if (!fs.existsSync(filePath)) return; // file was deleted
285 - touchActivity();
287 - if (!knownFiles.has(filename)) {
288 - knownFiles.add(filename);
289 - const eventsFile = path.join(STATE_DIR, 'events');
290 - if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
291 - console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
292 - } else {
293 - console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
294 - }
296 - broadcast({ type: 'reload' });
297 - }, 100));
298 - });
299 - watcher.on('error', (err) => console.error('fs.watch error:', err.message));
301 - function shutdown(reason) {
302 - console.log(JSON.stringify({ type: 'server-stopped', reason }));
303 - const infoFile = path.join(STATE_DIR, 'server-info');
304 - if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
305 - fs.writeFileSync(
306 - path.join(STATE_DIR, 'server-stopped'),
307 - JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
308 - );
309 - watcher.close();
310 - clearInterval(lifecycleCheck);
311 - server.close(() => process.exit(0));
312 - }
314 - function ownerAlive() {
315 - if (!ownerPid) return true;
316 - try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
317 - }
319 - // Check every 60s: exit if owner process died or idle for 30 minutes
320 - const lifecycleCheck = setInterval(() => {
321 - if (!ownerAlive()) shutdown('owner process exited');
322 - else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
323 - }, 60 * 1000);
324 - lifecycleCheck.unref();
326 - // Validate owner PID at startup. If it's already dead, the PID resolution
327 - // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
328 - // Disable monitoring and rely on the idle timeout instead.
329 - if (ownerPid) {
330 - try { process.kill(ownerPid, 0); }
331 - catch (e) {
332 - if (e.code !== 'EPERM') {
333 - console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
334 - ownerPid = null;
335 - }
336 - }
337 - }
339 - server.listen(PORT, HOST, () => {
340 - const info = JSON.stringify({
341 - type: 'server-started', port: Number(PORT), host: HOST,
342 - url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
343 - screen_dir: CONTENT_DIR, state_dir: STATE_DIR
344 - });
345 - console.log(info);
346 - fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
347 - });
350 -if (require.main === module) {
351 - startServer();
354 -module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };

skills/super/brainstorming/scripts/server.mjs

Added
new file mode 100644
1 +import crypto from 'node:crypto';
2 +import http from 'node:http';
3 +import fs from 'node:fs';
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.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
18 +function encodeFrame(opcode, payload) {
19 + const fin = 0x80;
20 + const len = payload.length;
21 + let header;
23 + if (len < 126) {
24 + header = Buffer.alloc(2);
25 + header[0] = fin | opcode;
26 + header[1] = len;
27 + } else if (len < 65536) {
28 + header = Buffer.alloc(4);
29 + header[0] = fin | opcode;
30 + header[1] = 126;
31 + header.writeUInt16BE(len, 2);
32 + } else {
33 + header = Buffer.alloc(10);
34 + header[0] = fin | opcode;
35 + header[1] = 127;
36 + header.writeBigUInt64BE(BigInt(len), 2);
37 + }
39 + return Buffer.concat([header, payload]);
42 +function decodeFrame(buffer) {
43 + if (buffer.length < 2) return null;
45 + const secondByte = buffer[1];
46 + const opcode = buffer[0] & 0x0F;
47 + const masked = (secondByte & 0x80) !== 0;
48 + let payloadLen = secondByte & 0x7F;
49 + let offset = 2;
51 + if (!masked) throw new Error('Client frames must be masked');
53 + if (payloadLen === 126) {
54 + if (buffer.length < 4) return null;
55 + payloadLen = buffer.readUInt16BE(2);
56 + offset = 4;
57 + } else if (payloadLen === 127) {
58 + if (buffer.length < 10) return null;
59 + payloadLen = Number(buffer.readBigUInt64BE(2));
60 + offset = 10;
61 + }
63 + const maskOffset = offset;
64 + const dataOffset = offset + 4;
65 + const totalLen = dataOffset + payloadLen;
66 + if (buffer.length < totalLen) return null;
68 + const mask = buffer.slice(maskOffset, dataOffset);
69 + const data = Buffer.alloc(payloadLen);
70 + for (let i = 0; i < payloadLen; i++) {
71 + data[i] = buffer[dataOffset + i] ^ mask[i % 4];
72 + }
74 + return { opcode, payload: data, bytesConsumed: totalLen };
77 +// ========== Configuration ==========
79 +const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
80 +const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
81 +const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
82 +const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
83 +const CONTENT_DIR = path.join(SESSION_DIR, 'content');
84 +const STATE_DIR = path.join(SESSION_DIR, 'state');
85 +let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
86 +const NO_BROWSER_TIMEOUT_MS = Number(process.env.BRAINSTORM_NO_BROWSER_TIMEOUT_MS || 60_000);
88 +const MIME_TYPES = {
89 + '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
90 + '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
91 + '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
92 +};
94 +// ========== Templates and Constants ==========
96 +const WAITING_PAGE = `<!DOCTYPE html>
97 +<html>
98 +<head><meta charset="utf-8"><title>Brainstorm Companion</title>
99 +<style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
100 +h1 { color: #333; } p { color: #666; }</style>
101 +</head>
102 +<body><h1>Brainstorm Companion</h1>
103 +<p>Waiting for the agent to push a screen...</p></body></html>`;
105 +const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
106 +const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
107 +const helperInjection = '<script>\n' + helperScript + '\n</script>';
109 +// ========== Helper Functions ==========
111 +function isFullDocument(html) {
112 + const trimmed = html.trimStart().toLowerCase();
113 + return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
116 +function wrapInFrame(content) {
117 + return frameTemplate.replace('<!-- CONTENT -->', content);
120 +function getNewestScreen() {
121 + const files = fs.readdirSync(CONTENT_DIR)
122 + .filter(f => f.endsWith('.html'))
123 + .map(f => {
124 + const fp = path.join(CONTENT_DIR, f);
125 + return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
126 + })
127 + .sort((a, b) => b.mtime - a.mtime);
128 + return files.length > 0 ? files[0].path : null;
131 +// ========== HTTP Request Handler ==========
133 +function handleRequest(req, res) {
134 + touchActivity();
135 + if (req.method === 'GET' && req.url === '/') {
136 + const screenFile = getNewestScreen();
137 + let html = screenFile
138 + ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
139 + : WAITING_PAGE;
141 + if (html.includes('</body>')) {
142 + html = html.replace('</body>', helperInjection + '\n</body>');
143 + } else {
144 + html += helperInjection;
147 + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
148 + res.end(html);
149 + } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
150 + const fileName = req.url.slice(7);
151 + const filePath = path.join(CONTENT_DIR, path.basename(fileName));
152 + if (!fs.existsSync(filePath)) {
153 + res.writeHead(404);
154 + res.end('Not found');
155 + return;
157 + const ext = path.extname(filePath).toLowerCase();
158 + const contentType = MIME_TYPES[ext] || 'application/octet-stream';
159 + res.writeHead(200, { 'Content-Type': contentType });
160 + res.end(fs.readFileSync(filePath));
161 + } else {
162 + res.writeHead(404);
163 + res.end('Not found');
167 +// ========== WebSocket Connection Handling ==========
169 +const clients = new Set();
170 +let browserEverConnected = false;
171 +let browserDisconnectedAt = null;
173 +function handleUpgrade(req, socket) {
174 + const key = req.headers['sec-websocket-key'];
175 + if (!key) { socket.destroy(); return; }
177 + const accept = computeAcceptKey(key);
178 + socket.write(
179 + 'HTTP/1.1 101 Switching Protocols\r\n' +
180 + 'Upgrade: websocket\r\n' +
181 + 'Connection: Upgrade\r\n' +
182 + 'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
183 + );
185 + let buffer = Buffer.alloc(0);
186 + clients.add(socket);
187 + browserEverConnected = true;
188 + browserDisconnectedAt = null;
190 + socket.on('data', (chunk) => {
191 + buffer = Buffer.concat([buffer, chunk]);
192 + while (buffer.length > 0) {
193 + let result;
194 + try {
195 + result = decodeFrame(buffer);
196 + } catch (e) {
197 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
198 + removeClient();
199 + return;
201 + if (!result) break;
202 + buffer = buffer.slice(result.bytesConsumed);
204 + switch (result.opcode) {
205 + case OPCODES.TEXT:
206 + handleMessage(result.payload.toString());
207 + break;
208 + case OPCODES.CLOSE:
209 + socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
210 + removeClient();
211 + return;
212 + case OPCODES.PING:
213 + socket.write(encodeFrame(OPCODES.PONG, result.payload));
214 + break;
215 + case OPCODES.PONG:
216 + break;
217 + default: {
218 + const closeBuf = Buffer.alloc(2);
219 + closeBuf.writeUInt16BE(1003);
220 + socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
221 + removeClient();
222 + return;
226 + });
228 + function removeClient() {
229 + clients.delete(socket);
230 + if (browserEverConnected && clients.size === 0) browserDisconnectedAt = Date.now();
233 + socket.on('close', removeClient);
234 + socket.on('end', removeClient);
235 + socket.on('error', removeClient);
238 +function handleMessage(text) {
239 + let event;
240 + try {
241 + event = JSON.parse(text);
242 + } catch (e) {
243 + console.error('Failed to parse WebSocket message:', e.message);
244 + return;
246 + touchActivity();
247 + console.log(JSON.stringify({ source: 'user-event', ...event }));
248 + if (event.choice) {
249 + const eventsFile = path.join(STATE_DIR, 'events');
250 + fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
254 +function broadcast(msg) {
255 + const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
256 + for (const socket of clients) {
257 + try { socket.write(frame); } catch (e) { clients.delete(socket); }
261 +// ========== Activity Tracking ==========
263 +const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
264 +let lastActivity = Date.now();
266 +function touchActivity() {
267 + lastActivity = Date.now();
270 +// ========== File Watching ==========
272 +const debounceTimers = new Map();
274 +// ========== Server Startup ==========
276 +function startServer() {
277 + if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
278 + if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
280 + // Track known files to distinguish new screens from updates.
281 + // macOS fs.watch reports 'rename' for both new files and overwrites,
282 + // so we can't rely on eventType alone.
283 + const knownFiles = new Set(
284 + fs.readdirSync(CONTENT_DIR).filter(f => f.endsWith('.html'))
285 + );
287 + const server = http.createServer(handleRequest);
288 + server.on('upgrade', handleUpgrade);
290 + const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
291 + if (!filename || !filename.endsWith('.html')) return;
293 + if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
294 + debounceTimers.set(filename, setTimeout(() => {
295 + debounceTimers.delete(filename);
296 + const filePath = path.join(CONTENT_DIR, filename);
298 + if (!fs.existsSync(filePath)) return; // file was deleted
299 + touchActivity();
301 + if (!knownFiles.has(filename)) {
302 + knownFiles.add(filename);
303 + console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
304 + } else {
305 + console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
308 + broadcast({ type: 'reload' });
309 + }, 100));
310 + });
311 + watcher.on('error', (err) => console.error('fs.watch error:', err.message));
313 + function shutdown(reason) {
314 + console.log(JSON.stringify({ type: 'server-stopped', reason }));
315 + const infoFile = path.join(STATE_DIR, 'server-info');
316 + if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
317 + fs.writeFileSync(
318 + path.join(STATE_DIR, 'server-stopped'),
319 + JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
320 + );
321 + watcher.close();
322 + clearInterval(lifecycleCheck);
323 + server.close(() => process.exit(0));
326 + function ownerAlive() {
327 + if (!ownerPid) return true;
328 + try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
331 + // Check every 60s: exit if owner process died or idle for 30 minutes
332 + const lifecycleCheck = setInterval(() => {
333 + if (!ownerAlive()) shutdown('owner process exited');
334 + else if (browserDisconnectedAt && Date.now() - browserDisconnectedAt > NO_BROWSER_TIMEOUT_MS) shutdown('no browser clients');
335 + else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
336 + }, 100);
337 + lifecycleCheck.unref();
339 + // Validate owner PID at startup. If it's already dead, the PID resolution
340 + // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
341 + // Disable monitoring and rely on the idle timeout instead.
342 + if (ownerPid) {
343 + try { process.kill(ownerPid, 0); }
344 + catch (e) {
345 + if (e.code !== 'EPERM') {
346 + console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
347 + ownerPid = null;
352 + server.listen(PORT, HOST, () => {
353 + const info = JSON.stringify({
354 + type: 'server-started', port: Number(PORT), host: HOST,
355 + url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
356 + screen_dir: CONTENT_DIR, state_dir: STATE_DIR
357 + });
358 + console.log(info);
359 + fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n');
360 + });
363 +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
364 + startServer();
367 +export { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };

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

Added
new 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 { spawn } from 'node:child_process';
6 +import { fileURLToPath, pathToFileURL } from 'node:url';
8 +const scriptDir = path.dirname(fileURLToPath(import.meta.url));
10 +const registryFile = path.join(os.homedir(), '.local', 'state', 'pi', 'brainstorm-companion', 'servers.jsonl');
12 +function usage(error) {
13 + const message = error ? { error } : { usage: 'start-server.mjs [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--owner-pid <pid>] [--no-browser-timeout-ms <ms>]' };
14 + console.log(JSON.stringify(message));
15 + process.exit(error ? 1 : 0);
18 +function parentPid(pid) {
19 + try {
20 + const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
21 + const afterName = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
22 + return Number(afterName[1]);
23 + } catch {
24 + return null;
25 + }
28 +function defaultOwnerPid() {
29 + return parentPid(process.ppid) || process.ppid;
32 +function parseArgs(argv) {
33 + const options = { projectDir: '', host: '127.0.0.1', urlHost: '', ownerPid: defaultOwnerPid(), noBrowserTimeoutMs: 60_000 };
35 + for (let i = 0; i < argv.length; i++) {
36 + const arg = argv[i];
37 + if (arg === '--project-dir') options.projectDir = argv[++i] ?? usage('Missing value for --project-dir');
38 + else if (arg === '--host') options.host = argv[++i] ?? usage('Missing value for --host');
39 + else if (arg === '--url-host') options.urlHost = argv[++i] ?? usage('Missing value for --url-host');
40 + else if (arg === '--owner-pid') options.ownerPid = Number(argv[++i] ?? usage('Missing value for --owner-pid'));
41 + else if (arg === '--no-browser-timeout-ms') options.noBrowserTimeoutMs = Number(argv[++i] ?? usage('Missing value for --no-browser-timeout-ms'));
42 + else if (arg === '--help' || arg === '-h') usage();
43 + else usage(`Unknown argument: ${arg}`);
44 + }
46 + if (!options.urlHost) {
47 + options.urlHost = options.host === '127.0.0.1' || options.host === 'localhost' ? 'localhost' : options.host;
48 + }
50 + return options;
53 +function sleep(ms) {
54 + return new Promise(resolve => setTimeout(resolve, ms));
57 +function appendRegistry(entry) {
58 + fs.mkdirSync(path.dirname(registryFile), { recursive: true });
59 + fs.appendFileSync(registryFile, `${JSON.stringify(entry)}\n`);
62 +async function waitForStart(stateDir, child, logFile) {
63 + const infoFile = path.join(stateDir, 'server-info');
65 + for (let i = 0; i < 50; i++) {
66 + if (fs.existsSync(infoFile)) return fs.readFileSync(infoFile, 'utf8').trim();
67 + if (child.exitCode !== null) break;
68 + await sleep(100);
69 + }
71 + const log = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').trim() : '';
72 + const suffix = log ? `: ${log}` : '';
73 + throw new Error(`Server failed to start within 5 seconds${suffix}`);
76 +async function startServer(argv = process.argv.slice(2)) {
77 + const options = parseArgs(argv);
78 + const sessionId = `${process.pid}-${Math.floor(Date.now() / 1000)}`;
79 + const sessionDir = options.projectDir
80 + ? path.join(options.projectDir, '.superpowers', 'brainstorm', sessionId)
81 + : path.join(os.tmpdir(), `brainstorm-${sessionId}`);
82 + const contentDir = path.join(sessionDir, 'content');
83 + const stateDir = path.join(sessionDir, 'state');
84 + const pidFile = path.join(stateDir, 'server.pid');
85 + const logFile = path.join(stateDir, 'server.log');
87 + fs.mkdirSync(contentDir, { recursive: true });
88 + fs.mkdirSync(stateDir, { recursive: true });
90 + const log = fs.openSync(logFile, 'a');
91 + const child = spawn(process.execPath, [path.join(scriptDir, 'server.mjs')], {
92 + detached: true,
93 + stdio: ['ignore', log, log],
94 + env: {
95 + ...process.env,
96 + BRAINSTORM_DIR: sessionDir,
97 + BRAINSTORM_HOST: options.host,
98 + BRAINSTORM_URL_HOST: options.urlHost,
99 + BRAINSTORM_OWNER_PID: String(options.ownerPid),
100 + BRAINSTORM_NO_BROWSER_TIMEOUT_MS: String(options.noBrowserTimeoutMs),
101 + },
102 + });
104 + child.unref();
105 + fs.writeFileSync(pidFile, `${child.pid}\n`);
107 + try {
108 + const info = JSON.parse(await waitForStart(stateDir, child, logFile));
109 + fs.writeFileSync(path.join(stateDir, 'owner'), `${options.ownerPid}\n`);
110 + appendRegistry({ pid: child.pid, owner_pid: options.ownerPid, session_dir: sessionDir, url: info.url, started_at: Date.now() });
111 + return info;
112 + } finally {
113 + fs.closeSync(log);
117 +async function main() {
118 + console.log(JSON.stringify({ error: 'start-server.mjs is internal. Use companion.mjs start-choice or companion.mjs start-screen.' }));
119 + process.exit(1);
122 +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
123 + main().catch(error => {
124 + console.log(JSON.stringify({ error: error.message }));
125 + process.exit(1);
126 + });
129 +export { defaultOwnerPid, main, parentPid, parseArgs, startServer };

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

Deleted
deleted file mode 100755
1 -#!/usr/bin/env bash
2 -# Start the brainstorm server and output connection info
3 -# Usage: start-server.sh [--project-dir <path>] [--host <bind-host>] [--url-host <display-host>] [--foreground] [--background]
4 -#
5 -# Starts server on a random high port, outputs JSON with URL.
6 -# Each session gets its own directory to avoid conflicts.
7 -#
8 -# Options:
9 -# --project-dir <path> Store session files under <path>/.superpowers/brainstorm/
10 -# instead of /tmp. Files persist after server stops.
11 -# --host <bind-host> Host/interface to bind (default: 127.0.0.1).
12 -# Use 0.0.0.0 in remote/containerized environments.
13 -# --url-host <host> Hostname shown in returned URL JSON.
14 -# --foreground Run server in the current terminal (no backgrounding).
15 -# --background Force background mode (overrides Codex auto-foreground).
17 -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
19 -# Parse arguments
20 -PROJECT_DIR=""
21 -FOREGROUND="false"
22 -FORCE_BACKGROUND="false"
23 -BIND_HOST="127.0.0.1"
24 -URL_HOST=""
25 -while [[ $# -gt 0 ]]; do
26 - case "$1" in
27 - --project-dir)
28 - PROJECT_DIR="$2"
29 - shift 2
30 - ;;
31 - --host)
32 - BIND_HOST="$2"
33 - shift 2
34 - ;;
35 - --url-host)
36 - URL_HOST="$2"
37 - shift 2
38 - ;;
39 - --foreground|--no-daemon)
40 - FOREGROUND="true"
41 - shift
42 - ;;
43 - --background|--daemon)
44 - FORCE_BACKGROUND="true"
45 - shift
46 - ;;
47 - *)
48 - echo "{\"error\": \"Unknown argument: $1\"}"
49 - exit 1
50 - ;;
51 - esac
52 -done
54 -if [[ -z "$URL_HOST" ]]; then
55 - if [[ "$BIND_HOST" == "127.0.0.1" || "$BIND_HOST" == "localhost" ]]; then
56 - URL_HOST="localhost"
57 - else
58 - URL_HOST="$BIND_HOST"
59 - fi
60 -fi
62 -# Some environments reap detached/background processes. Auto-foreground when detected.
63 -if [[ -n "${CODEX_CI:-}" && "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
64 - FOREGROUND="true"
65 -fi
67 -# Windows/Git Bash reaps nohup background processes. Auto-foreground when detected.
68 -if [[ "$FOREGROUND" != "true" && "$FORCE_BACKGROUND" != "true" ]]; then
69 - case "${OSTYPE:-}" in
70 - msys*|cygwin*|mingw*) FOREGROUND="true" ;;
71 - esac
72 - if [[ -n "${MSYSTEM:-}" ]]; then
73 - FOREGROUND="true"
74 - fi
75 -fi
77 -# Generate unique session directory
78 -SESSION_ID="$$-$(date +%s)"
80 -if [[ -n "$PROJECT_DIR" ]]; then
81 - SESSION_DIR="${PROJECT_DIR}/.superpowers/brainstorm/${SESSION_ID}"
82 -else
83 - SESSION_DIR="/tmp/brainstorm-${SESSION_ID}"
84 -fi
86 -STATE_DIR="${SESSION_DIR}/state"
87 -PID_FILE="${STATE_DIR}/server.pid"
88 -LOG_FILE="${STATE_DIR}/server.log"
90 -# Create fresh session directory with content and state peers
91 -mkdir -p "${SESSION_DIR}/content" "$STATE_DIR"
93 -# Kill any existing server
94 -if [[ -f "$PID_FILE" ]]; then
95 - old_pid=$(cat "$PID_FILE")
96 - kill "$old_pid" 2>/dev/null
97 - rm -f "$PID_FILE"
98 -fi
100 -cd "$SCRIPT_DIR"
102 -# Resolve the harness PID (grandparent of this script).
103 -# $PPID is the ephemeral shell the harness spawned to run us — it dies
104 -# when this script exits. The harness itself is $PPID's parent.
105 -OWNER_PID="$(ps -o ppid= -p "$PPID" 2>/dev/null | tr -d ' ')"
106 -if [[ -z "$OWNER_PID" || "$OWNER_PID" == "1" ]]; then
107 - OWNER_PID="$PPID"
108 -fi
110 -# Foreground mode for environments that reap detached/background processes.
111 -if [[ "$FOREGROUND" == "true" ]]; then
112 - echo "$$" > "$PID_FILE"
113 - env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs
114 - exit $?
115 -fi
117 -# Start server, capturing output to log file
118 -# Use nohup to survive shell exit; disown to remove from job table
119 -nohup env BRAINSTORM_DIR="$SESSION_DIR" BRAINSTORM_HOST="$BIND_HOST" BRAINSTORM_URL_HOST="$URL_HOST" BRAINSTORM_OWNER_PID="$OWNER_PID" node server.cjs > "$LOG_FILE" 2>&1 &
120 -SERVER_PID=$!
121 -disown "$SERVER_PID" 2>/dev/null
122 -echo "$SERVER_PID" > "$PID_FILE"
124 -# Wait for server-started message (check log file)
125 -for i in {1..50}; do
126 - if grep -q "server-started" "$LOG_FILE" 2>/dev/null; then
127 - # Verify server is still alive after a short window (catches process reapers)
128 - alive="true"
129 - for _ in {1..20}; do
130 - if ! kill -0 "$SERVER_PID" 2>/dev/null; then
131 - alive="false"
132 - break
133 - fi
134 - sleep 0.1
135 - done
136 - if [[ "$alive" != "true" ]]; then
137 - echo "{\"error\": \"Server started but was killed. Retry in a persistent terminal with: $SCRIPT_DIR/start-server.sh${PROJECT_DIR:+ --project-dir $PROJECT_DIR} --host $BIND_HOST --url-host $URL_HOST --foreground\"}"
138 - exit 1
139 - fi
140 - grep "server-started" "$LOG_FILE" | head -1
141 - exit 0
142 - fi
143 - sleep 0.1
144 -done
146 -# Timeout - server didn't start
147 -echo '{"error": "Server failed to start within 5 seconds"}'
148 -exit 1

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

Added
new 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 + }
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;
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) return { status: 'failed', error: 'invalid pid file' };
38 + if (isAlive(pid)) {
39 + process.kill(pid, 'SIGTERM');
40 + if (!(await waitUntilDead(pid))) {
41 + process.kill(pid, 'SIGKILL');
42 + await sleep(100);
43 + }
44 + }
46 + if (isAlive(pid)) return { status: 'failed', error: 'process still running' };
48 + fs.rmSync(pidFile, { force: true });
49 + fs.rmSync(path.join(stateDir, 'server.log'), { force: true });
51 + const resolvedSession = path.resolve(sessionDir);
52 + const resolvedTmp = path.resolve(os.tmpdir());
53 + if (resolvedSession.startsWith(resolvedTmp + path.sep)) {
54 + fs.rmSync(sessionDir, { recursive: true, force: true });
55 + }
57 + return { status: 'stopped' };
60 +async function main(argv = process.argv.slice(2)) {
61 + const result = await stop(argv[0]);
62 + console.log(JSON.stringify(result));
63 + if (result.error) process.exit(1);
66 +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
67 + main().catch(error => {
68 + console.log(JSON.stringify({ status: 'failed', error: error.message }));
69 + process.exit(1);
70 + });
73 +export { stop };

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

Deleted
deleted file mode 100755
1 -#!/usr/bin/env bash
2 -# Stop the brainstorm server and clean up
3 -# Usage: stop-server.sh <session_dir>
4 -#
5 -# Kills the server process. Only deletes session directory if it's
6 -# under /tmp (ephemeral). Persistent directories (.superpowers/) are
7 -# kept so mockups can be reviewed later.
9 -SESSION_DIR="$1"
11 -if [[ -z "$SESSION_DIR" ]]; then
12 - echo '{"error": "Usage: stop-server.sh <session_dir>"}'
13 - exit 1
14 -fi
16 -STATE_DIR="${SESSION_DIR}/state"
17 -PID_FILE="${STATE_DIR}/server.pid"
19 -if [[ -f "$PID_FILE" ]]; then
20 - pid=$(cat "$PID_FILE")
22 - # Try to stop gracefully, fallback to force if still alive
23 - kill "$pid" 2>/dev/null || true
25 - # Wait for graceful shutdown (up to ~2s)
26 - for i in {1..20}; do
27 - if ! kill -0 "$pid" 2>/dev/null; then
28 - break
29 - fi
30 - sleep 0.1
31 - done
33 - # If still running, escalate to SIGKILL
34 - if kill -0 "$pid" 2>/dev/null; then
35 - kill -9 "$pid" 2>/dev/null || true
37 - # Give SIGKILL a moment to take effect
38 - sleep 0.1
39 - fi
41 - if kill -0 "$pid" 2>/dev/null; then
42 - echo '{"status": "failed", "error": "process still running"}'
43 - exit 1
44 - fi
46 - rm -f "$PID_FILE" "${STATE_DIR}/server.log"
48 - # Only delete ephemeral /tmp directories
49 - if [[ "$SESSION_DIR" == /tmp/* ]]; then
50 - rm -rf "$SESSION_DIR"
51 - fi
53 - echo '{"status": "stopped"}'
54 -else
55 - echo '{"status": "not_running"}'
56 -fi

skills/super/brainstorming/visual-companion.md

Modified
25 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.
27 48 ## How It Works
29 -The server watches a directory for HTML files and serves the newest one to the browser. You write HTML content to `screen_dir`, the user sees it in their browser and can click to select options. Selections are recorded to `state_dir/events` that you read on your next turn.
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`.
31 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.
33 54 ## Starting a Session
35 -```bash
36 -# Start server with persistence (mockups saved to project)
37 -scripts/start-server.sh --project-dir /path/to/project
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.
39 -# Returns: {"type":"server-started","port":52341,"url":"http://localhost:52341",
40 -# "screen_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/content",
41 -# "state_dir":"/path/to/project/.superpowers/brainstorm/12345-1706000000/state"}
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/.superpowers/brainstorm/12345-1706000000",
69 +# "screen_file":".../content/first-layout.html"}
44 -Save `screen_dir` and `state_dir` from the response. Tell user to open the URL.
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 +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.
46 83 **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>/.superpowers/brainstorm/` for the session directory.
48 85 **Note:** Pass the project root as `--project-dir` so mockups persist in `.superpowers/brainstorm/` and survive server restarts. Without it, files go to `/tmp` and get cleaned up. Remind the user to add `.superpowers/` to `.gitignore` if it's not already there.
50 -**Launching the server by platform:**
87 +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`.
52 -**Pi (macOS / Linux):**
53 -```bash
54 -# Default mode works — the script backgrounds the server itself
55 -scripts/start-server.sh --project-dir /path/to/project
56 -```
58 -**Pi (Windows):**
59 -```bash
60 -# Windows auto-detects and uses foreground mode, which blocks the tool call.
61 -# Use run_in_background: true on the Bash tool call so the server survives
62 -# across conversation turns.
63 -scripts/start-server.sh --project-dir /path/to/project
64 -```
65 -When calling this via the Bash tool, set `run_in_background: true`. Then read `$STATE_DIR/server-info` on the next turn to get the URL and port.
67 -**Codex:**
68 -```bash
69 -# Codex reaps background processes. The script auto-detects CODEX_CI and
70 -# switches to foreground mode. Run it normally — no extra flags needed.
71 -scripts/start-server.sh --project-dir /path/to/project
72 -```
74 -**Gemini CLI:**
75 -```bash
76 -# Use --foreground and set is_background: true on your shell tool call
77 -# so the process survives across turns
78 -scripts/start-server.sh --project-dir /path/to/project --foreground
79 -```
81 -**Other environments:** The server must keep running in the background across conversation turns. If your environment reaps detached processes, use `--foreground` and launch the command with your platform's background execution mechanism.
83 -If the URL is unreachable from your browser (common in remote/containerized setups), bind a non-loopback host:
89 +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`:
85 91 ```bash
86 -scripts/start-server.sh \
92 +node scripts/companion.mjs open-choice \
87 93 --project-dir /path/to/project \
88 94 --host 0.0.0.0 \
89 - --url-host localhost
95 + --url-host localhost \
96 + --name first-layout \
97 + --title "Which layout direction?" \
98 + --option "timeline|Timeline first|Session tree dominates" \
99 + --option "diff|Diff first|Review surface dominates"
92 102 Use `--url-host` to control what hostname is printed in the returned URL JSON.
104 +Lifecycle controls:
106 +```bash
107 +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"
108 +node scripts/companion.mjs cleanup
109 +node scripts/companion.mjs stop "$SESSION_DIR"
110 +```
112 +`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.
94 114 ## The Loop
96 -1. **Check server is alive**, then **write HTML** to a new file in `screen_dir`:
97 - - Before each write, check that `$STATE_DIR/server-info` exists. If it doesn't (or `$STATE_DIR/server-stopped` exists), the server has shut down — restart it with `start-server.sh` before continuing. The server auto-exits after 30 minutes of inactivity.
98 - - Use semantic filenames: `platform.html`, `visual-style.html`, `layout.html`
99 - - **Never reuse filenames** — each screen gets a fresh file
100 - - Use Write tool — **never use cat/heredoc** (dumps noise into terminal)
101 - - Server automatically serves the newest file
116 +1. **For visual choices, 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:
103 -2. **Tell user what to expect and end your turn:**
104 - - Remind them of the URL (every step, not just first)
105 - - Give a brief text summary of what's on screen (e.g., "Showing 3 layout options for the homepage")
106 - - Ask them to respond in the terminal: "Take a look and let me know what you think. Click to select an option if you'd like."
108 -3. **On your next turn** — after the user responds in the terminal:
109 - - Read `$STATE_DIR/events` if it exists — this contains the user's browser interactions (clicks, selections) as JSON lines
110 - - Merge with the user's terminal text to get the full picture
111 - - The terminal message is the primary feedback; `state_dir/events` provides structured interaction data
113 -4. **Iterate or advance** — if feedback changes current screen, write a new file (e.g., `layout-v2.html`). Only move to the next question when the current step is validated.
115 -5. **Unload when returning to terminal** — when the next step doesn't need the browser (e.g., a clarifying question, a tradeoff discussion), push a waiting screen to clear the stale content:
117 - ```html
118 - <!-- filename: waiting.html (or waiting-2.html, etc.) -->
119 - <div style="display:flex;align-items:center;justify-content:center;min-height:60vh">
120 - <p class="subtitle">Continuing in terminal...</p>
121 - </div>
118 + ```bash
119 + node scripts/companion.mjs ask-choice "$SESSION_DIR" \
120 + --name layout \
121 + --title "Which layout works better?" \
122 + --subtitle "Consider readability and visual hierarchy" \
123 + --option "single|Single Column|Clean, focused reading experience" \
124 + --option "two|Two Column|Sidebar navigation with main content" \
125 + --timeout-ms 30000
124 - This prevents the user from staring at a resolved choice while the conversation has moved on. When the next visual question comes up, push a new content file as usual.
128 + 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. Never set `--timeout-ms` above `30000`; the script rejects slower waits.
126 -6. Repeat until done.
130 +2. **For custom visual choices, write HTML to a file, then ask and wait.** Do not embed large HTML in shell args or heredocs.
132 + ```bash
133 + # First create /tmp/layout-options.html with Write tool.
134 + node scripts/companion.mjs ask-screen "$SESSION_DIR" \
135 + --name layout-custom \
136 + --html-file /tmp/layout-options.html \
137 + --timeout-ms 30000
138 + ```
140 + The HTML must include clickable elements with `data-choice` and `onclick="toggleSelect(this)"`.
142 +3. **For display-only visuals, push a screen and end the turn:**
144 + ```bash
145 + # First create /tmp/custom-screen.html with Write tool.
146 + node scripts/companion.mjs write-screen "$SESSION_DIR" \
147 + --name layout-custom \
148 + --html-file /tmp/custom-screen.html
149 + ```
151 + Remind them of the URL and ask for terminal feedback only when the answer is open-ended text, not a choice.
153 +4. **For existing browser feedback, use the script:**
155 + ```bash
156 + node scripts/companion.mjs events "$SESSION_DIR"
157 + node scripts/companion.mjs wait-choice "$SESSION_DIR" --timeout-ms 30000
158 + node scripts/companion.mjs events "$SESSION_DIR" --clear
159 + ```
161 + Merge browser events with any terminal text if both exist. Terminal text is primary for open-ended feedback; browser events are primary for visual choices.
163 +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.
165 +6. **Unload when returning to terminal** — when the next step doesn't need the browser, push the deterministic waiting screen:
167 + ```bash
168 + node scripts/companion.mjs waiting-screen "$SESSION_DIR" --name terminal
169 + ```
171 + This prevents the user from staring at a resolved choice while the conversation has moved on.
173 +7. Repeat until done.
128 175 ## Writing Content Fragments
130 -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).
177 +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.
179 +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).
132 181 **Minimal example:**
276 325 ## Cleaning Up
278 327 ```bash
279 -scripts/stop-server.sh $SESSION_DIR
328 +node scripts/companion.mjs stop $SESSION_DIR
282 331 If the session used `--project-dir`, mockup files persist in `.superpowers/brainstorm/` for later reference. Only `/tmp` sessions get deleted on stop.

skills/tmux/SKILL.md

Modified
116 116 Pi uses an alternate screen and an editor; `capture-pane` may be incomplete. Verify via panes **and** artifacts/session JSONL.
118 +### Wait Budget
120 +Default to short, condition-based waits. Long timeouts hide harness bugs and delay work.
122 +- Readiness/startup: 15s default.
123 +- UI settle after keypress: 0.2–1s.
124 +- No-progress checkpoint: 10s; capture pane/artifacts and decide.
125 +- Any wait >30s requires a recorded reason and progress signal.
126 +- Never use `sleep N` as control flow; poll a state/artifact/process.
118 128 ```bash
119 129 wait_for_pi() {
120 - local pane="$1"
121 - for _ in {1..60}; do
122 - [ "$(pane_cmd "$pane")" = pi ] || { sleep 1; continue; }
123 - # Require stability across two polls; pane text may be sparse in alt screen.
124 - sleep 1
125 - [ "$(pane_cmd "$pane")" = pi ] && return 0
130 + local pane="$1" timeout="${2:-15}" start now
131 + start="$(date +%s)"
132 + while :; do
133 + if [ "$(pane_cmd "$pane")" = pi ]; then
134 + # Require stability across two polls; pane text may be sparse in alt screen.
135 + sleep 0.25
136 + [ "$(pane_cmd "$pane")" = pi ] && return 0
137 + fi
138 + now="$(date +%s)"
139 + [ $((now - start)) -ge "$timeout" ] && break
140 + sleep 0.5
127 142 capture "$pane" -80 >&2
128 143 return 1
156 171 1. If testing product stop UX, send the documented stop input once.
157 172 2. Wait a bounded time and capture evidence.
158 -3. If still busy, record UX failure.
173 +3. If still busy after 10s without visible progress, record UX failure.
159 174 4. Find child process and signal directly:
161 176 ```bash
181 196 - Slash command sent while pane is `nu`/`bash` → check `pane_current_command` first.
182 197 - Launch Pi then immediately paste prompt → wait for `pi` readiness.
183 198 - `sleep 5` as readiness → poll state/artifacts.
199 +- Huge defensive timeouts → small budget + progress checkpoints + explicit escalation.
184 200 - Capture old scrollback as current output → use markers/timestamps and recent captures.
185 201 - Continue from command-concatenated pane → declare polluted and open clean pane.
186 202 - Complex Bash pasted into Nushell/Fish/PowerShell → orchestrate outside pane or use shell-aware syntax.

skills/web-ui/SKILL.md

Added
new file mode 100644
1 +---
2 +name: web-ui
3 +description: Use when creating or improving standalone HTML/CSS browser UI, mockups, landing pages, dashboards, visual companion screens, or small no-build web tools; especially vanilla HTML/CSS with minimal JavaScript and no React/Vue/Angular.
4 +---
6 +# Web UI
8 +Build sharp standalone web UI with plain HTML, CSS, and minimal vanilla JS. Default to one complete file, no build step, no framework, no decorative sludge.
10 +## Default Stack
12 +- HTML: semantic elements first: `main`, `section`, `article`, `nav`, `button`, `label`, `table`.
13 +- CSS: inline `<style>` for single artifacts; CSS variables for palette/spacing/type.
14 +- JS: only for real interaction/state. Use small functions, event listeners, `classList`, `dataset`. Avoid building parsers/rendering engines in one-shot HTML.
15 +- Dependencies: none by default. CDN only for a clearly valuable, pinned library.
16 +- Never use React, Vue, Angular, JSX, Tailwind build chains, or bundlers unless explicitly requested.
18 +## Workflow
20 +1. Pick a strong aesthetic direction before writing markup.
21 +2. Pick one representative screen. Do not build the whole product. For complex viewers/traces/graphs, render a static representative slice with tiny toggles, not a full analyzer.
22 +3. Sketch layout as named regions: topbar, sidebar, workbench, drawer, cards, footer.
23 +4. Define tokens in `:root`: bg, panel, text, muted, line, accent, danger, ok, radius, gap.
24 +5. Write a complete HTML document with real content, not lorem ipsum.
25 +6. CSS layout with grid/flex. Avoid JS layout measurement.
26 +7. Add minimal JS last, only if static HTML cannot express the interaction.
27 +8. Self-review with the checklist below.
29 +## Aesthetic Defaults
31 +User prefs here: SIMPLE. MINIMAL. BRUTAL.
33 +Good defaults for coding-agent/cockpit/tool UI:
35 +```css
36 +:root {
37 + color-scheme: dark;
38 + --bg: #050505;
39 + --panel: #0d0d0d;
40 + --text: #f2f2f2;
41 + --muted: #8a8a8a;
42 + --line: #f2f2f2;
43 + --accent: #d86dd8;
44 + --ok: #7ee787;
45 + --warn: #f5c542;
46 + --bad: #ff6b6b;
47 + --gap: 12px;
48 + --radius: 0;
49 + font: 14px/1.45 "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace;
51 +* { box-sizing: border-box; }
52 +body { margin: 0; background: var(--bg); color: var(--text); }
53 +button, input, textarea, select { font: inherit; }
54 +button { border: 2px solid var(--line); background: var(--text); color: var(--bg); }
55 +.panel { border: 2px solid var(--line); background: var(--panel); }
56 +.muted { color: var(--muted); }
57 +```
59 +Use color sparingly for state, not decoration. Hard borders beat mushy shadows. Dense is OK if hierarchy is obvious.
61 +## Patterns From Scout
63 +- Vercel/Web Interface Guidelines: accessibility/focus/forms/perf checklist catches most UI bugs.
64 +- Anthropic/frontend-design: choose a distinct aesthetic; intentional brutal minimalism beats generic AI gradients.
65 +- html-tools: single-file, no build, copy-pasteable artifacts; JS only for utility.
66 +- popular-web-designs: borrow vocabulary from real systems, but do not clone brand clutter.
67 +- architecture-diagram: inline SVG works well for diagrams; no canvas/lib needed.
68 +- Repo examples:
69 + - `extensions/diff-review/browser/`: real app shell, semantic panes, theme vars, aria labels, splitters.
70 + - `skills/super/brainstorming/scripts/frame-template.html`: reusable mockup/card/option primitives.
71 + - `pilot-desk/site/index.html`: tight single-file landing page.
72 + - `pilot-desk/src/main/resources/theme.css`: brutal mono cockpit language.
74 +## Layout Recipes
76 +### Dashboard / cockpit
78 +```html
79 +<div class="shell">
80 + <header class="topbar">…</header>
81 + <aside class="rail">…</aside>
82 + <main class="workbench">…</main>
83 + <aside class="drawer">…</aside>
84 +</div>
85 +```
87 +```css
88 +.shell { min-height: 100vh; display: grid; grid-template: auto 1fr / 220px 1fr 320px; }
89 +.topbar { grid-column: 1 / -1; border-bottom: 2px solid var(--line); }
90 +.rail { border-right: 2px solid var(--line); }
91 +.drawer { border-left: 2px solid var(--line); }
92 +.workbench, .rail, .drawer, .topbar { padding: var(--gap); }
93 +@media (max-width: 800px) { .shell { grid-template-columns: 1fr; } .rail, .drawer { border: 0; } }
94 +```
96 +### Clickable mockup cards
98 +```html
99 +<div class="cards">
100 + <button class="card" data-choice="a">
101 + <strong>A · Command Center</strong>
102 + <span>Transcript → prompt → terminal, one vertical loop.</span>
103 + </button>
104 +</div>
105 +```
107 +Use real `<button>` for choices unless a host helper requires `onclick="toggleSelect(this)"`.
109 +### Inline SVG diagram
111 +Use `<svg viewBox="0 0 1200 700" role="img" aria-labelledby="title desc">`. Draw arrows before boxes so lines sit behind nodes. Keep labels short.
113 +## Accessibility / UX Checklist
115 +- Every icon-only button has `aria-label`.
116 +- Every input/select/textarea has `<label>` or `aria-label`.
117 +- Use `<button>` for actions; `<a href>` for navigation.
118 +- Always include a visible `:focus-visible` rule, even for mostly static pages; never remove outline without replacement.
119 +- Hover/active/focus states are obvious.
120 +- Text handles long content: `min-width: 0`, `overflow-wrap: anywhere`, truncation where needed.
121 +- Empty/loading/error states exist.
122 +- `prefers-reduced-motion` honored if animations exist.
123 +- Use `font-variant-numeric: tabular-nums` for counters/tables.
124 +- No `transition: all`.
125 +- No disabled zoom meta.
127 +## HTML Quality Checklist
129 +- Full document, never an isolated CSS/JS snippet: `<!doctype html>`, `<html lang="en">`, charset, viewport, title.
130 +- If the user asks for a "preview", "viewer", "diagram", "tool", or "page", still output the full HTML document.
131 +- Keep first pass bounded: one screen, representative data, usually 4–20 KB. Large apps time out and are harder to judge.
132 +- Complex visualization pages: fake the data, draw the shape, keep interactions tiny. Do not implement full parsing, virtualization, or data processing unless explicitly requested.
133 +- CSS tokens in `:root` for colors/spacing/type; no one-off magic palette scattered everywhere.
134 +- One obvious primary surface.
135 +- Meaningful headings in order.
136 +- No lorem ipsum in final artifact.
137 +- No giant unstructured style soup: group CSS by tokens, base, layout, components, state, responsive.
138 +- No fragile shell heredocs for large HTML; write files directly.
139 +- Before final answer, scan for literal `:focus-visible`; add it if missing.
140 +- If used in brainstorming visual companion, include clickable `data-choice` targets and keep labels readable at browser zoom.
142 +## Common Failures
144 +- Generic SaaS slop: purple gradient, glass cards, vague blobs. Fix: pick a concrete style direction.
145 +- Too many rounded cards. Fix: grid, hard regions, stronger hierarchy.
146 +- JS for layout. Fix: CSS grid/flex.
147 +- Div-buttons. Fix: actual buttons.
148 +- Mockups that are text lists in boxes. Fix: draw the spatial relationship: panes, drawers, rails, tabs, depth.
149 +- Outputting only JS/CSS because the use case says "preview" or "viewer". Fix: full HTML document every time.
150 +- Building an entire app instead of one representative screen. Fix: one screen with realistic sample content.
151 +- Complex viewer timeout. Fix: static representative slice + tiny filter/highlight toggle; no full parser/renderer.
152 +- Over-polishing one screen. Fix: rough visual option now, iterate after click.