superpowers-zh 1.3.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.cursor-plugin/plugin.json +2 -2
  5. package/.pi/extensions/superpowers.ts +121 -0
  6. package/CLAUDE.md +1 -1
  7. package/README.md +77 -34
  8. package/RELEASE-NOTES.zh.md +150 -0
  9. package/assets/qr-wechat.jpg +0 -0
  10. package/assets/sponsors/5cookie-code.png +0 -0
  11. package/bin/superpowers-zh.js +69 -18
  12. package/docs/README.antigravity.md +7 -7
  13. package/docs/README.kimi.md +86 -0
  14. package/docs/README.openclaw.md +7 -4
  15. package/docs/README.pi.md +54 -0
  16. package/docs/README.qoder.md +95 -0
  17. package/docs/README.trae.md +6 -4
  18. package/gemini-extension.json +1 -1
  19. package/hooks/hooks-cursor.json +1 -1
  20. package/hooks/session-start +4 -12
  21. package/package.json +18 -5
  22. package/skills/brainstorming/SKILL.md +5 -0
  23. package/skills/brainstorming/scripts/frame-template.html +25 -26
  24. package/skills/brainstorming/scripts/helper.js +101 -22
  25. package/skills/brainstorming/scripts/server.cjs +428 -43
  26. package/skills/brainstorming/scripts/start-server.sh +76 -20
  27. package/skills/brainstorming/scripts/stop-server.sh +74 -9
  28. package/skills/chinese-code-review/SKILL.md +5 -0
  29. package/skills/chinese-commit-conventions/SKILL.md +5 -0
  30. package/skills/chinese-documentation/SKILL.md +5 -0
  31. package/skills/chinese-git-workflow/SKILL.md +5 -0
  32. package/skills/dispatching-parallel-agents/SKILL.md +5 -0
  33. package/skills/executing-plans/SKILL.md +7 -2
  34. package/skills/finishing-a-development-branch/SKILL.md +112 -32
  35. package/skills/mcp-builder/SKILL.md +5 -0
  36. package/skills/receiving-code-review/SKILL.md +5 -0
  37. package/skills/requesting-code-review/SKILL.md +13 -10
  38. package/skills/requesting-code-review/code-reviewer.md +124 -104
  39. package/skills/subagent-driven-development/SKILL.md +5 -0
  40. package/skills/systematic-debugging/SKILL.md +5 -0
  41. package/skills/test-driven-development/SKILL.md +5 -0
  42. package/skills/using-git-worktrees/SKILL.md +104 -97
  43. package/skills/using-superpowers/SKILL.md +6 -1
  44. package/skills/using-superpowers/references/pi-tools.md +28 -0
  45. package/skills/using-superpowers/references/qoder-tools.md +43 -0
  46. package/skills/verification-before-completion/SKILL.md +5 -0
  47. package/skills/workflow-runner/SKILL.md +5 -0
  48. package/skills/writing-plans/SKILL.md +5 -0
  49. package/skills/writing-skills/SKILL.md +5 -0
@@ -7,6 +7,7 @@ const path = require('path');
7
7
 
8
8
  const OPCODES = { TEXT: 0x01, CLOSE: 0x08, PING: 0x09, PONG: 0x0A };
9
9
  const WS_MAGIC = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
10
+ const MAX_FRAME_PAYLOAD_BYTES = 10 * 1024 * 1024;
10
11
 
