claude-everything-workflow 0.2.13 → 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/AGENTS.md +13 -23
- package/commands/pr.md +1 -1
- package/docs/plugins.md +1 -1
- package/evals/routing-scenarios.json +19 -19
- package/harness/manifest.json +28 -62
- package/package.json +1 -1
- package/rules/common/performance.md +3 -1
- package/rules/common/testing.md +2 -8
- package/scripts/install-antigravity.js +242 -18
- package/scripts/retired-skill-files.json +25 -0
- package/scripts/upstream-capability-map.json +16 -13
- package/scripts/verify/install-rules.test.js +137 -3
- package/scripts/verify/skill-invocation.test.js +18 -2
- package/scripts/verify/skill-manifest-checks.js +1 -1
- package/scripts/verify/skill-manifest-checks.test.js +53 -0
- package/scripts/verify/workflow-checks.js +87 -8
- package/skills/README.md +2 -6
- package/skills/code-review/SKILL.md +1 -1
- package/skills/codebase-design/SKILL.md +7 -1
- package/skills/feature-acceptance/references/e2e-testing.md +8 -2
- package/skills/grilling/SKILL.md +1 -1
- package/skills/handoff/SKILL.md +2 -2
- package/skills/implement/SKILL.md +3 -2
- package/skills/resolving-merge-conflicts/SKILL.md +1 -1
- package/skills/spec-gate/SKILL.md +1 -1
- package/skills/systematic-debugging/SKILL.md +1 -1
- package/skills/systematic-debugging/references/diagnosing-bugs.upstream.md +1 -1
- package/skills/test-driven-development/SKILL.md +1 -1
- package/skills/to-tickets/SKILL.md +1 -1
- package/skills/triage/SKILL.md +2 -2
- package/skills/using-superpowers/SKILL.md +5 -5
- package/skills/using-superpowers/references/process-outcomes.md +1 -1
- package/skills/domain-modeling/SKILL.md +0 -103
- package/skills/improve-codebase-architecture/SKILL.md +0 -47
- package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
- package/skills/prototype/SKILL.md +0 -50
- package/skills/prototype/references/logic.md +0 -28
- package/skills/prototype/references/ui.md +0 -30
- package/skills/visual-companion/SKILL.md +0 -62
- package/skills/visual-companion/agents/openai.yaml +0 -4
- package/skills/visual-companion/references/guide.md +0 -298
- package/skills/visual-companion/scripts/frame-template.html +0 -243
- package/skills/visual-companion/scripts/helper.js +0 -167
- package/skills/visual-companion/scripts/pages.cjs +0 -28
- package/skills/visual-companion/scripts/server-utils.cjs +0 -82
- package/skills/visual-companion/scripts/server.cjs +0 -583
- package/skills/visual-companion/scripts/start-server.sh +0 -223
- package/skills/visual-companion/scripts/stop-server.sh +0 -120
- package/skills/visual-companion/scripts/websocket.cjs +0 -86
|
@@ -1,583 +0,0 @@
|
|
|
1
|
-
const crypto = require('crypto');
|
|
2
|
-
const http = require('http');
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const path = require('path');
|
|
5
|
-
const {
|
|
6
|
-
computeAcceptKey,
|
|
7
|
-
encodeFrame,
|
|
8
|
-
decodeFrame,
|
|
9
|
-
OPCODES,
|
|
10
|
-
MAX_FRAME_PAYLOAD_BYTES,
|
|
11
|
-
} = require('./websocket.cjs');
|
|
12
|
-
const {
|
|
13
|
-
urlHostForHttp,
|
|
14
|
-
browserLauncherForPlatform,
|
|
15
|
-
timingSafeEqualStr,
|
|
16
|
-
parseCookies,
|
|
17
|
-
pathnameOf,
|
|
18
|
-
queryKey,
|
|
19
|
-
securityHeaders,
|
|
20
|
-
isAllowedWebSocketOrigin,
|
|
21
|
-
} = require('./server-utils.cjs');
|
|
22
|
-
const { FORBIDDEN_PAGE, bootstrapPage } = require('./pages.cjs');
|
|
23
|
-
|
|
24
|
-
// ========== Configuration ==========
|
|
25
|
-
|
|
26
|
-
const PORT_FILE = process.env.BRAINSTORM_PORT_FILE || null;
|
|
27
|
-
const randomPort = () => 49152 + Math.floor(Math.random() * 16383);
|
|
28
|
-
// Prefer an explicit port, else the port this session last bound (so a restart
|
|
29
|
-
// reuses it and an already-open browser tab reconnects), else a random high port.
|
|
30
|
-
function preferredPort() {
|
|
31
|
-
if (process.env.BRAINSTORM_PORT) return Number(process.env.BRAINSTORM_PORT);
|
|
32
|
-
if (PORT_FILE) {
|
|
33
|
-
try {
|
|
34
|
-
const p = Number(fs.readFileSync(PORT_FILE, 'utf-8').trim());
|
|
35
|
-
if (Number.isInteger(p) && p > 1023 && p < 65536) return p;
|
|
36
|
-
} catch (e) { /* no prior port recorded */ }
|
|
37
|
-
}
|
|
38
|
-
return randomPort();
|
|
39
|
-
}
|
|
40
|
-
let PORT = preferredPort();
|
|
41
|
-
const HOST = process.env.BRAINSTORM_HOST || '127.0.0.1';
|
|
42
|
-
const URL_HOST = process.env.BRAINSTORM_URL_HOST || (HOST === '127.0.0.1' ? 'localhost' : HOST);
|
|
43
|
-
const SESSION_DIR = process.env.BRAINSTORM_DIR || '/tmp/brainstorm';
|
|
44
|
-
const CONTENT_DIR = path.join(SESSION_DIR, 'content');
|
|
45
|
-
const STATE_DIR = path.join(SESSION_DIR, 'state');
|
|
46
|
-
const SUPERPOWERS_VERSION = readSuperpowersVersion();
|
|
47
|
-
const SUPERPOWERS_BRAND_IMAGE_URL = 'https://primeradiant.com/brand/superpowers-visual-brainstorming-logo.png';
|
|
48
|
-
const TELEMETRY_DISABLE_ENV_VARS = [
|
|
49
|
-
'SUPERPOWERS_DISABLE_TELEMETRY',
|
|
50
|
-
'DISABLE_TELEMETRY',
|
|
51
|
-
'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'
|
|
52
|
-
];
|
|
53
|
-
const SUPERPOWERS_TELEMETRY_DISABLED = TELEMETRY_DISABLE_ENV_VARS.some(name => isTruthyEnv(process.env[name]));
|
|
54
|
-
let ownerPid = process.env.BRAINSTORM_OWNER_PID ? Number(process.env.BRAINSTORM_OWNER_PID) : null;
|
|
55
|
-
|
|
56
|
-
// Per-session secret key. The companion is reachable by any local browser tab
|
|
57
|
-
// and, when bound to a non-loopback host, by any host that can route to it.
|
|
58
|
-
// The key authenticates the real client uniformly across loopback, tunnel, and
|
|
59
|
-
// remote binds — and defeats DNS rebinding — where a Host/Origin allowlist
|
|
60
|
-
// cannot. It rides the served URL as ?key= and is mirrored into a cookie on
|
|
61
|
-
// first load so same-origin subresources and the WebSocket carry it for free.
|
|
62
|
-
// Persisted alongside the port (BRAINSTORM_TOKEN_FILE) so a restart keeps the
|
|
63
|
-
// same key and an already-open tab's cookie still validates.
|
|
64
|
-
const TOKEN_FILE = process.env.BRAINSTORM_TOKEN_FILE || null;
|
|
65
|
-
function generateToken() {
|
|
66
|
-
return crypto.randomBytes(32).toString('hex');
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function chmodOwnerOnly(file) {
|
|
70
|
-
try { fs.chmodSync(file, 0o600); } catch (e) { /* best effort */ }
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function initialToken() {
|
|
74
|
-
if (process.env.BRAINSTORM_TOKEN) {
|
|
75
|
-
return { value: process.env.BRAINSTORM_TOKEN, source: 'env' };
|
|
76
|
-
}
|
|
77
|
-
if (TOKEN_FILE) {
|
|
78
|
-
try {
|
|
79
|
-
const t = fs.readFileSync(TOKEN_FILE, 'utf-8').trim();
|
|
80
|
-
if (/^[0-9a-f]{32,}$/i.test(t)) {
|
|
81
|
-
chmodOwnerOnly(TOKEN_FILE);
|
|
82
|
-
return { value: t, source: 'file' };
|
|
83
|
-
}
|
|
84
|
-
} catch (e) { /* no prior token recorded */ }
|
|
85
|
-
}
|
|
86
|
-
return { value: generateToken(), source: 'generated' };
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const tokenInfo = initialToken();
|
|
90
|
-
let TOKEN = tokenInfo.value;
|
|
91
|
-
let tokenSource = tokenInfo.source;
|
|
92
|
-
let COOKIE_NAME = 'brainstorm-key-' + PORT; // refined to the actual bound port in onListen
|
|
93
|
-
|
|
94
|
-
const MIME_TYPES = {
|
|
95
|
-
'.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript',
|
|
96
|
-
'.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg',
|
|
97
|
-
'.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml'
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
// ========== Templates and Constants ==========
|
|
101
|
-
|
|
102
|
-
function waitingPage() {
|
|
103
|
-
return renderBranding(`<!DOCTYPE html>
|
|
104
|
-
<html>
|
|
105
|
-
<head><meta charset="utf-8"><title>Visual Companion</title>
|
|
106
|
-
<style>
|
|
107
|
-
body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; }
|
|
108
|
-
h1 { color: #333; } p { color: #666; }
|
|
109
|
-
.brand { display: flex; align-items: center; min-width: 0; overflow: hidden;
|
|
110
|
-
margin-bottom: 1.5rem; color: #666; font-size: 0.9rem; line-height: 1; }
|
|
111
|
-
.brand a { color: inherit; text-decoration: none; display: flex; align-items: center;
|
|
112
|
-
gap: 0.5rem; min-width: 0; max-width: 100%; line-height: 1; }
|
|
113
|
-
.brand-copy { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis;
|
|
114
|
-
white-space: nowrap; line-height: 1; transform: translateY(-1px); }
|
|
115
|
-
.brand-logo { display: block; height: 1em; width: auto; max-width: 180px; filter: invert(1); }
|
|
116
|
-
</style>
|
|
117
|
-
</head>
|
|
118
|
-
<body><!-- BRANDING --><h1>Visual Companion</h1>
|
|
119
|
-
<p>Waiting for the agent to push a screen...</p></body></html>`);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const frameTemplate = fs.readFileSync(path.join(__dirname, 'frame-template.html'), 'utf-8');
|
|
123
|
-
const helperScript = fs.readFileSync(path.join(__dirname, 'helper.js'), 'utf-8');
|
|
124
|
-
const helperInjection = '<script>\n' + helperScript + '\n</script>';
|
|
125
|
-
|
|
126
|
-
// ========== Helper Functions ==========
|
|
127
|
-
|
|
128
|
-
function readSuperpowersVersion() {
|
|
129
|
-
const root = path.join(__dirname, '../../..');
|
|
130
|
-
const manifests = [
|
|
131
|
-
path.join(root, 'package.json'),
|
|
132
|
-
path.join(root, '.codex-plugin/plugin.json')
|
|
133
|
-
];
|
|
134
|
-
|
|
135
|
-
for (const manifest of manifests) {
|
|
136
|
-
try {
|
|
137
|
-
const data = JSON.parse(fs.readFileSync(manifest, 'utf-8'));
|
|
138
|
-
if (data.version) return String(data.version);
|
|
139
|
-
} catch (e) {
|
|
140
|
-
// Packaged Codex plugins omit package.json; try the next manifest.
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
return 'unknown';
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function isTruthyEnv(value) {
|
|
148
|
-
if (!value) return false;
|
|
149
|
-
const normalized = String(value).trim().toLowerCase();
|
|
150
|
-
if (!normalized) return false;
|
|
151
|
-
return !['0', 'false', 'no', 'off'].includes(normalized);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
function escapeHtmlText(value) {
|
|
155
|
-
return String(value)
|
|
156
|
-
.replace(/&/g, '&')
|
|
157
|
-
.replace(/</g, '<')
|
|
158
|
-
.replace(/>/g, '>')
|
|
159
|
-
.replace(/"/g, '"');
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function brandMarkup() {
|
|
163
|
-
const version = escapeHtmlText(SUPERPOWERS_VERSION);
|
|
164
|
-
const text = SUPERPOWERS_TELEMETRY_DISABLED
|
|
165
|
-
? 'Prime Radiant Superpowers v' + version
|
|
166
|
-
: 'Superpowers v' + version;
|
|
167
|
-
const logo = SUPERPOWERS_TELEMETRY_DISABLED
|
|
168
|
-
? ''
|
|
169
|
-
: '<img class="brand-logo" src="' + SUPERPOWERS_BRAND_IMAGE_URL +
|
|
170
|
-
'?v=' + encodeURIComponent(SUPERPOWERS_VERSION) +
|
|
171
|
-
'" alt="Prime Radiant" referrerpolicy="no-referrer" decoding="async">';
|
|
172
|
-
|
|
173
|
-
return '<div class="brand"><a href="https://github.com/obra/superpowers">' +
|
|
174
|
-
logo + '<span class="brand-copy">' + text + '</span></a></div>';
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function renderBranding(html) {
|
|
178
|
-
return html.split('<!-- BRANDING -->').join(brandMarkup());
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function isFullDocument(html) {
|
|
182
|
-
const trimmed = html.trimStart().toLowerCase();
|
|
183
|
-
return trimmed.startsWith('<!doctype') || trimmed.startsWith('<html');
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
function wrapInFrame(content) {
|
|
187
|
-
return renderBranding(frameTemplate).replace('<!-- CONTENT -->', content);
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
function getNewestScreen() {
|
|
191
|
-
const files = fs.readdirSync(CONTENT_DIR)
|
|
192
|
-
.filter(f => !f.startsWith('.') && f.endsWith('.html'))
|
|
193
|
-
.map(f => {
|
|
194
|
-
const fp = path.join(CONTENT_DIR, f);
|
|
195
|
-
if (!isRegularFileInsideContentDir(fp)) return null;
|
|
196
|
-
return { path: fp, mtime: fs.statSync(fp).mtime.getTime() };
|
|
197
|
-
})
|
|
198
|
-
.filter(Boolean)
|
|
199
|
-
.sort((a, b) => b.mtime - a.mtime);
|
|
200
|
-
return files.length > 0 ? files[0].path : null;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
function companionUrl() {
|
|
204
|
-
return 'http://' + urlHostForHttp(URL_HOST) + ':' + PORT + '/?key=' + TOKEN;
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
function isRegularFileInsideContentDir(filePath) {
|
|
208
|
-
let stat, realContentDir, realFilePath;
|
|
209
|
-
try {
|
|
210
|
-
stat = fs.lstatSync(filePath);
|
|
211
|
-
if (stat.isSymbolicLink()) return false;
|
|
212
|
-
if (!stat.isFile()) return false;
|
|
213
|
-
if (stat.nlink !== 1) return false;
|
|
214
|
-
realContentDir = fs.realpathSync(CONTENT_DIR);
|
|
215
|
-
realFilePath = fs.realpathSync(filePath);
|
|
216
|
-
} catch (e) {
|
|
217
|
-
return false;
|
|
218
|
-
}
|
|
219
|
-
return realFilePath.startsWith(realContentDir + path.sep);
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// ========== Authentication ==========
|
|
223
|
-
|
|
224
|
-
// A request is authorized if it carries the session key as ?key= or as the
|
|
225
|
-
// session cookie. Both are compared in constant time.
|
|
226
|
-
function isAuthorized(req) {
|
|
227
|
-
const q = req.url.indexOf('?');
|
|
228
|
-
if (q >= 0) {
|
|
229
|
-
const params = new URLSearchParams(req.url.slice(q + 1));
|
|
230
|
-
if (params.has('key')) {
|
|
231
|
-
const key = params.get('key');
|
|
232
|
-
return Boolean(key && timingSafeEqualStr(key, TOKEN));
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
const cookie = parseCookies(req.headers['cookie'])[COOKIE_NAME];
|
|
236
|
-
if (cookie && timingSafeEqualStr(cookie, TOKEN)) return true;
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
// ========== HTTP Request Handler ==========
|
|
241
|
-
|
|
242
|
-
function handleRequest(req, res) {
|
|
243
|
-
if (!isAuthorized(req)) {
|
|
244
|
-
res.writeHead(403, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
|
|
245
|
-
res.end(FORBIDDEN_PAGE);
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
touchActivity(); // only authorized requests count as activity
|
|
249
|
-
|
|
250
|
-
// Mirror the key into a cookie so same-origin subresources (/files/*) can
|
|
251
|
-
// authenticate after bootstrap. HttpOnly keeps it away from page scripts; the
|
|
252
|
-
// WebSocket Origin check below is what blocks cross-origin localhost injection.
|
|
253
|
-
res.setHeader('Set-Cookie',
|
|
254
|
-
COOKIE_NAME + '=' + TOKEN + '; HttpOnly; SameSite=Strict; Path=/');
|
|
255
|
-
|
|
256
|
-
const pathname = pathnameOf(req.url);
|
|
257
|
-
const keyFromQuery = queryKey(req.url);
|
|
258
|
-
if (req.method === 'GET' && pathname === '/' && keyFromQuery && timingSafeEqualStr(keyFromQuery, TOKEN)) {
|
|
259
|
-
res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
|
|
260
|
-
res.end(bootstrapPage(keyFromQuery));
|
|
261
|
-
} else if (req.method === 'GET' && pathname === '/') {
|
|
262
|
-
const screenFile = getNewestScreen();
|
|
263
|
-
let html = screenFile
|
|
264
|
-
? (raw => isFullDocument(raw) ? raw : wrapInFrame(raw))(fs.readFileSync(screenFile, 'utf-8'))
|
|
265
|
-
: waitingPage();
|
|
266
|
-
|
|
267
|
-
if (html.includes('</body>')) {
|
|
268
|
-
html = html.replace('</body>', helperInjection + '\n</body>');
|
|
269
|
-
} else {
|
|
270
|
-
html += helperInjection;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
res.writeHead(200, securityHeaders({ 'Content-Type': 'text/html; charset=utf-8' }));
|
|
274
|
-
res.end(html);
|
|
275
|
-
} else if (req.method === 'GET' && pathname.startsWith('/files/')) {
|
|
276
|
-
const fileName = path.basename(pathname.slice(7));
|
|
277
|
-
const filePath = path.join(CONTENT_DIR, fileName);
|
|
278
|
-
// Reject empty/dotfile names and anything that isn't a regular file —
|
|
279
|
-
// `/files/` would otherwise resolve to CONTENT_DIR and crash readFileSync (EISDIR).
|
|
280
|
-
if (!fileName || fileName.startsWith('.') || !isRegularFileInsideContentDir(filePath)) {
|
|
281
|
-
res.writeHead(404, securityHeaders());
|
|
282
|
-
res.end('Not found');
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
const ext = path.extname(filePath).toLowerCase();
|
|
286
|
-
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
287
|
-
res.writeHead(200, securityHeaders({ 'Content-Type': contentType }));
|
|
288
|
-
res.end(fs.readFileSync(filePath));
|
|
289
|
-
} else {
|
|
290
|
-
res.writeHead(404, securityHeaders());
|
|
291
|
-
res.end('Not found');
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// ========== WebSocket Connection Handling ==========
|
|
296
|
-
|
|
297
|
-
const clients = new Set();
|
|
298
|
-
|
|
299
|
-
function handleUpgrade(req, socket) {
|
|
300
|
-
if (!isAuthorized(req) || !isAllowedWebSocketOrigin(req)) { socket.destroy(); return; }
|
|
301
|
-
|
|
302
|
-
const key = req.headers['sec-websocket-key'];
|
|
303
|
-
if (!key) { socket.destroy(); return; }
|
|
304
|
-
|
|
305
|
-
const accept = computeAcceptKey(key);
|
|
306
|
-
socket.write(
|
|
307
|
-
'HTTP/1.1 101 Switching Protocols\r\n' +
|
|
308
|
-
'Upgrade: websocket\r\n' +
|
|
309
|
-
'Connection: Upgrade\r\n' +
|
|
310
|
-
'Sec-WebSocket-Accept: ' + accept + '\r\n\r\n'
|
|
311
|
-
);
|
|
312
|
-
|
|
313
|
-
let buffer = Buffer.alloc(0);
|
|
314
|
-
clients.add(socket);
|
|
315
|
-
|
|
316
|
-
socket.on('data', (chunk) => {
|
|
317
|
-
buffer = Buffer.concat([buffer, chunk]);
|
|
318
|
-
while (buffer.length > 0) {
|
|
319
|
-
let result;
|
|
320
|
-
try {
|
|
321
|
-
result = decodeFrame(buffer);
|
|
322
|
-
} catch (e) {
|
|
323
|
-
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
|
|
324
|
-
clients.delete(socket);
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if (!result) break;
|
|
328
|
-
buffer = buffer.slice(result.bytesConsumed);
|
|
329
|
-
|
|
330
|
-
switch (result.opcode) {
|
|
331
|
-
case OPCODES.TEXT:
|
|
332
|
-
handleMessage(result.payload.toString());
|
|
333
|
-
break;
|
|
334
|
-
case OPCODES.CLOSE:
|
|
335
|
-
socket.end(encodeFrame(OPCODES.CLOSE, Buffer.alloc(0)));
|
|
336
|
-
clients.delete(socket);
|
|
337
|
-
return;
|
|
338
|
-
case OPCODES.PING:
|
|
339
|
-
socket.write(encodeFrame(OPCODES.PONG, result.payload));
|
|
340
|
-
break;
|
|
341
|
-
case OPCODES.PONG:
|
|
342
|
-
break;
|
|
343
|
-
default: {
|
|
344
|
-
const closeBuf = Buffer.alloc(2);
|
|
345
|
-
closeBuf.writeUInt16BE(1003);
|
|
346
|
-
socket.end(encodeFrame(OPCODES.CLOSE, closeBuf));
|
|
347
|
-
clients.delete(socket);
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
});
|
|
353
|
-
|
|
354
|
-
socket.on('close', () => clients.delete(socket));
|
|
355
|
-
socket.on('error', () => clients.delete(socket));
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
function handleMessage(text) {
|
|
359
|
-
let event;
|
|
360
|
-
try {
|
|
361
|
-
event = JSON.parse(text);
|
|
362
|
-
} catch (e) {
|
|
363
|
-
console.error('Failed to parse WebSocket message:', e.message);
|
|
364
|
-
return;
|
|
365
|
-
}
|
|
366
|
-
touchActivity();
|
|
367
|
-
console.log(JSON.stringify({ source: 'user-event', ...event }));
|
|
368
|
-
if (event && event.choice) {
|
|
369
|
-
const eventsFile = path.join(STATE_DIR, 'events');
|
|
370
|
-
fs.appendFileSync(eventsFile, JSON.stringify(event) + '\n');
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
function broadcast(msg) {
|
|
375
|
-
const frame = encodeFrame(OPCODES.TEXT, Buffer.from(JSON.stringify(msg)));
|
|
376
|
-
for (const socket of clients) {
|
|
377
|
-
try { socket.write(frame); } catch (e) { clients.delete(socket); }
|
|
378
|
-
}
|
|
379
|
-
}
|
|
380
|
-
|
|
381
|
-
// Best-effort: open the user's browser the first time a screen is actually ready
|
|
382
|
-
// to show. Skips when disabled, on a non-loopback (remote) bind, or when a
|
|
383
|
-
// browser is already connected. Override the launcher with BRAINSTORM_OPEN_CMD.
|
|
384
|
-
let browserOpened = false;
|
|
385
|
-
function maybeOpenBrowser() {
|
|
386
|
-
if (browserOpened) return;
|
|
387
|
-
browserOpened = true;
|
|
388
|
-
if (!process.env.BRAINSTORM_OPEN) return; // opt-in: only after the user approves the companion
|
|
389
|
-
if (HOST !== '127.0.0.1' && HOST !== 'localhost') return;
|
|
390
|
-
if (clients.size > 0) return; // the user already opened it
|
|
391
|
-
const url = companionUrl(); // must carry the key or the gate 403s it
|
|
392
|
-
const cp = require('child_process');
|
|
393
|
-
// Operator-provided launcher: run as given (this env var is trusted operator input).
|
|
394
|
-
if (process.env.BRAINSTORM_OPEN_CMD) {
|
|
395
|
-
try {
|
|
396
|
-
cp.exec(process.env.BRAINSTORM_OPEN_CMD + ' ' + JSON.stringify(url), () => {});
|
|
397
|
-
} catch (e) { /* best effort */ }
|
|
398
|
-
return;
|
|
399
|
-
}
|
|
400
|
-
// Platform launchers: pass the URL as an argv element via execFile (no shell),
|
|
401
|
-
// so a url-host containing shell metacharacters can't inject a command.
|
|
402
|
-
const launcher = browserLauncherForPlatform(url);
|
|
403
|
-
if (!launcher) return; // headless: nothing to open
|
|
404
|
-
try { cp.execFile(launcher.bin, launcher.args, () => {}); } catch (e) { /* best effort */ }
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// ========== Activity Tracking ==========
|
|
408
|
-
|
|
409
|
-
// Idle timeout: shut down after this long with no activity. Default 4 hours;
|
|
410
|
-
// override with BRAINSTORM_IDLE_TIMEOUT_MS (start-server.sh: --idle-timeout-minutes).
|
|
411
|
-
const IDLE_TIMEOUT_MS = (() => {
|
|
412
|
-
const ms = Number(process.env.BRAINSTORM_IDLE_TIMEOUT_MS);
|
|
413
|
-
return Number.isFinite(ms) && ms > 0 ? ms : 4 * 60 * 60 * 1000;
|
|
414
|
-
})();
|
|
415
|
-
// How often the watchdog checks for owner-death / idleness. Configurable mainly
|
|
416
|
-
// so tests can run fast; production default is 60s.
|
|
417
|
-
const LIFECYCLE_CHECK_MS = (() => {
|
|
418
|
-
const ms = Number(process.env.BRAINSTORM_LIFECYCLE_CHECK_MS);
|
|
419
|
-
return Number.isFinite(ms) && ms > 0 ? ms : 60 * 1000;
|
|
420
|
-
})();
|
|
421
|
-
let lastActivity = Date.now();
|
|
422
|
-
|
|
423
|
-
function touchActivity() {
|
|
424
|
-
lastActivity = Date.now();
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
// ========== File Watching ==========
|
|
428
|
-
|
|
429
|
-
const debounceTimers = new Map();
|
|
430
|
-
|
|
431
|
-
// ========== Server Startup ==========
|
|
432
|
-
|
|
433
|
-
function ensureSessionDirectories() {
|
|
434
|
-
if (!fs.existsSync(CONTENT_DIR)) fs.mkdirSync(CONTENT_DIR, { recursive: true });
|
|
435
|
-
if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
function createContentWatcher() {
|
|
439
|
-
const knownFiles = new Set(
|
|
440
|
-
fs.readdirSync(CONTENT_DIR).filter(f => !f.startsWith('.') && f.endsWith('.html'))
|
|
441
|
-
);
|
|
442
|
-
const watcher = fs.watch(CONTENT_DIR, (eventType, filename) => {
|
|
443
|
-
if (!filename || filename.startsWith('.') || !filename.endsWith('.html')) return;
|
|
444
|
-
if (debounceTimers.has(filename)) clearTimeout(debounceTimers.get(filename));
|
|
445
|
-
debounceTimers.set(filename, setTimeout(() => {
|
|
446
|
-
debounceTimers.delete(filename);
|
|
447
|
-
const filePath = path.join(CONTENT_DIR, filename);
|
|
448
|
-
if (!fs.existsSync(filePath)) return; // file was deleted
|
|
449
|
-
touchActivity();
|
|
450
|
-
if (!knownFiles.has(filename)) {
|
|
451
|
-
knownFiles.add(filename);
|
|
452
|
-
const eventsFile = path.join(STATE_DIR, 'events');
|
|
453
|
-
if (fs.existsSync(eventsFile)) fs.unlinkSync(eventsFile);
|
|
454
|
-
console.log(JSON.stringify({ type: 'screen-added', file: filePath }));
|
|
455
|
-
maybeOpenBrowser();
|
|
456
|
-
} else {
|
|
457
|
-
console.log(JSON.stringify({ type: 'screen-updated', file: filePath }));
|
|
458
|
-
}
|
|
459
|
-
broadcast({ type: 'reload' });
|
|
460
|
-
}, 100));
|
|
461
|
-
});
|
|
462
|
-
watcher.on('error', (err) => console.error('fs.watch error:', err.message));
|
|
463
|
-
return watcher;
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
function shutdown(runtime, reason) {
|
|
467
|
-
console.log(JSON.stringify({ type: 'server-stopped', reason }));
|
|
468
|
-
const infoFile = path.join(STATE_DIR, 'server-info');
|
|
469
|
-
if (fs.existsSync(infoFile)) fs.unlinkSync(infoFile);
|
|
470
|
-
fs.writeFileSync(
|
|
471
|
-
path.join(STATE_DIR, 'server-stopped'),
|
|
472
|
-
JSON.stringify({ reason, timestamp: Date.now() }) + '\n'
|
|
473
|
-
);
|
|
474
|
-
runtime.watcher.close();
|
|
475
|
-
clearInterval(runtime.lifecycleCheck);
|
|
476
|
-
for (const socket of clients) {
|
|
477
|
-
try { socket.destroy(); } catch (e) { /* already gone */ }
|
|
478
|
-
}
|
|
479
|
-
runtime.server.close(() => process.exit(0));
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
function ownerAlive() {
|
|
483
|
-
if (!ownerPid) return true;
|
|
484
|
-
try { process.kill(ownerPid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
function startLifecycleCheck(runtime) {
|
|
488
|
-
runtime.lifecycleCheck = setInterval(() => {
|
|
489
|
-
if (!ownerAlive()) shutdown(runtime, 'owner process exited');
|
|
490
|
-
else if (Date.now() - lastActivity > IDLE_TIMEOUT_MS) shutdown(runtime, 'idle timeout');
|
|
491
|
-
}, LIFECYCLE_CHECK_MS);
|
|
492
|
-
runtime.lifecycleCheck.unref();
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
function validateOwnerPid() {
|
|
496
|
-
if (ownerPid) {
|
|
497
|
-
try { process.kill(ownerPid, 0); }
|
|
498
|
-
catch (e) {
|
|
499
|
-
if (e.code !== 'EPERM') {
|
|
500
|
-
console.log(JSON.stringify({
|
|
501
|
-
type: 'owner-pid-invalid',
|
|
502
|
-
pid: ownerPid,
|
|
503
|
-
reason: 'dead at startup'
|
|
504
|
-
}));
|
|
505
|
-
ownerPid = null;
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
function writeServerInfo(triedFallback) {
|
|
512
|
-
COOKIE_NAME = 'brainstorm-key-' + PORT;
|
|
513
|
-
if (PORT_FILE && !triedFallback) {
|
|
514
|
-
try { fs.writeFileSync(PORT_FILE, String(PORT)); } catch (e) { /* best effort */ }
|
|
515
|
-
if (TOKEN_FILE) {
|
|
516
|
-
try {
|
|
517
|
-
fs.writeFileSync(TOKEN_FILE, TOKEN, { mode: 0o600 });
|
|
518
|
-
chmodOwnerOnly(TOKEN_FILE);
|
|
519
|
-
} catch (e) { /* best effort */ }
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
const info = JSON.stringify({
|
|
523
|
-
type: 'server-started', port: Number(PORT), host: HOST,
|
|
524
|
-
url_host: URL_HOST, url: companionUrl(),
|
|
525
|
-
screen_dir: CONTENT_DIR, state_dir: STATE_DIR, idle_timeout_ms: IDLE_TIMEOUT_MS
|
|
526
|
-
});
|
|
527
|
-
console.log(info);
|
|
528
|
-
fs.writeFileSync(path.join(STATE_DIR, 'server-info'), info + '\n', { mode: 0o600 });
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
function listenWithFallback(server) {
|
|
532
|
-
let triedFallback = false;
|
|
533
|
-
const onListen = () => writeServerInfo(triedFallback);
|
|
534
|
-
server.on('error', (err) => {
|
|
535
|
-
if (err.code === 'EADDRINUSE' && !triedFallback) {
|
|
536
|
-
if (tokenSource === 'env') {
|
|
537
|
-
console.error(
|
|
538
|
-
'Server failed to bind: preferred port is in use and BRAINSTORM_TOKEN is set; ' +
|
|
539
|
-
'refusing fallback with explicit token'
|
|
540
|
-
);
|
|
541
|
-
process.exit(1);
|
|
542
|
-
}
|
|
543
|
-
triedFallback = true;
|
|
544
|
-
PORT = randomPort();
|
|
545
|
-
if (tokenSource === 'file') {
|
|
546
|
-
TOKEN = generateToken();
|
|
547
|
-
tokenSource = 'generated-fallback';
|
|
548
|
-
}
|
|
549
|
-
server.listen(PORT, HOST, onListen);
|
|
550
|
-
} else {
|
|
551
|
-
console.error('Server failed to bind:', err.message);
|
|
552
|
-
process.exit(1);
|
|
553
|
-
}
|
|
554
|
-
});
|
|
555
|
-
server.listen(PORT, HOST, onListen);
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
function startServer() {
|
|
559
|
-
ensureSessionDirectories();
|
|
560
|
-
const server = http.createServer(handleRequest);
|
|
561
|
-
server.on('upgrade', handleUpgrade);
|
|
562
|
-
const runtime = {
|
|
563
|
-
server,
|
|
564
|
-
watcher: createContentWatcher(),
|
|
565
|
-
lifecycleCheck: null,
|
|
566
|
-
};
|
|
567
|
-
startLifecycleCheck(runtime);
|
|
568
|
-
validateOwnerPid();
|
|
569
|
-
listenWithFallback(server);
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
if (require.main === module) {
|
|
573
|
-
startServer();
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
module.exports = {
|
|
577
|
-
computeAcceptKey,
|
|
578
|
-
encodeFrame,
|
|
579
|
-
decodeFrame,
|
|
580
|
-
browserLauncherForPlatform,
|
|
581
|
-
OPCODES,
|
|
582
|
-
MAX_FRAME_PAYLOAD_BYTES
|
|
583
|
-
};
|