@gwro/codeaside 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,40 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
6
+ <title>CodeAside</title>
7
+ <style>
8
+ :root { color-scheme: dark; }
9
+ body { margin: 0; background: #151515; color: #e6e6e6; font: 15px/1.45 -apple-system, system-ui, sans-serif; }
10
+ main { max-width: 640px; margin: 0 auto; padding: 20px 16px 40px; }
11
+ h1 { font-size: 18px; font-weight: 600; margin: 0 0 4px; }
12
+ #status { display: block; color: #9a9a9a; font-size: 13px; margin-bottom: 16px; min-height: 1.4em; }
13
+ pre { background: #0b0b0b; color: #7dff8a; border: 1px solid #2a2a2a; border-radius: 12px; padding: 14px; font: 13px/1.5 ui-monospace, Menlo, monospace; white-space: pre-wrap; word-break: break-word; margin: 0 0 16px; min-height: 12em; }
14
+ form { display: flex; gap: 8px; margin-bottom: 16px; }
15
+ input { flex: 1; min-width: 0; background: #222; color: #eee; border: 1px solid #333; border-radius: 8px; padding: 10px; font: inherit; }
16
+ button { background: #2d2d2d; color: #eee; border: 1px solid #3a3a3a; border-radius: 8px; padding: 10px 14px; font: inherit; }
17
+ .help { color: #8a8a8a; font-size: 13px; }
18
+ .help b { color: #bdbdbd; font-weight: 600; }
19
+ </style>
20
+ <script type="module" crossorigin src="./assets/index-BOTAJr1P.js"></script>
21
+ </head>
22
+ <body>
23
+ <main>
24
+ <h1>CodeAside <span id="version" style="font-size:12px;font-weight:400;color:#8a8a8a"></span></h1>
25
+ <span id="status">Starting…</span>
26
+ <pre id="mirror"></pre>
27
+ <form id="pair" hidden>
28
+ <input id="pair-code" placeholder="Pairing code from codeaside pair" autocomplete="off" autocapitalize="off" spellcheck="false" />
29
+ <button type="submit">Pair</button>
30
+ </form>
31
+ <p class="help">
32
+ <b>Swipe</b> moves or scrolls. <b>Tap</b> opens or picks. <b>Hold</b> to talk; words appear as you speak. Release to review it, then <b>tap</b> to send, hold again to redo, or <b>double-tap</b> to cancel.
33
+ <b>Double-tap</b> goes back. <b>Tap then hold</b> opens the menu: interrupt, switch model, compact.
34
+ </p>
35
+ <p><button id="demo" type="button" hidden>Try the demo</button> <button id="unpair" type="button">Forget this hub</button></p>
36
+ <p class="help">CodeAside works with Claude Code on your own PC through the free codeaside hub, which runs on Windows. It is built on GlanceCode by sousy. Not affiliated with or endorsed by Anthropic or Even Realities.
37
+ <a href="https://github.com/gwro/CodeAside#readme" style="color:#9ecbff">Setup guide</a> · <a href="https://github.com/gwro/CodeAside/blob/main/docs/privacy.md" style="color:#9ecbff">Privacy</a></p>
38
+ </main>
39
+ </body>
40
+ </html>
package/bin/codeaside ADDED
@@ -0,0 +1,603 @@
1
+ #!/usr/bin/env node
2
+ // codeaside: set up and run the hub, and start or attach Claude Code sessions in the host.
3
+ import { spawnSync } from "node:child_process";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+
8
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
9
+ // Windows absolute paths are not import specifiers; go through file:// URLs.
10
+ const load = (...p) => import(pathToFileURL(join(ROOT, ...p)).href);
11
+ const { BRAND } = await load("hub", "brand.mjs");
12
+ const { CLAUDE_SETTINGS, DATA_DIR, LOG_DIR, loadConfig, tailscaleAddress } = await load("hub", "config.mjs");
13
+ const { HostClient, attach, ensureHost, pipeAnswers, resolveClaude } = await load("host", "client.mjs");
14
+ const { TASK_NAME, installFileLogger, installService, serviceStatus, startService, stopService, uninstallService } = await load("hub", "service.mjs");
15
+ const PKG = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
16
+
17
+ const CLI = BRAND.name;
18
+ const HOOK_SCRIPT = join(ROOT, "bin", `${CLI}-hook.mjs`);
19
+ // Claude Code runs the hook through PowerShell (forced with `shell`, so it is the
20
+ // same with or without Git Bash). PowerShell's $PID lets the hub find Claude's pid.
21
+ const HOOK_COMMAND = `& "${process.execPath}" "${HOOK_SCRIPT}" $PID`;
22
+ const HOOK_EVENTS = [
23
+ "SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure",
24
+ "PermissionDenied", "Notification", "Stop", "StopFailure", "SessionEnd",
25
+ ];
26
+ const WIN = process.platform === "win32";
27
+
28
+ const [cmd = "help", ...rest] = process.argv.slice(2);
29
+
30
+ const ok = (s) => console.log(` ✓ ${s}`);
31
+ const warn = (s) => console.log(` ! ${s}`);
32
+ const info = (s) => console.log(` ${s}`);
33
+
34
+ const commands = {
35
+ // ---------- one-shot setup ----------
36
+ async setup() {
37
+ console.log(`${BRAND.displayName} setup\n`);
38
+ const problems = await checkPrerequisites();
39
+ if (problems.blocking) {
40
+ console.log("\nFix the items above, then run setup again.");
41
+ process.exit(1);
42
+ }
43
+ console.log("\nHooks");
44
+ commands.install({ quiet: true });
45
+ console.log("\nVoice");
46
+ await commands["setup-voice"]();
47
+ console.log("\nBackground service");
48
+ commands.service("install");
49
+ console.log("\nHTTPS for the glasses app");
50
+ const served = commands.serve("on", { quiet: true });
51
+ console.log("\nPairing");
52
+ if (served) await commands.pair();
53
+ else info(`After enabling HTTPS, run: ${CLI} serve && ${CLI} pair`);
54
+ console.log(`\nTo let the glasses drive sessions you start at your desk, start Claude with \`${CLI} claude\`.`);
55
+ },
56
+
57
+ async doctor() {
58
+ console.log(`${BRAND.displayName} ${PKG.version} doctor\n`);
59
+ const { blocking } = await checkPrerequisites();
60
+ const cfg = loadConfig();
61
+ const settings = readSettings();
62
+ const hooked = HOOK_EVENTS.every((e) => (settings.hooks?.[e] || []).some((g) => (g.hooks || []).some((h) => h.command === HOOK_COMMAND)));
63
+ hooked ? ok("Claude Code hooks installed") : warn(`hooks not installed: ${CLI} install`);
64
+ const stale = staleHookCommands(settings);
65
+ if (stale.length) warn(`hooks point at missing scripts: ${[...new Set(stale)].join(", ")} (run ${CLI} install)`);
66
+ (await pipeAnswers(cfg.hostPipe)) ? ok(`session host running (${cfg.hostPipe})`) : info(`session host not running; it starts with the first \`${CLI} claude\``);
67
+ try {
68
+ const res = await fetch(`http://127.0.0.1:${cfg.port}/api/health`, { signal: AbortSignal.timeout(1500) });
69
+ res.ok ? ok(`hub running on 127.0.0.1:${cfg.port}`) : warn(`hub answered ${res.status}`);
70
+ } catch {
71
+ warn(`hub not running: ${CLI} service install (or ${CLI} hub)`);
72
+ }
73
+ if (WIN) {
74
+ const st = serviceStatus();
75
+ if (!st.installed) info(`hub service not installed, so the hub won't start at logon: ${CLI} service install`);
76
+ else if (st.state === "Running") ok("hub service running (Task Scheduler)");
77
+ else warn(`hub service is ${st.state}: ${CLI} service restart`);
78
+ }
79
+ existsSync(cfg.whisperModel) ? ok("speech model present") : warn(`speech model missing: ${CLI} setup-voice`);
80
+ const voiceReady = existsSync(cfg.whisperModel) && (/[\\/]/.test(cfg.whisperBin) ? existsSync(cfg.whisperBin) : commandExists(cfg.whisperBin));
81
+ if (voiceReady) {
82
+ try {
83
+ const res = await fetch(`http://127.0.0.1:${cfg.whisperPort}/`, { signal: AbortSignal.timeout(1500) });
84
+ res.status < 500 ? ok(`whisper-server running on 127.0.0.1:${cfg.whisperPort}`) : warn(`whisper-server answered ${res.status}`);
85
+ } catch {
86
+ info("whisper-server not running; the hub starts it on the first hold to talk");
87
+ }
88
+ }
89
+ const ts = tailscaleStatus();
90
+ if (!ts) warn("Tailscale not running on this machine");
91
+ else {
92
+ ok(`Tailscale up as ${ts.dnsName}`);
93
+ ts.httpsEnabled ? ok("tailnet HTTPS certificates enabled") : warn("tailnet HTTPS is off: enable it at https://login.tailscale.com/admin/dns");
94
+ serveActive(cfg) ? ok(`tailscale serve on https://${ts.dnsName}:${cfg.httpsPort}`) : warn(`not served over HTTPS: ${CLI} serve`);
95
+ }
96
+ if (blocking) process.exitCode = 1;
97
+ },
98
+
99
+ // ---------- hub ----------
100
+ hub() {
101
+ // --service: started hidden by Task Scheduler, so log to a file and skip the terminal feed.
102
+ const service = rest.includes("--service");
103
+ if (service) installFileLogger(join(LOG_DIR, "hub.log"));
104
+ return load("hub", "server.mjs").then(({ startHub }) => {
105
+ const hub = startHub({ feed: !service });
106
+ const stop = () => {
107
+ hub.close();
108
+ process.exit(0);
109
+ };
110
+ process.on("SIGINT", stop);
111
+ process.on("SIGTERM", stop);
112
+ });
113
+ },
114
+
115
+ // ---------- Claude Code hooks ----------
116
+ install({ quiet = false } = {}) {
117
+ const entry = { type: "command", command: HOOK_COMMAND, shell: "powershell", async: true, timeout: 10 };
118
+ const r = addHooks(CLAUDE_SETTINGS, HOOK_EVENTS, entry);
119
+ if (r.added || r.removed) ok(`hook installed on ${r.added} event(s)${r.removed ? `, ${r.removed} old entr${r.removed === 1 ? "y" : "ies"} removed` : ""} in ${CLAUDE_SETTINGS}`);
120
+ else ok("Claude Code hooks already installed");
121
+ if (!quiet) info("Sessions already open pick it up when their settings reload; restart them if they don't appear.");
122
+ },
123
+
124
+ uninstall() {
125
+ const removed = removeHooks(CLAUDE_SETTINGS);
126
+ console.log(`Removed ${removed} ${CLI} hook entr${removed === 1 ? "y" : "ies"}.`);
127
+ },
128
+
129
+ // ---------- sessions ----------
130
+ async claude() {
131
+ const claude = resolveClaude();
132
+ if (!claude) {
133
+ console.error("claude not found on PATH. Install Claude Code: https://claude.com/claude-code");
134
+ process.exit(1);
135
+ }
136
+ if (process.env.CODEASIDE_PANE) {
137
+ // Already inside a host session: just run Claude Code here.
138
+ const r = spawnSync(claude.cmd, [...claude.args, ...rest], { stdio: "inherit" });
139
+ process.exit(r.status ?? 0);
140
+ }
141
+ const cfg = loadConfig();
142
+ const cwd = process.cwd();
143
+ await ensureHost(cfg.hostPipe, { logFile: join(LOG_DIR, "host.log"), launcherDir: DATA_DIR });
144
+ const host = new HostClient(cfg.hostPipe);
145
+ const { id, name } = await host.request("new", {
146
+ name: basename(cwd),
147
+ cwd,
148
+ cmd: claude.cmd,
149
+ args: [...claude.args, ...rest],
150
+ env: { CODEASIDE_HOOK_PORT: String(cfg.hookPort) },
151
+ cols: process.stdout.columns || 120,
152
+ rows: process.stdout.rows || 40,
153
+ });
154
+ await attachAndReport(host, id, name);
155
+ },
156
+
157
+ async attach() {
158
+ const cfg = loadConfig();
159
+ const host = new HostClient(cfg.hostPipe);
160
+ const sessions = await hostSessions(host);
161
+ if (!sessions.length) return console.log(`No ${CLI} sessions running.`);
162
+ const want = rest[0];
163
+ const target = want ? sessions.find((s) => s.name === want || s.id === want) || sessions.find((s) => s.name.startsWith(want)) : sessions.length === 1 ? sessions[0] : null;
164
+ if (!target) {
165
+ console.log("Sessions:");
166
+ for (const s of sessions) console.log(` ${s.name.padEnd(24)} ${s.attached ? "attached" : ""}`);
167
+ console.log(`\n${CLI} attach <name>`);
168
+ return;
169
+ }
170
+ await attachAndReport(host, target.id, target.name);
171
+ },
172
+
173
+ async ls() {
174
+ const cfg = loadConfig();
175
+ const sessions = await hostSessions(new HostClient(cfg.hostPipe));
176
+ if (!sessions.length) return console.log(`No ${CLI} sessions running.`);
177
+ for (const s of sessions) console.log(`${s.name.padEnd(24)} ${s.cwd}${s.attached ? " (attached)" : ""}`);
178
+ process.exit(0);
179
+ },
180
+
181
+ async feed() {
182
+ const cfg = loadConfig();
183
+ const { printFeed, printState } = await load("hub", "feed.mjs");
184
+ const base = `http://127.0.0.1:${cfg.port}`;
185
+ const headers = { Authorization: `Bearer ${cfg.token}` };
186
+ const known = new Map();
187
+ let since = 0;
188
+ for (;;) {
189
+ try {
190
+ const state = await (await fetch(`${base}/api/state`, { headers })).json();
191
+ if (!since) {
192
+ since = state.seq;
193
+ console.log(`Watching ${state.sessions.length} session(s). Ctrl-C to stop.`);
194
+ }
195
+ for (const s of state.sessions) known.set(s.id, s);
196
+ const res = await fetch(`${base}/api/events?since=${since}`, { headers });
197
+ const decoder = new TextDecoder();
198
+ let buf = "";
199
+ for await (const chunk of res.body) {
200
+ buf += decoder.decode(chunk, { stream: true });
201
+ let idx;
202
+ while ((idx = buf.indexOf("\n\n")) >= 0) {
203
+ const block = buf.slice(0, idx);
204
+ buf = buf.slice(idx + 2);
205
+ const id = /^id: (\d+)$/m.exec(block)?.[1];
206
+ const data = /^data: (.*)$/m.exec(block)?.[1];
207
+ if (id) since = Number(id);
208
+ if (!data) continue;
209
+ const ev = JSON.parse(data);
210
+ if (ev.type === "session") {
211
+ printState(ev.session, known.get(ev.session.id));
212
+ known.set(ev.session.id, ev.session);
213
+ } else if (ev.type === "items") {
214
+ printFeed(known.get(ev.id) || { project: ev.id.slice(0, 8) }, ev.items);
215
+ }
216
+ }
217
+ }
218
+ } catch {
219
+ /* hub restarting */
220
+ }
221
+ await new Promise((r) => setTimeout(r, 2000));
222
+ }
223
+ },
224
+
225
+ async status() {
226
+ const cfg = loadConfig();
227
+ try {
228
+ const res = await fetch(`http://127.0.0.1:${cfg.port}/api/state`, { headers: { Authorization: `Bearer ${cfg.token}` }, signal: AbortSignal.timeout(1500) });
229
+ const { sessions } = await res.json();
230
+ console.log(`hub: running, ${sessions.length} session(s)`);
231
+ for (const s of sessions) console.log(` ${s.project.padEnd(16)} ${s.state.padEnd(8)} ${s.controllable ? "live" : "view-only"} ${s.activity || ""}`);
232
+ } catch {
233
+ console.log(`hub: not running (${CLI} service install, or ${CLI} hub)`);
234
+ }
235
+ console.log(`run \`${CLI} doctor\` for a full check`);
236
+ },
237
+
238
+ // ---------- service ----------
239
+ service(sub = rest[0] || "status") {
240
+ if (!WIN) {
241
+ warn("the background service uses Task Scheduler, so it is Windows only");
242
+ return false;
243
+ }
244
+ if (sub === "install") {
245
+ try {
246
+ installService({ nodePath: process.execPath, cliPath: join(ROOT, "bin", CLI), dataDir: DATA_DIR });
247
+ ok(`hub service installed and started (Task Scheduler task "${TASK_NAME}"; logs: ${join(LOG_DIR, "hub.log")})`);
248
+ return true;
249
+ } catch (err) {
250
+ warn(err.message);
251
+ return false;
252
+ }
253
+ }
254
+ if (sub === "uninstall") {
255
+ uninstallService() ? ok("hub service removed") : warn("no hub service was installed");
256
+ return true;
257
+ }
258
+ if (sub === "restart") {
259
+ stopService({ quiet: true });
260
+ try {
261
+ startService();
262
+ ok("restarted");
263
+ } catch (err) {
264
+ warn(err.message);
265
+ }
266
+ return true;
267
+ }
268
+ if (sub === "stop") {
269
+ stopService();
270
+ ok(`stopped; it starts again at logon (\`${CLI} service uninstall\` removes it)`);
271
+ return true;
272
+ }
273
+ const st = serviceStatus();
274
+ if (!st.installed) {
275
+ console.log(`not installed (${CLI} service install)`);
276
+ return false;
277
+ }
278
+ console.log(`${st.state}${st.lastRun && !/^0001/.test(st.lastRun) ? `, last run ${st.lastRun}` : ""}${st.lastResult ? ` (last result ${st.lastResult})` : ""}`);
279
+ return st.state === "Running";
280
+ },
281
+
282
+ // ---------- HTTPS through tailscale serve ----------
283
+ serve(sub = rest[0] || "on", { quiet = false } = {}) {
284
+ const cfg = loadConfig();
285
+ const ts = tailscaleStatus();
286
+ if (!ts) {
287
+ warn("Tailscale is not running on this machine. Install it and sign in: https://tailscale.com/download");
288
+ return false;
289
+ }
290
+ if (sub === "off") {
291
+ runTailscale(["serve", `--https=${cfg.httpsPort}`, "off"]);
292
+ ok("stopped serving over HTTPS");
293
+ return true;
294
+ }
295
+ if (sub === "status") {
296
+ serveActive(cfg) ? ok(`serving https://${ts.dnsName}:${cfg.httpsPort}`) : warn("not serving");
297
+ return serveActive(cfg);
298
+ }
299
+ if (!ts.httpsEnabled) {
300
+ warn("HTTPS certificates are off for your tailnet.");
301
+ info("Turn on HTTPS at https://login.tailscale.com/admin/dns (one click), then run this again.");
302
+ return false;
303
+ }
304
+ const r = runTailscale(["serve", "--bg", `--https=${cfg.httpsPort}`, `http://127.0.0.1:${cfg.port}`]);
305
+ if (r.status !== 0) {
306
+ warn(`tailscale serve failed: ${(r.stderr || r.stdout || "").trim()}`);
307
+ return false;
308
+ }
309
+ ok(`serving the hub at https://${ts.dnsName}:${cfg.httpsPort}`);
310
+ if (!quiet) info(`Pair the glasses app: ${CLI} pair`);
311
+ return true;
312
+ },
313
+
314
+ // ---------- pairing ----------
315
+ async pair() {
316
+ const cfg = loadConfig();
317
+ const url = hubUrl(cfg);
318
+ if (!url) {
319
+ warn(`No reachable address for the phone. Run: ${CLI} serve`);
320
+ return;
321
+ }
322
+ const code = `${url}#${cfg.token}`;
323
+ console.log("Pairing code (paste it on the phone screen of the glasses app):\n");
324
+ console.log(` ${code}\n`);
325
+ try {
326
+ const { createRequire } = await import("node:module");
327
+ const qr = createRequire(import.meta.url)("qrcode-terminal");
328
+ console.log("Or scan this with the phone camera and copy the text:\n");
329
+ await new Promise((resolve) => qr.generate(code, { small: true }, (s) => resolve(console.log(s.replace(/^/gm, " ")))));
330
+ } catch {
331
+ /* no QR encoder; the code above is enough */
332
+ }
333
+ info("Anyone with this code and access to your tailnet can type into your sessions. Keep it private.");
334
+ if (rest.includes("--dev")) {
335
+ const appUrl = `${url}/?hub=${encodeURIComponent(url)}&token=${encodeURIComponent(cfg.token)}`;
336
+ console.log("\nDevelopment sideload (Even app > Even Hub > developer > Scan QR):");
337
+ // On Windows npx is a .cmd file and needs the shell, and cmd.exe splits an
338
+ // unquoted URL at its "&": the QR code would lose the token. Quote it.
339
+ const r = WIN
340
+ ? spawnSync(`npx --yes @evenrealities/evenhub-cli qr --url "${appUrl}"`, { stdio: "inherit", shell: true })
341
+ : spawnSync("npx", ["--yes", "@evenrealities/evenhub-cli", "qr", "--url", appUrl], { stdio: "inherit" });
342
+ if (r.status !== 0) console.log(appUrl);
343
+ }
344
+ },
345
+
346
+ // ---------- voice ----------
347
+ async "setup-voice"() {
348
+ const cfg = loadConfig();
349
+ const { formatProgress, hasNvidiaGpu, installModel, installWhisper, installedWhisper, WHISPER_BUILD } = await load("hub", "voice.mjs");
350
+ const progress = (label) => (done, total) => {
351
+ if (process.stdout.isTTY) process.stdout.write(`\r ${label}: ${formatProgress(done, total)} `);
352
+ };
353
+ const endLine = () => process.stdout.isTTY && process.stdout.write("\n");
354
+ const binIsPath = /[\\/]/.test(cfg.whisperBin);
355
+ // --cuda / --cpu pick the whisper.cpp build; by default an NVIDIA PC gets CUDA.
356
+ const cuda = rest.includes("--cuda") ? true : rest.includes("--cpu") ? false : hasNvidiaGpu();
357
+ const have = binIsPath ? installedWhisper(dirname(cfg.whisperBin)) : null;
358
+ const explicit = rest.includes("--cuda") || rest.includes("--cpu");
359
+ const wantSwitch = binIsPath && existsSync(cfg.whisperBin) && explicit && (have?.cuda ?? false) !== cuda;
360
+ if (binIsPath && (!existsSync(cfg.whisperBin) || wantSwitch)) {
361
+ if (!WIN) {
362
+ warn(`whisper-server not found at ${cfg.whisperBin}; install whisper.cpp and set whisperBin`);
363
+ return false;
364
+ }
365
+ try {
366
+ info(cuda ? "NVIDIA GPU found: installing whisper.cpp's CUDA build (about 685 MB); --cpu picks the CPU build" : "installing whisper.cpp's CPU build (about 9 MB)");
367
+ const { files, asset } = await installWhisper(dirname(cfg.whisperBin), { cuda, onProgress: progress("whisper.cpp"), log: info });
368
+ endLine();
369
+ ok(`whisper.cpp ${WHISPER_BUILD} installed from ${asset} (${files} files in ${dirname(cfg.whisperBin)})`);
370
+ } catch (err) {
371
+ endLine();
372
+ warn(`whisper.cpp download failed: ${err.message}; run setup-voice again later`);
373
+ return false;
374
+ }
375
+ } else if (binIsPath) ok(`whisper.cpp present (${have?.cuda ? "CUDA" : "CPU"} build, ${cfg.whisperBin})`);
376
+ else if (commandExists(cfg.whisperBin)) ok(`whisper.cpp found on PATH (${cfg.whisperBin})`);
377
+ else warn(`${cfg.whisperBin} not found on PATH`);
378
+ if (existsSync(cfg.whisperModel)) {
379
+ ok(`speech model present (${basename(cfg.whisperModel)})`);
380
+ return true;
381
+ }
382
+ try {
383
+ info(`the speech model is about 550 MB`);
384
+ await installModel(cfg.whisperModel, { onProgress: progress("speech model"), log: info });
385
+ endLine();
386
+ ok("speech model downloaded");
387
+ return true;
388
+ } catch (err) {
389
+ endLine();
390
+ warn(`model download failed: ${err.message}; run setup-voice again to resume`);
391
+ return false;
392
+ }
393
+ },
394
+
395
+ version() {
396
+ console.log(`${CLI} ${PKG.version}`);
397
+ },
398
+
399
+ help() {
400
+ console.log(`${CLI} ${PKG.version} - ${BRAND.tagline}
401
+
402
+ Setup
403
+ ${CLI} setup install hooks, voice, background service and HTTPS, then pair
404
+ ${CLI} doctor check every piece and say what to fix
405
+ ${CLI} pair pairing code for the glasses app (--dev adds a sideload QR)
406
+
407
+ Sessions
408
+ ${CLI} claude [args] start Claude Code in the session host so the glasses can drive it
409
+ ${CLI} attach [name] open a running session in this terminal (Ctrl+] detaches)
410
+ ${CLI} ls list sessions
411
+ ${CLI} feed live feed of every session
412
+ ${CLI} status hub and sessions
413
+
414
+ Pieces
415
+ ${CLI} install|uninstall add or remove the Claude Code hook
416
+ ${CLI} service [install|uninstall|restart|stop|status] hub as a Task Scheduler task that starts at logon
417
+ ${CLI} serve [on|off|status] HTTPS on your *.ts.net name through tailscale serve
418
+ ${CLI} hub run the hub in the foreground
419
+ ${CLI} setup-voice download whisper.cpp (--cuda or --cpu) and the local speech model`);
420
+ },
421
+ };
422
+
423
+ // ---------- sessions ----------
424
+
425
+ async function hostSessions(host) {
426
+ try {
427
+ return (await host.request("list")).sessions;
428
+ } catch {
429
+ return []; // no host running
430
+ } finally {
431
+ host.close();
432
+ }
433
+ }
434
+
435
+ /** Attach this console to a session, then say what happened when it ends or detaches. */
436
+ async function attachAndReport(host, id, name) {
437
+ const result = await attach({ pipe: host.pipe, id });
438
+ host.close();
439
+ process.stdout.write("\x1b[0m\r\n");
440
+ if (result.reason === "detached") console.log(`Detached. The session keeps running: ${CLI} attach ${name}`);
441
+ else {
442
+ const still = await pipeAnswers(host.pipe) && (await new HostClient(host.pipe).request("alive", { session: id }).catch(() => ({ alive: false }))).alive;
443
+ if (still) console.log(`Connection lost. The session keeps running: ${CLI} attach ${name}`);
444
+ }
445
+ process.exit(0);
446
+ }
447
+
448
+ // ---------- prerequisites ----------
449
+
450
+ async function checkPrerequisites() {
451
+ let blocking = false;
452
+ const [major] = process.versions.node.split(".").map(Number);
453
+ if (major >= 20) ok(`Node ${process.versions.node}`);
454
+ else {
455
+ warn(`Node ${process.versions.node} is too old; need 20 or newer`);
456
+ blocking = true;
457
+ }
458
+ const claude = resolveClaude();
459
+ if (claude) ok(`Claude Code found (${claude.display})`);
460
+ else {
461
+ warn("Claude Code not found on PATH: https://claude.com/claude-code");
462
+ blocking = true;
463
+ }
464
+ const cfg = loadConfig();
465
+ commandExists(cfg.whisperBin) ? ok("whisper.cpp found") : warn(`whisper.cpp not found (optional, for voice): ${CLI} setup-voice`);
466
+ tailscaleStatus() ? ok("Tailscale running") : warn("Tailscale not running (needed for the phone to reach this machine)");
467
+ return { blocking };
468
+ }
469
+
470
+ function commandExists(name) {
471
+ if (/[\\/]/.test(name)) return existsSync(name);
472
+ return spawnSync(WIN ? "where.exe" : "which", [name], { stdio: "ignore" }).status === 0;
473
+ }
474
+
475
+ // ---------- tailscale ----------
476
+
477
+ function tailscaleBin() {
478
+ if (commandExists("tailscale")) return "tailscale";
479
+ const candidates = WIN ? [join(process.env.ProgramFiles || "C:\\Program Files", "Tailscale", "tailscale.exe")] : ["/Applications/Tailscale.app/Contents/MacOS/Tailscale"];
480
+ return candidates.find((p) => existsSync(p)) || null;
481
+ }
482
+
483
+ function runTailscale(args) {
484
+ const bin = tailscaleBin();
485
+ if (!bin) return { status: 1, stderr: "tailscale not installed" };
486
+ return spawnSync(bin, args, { encoding: "utf8", windowsHide: true });
487
+ }
488
+
489
+ function tailscaleStatus() {
490
+ const r = runTailscale(["status", "--json"]);
491
+ if (r.status !== 0) return null;
492
+ try {
493
+ const s = JSON.parse(r.stdout);
494
+ if (s.BackendState && s.BackendState !== "Running") return null;
495
+ return {
496
+ dnsName: String(s.Self?.DNSName || "").replace(/\.$/, ""),
497
+ ip: s.Self?.TailscaleIPs?.find((a) => a.includes(".")) || null,
498
+ httpsEnabled: Array.isArray(s.CertDomains) && s.CertDomains.length > 0,
499
+ };
500
+ } catch {
501
+ return null;
502
+ }
503
+ }
504
+
505
+ function serveActive(cfg) {
506
+ const r = runTailscale(["serve", "status", "--json"]);
507
+ if (r.status !== 0) return false;
508
+ try {
509
+ const s = JSON.parse(r.stdout || "{}");
510
+ return Object.keys(s.TCP || {}).includes(String(cfg.httpsPort));
511
+ } catch {
512
+ return false;
513
+ }
514
+ }
515
+
516
+ /** The address the phone should use: HTTPS through tailscale serve, else the raw IP if enabled. */
517
+ function hubUrl(cfg) {
518
+ const ts = tailscaleStatus();
519
+ if (ts && serveActive(cfg)) return `https://${ts.dnsName}:${cfg.httpsPort}`;
520
+ const ip = cfg.bindTailscaleIP ? tailscaleAddress() : null;
521
+ return ip ? `http://${ip}:${cfg.port}` : null;
522
+ }
523
+
524
+ // ---------- hooks in settings.json ----------
525
+
526
+ function isOurHook(command) {
527
+ return typeof command === "string" && (command.includes(`${CLI}-hook`) || BRAND.legacy.hookScripts.some((h) => command.includes(h)));
528
+ }
529
+
530
+ /** The script path inside one of our hook commands, for the stale check. */
531
+ function hookScriptPath(command) {
532
+ return /"([^"]*codeaside-hook[^"]*)"/.exec(command)?.[1] || null;
533
+ }
534
+
535
+ function staleHookCommands(settings) {
536
+ const out = [];
537
+ for (const groups of Object.values(settings.hooks || {})) {
538
+ for (const g of groups) {
539
+ for (const h of g.hooks || []) {
540
+ if (!isOurHook(h.command)) continue;
541
+ const script = hookScriptPath(h.command);
542
+ if (script && !existsSync(script)) out.push(script);
543
+ }
544
+ }
545
+ }
546
+ return out;
547
+ }
548
+
549
+ function readSettings(path = CLAUDE_SETTINGS) {
550
+ if (!existsSync(path)) return {};
551
+ return JSON.parse(readFileSync(path, "utf8"));
552
+ }
553
+
554
+ function writeSettings(settings, path = CLAUDE_SETTINGS) {
555
+ mkdirSync(dirname(path), { recursive: true });
556
+ if (existsSync(path)) copyFileSync(path, `${path}.bak-${CLI}`);
557
+ const tmp = path + ".tmp";
558
+ writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n");
559
+ renameSync(tmp, path);
560
+ }
561
+
562
+ /** Put our hook on each event in a settings file, dropping entries from older installs. */
563
+ function addHooks(path, events, entry) {
564
+ const settings = readSettings(path);
565
+ settings.hooks ||= {};
566
+ let added = 0;
567
+ let removed = 0;
568
+ for (const event of events) {
569
+ const groups = (settings.hooks[event] ||= []);
570
+ for (const g of groups) {
571
+ const before = (g.hooks || []).length;
572
+ g.hooks = (g.hooks || []).filter((h) => !isOurHook(h.command) || h.command === entry.command);
573
+ removed += before - g.hooks.length;
574
+ }
575
+ settings.hooks[event] = groups.filter((g) => (g.hooks || []).length);
576
+ if (!settings.hooks[event].some((g) => g.hooks.some((h) => h.command === entry.command))) {
577
+ settings.hooks[event].push({ hooks: [entry] });
578
+ added++;
579
+ }
580
+ }
581
+ if (added || removed) writeSettings(settings, path);
582
+ return { added, removed };
583
+ }
584
+
585
+ function removeHooks(path) {
586
+ const settings = readSettings(path);
587
+ let removed = 0;
588
+ for (const [event, groups] of Object.entries(settings.hooks || {})) {
589
+ const kept = groups.map((g) => ({ ...g, hooks: (g.hooks || []).filter((h) => !isOurHook(h.command)) })).filter((g) => g.hooks.length);
590
+ removed += groups.reduce((n, g) => n + (g.hooks || []).length, 0) - kept.reduce((n, g) => n + g.hooks.length, 0);
591
+ if (kept.length) settings.hooks[event] = kept;
592
+ else delete settings.hooks[event];
593
+ }
594
+ if (removed) writeSettings(settings, path);
595
+ return removed;
596
+ }
597
+
598
+ const fn = commands[cmd] || (cmd === "--version" || cmd === "-v" ? commands.version : null);
599
+ if (!fn) {
600
+ commands.help();
601
+ process.exit(cmd === "help" || cmd === "--help" || cmd === "-h" ? 0 : 1);
602
+ }
603
+ await fn();
@@ -0,0 +1,28 @@
1
+ // Claude Code hook -> codeaside hub. Registered as an async PowerShell hook:
2
+ // & "node.exe" "...\codeaside-hook.mjs" $PID
3
+ // It forwards the hook's JSON to the hub with where it ran (the host pane, from the
4
+ // environment the host gave Claude Code) and PowerShell's pid, whose parent is Claude.
5
+ // It always exits 0 and swallows every error, so a stopped hub is harmless.
6
+ const port = process.env.CODEASIDE_HOOK_PORT || "7718";
7
+ const chunks = [];
8
+ process.stdin.on("data", (c) => chunks.push(c));
9
+ process.stdin.on("end", async () => {
10
+ try {
11
+ await fetch(`http://127.0.0.1:${port}/hook`, {
12
+ method: "POST",
13
+ headers: {
14
+ "Content-Type": "application/json",
15
+ "X-Host": process.env.CODEASIDE_HOST || "",
16
+ "X-Pane": process.env.CODEASIDE_PANE || "",
17
+ "X-Shell-Pid": process.argv[2] || "",
18
+ },
19
+ body: Buffer.concat(chunks),
20
+ signal: AbortSignal.timeout(2000),
21
+ });
22
+ } catch {
23
+ /* hub not running */
24
+ }
25
+ process.exit(0);
26
+ });
27
+ process.stdin.on("error", () => process.exit(0));
28
+ setTimeout(() => process.exit(0), 4000).unref();