11
12
  function computeAcceptKey(clientKey) {
12
13
  return crypto.createHash('sha1').update(clientKey + WS_MAGIC).digest('base64');
@@ -53,10 +54,18 @@ function decodeFrame(buffer) {
53
54
  offset = 4;
54
55
  } else if (payloadLen === 127) {
55
56
  if (buffer.length < 10) return null;
56
- payloadLen = Number(buffer.readBigUInt64BE(2));
57
+ const extendedLen = buffer.readBigUInt64BE(2);
58
+ if (extendedLen > BigInt(MAX_FRAME_PAYLOAD_BYTES)) {
59
+ throw new Error('WebSocket frame payload exceeds maximum allowed size');
60
+ }
61
+ payloadLen = Number(extendedLen);
57
62
  offset = 10;
58
63
  }
59
64
 
65
+ if (payloadLen > MAX_FRAME_PAYLOAD_BYTES) {
66
+ throw new Error('WebSocket frame payload exceeds maximum allowed size');
67
+ }
68
+
60
69
  const maskOffset = offset;
61
70
  const dataOffset = offset + 4;
62
71
  const totalLen = dataOffset + payloadLen;
@@ -73,11 +82,73 @@ function decodeFrame(buffer) {
73
82
 
74
83
  // ========== Configuration ==========
75
84
 
76
- const PORT = process.env.BRAINSTORM_PORT || (49152 + Math.floor(Math.random() * 16383));
85
+ const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null;
86
+ const randomPort = () => 49152 + Math.floor(Math.random() * 16383);
87
+ // Prefer an explicit port, else the port this session last bound (so a restart
88
+ // reuses it and an already-open browser tab reconnects), else a random high port.
89
+ function preferredPort() {
90
+ if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT);
91
+ if (PORT_FILE) {
92
+ try {
93
+ const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim());
94
+ if (Number.isInteger(p) && p > 1023 && p < 65536) return p;
95
+ } catch (e) { /* no prior port recorded */ }
96
+ }
97
+ return randomPort();
98
+ }
99
+ let PORT = preferredPort();
77
100
  const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
78
101
  const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
79
- const SCREEN_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
80
- const OWNER_PID = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
102
+ const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
103
+ const CONTENT_DIR = path.join(SESSION_DIR, 'content');
104
+ const STATE_DIR = path.join(SESSION_DIR, 'state');
105
+ const SUPERPOWERS_VERSION = readSuperpowersVersion();
106
+ const SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png';
107
+ const TELEMETRY_DISABLE_ENV_VARS = [
108
+ 'SUPERPOWERS_DISABLE_TELEMETRY',
109
+ 'DISABLE_TELEMETRY',
110
+ 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'
111
+ ];
112
+ const SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some(name => isTruthyEnv(process.env[name]));
113
+ let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
114
+
115
+ // Per-session secret key. The companion is reachable by any local browser tab
116
+ // and, when bound to a non-loopback host, by any host that can route to it.
117
+ // The key authenticates the real client uniformly across loopback, tunnel, and
118
+ // remote binds — and defeats DNS rebinding — where a Host/Origin allowlist
119
+ // cannot. It rides the served URL as ?key= and is mirrored into a cookie on
120
+ // first load so same-origin subresources and the WebSocket carry it for free.
121
+ // Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the
122
+ // same key and an already-open tab's cookie still validates.
123
+ const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null;
124
+ function generateToken() {
125
+ return crypto.randomBytes(32).toString('hex');
126
+ }
127
+
128
+ function chmodOwnerOnly(file) {
129
+ try { fs.chmodSync(file, 0o600); } catch (e) { /* best effort */ }
130
+ }
131
+
132
+ function initialToken() {
133
+ if (process.env.BRAINSTORM_TOKEN) {
134
+ return { value: process.env.BRAINSTORM_TOKEN, source: 'env' };
135
+ }
136
+ if (TOKEN_FILE) {
137
+ try {
138
+ const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();
139
+ if (/^[0-9a-f]{32,}$/i.test(t)) {
140
+ chmodOwnerOnly(TOKEN_FILE);
141
+ return { value: t, source: 'file' };
142
+ }
143
+ } catch (e) { /* no prior token recorded */ }
144
+ }
145
+ return { value: generateToken(), source: 'generated' };
146
+ }
147
+
148
+ const tokenInfo = initialToken();
149
+ let TOKEN = tokenInfo.value;
150
+ let tokenSource = tokenInfo.source;
151
+ let COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen
81
152
 
