opengstack 0.13.10 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/{skills/land-and-deploy/SKILL.md → commands/autoplan.md} +0 -16
- package/{skills/benchmark/SKILL.md → commands/benchmark.md} +0 -17
- package/{skills/browse/SKILL.md → commands/browse.md} +0 -17
- package/{skills/ship/SKILL.md → commands/canary.md} +0 -18
- package/{skills/careful/SKILL.md → commands/careful.md} +0 -20
- package/{skills/canary/SKILL.md → commands/codex.md} +0 -17
- package/{skills/connect-chrome/SKILL.md → commands/connect-chrome.md} +0 -15
- package/commands/cso.md +72 -0
- package/commands/design-consultation.md +72 -0
- package/commands/design-review.md +72 -0
- package/commands/design-shotgun.md +72 -0
- package/commands/document-release.md +72 -0
- package/{skills/freeze/SKILL.md → commands/freeze.md} +0 -26
- package/{skills/gstack-upgrade/SKILL.md → commands/gstack-upgrade.md} +0 -14
- package/{skills/guard/SKILL.md → commands/guard.md} +0 -31
- package/commands/investigate.md +72 -0
- package/commands/land-and-deploy.md +72 -0
- package/commands/office-hours.md +72 -0
- package/commands/plan-ceo-review.md +72 -0
- package/commands/plan-design-review.md +72 -0
- package/commands/plan-eng-review.md +72 -0
- package/commands/qa-only.md +72 -0
- package/commands/qa.md +72 -0
- package/commands/retro.md +72 -0
- package/commands/review.md +72 -0
- package/{skills/setup-browser-cookies/SKILL.md → commands/setup-browser-cookies.md} +0 -14
- package/commands/setup-deploy.md +72 -0
- package/commands/ship.md +72 -0
- package/{skills/unfreeze/SKILL.md → commands/unfreeze.md} +0 -12
- package/package.json +4 -4
- package/scripts/install-commands.js +45 -0
- package/skills/autoplan/SKILL.md +0 -96
- package/skills/autoplan/SKILL.md.tmpl +0 -694
- package/skills/benchmark/SKILL.md.tmpl +0 -222
- package/skills/browse/SKILL.md.tmpl +0 -131
- package/skills/browse/bin/find-browse +0 -21
- package/skills/browse/bin/remote-slug +0 -14
- package/skills/browse/scripts/build-node-server.sh +0 -48
- package/skills/browse/src/activity.ts +0 -208
- package/skills/browse/src/browser-manager.ts +0 -959
- package/skills/browse/src/buffers.ts +0 -137
- package/skills/browse/src/bun-polyfill.cjs +0 -109
- package/skills/browse/src/cli.ts +0 -678
- package/skills/browse/src/commands.ts +0 -128
- package/skills/browse/src/config.ts +0 -150
- package/skills/browse/src/cookie-import-browser.ts +0 -625
- package/skills/browse/src/cookie-picker-routes.ts +0 -230
- package/skills/browse/src/cookie-picker-ui.ts +0 -688
- package/skills/browse/src/find-browse.ts +0 -61
- package/skills/browse/src/meta-commands.ts +0 -550
- package/skills/browse/src/platform.ts +0 -17
- package/skills/browse/src/read-commands.ts +0 -358
- package/skills/browse/src/server.ts +0 -1192
- package/skills/browse/src/sidebar-agent.ts +0 -280
- package/skills/browse/src/sidebar-utils.ts +0 -21
- package/skills/browse/src/snapshot.ts +0 -407
- package/skills/browse/src/url-validation.ts +0 -95
- package/skills/browse/src/write-commands.ts +0 -364
- package/skills/browse/test/activity.test.ts +0 -120
- package/skills/browse/test/adversarial-security.test.ts +0 -32
- package/skills/browse/test/browser-manager-unit.test.ts +0 -17
- package/skills/browse/test/bun-polyfill.test.ts +0 -72
- package/skills/browse/test/commands.test.ts +0 -2075
- package/skills/browse/test/compare-board.test.ts +0 -342
- package/skills/browse/test/config.test.ts +0 -316
- package/skills/browse/test/cookie-import-browser.test.ts +0 -519
- package/skills/browse/test/cookie-picker-routes.test.ts +0 -260
- package/skills/browse/test/file-drop.test.ts +0 -271
- package/skills/browse/test/find-browse.test.ts +0 -50
- package/skills/browse/test/findport.test.ts +0 -191
- package/skills/browse/test/fixtures/basic.html +0 -33
- package/skills/browse/test/fixtures/cursor-interactive.html +0 -22
- package/skills/browse/test/fixtures/dialog.html +0 -15
- package/skills/browse/test/fixtures/empty.html +0 -2
- package/skills/browse/test/fixtures/forms.html +0 -55
- package/skills/browse/test/fixtures/iframe.html +0 -30
- package/skills/browse/test/fixtures/network-idle.html +0 -30
- package/skills/browse/test/fixtures/qa-eval-checkout.html +0 -108
- package/skills/browse/test/fixtures/qa-eval-spa.html +0 -98
- package/skills/browse/test/fixtures/qa-eval.html +0 -51
- package/skills/browse/test/fixtures/responsive.html +0 -49
- package/skills/browse/test/fixtures/snapshot.html +0 -55
- package/skills/browse/test/fixtures/spa.html +0 -24
- package/skills/browse/test/fixtures/states.html +0 -17
- package/skills/browse/test/fixtures/upload.html +0 -25
- package/skills/browse/test/gstack-config.test.ts +0 -138
- package/skills/browse/test/gstack-update-check.test.ts +0 -514
- package/skills/browse/test/handoff.test.ts +0 -235
- package/skills/browse/test/path-validation.test.ts +0 -91
- package/skills/browse/test/platform.test.ts +0 -37
- package/skills/browse/test/server-auth.test.ts +0 -65
- package/skills/browse/test/sidebar-agent-roundtrip.test.ts +0 -226
- package/skills/browse/test/sidebar-agent.test.ts +0 -199
- package/skills/browse/test/sidebar-integration.test.ts +0 -320
- package/skills/browse/test/sidebar-unit.test.ts +0 -96
- package/skills/browse/test/snapshot.test.ts +0 -467
- package/skills/browse/test/state-ttl.test.ts +0 -35
- package/skills/browse/test/test-server.ts +0 -57
- package/skills/browse/test/url-validation.test.ts +0 -72
- package/skills/browse/test/watch.test.ts +0 -129
- package/skills/canary/SKILL.md.tmpl +0 -212
- package/skills/careful/SKILL.md.tmpl +0 -56
- package/skills/careful/bin/check-careful.sh +0 -112
- package/skills/codex/SKILL.md +0 -90
- package/skills/codex/SKILL.md.tmpl +0 -417
- package/skills/connect-chrome/SKILL.md.tmpl +0 -195
- package/skills/cso/ACKNOWLEDGEMENTS.md +0 -14
- package/skills/cso/SKILL.md +0 -93
- package/skills/cso/SKILL.md.tmpl +0 -606
- package/skills/design-consultation/SKILL.md +0 -94
- package/skills/design-consultation/SKILL.md.tmpl +0 -415
- package/skills/design-review/SKILL.md +0 -94
- package/skills/design-review/SKILL.md.tmpl +0 -290
- package/skills/design-shotgun/SKILL.md +0 -91
- package/skills/design-shotgun/SKILL.md.tmpl +0 -285
- package/skills/document-release/SKILL.md +0 -91
- package/skills/document-release/SKILL.md.tmpl +0 -359
- package/skills/freeze/SKILL.md.tmpl +0 -77
- package/skills/freeze/bin/check-freeze.sh +0 -79
- package/skills/gstack-upgrade/SKILL.md.tmpl +0 -222
- package/skills/guard/SKILL.md.tmpl +0 -77
- package/skills/investigate/SKILL.md +0 -105
- package/skills/investigate/SKILL.md.tmpl +0 -194
- package/skills/land-and-deploy/SKILL.md.tmpl +0 -881
- package/skills/office-hours/SKILL.md +0 -96
- package/skills/office-hours/SKILL.md.tmpl +0 -645
- package/skills/plan-ceo-review/SKILL.md +0 -94
- package/skills/plan-ceo-review/SKILL.md.tmpl +0 -811
- package/skills/plan-design-review/SKILL.md +0 -92
- package/skills/plan-design-review/SKILL.md.tmpl +0 -446
- package/skills/plan-eng-review/SKILL.md +0 -93
- package/skills/plan-eng-review/SKILL.md.tmpl +0 -303
- package/skills/qa/SKILL.md +0 -95
- package/skills/qa/SKILL.md.tmpl +0 -316
- package/skills/qa/references/issue-taxonomy.md +0 -85
- package/skills/qa/templates/qa-report-template.md +0 -126
- package/skills/qa-only/SKILL.md +0 -89
- package/skills/qa-only/SKILL.md.tmpl +0 -101
- package/skills/retro/SKILL.md +0 -89
- package/skills/retro/SKILL.md.tmpl +0 -820
- package/skills/review/SKILL.md +0 -92
- package/skills/review/SKILL.md.tmpl +0 -281
- package/skills/review/TODOS-format.md +0 -62
- package/skills/review/checklist.md +0 -220
- package/skills/review/design-checklist.md +0 -132
- package/skills/review/greptile-triage.md +0 -220
- package/skills/setup-browser-cookies/SKILL.md.tmpl +0 -81
- package/skills/setup-deploy/SKILL.md +0 -92
- package/skills/setup-deploy/SKILL.md.tmpl +0 -215
- package/skills/ship/SKILL.md.tmpl +0 -636
- package/skills/unfreeze/SKILL.md.tmpl +0 -36
package/skills/browse/src/cli.ts
DELETED
|
@@ -1,678 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* gstack CLI — thin wrapper that talks to the persistent server
|
|
3
|
-
*
|
|
4
|
-
* Flow:
|
|
5
|
-
* 1. Read .gstack/browse.json for port + token
|
|
6
|
-
* 2. If missing or stale PID → start server in background
|
|
7
|
-
* 3. Health check + version mismatch detection
|
|
8
|
-
* 4. Send command via HTTP POST
|
|
9
|
-
* 5. Print response to stdout (or stderr for errors)
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import * as fs from 'fs';
|
|
13
|
-
import * as path from 'path';
|
|
14
|
-
import { resolveConfig, ensureStateDir, readVersionHash } from './config';
|
|
15
|
-
|
|
16
|
-
const config = resolveConfig();
|
|
17
|
-
const IS_WINDOWS = process.platform === 'win32';
|
|
18
|
-
const MAX_START_WAIT = IS_WINDOWS ? 15000 : (process.env.CI ? 30000 : 8000); // Node+Chromium takes longer on Windows
|
|
19
|
-
|
|
20
|
-
export function resolveServerScript(
|
|
21
|
-
env: Record<string, string | undefined> = process.env,
|
|
22
|
-
metaDir: string = import.meta.dir,
|
|
23
|
-
execPath: string = process.execPath
|
|
24
|
-
): string {
|
|
25
|
-
if (env.BROWSE_SERVER_SCRIPT) {
|
|
26
|
-
return env.BROWSE_SERVER_SCRIPT;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// Dev mode: cli.ts runs directly from browse/src
|
|
30
|
-
// On macOS/Linux, import.meta.dir starts with /
|
|
31
|
-
// On Windows, it starts with a drive letter (e.g., C:\...)
|
|
32
|
-
if (!metaDir.includes('$bunfs')) {
|
|
33
|
-
const direct = path.resolve(metaDir, 'server.ts');
|
|
34
|
-
if (fs.existsSync(direct)) {
|
|
35
|
-
return direct;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Compiled binary: derive the source tree from browse/dist/browse
|
|
40
|
-
if (execPath) {
|
|
41
|
-
const adjacent = path.resolve(path.dirname(execPath), '..', 'src', 'server.ts');
|
|
42
|
-
if (fs.existsSync(adjacent)) {
|
|
43
|
-
return adjacent;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
throw new Error(
|
|
48
|
-
'Cannot find server.ts. Set BROWSE_SERVER_SCRIPT env or run from the browse source tree.'
|
|
49
|
-
);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const SERVER_SCRIPT = resolveServerScript();
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* On Windows, resolve the Node.js-compatible server bundle.
|
|
56
|
-
* Falls back to null if not found (server will use Bun instead).
|
|
57
|
-
*/
|
|
58
|
-
export function resolveNodeServerScript(
|
|
59
|
-
metaDir: string = import.meta.dir,
|
|
60
|
-
execPath: string = process.execPath
|
|
61
|
-
): string | null {
|
|
62
|
-
// Dev mode
|
|
63
|
-
if (!metaDir.includes('$bunfs')) {
|
|
64
|
-
const distScript = path.resolve(metaDir, '..', 'dist', 'server-node.mjs');
|
|
65
|
-
if (fs.existsSync(distScript)) return distScript;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
// Compiled binary: browse/dist/browse → browse/dist/server-node.mjs
|
|
69
|
-
if (execPath) {
|
|
70
|
-
const adjacent = path.resolve(path.dirname(execPath), 'server-node.mjs');
|
|
71
|
-
if (fs.existsSync(adjacent)) return adjacent;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
return null;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const NODE_SERVER_SCRIPT = IS_WINDOWS ? resolveNodeServerScript() : null;
|
|
78
|
-
|
|
79
|
-
// On Windows, hard-fail if server-node.mjs is missing — the Bun path is known broken.
|
|
80
|
-
if (IS_WINDOWS && !NODE_SERVER_SCRIPT) {
|
|
81
|
-
throw new Error(
|
|
82
|
-
'server-node.mjs not found. Run `bun run build` to generate the Windows server bundle.'
|
|
83
|
-
);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
interface ServerState {
|
|
87
|
-
pid: number;
|
|
88
|
-
port: number;
|
|
89
|
-
token: string;
|
|
90
|
-
startedAt: string;
|
|
91
|
-
serverPath: string;
|
|
92
|
-
binaryVersion?: string;
|
|
93
|
-
mode?: 'launched' | 'headed';
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// ─── State File ────────────────────────────────────────────────
|
|
97
|
-
function readState(): ServerState | null {
|
|
98
|
-
try {
|
|
99
|
-
const data = fs.readFileSync(config.stateFile, 'utf-8');
|
|
100
|
-
return JSON.parse(data);
|
|
101
|
-
} catch {
|
|
102
|
-
return null;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function isProcessAlive(pid: number): boolean {
|
|
107
|
-
if (IS_WINDOWS) {
|
|
108
|
-
// Bun's compiled binary can't signal Windows PIDs (always throws ESRCH).
|
|
109
|
-
// Use tasklist as a fallback. Only for one-shot calls — too slow for polling loops.
|
|
110
|
-
try {
|
|
111
|
-
const result = Bun.spawnSync(
|
|
112
|
-
['tasklist', '/FI', `PID eq ${pid}`, '/NH', '/FO', 'CSV'],
|
|
113
|
-
{ stdout: 'pipe', stderr: 'pipe', timeout: 3000 }
|
|
114
|
-
);
|
|
115
|
-
return result.stdout.toString().includes(`"${pid}"`);
|
|
116
|
-
} catch {
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
try {
|
|
121
|
-
process.kill(pid, 0);
|
|
122
|
-
return true;
|
|
123
|
-
} catch {
|
|
124
|
-
return false;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* HTTP health check — definitive proof the server is alive and responsive.
|
|
130
|
-
* Used in all polling loops instead of isProcessAlive() (which is slow on Windows).
|
|
131
|
-
*/
|
|
132
|
-
export async function isServerHealthy(port: number): Promise<boolean> {
|
|
133
|
-
try {
|
|
134
|
-
const resp = await fetch(`http://127.0.0.1:${port}/health`, {
|
|
135
|
-
signal: AbortSignal.timeout(2000),
|
|
136
|
-
});
|
|
137
|
-
if (!resp.ok) return false;
|
|
138
|
-
const health = await resp.json() as any;
|
|
139
|
-
return health.status === 'healthy';
|
|
140
|
-
} catch {
|
|
141
|
-
return false;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// ─── Process Management ─────────────────────────────────────────
|
|
146
|
-
async function killServer(pid: number): Promise<void> {
|
|
147
|
-
if (!isProcessAlive(pid)) return;
|
|
148
|
-
|
|
149
|
-
if (IS_WINDOWS) {
|
|
150
|
-
// taskkill /T /F kills the process tree (Node + Chromium)
|
|
151
|
-
try {
|
|
152
|
-
Bun.spawnSync(
|
|
153
|
-
['taskkill', '/PID', String(pid), '/T', '/F'],
|
|
154
|
-
{ stdout: 'pipe', stderr: 'pipe', timeout: 5000 }
|
|
155
|
-
);
|
|
156
|
-
} catch {}
|
|
157
|
-
const deadline = Date.now() + 2000;
|
|
158
|
-
while (Date.now() < deadline && isProcessAlive(pid)) {
|
|
159
|
-
await Bun.sleep(100);
|
|
160
|
-
}
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
try { process.kill(pid, 'SIGTERM'); } catch { return; }
|
|
165
|
-
|
|
166
|
-
// Wait up to 2s for graceful shutdown
|
|
167
|
-
const deadline = Date.now() + 2000;
|
|
168
|
-
while (Date.now() < deadline && isProcessAlive(pid)) {
|
|
169
|
-
await Bun.sleep(100);
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
// Force kill if still alive
|
|
173
|
-
if (isProcessAlive(pid)) {
|
|
174
|
-
try { process.kill(pid, 'SIGKILL'); } catch {}
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Clean up legacy /tmp/browse-server*.json files from before project-local state.
|
|
180
|
-
* Verifies PID ownership before sending signals.
|
|
181
|
-
*/
|
|
182
|
-
function cleanupLegacyState(): void {
|
|
183
|
-
// No legacy state on Windows — /tmp and `ps` don't exist, and gstack
|
|
184
|
-
// never ran on Windows before the Node.js fallback was added.
|
|
185
|
-
if (IS_WINDOWS) return;
|
|
186
|
-
|
|
187
|
-
try {
|
|
188
|
-
const files = fs.readdirSync('/tmp').filter(f => f.startsWith('browse-server') && f.endsWith('.json'));
|
|
189
|
-
for (const file of files) {
|
|
190
|
-
const fullPath = `/tmp/${file}`;
|
|
191
|
-
try {
|
|
192
|
-
const data = JSON.parse(fs.readFileSync(fullPath, 'utf-8'));
|
|
193
|
-
if (data.pid && isProcessAlive(data.pid)) {
|
|
194
|
-
// Verify this is actually a browse server before killing
|
|
195
|
-
const check = Bun.spawnSync(['ps', '-p', String(data.pid), '-o', 'command='], {
|
|
196
|
-
stdout: 'pipe', stderr: 'pipe', timeout: 2000,
|
|
197
|
-
});
|
|
198
|
-
const cmd = check.stdout.toString().trim();
|
|
199
|
-
if (cmd.includes('bun') || cmd.includes('server.ts')) {
|
|
200
|
-
try { process.kill(data.pid, 'SIGTERM'); } catch {}
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
fs.unlinkSync(fullPath);
|
|
204
|
-
} catch {
|
|
205
|
-
// Best effort — skip files we can't parse or clean up
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
// Clean up legacy log files too
|
|
209
|
-
const logFiles = fs.readdirSync('/tmp').filter(f =>
|
|
210
|
-
f.startsWith('browse-console') || f.startsWith('browse-network') || f.startsWith('browse-dialog')
|
|
211
|
-
);
|
|
212
|
-
for (const file of logFiles) {
|
|
213
|
-
try { fs.unlinkSync(`/tmp/${file}`); } catch {}
|
|
214
|
-
}
|
|
215
|
-
} catch {
|
|
216
|
-
// /tmp read failed — skip legacy cleanup
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// ─── Server Lifecycle ──────────────────────────────────────────
|
|
221
|
-
async function startServer(extraEnv?: Record<string, string>): Promise<ServerState> {
|
|
222
|
-
ensureStateDir(config);
|
|
223
|
-
|
|
224
|
-
// Clean up stale state file and error log
|
|
225
|
-
try { fs.unlinkSync(config.stateFile); } catch {}
|
|
226
|
-
try { fs.unlinkSync(path.join(config.stateDir, 'browse-startup-error.log')); } catch {}
|
|
227
|
-
|
|
228
|
-
let proc: any = null;
|
|
229
|
-
|
|
230
|
-
if (IS_WINDOWS && NODE_SERVER_SCRIPT) {
|
|
231
|
-
// Windows: Bun.spawn() + proc.unref() doesn't truly detach on Windows —
|
|
232
|
-
// when the CLI exits, the server dies with it. Use Node's child_process.spawn
|
|
233
|
-
// with { detached: true } instead, which is the gold standard for Windows
|
|
234
|
-
// process independence. Credit: PR #191 by @fqueiro.
|
|
235
|
-
const launcherCode =
|
|
236
|
-
`const{spawn}=require('child_process');` +
|
|
237
|
-
`spawn(process.execPath,[${JSON.stringify(NODE_SERVER_SCRIPT)}],` +
|
|
238
|
-
`{detached:true,stdio:['ignore','ignore','ignore'],env:Object.assign({},process.env,` +
|
|
239
|
-
`{BROWSE_STATE_FILE:${JSON.stringify(config.stateFile)}})}).unref()`;
|
|
240
|
-
Bun.spawnSync(['node', '-e', launcherCode], { stdio: ['ignore', 'ignore', 'ignore'] });
|
|
241
|
-
} else {
|
|
242
|
-
// macOS/Linux: Bun.spawn + unref works correctly
|
|
243
|
-
proc = Bun.spawn(['bun', 'run', SERVER_SCRIPT], {
|
|
244
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
245
|
-
env: { ...process.env, BROWSE_STATE_FILE: config.stateFile, ...extraEnv },
|
|
246
|
-
});
|
|
247
|
-
proc.unref();
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
// Wait for server to become healthy.
|
|
251
|
-
// Use HTTP health check (not isProcessAlive) — it's fast (~instant ECONNREFUSED)
|
|
252
|
-
// and works reliably on all platforms including Windows.
|
|
253
|
-
const start = Date.now();
|
|
254
|
-
while (Date.now() - start < MAX_START_WAIT) {
|
|
255
|
-
const state = readState();
|
|
256
|
-
if (state && await isServerHealthy(state.port)) {
|
|
257
|
-
return state;
|
|
258
|
-
}
|
|
259
|
-
await Bun.sleep(100);
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Server didn't start in time — try to get error details
|
|
263
|
-
if (proc?.stderr) {
|
|
264
|
-
// macOS/Linux: read stderr from the spawned process
|
|
265
|
-
const reader = proc.stderr.getReader();
|
|
266
|
-
const { value } = await reader.read();
|
|
267
|
-
if (value) {
|
|
268
|
-
const errText = new TextDecoder().decode(value);
|
|
269
|
-
throw new Error(`Server failed to start:\n${errText}`);
|
|
270
|
-
}
|
|
271
|
-
} else {
|
|
272
|
-
// Windows: check startup error log (server writes errors to disk since
|
|
273
|
-
// stderr is unavailable due to stdio: 'ignore' for detachment)
|
|
274
|
-
const errorLogPath = path.join(config.stateDir, 'browse-startup-error.log');
|
|
275
|
-
try {
|
|
276
|
-
const errorLog = fs.readFileSync(errorLogPath, 'utf-8').trim();
|
|
277
|
-
if (errorLog) {
|
|
278
|
-
throw new Error(`Server failed to start:\n${errorLog}`);
|
|
279
|
-
}
|
|
280
|
-
} catch (e: any) {
|
|
281
|
-
if (e.code !== 'ENOENT') throw e;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
throw new Error(`Server failed to start within ${MAX_START_WAIT / 1000}s`);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* Acquire an exclusive lockfile to prevent concurrent ensureServer() races (TOCTOU).
|
|
289
|
-
* Returns a cleanup function that releases the lock.
|
|
290
|
-
*/
|
|
291
|
-
function acquireServerLock(): (() => void) | null {
|
|
292
|
-
const lockPath = `${config.stateFile}.lock`;
|
|
293
|
-
try {
|
|
294
|
-
// 'wx' — create exclusively, fails if file already exists (atomic check-and-create)
|
|
295
|
-
// Using string flag instead of numeric constants for Bun Windows compatibility
|
|
296
|
-
const fd = fs.openSync(lockPath, 'wx');
|
|
297
|
-
fs.writeSync(fd, `${process.pid}\n`);
|
|
298
|
-
fs.closeSync(fd);
|
|
299
|
-
return () => { try { fs.unlinkSync(lockPath); } catch {} };
|
|
300
|
-
} catch {
|
|
301
|
-
// Lock already held — check if the holder is still alive
|
|
302
|
-
try {
|
|
303
|
-
const holderPid = parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10);
|
|
304
|
-
if (holderPid && isProcessAlive(holderPid)) {
|
|
305
|
-
return null; // Another live process holds the lock
|
|
306
|
-
}
|
|
307
|
-
// Stale lock — remove and retry
|
|
308
|
-
fs.unlinkSync(lockPath);
|
|
309
|
-
return acquireServerLock();
|
|
310
|
-
} catch {
|
|
311
|
-
return null;
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
async function ensureServer(): Promise<ServerState> {
|
|
317
|
-
const state = readState();
|
|
318
|
-
|
|
319
|
-
// Health-check-first: HTTP is definitive proof the server is alive and responsive.
|
|
320
|
-
// This replaces the PID-gated approach which breaks on Windows (Bun's process.kill
|
|
321
|
-
// always throws ESRCH for Windows PIDs in compiled binaries).
|
|
322
|
-
if (state && await isServerHealthy(state.port)) {
|
|
323
|
-
// Check for binary version mismatch (auto-restart on update)
|
|
324
|
-
const currentVersion = readVersionHash();
|
|
325
|
-
if (currentVersion && state.binaryVersion && currentVersion !== state.binaryVersion) {
|
|
326
|
-
console.error('[browse] Binary updated, restarting server...');
|
|
327
|
-
await killServer(state.pid);
|
|
328
|
-
return startServer();
|
|
329
|
-
}
|
|
330
|
-
return state;
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// Guard: never silently replace a headed server with a headless one.
|
|
334
|
-
// Headed mode means a user-visible Chrome window is (or was) controlled.
|
|
335
|
-
// Silently replacing it would be confusing — tell the user to reconnect.
|
|
336
|
-
if (state && state.mode === 'headed' && isProcessAlive(state.pid)) {
|
|
337
|
-
console.error(`[browse] Headed server running (PID ${state.pid}) but not responding.`);
|
|
338
|
-
console.error(`[browse] Run '$B connect' to restart.`);
|
|
339
|
-
process.exit(1);
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
// Ensure state directory exists before lock acquisition (lock file lives there)
|
|
343
|
-
ensureStateDir(config);
|
|
344
|
-
|
|
345
|
-
// Acquire lock to prevent concurrent restart races (TOCTOU)
|
|
346
|
-
const releaseLock = acquireServerLock();
|
|
347
|
-
if (!releaseLock) {
|
|
348
|
-
// Another process is starting the server — wait for it
|
|
349
|
-
console.error('[browse] Another instance is starting the server, waiting...');
|
|
350
|
-
const start = Date.now();
|
|
351
|
-
while (Date.now() - start < MAX_START_WAIT) {
|
|
352
|
-
const freshState = readState();
|
|
353
|
-
if (freshState && await isServerHealthy(freshState.port)) return freshState;
|
|
354
|
-
await Bun.sleep(200);
|
|
355
|
-
}
|
|
356
|
-
throw new Error('Timed out waiting for another instance to start the server');
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
try {
|
|
360
|
-
// Re-read state under lock in case another process just started the server
|
|
361
|
-
const freshState = readState();
|
|
362
|
-
if (freshState && await isServerHealthy(freshState.port)) {
|
|
363
|
-
return freshState;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// Kill the old server to avoid orphaned chromium processes
|
|
367
|
-
if (state && state.pid) {
|
|
368
|
-
await killServer(state.pid);
|
|
369
|
-
}
|
|
370
|
-
console.error('[browse] Starting server...');
|
|
371
|
-
return await startServer();
|
|
372
|
-
} finally {
|
|
373
|
-
releaseLock();
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// ─── Command Dispatch ──────────────────────────────────────────
|
|
378
|
-
async function sendCommand(state: ServerState, command: string, args: string[], retries = 0): Promise<void> {
|
|
379
|
-
const body = JSON.stringify({ command, args });
|
|
380
|
-
|
|
381
|
-
try {
|
|
382
|
-
const resp = await fetch(`http://127.0.0.1:${state.port}/command`, {
|
|
383
|
-
method: 'POST',
|
|
384
|
-
headers: {
|
|
385
|
-
'Content-Type': 'application/json',
|
|
386
|
-
'Authorization': `Bearer ${state.token}`,
|
|
387
|
-
},
|
|
388
|
-
body,
|
|
389
|
-
signal: AbortSignal.timeout(30000),
|
|
390
|
-
});
|
|
391
|
-
|
|
392
|
-
if (resp.status === 401) {
|
|
393
|
-
// Token mismatch — server may have restarted
|
|
394
|
-
console.error('[browse] Auth failed — server may have restarted. Retrying...');
|
|
395
|
-
const newState = readState();
|
|
396
|
-
if (newState && newState.token !== state.token) {
|
|
397
|
-
return sendCommand(newState, command, args);
|
|
398
|
-
}
|
|
399
|
-
throw new Error('Authentication failed');
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
const text = await resp.text();
|
|
403
|
-
|
|
404
|
-
if (resp.ok) {
|
|
405
|
-
process.stdout.write(text);
|
|
406
|
-
if (!text.endsWith('\n')) process.stdout.write('\n');
|
|
407
|
-
} else {
|
|
408
|
-
// Try to parse as JSON error
|
|
409
|
-
try {
|
|
410
|
-
const err = JSON.parse(text);
|
|
411
|
-
console.error(err.error || text);
|
|
412
|
-
if (err.hint) console.error(err.hint);
|
|
413
|
-
} catch {
|
|
414
|
-
console.error(text);
|
|
415
|
-
}
|
|
416
|
-
process.exit(1);
|
|
417
|
-
}
|
|
418
|
-
} catch (err: any) {
|
|
419
|
-
if (err.name === 'AbortError') {
|
|
420
|
-
console.error('[browse] Command timed out after 30s');
|
|
421
|
-
process.exit(1);
|
|
422
|
-
}
|
|
423
|
-
// Connection error — server may have crashed
|
|
424
|
-
if (err.code === 'ECONNREFUSED' || err.code === 'ECONNRESET' || err.message?.includes('fetch failed')) {
|
|
425
|
-
if (retries >= 1) throw new Error('[browse] Server crashed twice in a row — aborting');
|
|
426
|
-
console.error('[browse] Server connection lost. Restarting...');
|
|
427
|
-
// Kill the old server to avoid orphaned chromium processes
|
|
428
|
-
const oldState = readState();
|
|
429
|
-
if (oldState && oldState.pid) {
|
|
430
|
-
await killServer(oldState.pid);
|
|
431
|
-
}
|
|
432
|
-
const newState = await startServer();
|
|
433
|
-
return sendCommand(newState, command, args, retries + 1);
|
|
434
|
-
}
|
|
435
|
-
throw err;
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// ─── Main ──────────────────────────────────────────────────────
|
|
440
|
-
async function main() {
|
|
441
|
-
const args = process.argv.slice(2);
|
|
442
|
-
|
|
443
|
-
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
444
|
-
console.log(`gstack browse — Fast headless browser for AI coding agents
|
|
445
|
-
|
|
446
|
-
Usage: browse <command> [args...]
|
|
447
|
-
|
|
448
|
-
Navigation: goto <url> | back | forward | reload | url
|
|
449
|
-
Content: text | html [sel] | links | forms | accessibility
|
|
450
|
-
Interaction: click <sel> | fill <sel> <val> | select <sel> <val>
|
|
451
|
-
hover <sel> | type <text> | press <key>
|
|
452
|
-
scroll [sel] | wait <sel|--networkidle|--load> | viewport <WxH>
|
|
453
|
-
upload <sel> <file1> [file2...]
|
|
454
|
-
cookie-import <json-file>
|
|
455
|
-
cookie-import-browser [browser] [--domain <d>]
|
|
456
|
-
Inspection: js <expr> | eval <file> | css <sel> <prop> | attrs <sel>
|
|
457
|
-
console [--clear|--errors] | network [--clear] | dialog [--clear]
|
|
458
|
-
cookies | storage [set <k> <v>] | perf
|
|
459
|
-
is <prop> <sel> (visible|hidden|enabled|disabled|checked|editable|focused)
|
|
460
|
-
Visual: screenshot [--viewport] [--clip x,y,w,h] [@ref|sel] [path]
|
|
461
|
-
pdf [path] | responsive [prefix]
|
|
462
|
-
Snapshot: snapshot [-i] [-c] [-d N] [-s sel] [-D] [-a] [-o path] [-C]
|
|
463
|
-
-D/--diff: diff against previous snapshot
|
|
464
|
-
-a/--annotate: annotated screenshot with ref labels
|
|
465
|
-
-C/--cursor-interactive: find non-ARIA clickable elements
|
|
466
|
-
Compare: diff <url1> <url2>
|
|
467
|
-
Multi-step: chain (reads JSON from stdin)
|
|
468
|
-
Tabs: tabs | tab <id> | newtab [url] | closetab [id]
|
|
469
|
-
Server: status | cookie <n>=<v> | header <n>:<v>
|
|
470
|
-
useragent <str> | stop | restart
|
|
471
|
-
Dialogs: dialog-accept [text] | dialog-dismiss
|
|
472
|
-
|
|
473
|
-
Refs: After 'snapshot', use @e1, @e2... as selectors:
|
|
474
|
-
click @e3 | fill @e4 "value" | hover @e1
|
|
475
|
-
@c refs from -C: click @c1`);
|
|
476
|
-
process.exit(0);
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
// One-time cleanup of legacy /tmp state files
|
|
480
|
-
cleanupLegacyState();
|
|
481
|
-
|
|
482
|
-
const command = args[0];
|
|
483
|
-
const commandArgs = args.slice(1);
|
|
484
|
-
|
|
485
|
-
// ─── Headed Connect (pre-server command) ────────────────────
|
|
486
|
-
// connect must be handled BEFORE ensureServer() because it needs
|
|
487
|
-
// to restart the server in headed mode with the Chrome extension.
|
|
488
|
-
if (command === 'connect') {
|
|
489
|
-
// Check if already in headed mode and healthy
|
|
490
|
-
const existingState = readState();
|
|
491
|
-
if (existingState && existingState.mode === 'headed' && isProcessAlive(existingState.pid)) {
|
|
492
|
-
try {
|
|
493
|
-
const resp = await fetch(`http://127.0.0.1:${existingState.port}/health`, {
|
|
494
|
-
signal: AbortSignal.timeout(2000),
|
|
495
|
-
});
|
|
496
|
-
if (resp.ok) {
|
|
497
|
-
console.log('Already connected in headed mode.');
|
|
498
|
-
process.exit(0);
|
|
499
|
-
}
|
|
500
|
-
} catch {
|
|
501
|
-
// Headed server alive but not responding — kill and restart
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
// Kill ANY existing server (SIGTERM → wait 2s → SIGKILL)
|
|
506
|
-
if (existingState && isProcessAlive(existingState.pid)) {
|
|
507
|
-
try { process.kill(existingState.pid, 'SIGTERM'); } catch {}
|
|
508
|
-
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
509
|
-
if (isProcessAlive(existingState.pid)) {
|
|
510
|
-
try { process.kill(existingState.pid, 'SIGKILL'); } catch {}
|
|
511
|
-
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
// Kill orphaned Chromium processes that may still hold the profile lock.
|
|
516
|
-
// The server PID is the Bun process; Chromium is a child that can outlive it
|
|
517
|
-
// if the server is killed abruptly (SIGKILL, crash, manual rm of state file).
|
|
518
|
-
const profileDir = path.join(process.env.HOME || '/tmp', '.gstack', 'chromium-profile');
|
|
519
|
-
try {
|
|
520
|
-
const singletonLock = path.join(profileDir, 'SingletonLock');
|
|
521
|
-
const lockTarget = fs.readlinkSync(singletonLock); // e.g. "hostname-12345"
|
|
522
|
-
const orphanPid = parseInt(lockTarget.split('-').pop() || '', 10);
|
|
523
|
-
if (orphanPid && isProcessAlive(orphanPid)) {
|
|
524
|
-
try { process.kill(orphanPid, 'SIGTERM'); } catch {}
|
|
525
|
-
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
526
|
-
if (isProcessAlive(orphanPid)) {
|
|
527
|
-
try { process.kill(orphanPid, 'SIGKILL'); } catch {}
|
|
528
|
-
await new Promise(resolve => setTimeout(resolve, 500));
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
} catch {
|
|
532
|
-
// No lock symlink or not readable — nothing to kill
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// Clean up Chromium profile locks (can persist after crashes)
|
|
536
|
-
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
|
537
|
-
try { fs.unlinkSync(path.join(profileDir, lockFile)); } catch {}
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
// Delete stale state file
|
|
541
|
-
try { fs.unlinkSync(config.stateFile); } catch {}
|
|
542
|
-
|
|
543
|
-
console.log('Launching headed Chromium with extension + sidebar agent...');
|
|
544
|
-
try {
|
|
545
|
-
// Start server in headed mode with extension auto-loaded
|
|
546
|
-
// Use a well-known port so the Chrome extension auto-connects
|
|
547
|
-
const serverEnv: Record<string, string> = {
|
|
548
|
-
BROWSE_HEADED: '1',
|
|
549
|
-
BROWSE_PORT: '34567',
|
|
550
|
-
BROWSE_SIDEBAR_CHAT: '1',
|
|
551
|
-
};
|
|
552
|
-
const newState = await startServer(serverEnv);
|
|
553
|
-
|
|
554
|
-
// Print connected status
|
|
555
|
-
const resp = await fetch(`http://127.0.0.1:${newState.port}/command`, {
|
|
556
|
-
method: 'POST',
|
|
557
|
-
headers: {
|
|
558
|
-
'Content-Type': 'application/json',
|
|
559
|
-
'Authorization': `Bearer ${newState.token}`,
|
|
560
|
-
},
|
|
561
|
-
body: JSON.stringify({ command: 'status', args: [] }),
|
|
562
|
-
signal: AbortSignal.timeout(5000),
|
|
563
|
-
});
|
|
564
|
-
const status = await resp.text();
|
|
565
|
-
console.log(`Connected to real Chrome\n${status}`);
|
|
566
|
-
|
|
567
|
-
// Auto-start sidebar agent
|
|
568
|
-
// __dirname is inside $bunfs in compiled binaries — resolve from execPath instead
|
|
569
|
-
let agentScript = path.resolve(__dirname, 'sidebar-agent.ts');
|
|
570
|
-
if (!fs.existsSync(agentScript)) {
|
|
571
|
-
agentScript = path.resolve(path.dirname(process.execPath), '..', 'src', 'sidebar-agent.ts');
|
|
572
|
-
}
|
|
573
|
-
try {
|
|
574
|
-
if (!fs.existsSync(agentScript)) {
|
|
575
|
-
throw new Error(`sidebar-agent.ts not found at ${agentScript}`);
|
|
576
|
-
}
|
|
577
|
-
// Clear old agent queue
|
|
578
|
-
const agentQueue = path.join(process.env.HOME || '/tmp', '.gstack', 'sidebar-agent-queue.jsonl');
|
|
579
|
-
try { fs.writeFileSync(agentQueue, ''); } catch {}
|
|
580
|
-
|
|
581
|
-
// Resolve browse binary path the same way — execPath-relative
|
|
582
|
-
let browseBin = path.resolve(__dirname, '..', 'dist', 'browse');
|
|
583
|
-
if (!fs.existsSync(browseBin)) {
|
|
584
|
-
browseBin = process.execPath; // the compiled binary itself
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
// Kill any existing sidebar-agent processes before starting a new one.
|
|
588
|
-
// Old agents have stale auth tokens and will silently fail to relay events,
|
|
589
|
-
// causing the server to mark the agent as "hung".
|
|
590
|
-
try {
|
|
591
|
-
const { spawnSync } = require('child_process');
|
|
592
|
-
spawnSync('pkill', ['-f', 'sidebar-agent\\.ts'], { stdio: 'ignore', timeout: 3000 });
|
|
593
|
-
} catch {}
|
|
594
|
-
|
|
595
|
-
const agentProc = Bun.spawn(['bun', 'run', agentScript], {
|
|
596
|
-
cwd: config.projectDir,
|
|
597
|
-
env: {
|
|
598
|
-
...process.env,
|
|
599
|
-
BROWSE_BIN: browseBin,
|
|
600
|
-
BROWSE_STATE_FILE: config.stateFile,
|
|
601
|
-
BROWSE_SERVER_PORT: String(newState.port),
|
|
602
|
-
},
|
|
603
|
-
stdio: ['ignore', 'ignore', 'ignore'],
|
|
604
|
-
});
|
|
605
|
-
agentProc.unref();
|
|
606
|
-
console.log(`[browse] Sidebar agent started (PID: ${agentProc.pid})`);
|
|
607
|
-
} catch (err: any) {
|
|
608
|
-
console.error(`[browse] Sidebar agent failed to start: ${err.message}`);
|
|
609
|
-
console.error(`[browse] Run manually: bun run ${agentScript}`);
|
|
610
|
-
}
|
|
611
|
-
} catch (err: any) {
|
|
612
|
-
console.error(`[browse] Connect failed: ${err.message}`);
|
|
613
|
-
process.exit(1);
|
|
614
|
-
}
|
|
615
|
-
process.exit(0);
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
// ─── Headed Disconnect (pre-server command) ─────────────────
|
|
619
|
-
// disconnect must be handled BEFORE ensureServer() because the headed
|
|
620
|
-
// guard blocks all commands when the server is unresponsive.
|
|
621
|
-
if (command === 'disconnect') {
|
|
622
|
-
const existingState = readState();
|
|
623
|
-
if (!existingState || existingState.mode !== 'headed') {
|
|
624
|
-
console.log('Not in headed mode — nothing to disconnect.');
|
|
625
|
-
process.exit(0);
|
|
626
|
-
}
|
|
627
|
-
// Try graceful shutdown via server
|
|
628
|
-
try {
|
|
629
|
-
const resp = await fetch(`http://127.0.0.1:${existingState.port}/command`, {
|
|
630
|
-
method: 'POST',
|
|
631
|
-
headers: {
|
|
632
|
-
'Content-Type': 'application/json',
|
|
633
|
-
'Authorization': `Bearer ${existingState.token}`,
|
|
634
|
-
},
|
|
635
|
-
body: JSON.stringify({ command: 'disconnect', args: [] }),
|
|
636
|
-
signal: AbortSignal.timeout(3000),
|
|
637
|
-
});
|
|
638
|
-
if (resp.ok) {
|
|
639
|
-
console.log('Disconnected from real browser.');
|
|
640
|
-
process.exit(0);
|
|
641
|
-
}
|
|
642
|
-
} catch {
|
|
643
|
-
// Server not responding — force cleanup
|
|
644
|
-
}
|
|
645
|
-
// Force kill + cleanup
|
|
646
|
-
if (isProcessAlive(existingState.pid)) {
|
|
647
|
-
try { process.kill(existingState.pid, 'SIGTERM'); } catch {}
|
|
648
|
-
await new Promise(resolve => setTimeout(resolve, 2000));
|
|
649
|
-
if (isProcessAlive(existingState.pid)) {
|
|
650
|
-
try { process.kill(existingState.pid, 'SIGKILL'); } catch {}
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
// Clean profile locks and state file
|
|
654
|
-
const profileDir = path.join(process.env.HOME || '/tmp', '.gstack', 'chromium-profile');
|
|
655
|
-
for (const lockFile of ['SingletonLock', 'SingletonSocket', 'SingletonCookie']) {
|
|
656
|
-
try { fs.unlinkSync(path.join(profileDir, lockFile)); } catch {}
|
|
657
|
-
}
|
|
658
|
-
try { fs.unlinkSync(config.stateFile); } catch {}
|
|
659
|
-
console.log('Disconnected (server was unresponsive — force cleaned).');
|
|
660
|
-
process.exit(0);
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
// Special case: chain reads from stdin
|
|
664
|
-
if (command === 'chain' && commandArgs.length === 0) {
|
|
665
|
-
const stdin = await Bun.stdin.text();
|
|
666
|
-
commandArgs.push(stdin.trim());
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
const state = await ensureServer();
|
|
670
|
-
await sendCommand(state, command, commandArgs);
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
if (import.meta.main) {
|
|
674
|
-
main().catch((err) => {
|
|
675
|
-
console.error(`[browse] ${err.message}`);
|
|
676
|
-
process.exit(1);
|
|
677
|
-
});
|
|
678
|
-
}
|