82
153
  const MIME_TYPES = {
83
154
  '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
@@ -87,14 +158,46 @@ const MIME_TYPES = {
87
158
 
88
159
  // ========== Templates and Constants ==========
89
160
 
90
- const WAITING_PAGE = `<!DOCTYPE html>
161
+ function waitingPage() {
162
+ return renderBranding(`<!DOCTYPE html>
91
163
  <html>
92
164
  <head><meta charset="utf-8"><title>Brainstorm Companion</title>
165
+ <style>
166
+ body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
167
+ h1 { color: #333; } p { color: #666; }
168
+ .brand { display: flex; align-items: center; min-width: 0; overflow: hidden; margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
169
+ .brand a { color: inherit; text-decoration: none; display: flex; align-items: center; gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
170
+ .brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; line-height: 1; transform: translateY(-1px); }
171
+ .brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }
172
+ </style>
173
+ </head>
174
+ <body><!-- BRANDING --><h1>Brainstorm Companion</h1>
175
+ <p>Waiting for the agent to push a screen...</p></body></html>`);
176
+ }
177
+
178
+ const FORBIDDEN_PAGE = `<!DOCTYPE html>
179
+ <html>
180
+ <head><meta charset="utf-8"><title>Session key required</title>
93
181
  <style>body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
94
- h1 { color: #333; } p { color: #666; }</style>
182
+ h1 { color: #333; } p { color: #666; } code { background: #f0f0f0; padding: 0.1em 0.3em; border-radius: 4px; }</style>
95
183
  </head>
96
- <body><h1>Brainstorm Companion</h1>
97
- <p>Waiting for the agent to push a screen...</p></body></html>`;
184
+ <body><h1>Session key required</h1>
185
+ <p>This page needs the full URL your coding agent gave you, including the
186
+ <code>?key=&hellip;</code> part. Copy the complete URL and open it again.</p></body></html>`;
187
+
188
+ function bootstrapPage(key) {
189
+ const jsonKey = JSON.stringify(String(key));
190
+ return `<!DOCTYPE html>
191
+ <html>
192
+ <head><meta charset="utf-8"><title>Opening Brainstorm Companion</title></head>
193
+ <body>
194
+ <script>
195
+ try { sessionStorage.setItem('brainstorm-session-key', ${jsonKey}); } catch (e) {}
196
+ location.replace('/');
197
+ </script>
198
+ </body>
199
+ </html>`;
200
+ }
98
201
 
99
202
  const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
100
203
  const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
@@ -102,35 +205,209 @@ const helperInjection = '<script>\n' + helperScript + '\n</script>';
102
205
 
103
206
  // ========== Helper Functions ==========
104
207
 
208
+ function readSuperpowersVersion() {
209
+ const root = path.join(__dirname, '../../..');
210
+ const manifests = [
211
+ path.join(root, 'package.json'),
212
+ path.join(root, '.codex-plugin/plugin.json')
213
+ ];
214
+
215
+ for (const manifest of manifests) {
216
+ try {
217
+ const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
218
+ if (data.version) return String(data.version);
219
+ } catch (e) {
220
+ // Packaged Codex plugins omit package.json; try the next manifest.
221
+ }
222
+ }
223
+
224
+ return 'unknown';
225
+ }
226
+
227
+ function isTruthyEnv(value) {
228
+ if (!value) return false;
229
+ const normalized = String(value).trim().toLowerCase();
230
+ if (!normalized) return false;
231
+ return !['0', 'false', 'no', 'off'].includes(normalized);
232
+ }
233
+
234
+ function escapeHtmlText(value) {
235
+ return String(value)
236
+ .replace(/&/g, '&amp;')
237
+ .replace(/</g, '&lt;')
238
+ .replace(/>/g, '&gt;')
239
+ .replace(/"/g, '&quot;');
240
+ }
241
+
242
+ function brandMarkup() {
243
+ const version = escapeHtmlText(SUPERPOWERS_VERSION);
244
+ const text = SUPERPOWERS_TELEMETRY_DISABLED
245
+ ? 'Prime Radiant Superpowers v' + version
246
+ : 'Superpowers v' + version;
247
+ const logo = SUPERPOWERS_TELEMETRY_DISABLED
248
+ ? ''
249
+ : '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL + '?v=' + encodeURIComponent(SUPERPOWERS_VERSION) + '" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">';
250
+
251
+ return '<div class="brand"><a href="https://github.com/obra/superpowers">' + logo + '<span class="brand-copy">' + text + '</span></a></div>';
252
+ }
253
+
254
+ function renderBranding(html) {
255
+ return html.split('<!-- BRANDING -->').join(brandMarkup());
256
+ }
257
+
105
258
  function isFullDocument(html) {
106
259
  const trimmed = html.trimStart().toLowerCase();
107
260
  return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
108
261
  }
109
262
 
110
263
  function wrapInFrame(content) {
111
- return frameTemplate.replace('<!-- CONTENT -->', content);
264
+ return renderBranding(frameTemplate).replace('<!-- CONTENT -->', content);
112
265
  }
113
266
 
114
267
  function getNewestScreen() {
115
- const files = fs.readdirSync(SCREEN_DIR)
116
- .filter(f => f.endsWith('.html'))
268
+ const files = fs.readdirSync(CONTENT_DIR)
269
+ .filter(f => !f.startsWith('.') && f.endsWith('.html'))
117
270
  .map(f => {
118
- const fp = path.join(SCREEN_DIR, f);
271
+ const fp = path.join(CONTENT_DIR, f);
272
+ if (!isRegularFileInsideContentDir(fp)) return null;
119
273
  return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
120
274
  })
275
+ .filter(Boolean)
121
276
  .sort((a, b) => b.mtime - a.mtime);
122
277
  return files.length > 0 ? files[0].path : null;
123
278
  }
124
279
 
280
+ function urlHostForHttp(host) {
281
+ const h = String(host);
282
+ if (h.startsWith('[') && h.endsWith(']')) return h;
283
+ return h.includes(':') ? '[' + h + ']' : h;
284
+ }
285
+
286
+ function companionUrl() {
287
+ return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;
288
+ }
289
+
290
+ function browserLauncherForPlatform(url, {
291
+ platform = process.platform,
292
+ osRelease = require('os').release(),
293
+ env = process.env
294
+ } = {}) {
295
+ const isWSL = platform === 'linux' && /microsoft/i.test(osRelease);
296
+ if (platform === 'darwin') return { bin: 'open', args: [url] };
297
+ if (platform === 'win32' || isWSL) {
298
+ return { bin: 'rundll32.exe', args: ['url.dll,FileProtocolHandler', url] };
299
+ }
300
+ if (env.DISPLAY || env.WAYLAND_DISPLAY) return { bin: 'xdg-open', args: [url] };
301
+ return null;
302
+ }
303
+
304
+ function isRegularFileInsideContentDir(filePath) {
305
+ let stat, realContentDir, realFilePath;
306
+ try {
307
+ stat = fs.lstatSync(filePath);
308
+ if (stat.isSymbolicLink()) return false;
309
+ if (!stat.isFile()) return false;
310
+ if (stat.nlink !== 1) return false;
311
+ realContentDir = fs.realpathSync(CONTENT_DIR);
312
+ realFilePath = fs.realpathSync(filePath);
313
+ } catch (e) {
314
+ return false;
315
+ }
316
+ return realFilePath.startsWith(realContentDir + path.sep);
317
+ }
318
+
319
+ // ========== Authentication ==========
320
+
321
+ function timingSafeEqualStr(a, b) {
322
+ const ab = Buffer.from(String(a));
323
+ const bb = Buffer.from(String(b));
324
+ if (ab.length !== bb.length) return false;
325
+ return crypto.timingSafeEqual(ab, bb);
326
+ }
327
+
328
+ function parseCookies(header) {
329
+ const out = {};
330
+ if (!header) return out;
331
+ for (const part of header.split(';')) {
332
+ const eq = part.indexOf('=');
333
+ if (eq < 0) continue;
334
+ out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
335
+ }
336
+ return out;
337
+ }
338
+
339
+ // A request is authorized if it carries the session key as ?key= or as the
340
+ // session cookie. Both are compared in constant time.
341
+ function isAuthorized(req) {
342
+ const q = req.url.indexOf('?');
343
+ if (q >= 0) {
344
+ const params = new URLSearchParams(req.url.slice(q + 1));
345
+ if (params.has('key')) {
346
+ const key = params.get('key');
347
+ return Boolean(key && timingSafeEqualStr(key, TOKEN));
348
+ }
349
+ }
350
+ const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME];
351
+ if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true;
352
+ return false;
353
+ }
354
+
355
+ function pathnameOf(url) {
356
+ const q = url.indexOf('?');
357
+ return q >= 0 ? url.slice(0, q) : url;
358
+ }
359
+
360
+ function queryKey(url) {
361
+ const q = url.indexOf('?');
362
+ if (q < 0) return null;
363
+ return new URLSearchParams(url.slice(q + 1)).get('key');
364
+ }
365
+
366
+ function securityHeaders(headers = {}) {
367
+ return {
368
+ 'Referrer-Policy': 'no-referrer',
369
+ 'Cache-Control': 'no-store',
370
+ 'X-Frame-Options': 'DENY',
371
+ 'Content-Security-Policy': "frame-ancestors 'none'",
372
+ 'Cross-Origin-Resource-Policy': 'same-origin',
373
+ ...headers
374
+ };
375
+ }
376
+
377
+ function isAllowedWebSocketOrigin(req) {
378
+ const origin = req.headers.origin;
379
+ if (!origin) return true;
380
+ const host = req.headers.host;
381
+ if (!host) return false;
382
+ return origin === 'http://' + host;
383
+ }
384
+
125
385
  // ========== HTTP Request Handler ==========
126
386
 
127
387
  function handleRequest(req, res) {
128
- touchActivity();
129
- if (req.method === 'GET' && req.url === '/') {
388
+ if (!isAuthorized(req)) {
389
+ res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
390
+ res.end(FORBIDDEN_PAGE);
391
+ return;
392
+ }
393
+ touchActivity(); // only authorized requests count as activity
394
+
395
+ // Mirror the key into a cookie so same-origin subresources (/files/*) can
396
+ // authenticate after bootstrap. HttpOnly keeps it away from page scripts; the
397
+ // WebSocket Origin check below is what blocks cross-origin localhost injection.
398
+ res.setHeader('Set-Cookie',
399
+ COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');
400
+
401
+ const pathname = pathnameOf(req.url);
402
+ const keyFromQuery = queryKey(req.url);
403
+ if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
404
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
405
+ res.end(bootstrapPage(keyFromQuery));
406
+ } else if (req.method === 'GET' && pathname === '/') {
130
407
  const screenFile = getNewestScreen();
131
408
  let html = screenFile
132
409
  ? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
133
- : WAITING_PAGE;
410
+ : waitingPage();
134
411
 
135
412
  if (html.includes('</body>')) {
136
413
  html = html.replace('</body>', helperInjection + '\n</body>');
@@ -138,22 +415,24 @@ function handleRequest(req, res) {
138
415
  html += helperInjection;
139
416
  }
140
417
 
141
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
418
+ res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
142
419
  res.end(html);
143
- } else if (req.method === 'GET' && req.url.startsWith('/files/')) {
144
- const fileName = req.url.slice(7);
145
- const filePath = path.join(SCREEN_DIR, path.basename(fileName));
146
- if (!fs.existsSync(filePath)) {
147
- res.writeHead(404);
420
+ } else if (req.method === 'GET' && pathname.startsWith('/files/')) {
421
+ const fileName = path.basename(pathname.slice(7));
422
+ const filePath = path.join(CONTENT_DIR, fileName);
423
+ // Reject empty/dotfile names and anything that isn't a regular file —
424
+ // `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).
425
+ if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
426
+ res.writeHead(404, securityHeaders());
148
427
  res.end('Not found');
149
428
  return;
150
429
  }
151
430
  const ext = path.extname(filePath).toLowerCase();
152
431
  const contentType = MIME_TYPES[ext] || 'application/octet-stream';
153
- res.writeHead(200, { 'Content-Type': contentType });
432
+ res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));
154
433
  res.end(fs.readFileSync(filePath));
155
434
  } else {
156
- res.writeHead(404);
435
+ res.writeHead(404, securityHeaders());
157
436
  res.end('Not found');
158
437
  }
159
438
  }
@@ -163,6 +442,8 @@ function handleRequest(req, res) {
163
442
  const clients = new Set();
164
443
 
165
444
  function handleUpgrade(req, socket) {
445
+ if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }
446
+
166
447
  const key = req.headers['sec-websocket-key'];
167
448
  if (!key) { socket.destroy(); return; }
168
449
 
@@ -229,8 +510,8 @@ function handleMessage(text) {
229
510
  }
230
511
  touchActivity();
231
512
  console.log(JSON.stringify({ source: 'user-event', ...event }));
232
- if (event.choice) {
233
- const eventsFile = path.join(SCREEN_DIR, '.events');
513
+ if (event && event.choice) {
514
+ const eventsFile = path.join(STATE_DIR, 'events');
234
515
  fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
235
516
  }
236
517
  }
@@ -242,9 +523,44 @@ function broadcast(msg) {
242
523
  }
243
524
  }
244
525
 
526
+ // Best-effort: open the user's browser the first time a screen is actually ready
527
+ // to show. Skips when disabled, on a non-loopback (remote) bind, or when a
528
+ // browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
529
+ let browserOpened = false;
530
+ function maybeOpenBrowser() {
531
+ if (browserOpened) return;
532
+ browserOpened = true;
533
+ if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion
534
+ if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;
535
+ if (clients.size > 0) return; // the user already opened it
536
+ const url = companionUrl(); // must carry the key or the gate 403s it
537
+ const cp = require('child_process');
538
+ // Operator-provided launcher: run as given (this env var is trusted operator input).
539
+ if (process.env.BRAINSTORM_OPEN_CMD) {
540
+ try { cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {}); } catch (e) { /* best effort */ }
541
+ return;
542
+ }
543
+ // Platform launchers: pass the URL as an argv element via execFile (no shell),
544
+ // so a url-host containing shell metacharacters can't inject a command.
545
+ const launcher = browserLauncherForPlatform(url);
546
+ if (!launcher) return; // headless: nothing to open
547
+ try { cp.execFile(launcher.bin, launcher.args, () => {}); } catch (e) { /* best effort */ }
548
+ }
549
+
245
550
  // ========== Activity Tracking ==========
246
551
 
247
- const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
552
+ // Idle timeout: shut down after this long with no activity. Default 4 hours;
553
+ // override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
554
+ const IDLE_TIMEOUT_MS = (() => {
555
+ const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);
556
+ return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;
557
+ })();
558
+ // How often the watchdog checks for owner-death / idleness. Configurable mainly
559
+ // so tests can run fast; production default is 60s.
560
+ const LIFECYCLE_CHECK_MS = (() => {
561
+ const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);
562
+ return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;
563
+ })();
248
564
  let lastActivity = Date.now();
249
565
 
250
566
  function touchActivity() {
@@ -258,34 +574,36 @@ const debounceTimers = new Map();
258
574
  // ========== Server Startup ==========
259
575
 
260
576
  function startServer() {
261
- if (!fs.existsSync(SCREEN_DIR)) fs.mkdirSync(SCREEN_DIR, { recursive: true });
577
+ if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
578
+ if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
262
579
 
263
580
  // Track known files to distinguish new screens from updates.
264
581
  // macOS fs.watch reports 'rename' for both new files and overwrites,
265
582
  // so we can't rely on eventType alone.
266
583
  const knownFiles = new Set(
267
- fs.readdirSync(SCREEN_DIR).filter(f => f.endsWith('.html'))
584
+ fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
268
585
  );
269
586
 
270
587
  const server = http.createServer(handleRequest);
271
588
  server.on('upgrade', handleUpgrade);
272
589
 
273
- const watcher = fs.watch(SCREEN_DIR, (eventType, filename) => {
274
- if (!filename || !filename.endsWith('.html')) return;
590
+ const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
591
+ if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;
275
592
 
276
593
  if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
277
594
  debounceTimers.set(filename, setTimeout(() => {
278
595
  debounceTimers.delete(filename);
279
- const filePath = path.join(SCREEN_DIR, filename);
596
+ const filePath = path.join(CONTENT_DIR, filename);
280
597
 
281
598
  if (!fs.existsSync(filePath)) return; // file was deleted
282
599
  touchActivity();
283
600
 
284
601
  if (!knownFiles.has(filename)) {
285
602
  knownFiles.add(filename);
286
- const eventsFile = path.join(SCREEN_DIR, '.events');
603
+ const eventsFile = path.join(STATE_DIR, 'events');
287
604
  if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
288
605
  console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
606
+ maybeOpenBrowser();
289
607
  } else {
290
608
  console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
291
609
  }
@@ -297,42 +615,109 @@ function startServer() {
297
615
 
298
616
  function shutdown(reason) {
299
617
  console.log(JSON.stringify({ type: 'server-stopped', reason }));
300
- const infoFile = path.join(SCREEN_DIR, '.server-info');
618
+ const infoFile = path.join(STATE_DIR, 'server-info');
301
619
  if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
302
620
  fs.writeFileSync(
303
- path.join(SCREEN_DIR, '.server-stopped'),
621
+ path.join(STATE_DIR, 'server-stopped'),
304
622
  JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
305
623
  );
306
624
  watcher.close();
307
625
  clearInterval(lifecycleCheck);
626
+ // Close any upgraded WebSocket sockets so server.close() can complete and
627
+ // the process actually exits instead of lingering on an open connection.
628
+ for (const socket of clients) {
629
+ try { socket.destroy(); } catch (e) { /* already gone */ }
630
+ }
308
631
  server.close(() => process.exit(0));
309
632
  }
310
633
 
311
634
  function ownerAlive() {
312
- if (!OWNER_PID) return true;
313
- try { process.kill(OWNER_PID, 0); return true; } catch (e) { return false; }
635
+ if (!ownerPid) return true;
636
+ try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
314
637
  }
315
638
 
316
- // Check every 60s: exit if owner process died or idle for 30 minutes
639
+ // Periodically exit if the owner process died or we've been idle too long.
317
640
  const lifecycleCheck = setInterval(() => {
318
641
  if (!ownerAlive()) shutdown('owner process exited');
319
642
  else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown('idle timeout');
320
- }, 60 * 1000);
643
+ }, LIFECYCLE_CHECK_MS);
321
644
  lifecycleCheck.unref();
322
645
 
323
- server.listen(PORT, HOST, () => {
646
+ // Validate owner PID at startup. If it's already dead, the PID resolution
647
+ // was wrong (common on WSL, Tailscale SSH, and cross-user scenarios).
648
+ // Disable monitoring and rely on the idle timeout instead.
649
+ if (ownerPid) {
650
+ try { process.kill(ownerPid, 0); }
651
+ catch (e) {
652
+ if (e.code !== 'EPERM') {
653
+ console.log(JSON.stringify({ type: 'owner-pid-invalid', pid: ownerPid, reason: 'dead at startup' }));
654
+ ownerPid = null;
655
+ }
656
+ }
657
+ }
658
+
659
+ // If the preferred port is already taken (e.g. a previous server is still
660
+ // alive), fall back to a random port once instead of failing.
661
+ let triedFallback = false;
662
+
663
+ function onListen() {
664
+ // Cookie name keys on the ACTUAL bound port (may differ from the preferred
665
+ // one after an EADDRINUSE fallback) so it can't collide with another server's
666
+ // cookie in the shared localhost jar.
667
+ COOKIE_NAME = 'brainstorm-key-' + PORT;
668
+ // Record the bound port AND token so the next restart of this session reuses
669
+ // them — but ONLY when we got our preferred port. On a fallback we bound a
670
+ // *different* port because someone else holds the preferred one; persisting
671
+ // would overwrite the shared files and strand that other session's open tab.
672
+ if (PORT_FILE && !triedFallback) {
673
+ try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
674
+ if (TOKEN_FILE) {
675
+ try {
676
+ fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });
677
+ chmodOwnerOnly(TOKEN_FILE);
678
+ } catch (e) { /* best effort */ }
679
+ }
680
+ }
324
681
  const info = JSON.stringify({
325
682
  type: 'server-started', port: Number(PORT), host: HOST,
326
- url_host: URL_HOST, url: 'http://' + URL_HOST + ':' + PORT,
327
- screen_dir: SCREEN_DIR
683
+ url_host: URL_HOST, url: companionUrl(),
684
+ screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
328
685
  });
329
686
  console.log(info);
330
- fs.writeFileSync(path.join(SCREEN_DIR, '.server-info'), info + '\n');
687
+ // server-info embeds the key — keep it owner-only.
688
+ fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
689
+ }
690
+
691
+ server.on('error', (err) => {
692
+ if (err.code === 'EADDRINUSE' && !triedFallback) {
693
+ if (tokenSource === 'env') {
694
+ console.error('Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; refusing fallback with explicit token');
695
+ process.exit(1);
696
+ }
697
+ triedFallback = true;
698
+ PORT = randomPort();
699
+ if (tokenSource === 'file') {
700
+ TOKEN = generateToken();
701
+ tokenSource = 'generated-fallback';
702
+ }
703
+ server.listen(PORT, HOST, onListen);
704
+ } else {
705
+ console.error('Server failed to bind:', err.message);
706
+ process.exit(1);
707
+ }
331
708
  });
709
+ server.listen(PORT, HOST, onListen);
332
710
  }
333
711
 
334
712
  if (require.main === module) {
335
713
  startServer();
336
714
  }
337
715
 
338
- module.exports = { computeAcceptKey, encodeFrame, decodeFrame, OPCODES };
716
+ module.exports = {
717
+ computeAcceptKey,
718
+ encodeFrame,
719
+ decodeFrame,
720
+ browserLauncherForPlatform,
721
+ OPCODES,
722
+ MAX_FRAME_PAYLOAD_BYTES
723
+ };