@gwro/codeaside 0.0.0-stage → 0.1.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/hub/server.mjs ADDED
@@ -0,0 +1,441 @@
1
+ // The hub: HTTP API for the glasses app, hook intake for Claude Code, live feed in the terminal.
2
+ import { createServer } from "node:http";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
+ import { extname, join, normalize, resolve } from "node:path";
5
+ import { timingSafeEqual } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+ import { CLAUDE_SETTINGS, loadConfig, tailscaleAddress } from "./config.mjs";
8
+ import { Registry, recentProjects, recentTranscripts } from "./sessions.mjs";
9
+ import { Transcriber } from "./stt.mjs";
10
+ import { Notifier } from "./notify.mjs";
11
+ import * as paneCtl from "./pane.mjs";
12
+ import { parentPid } from "./procs.mjs";
13
+ import { startKeepAwake } from "./awake.mjs";
14
+ import { color, printFeed } from "./feed.mjs";
15
+ import { BRAND } from "./brand.mjs";
16
+
17
+ const HERE = fileURLToPath(new URL(".", import.meta.url));
18
+ const APP_DIST = resolve(HERE, "..", "app", "dist");
19
+ const EVENT_BUFFER = 3000;
20
+ // What the glasses menu offers for Claude sessions.
21
+ const CLAUDE_MODELS = [
22
+ { id: "opus", name: "Opus" },
23
+ { id: "sonnet", name: "Sonnet" },
24
+ { id: "fable", name: "Fable" },
25
+ { id: "haiku", name: "Haiku" },
26
+ ];
27
+ const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".png": "image/png", ".svg": "image/svg+xml", ".json": "application/json", ".ico": "image/x-icon" };
28
+
29
+ class HttpError extends Error {
30
+ constructor(status, message) {
31
+ super(message);
32
+ this.status = status;
33
+ }
34
+ }
35
+
36
+ export function startHub({ quiet = false, feed = true } = {}) {
37
+ const cfg = loadConfig();
38
+ const log = (...a) => {
39
+ if (!quiet) console.log(`[${new Date().toLocaleTimeString()}]`, ...a);
40
+ };
41
+ const registry = new Registry();
42
+ registry.readSuggestions = cfg.showSuggestions === true;
43
+ const transcriber = new Transcriber({ port: cfg.whisperPort, model: cfg.whisperModel, bin: cfg.whisperBin, threads: cfg.whisperThreads, log });
44
+ const notifier = new Notifier({ server: cfg.ntfyServer, topic: cfg.ntfyTopic, log });
45
+ const agents = ["claude"];
46
+
47
+ // ---------- event stream with replay ----------
48
+ let seq = 0;
49
+ const events = []; // {id, data}
50
+ const clients = new Set();
51
+ const publish = (payload) => {
52
+ const ev = { id: ++seq, data: JSON.stringify(payload) };
53
+ events.push(ev);
54
+ if (events.length > EVENT_BUFFER) events.splice(0, events.length - EVENT_BUFFER);
55
+ for (const res of clients) res.write(`id: ${ev.id}\ndata: ${ev.data}\n\n`);
56
+ };
57
+
58
+ registry.on("session", (s) => publish({ type: "session", session: s.summaryJSON() }));
59
+ registry.on("removed", (s) => publish({ type: "removed", id: s.id }));
60
+ registry.on("items", (s, items) => {
61
+ publish({ type: "items", id: s.id, items });
62
+ if (feed) printFeed(s, items);
63
+ });
64
+ registry.on("attention", (s, kind) => {
65
+ const what = kind === "permission" ? `needs permission: ${s.waiting?.detail || ""}` : "has a question for you";
66
+ if (feed) console.log(color(` ◆ ${s.project} ${what}`, 33));
67
+ notifier.send(`${s.id}:${kind}`, `${s.project} needs you`, what);
68
+ });
69
+ registry.on("finished", (s, last) => {
70
+ notifier.send(`${s.id}:done`, `${s.project} finished`, last.replace(/\s+/g, " ") || "Turn complete");
71
+ });
72
+
73
+ registry.load();
74
+ const sweepTimer = setInterval(() => registry.sweep().catch(() => {}), 5000);
75
+
76
+ // A sleeping PC answers nothing, so the glasses see a dead hub. The helper holds
77
+ // the system (not the display) awake while on AC power; on battery it sleeps as usual.
78
+ const awake = cfg.preventSleep ? startKeepAwake({ hubPid: process.pid, log }) : null;
79
+
80
+ let lastPresenceAt = 0;
81
+
82
+ // ---------- helpers ----------
83
+ const tokenBuf = Buffer.from(cfg.token);
84
+ function authorized(req, url) {
85
+ const header = req.headers.authorization || "";
86
+ const given = header.startsWith("Bearer ") ? header.slice(7) : url.searchParams.get("token") || "";
87
+ const buf = Buffer.from(given);
88
+ return buf.length === tokenBuf.length && timingSafeEqual(buf, tokenBuf);
89
+ }
90
+
91
+ async function readBody(req, limit = 8 * 1024 * 1024) {
92
+ const chunks = [];
93
+ let size = 0;
94
+ for await (const c of req) {
95
+ size += c.length;
96
+ if (size > limit) throw new HttpError(413, "body too large");
97
+ chunks.push(c);
98
+ }
99
+ return Buffer.concat(chunks);
100
+ }
101
+
102
+ async function readJSON(req) {
103
+ const raw = await readBody(req, 256 * 1024);
104
+ if (!raw.length) return {};
105
+ try {
106
+ return JSON.parse(raw.toString("utf8"));
107
+ } catch {
108
+ throw new HttpError(400, "invalid JSON");
109
+ }
110
+ }
111
+
112
+ function send(res, status, body) {
113
+ const data = typeof body === "string" ? body : JSON.stringify(body);
114
+ res.writeHead(status, { "Content-Type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json", "Cache-Control": "no-store" });
115
+ res.end(data);
116
+ }
117
+
118
+ function sessionOr404(id) {
119
+ const s = registry.sessions.get(id);
120
+ if (!s) throw new HttpError(404, "no such session");
121
+ return s;
122
+ }
123
+
124
+ function controllable(s) {
125
+ if (!s.pane) throw new HttpError(409, `this session was not started with \`${BRAND.name} claude\`, so it is view-only`);
126
+ if (s.state === "ended") throw new HttpError(409, "session has ended");
127
+ return s.pane;
128
+ }
129
+
130
+ /**
131
+ * Typing a prompt while a dialog is open would press its highlighted option
132
+ * with the final Enter (for example, approve a permission). Refuse instead.
133
+ */
134
+ async function refuseIfDialog(s) {
135
+ const dialog = await paneCtl.readDialogStable(controllable(s));
136
+ if (dialog.kind === "permission") throw new HttpError(409, "Claude is waiting for approval. Choose an option first.");
137
+ if (dialog.kind === "question") throw new HttpError(409, "Claude asked a question. Pick an option or answer it by voice.");
138
+ if (dialog.kind === "trust") throw new HttpError(409, "Claude is asking whether to trust this folder.");
139
+ }
140
+
141
+ /** Wait briefly for the prompt to show up on screen (queued or echoed) or in the transcript. */
142
+ async function confirmDelivered(s, text, ms = 4000) {
143
+ const snippet = paneCtl.promptSnippet(text);
144
+ const seenInItems = () => s.items.slice(-10).some((i) => i.kind === "user" && paneCtl.screenHasSnippet(i.text, snippet));
145
+ const until = Date.now() + ms;
146
+ while (Date.now() < until) {
147
+ if (seenInItems()) return true;
148
+ try {
149
+ if (paneCtl.screenHasSnippet(await paneCtl.capture(s.pane, 60), snippet)) return true;
150
+ } catch {
151
+ /* pane busy */
152
+ }
153
+ await new Promise((r) => setTimeout(r, 400));
154
+ }
155
+ return seenInItems();
156
+ }
157
+
158
+ function vocabulary() {
159
+ const names = new Set(registry.list().map((s) => s.project));
160
+ for (const p of recentProjects(10)) names.add(p.project);
161
+ return `${cfg.sttVocabulary}, ${[...names].join(", ")}`;
162
+ }
163
+
164
+ /** Start Claude Code in the host; its hooks register the session. */
165
+ async function launch({ cwd, resume }) {
166
+ if (resume) {
167
+ const live = registry.sessions.get(resume);
168
+ if (live && live.state !== "ended") throw new HttpError(409, "that session is already open");
169
+ }
170
+ if (!cwd || !existsSync(cwd) || !statSync(cwd).isDirectory()) throw new HttpError(400, "cwd must be an existing folder");
171
+ const args = [...(cfg.claudeArgs || []), ...(resume ? ["--resume", resume] : [])];
172
+ const { name, target } = await paneCtl.launchClaude({ cwd, args, env: { CODEASIDE_HOOK_PORT: String(cfg.hookPort) }, pipe: cfg.hostPipe });
173
+ registry.expectLaunch(target, { name, origin: "glasses" });
174
+ log(`launched ${name} in ${cwd}${resume ? ` (resume ${resume.slice(0, 8)})` : ""}`);
175
+ // Handle the trust dialog in the background; the SessionStart hook registers the session.
176
+ paneCtl.acceptTrustIfShown(target, 8000).catch(() => {});
177
+ return { name, target };
178
+ }
179
+
180
+ async function waitForSessionOnPane(target, ms = 25_000) {
181
+ const key = paneCtl.paneKey(target);
182
+ const until = Date.now() + ms;
183
+ while (Date.now() < until) {
184
+ const s = registry.list().find((x) => x.state !== "ended" && paneCtl.paneKey(x.pane) === key);
185
+ if (s) return s;
186
+ await new Promise((r) => setTimeout(r, 250));
187
+ }
188
+ return null;
189
+ }
190
+
191
+ // ---------- API ----------
192
+ async function api(req, res, url) {
193
+ const path = url.pathname;
194
+ const method = req.method;
195
+
196
+ if (path === "/api/health") return send(res, 200, { ok: true });
197
+ if (!authorized(req, url)) throw new HttpError(401, "bad token");
198
+
199
+ if (method === "GET" && path === "/api/events") {
200
+ res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-store", Connection: "keep-alive", "X-Accel-Buffering": "no" });
201
+ const since = Number(req.headers["last-event-id"] || url.searchParams.get("since") || 0);
202
+ res.write(`retry: 2000\n\n`);
203
+ const oldest = events[0]?.id ?? seq + 1;
204
+ // Gap in the buffer, or the client is ahead of us (the hub restarted): resync.
205
+ if ((since && since + 1 < oldest) || since > seq) {
206
+ res.write(`data: ${JSON.stringify({ type: "resync" })}\n\n`); // gap: client must refetch
207
+ } else {
208
+ for (const ev of events) if (ev.id > since) res.write(`id: ${ev.id}\ndata: ${ev.data}\n\n`);
209
+ }
210
+ clients.add(res);
211
+ // A data event, not an SSE comment, so the app can tell a live stream from a dead one.
212
+ const ping = setInterval(() => res.write(`data: {"type":"ping"}\n\n`), 15_000);
213
+ req.on("close", () => {
214
+ clearInterval(ping);
215
+ clients.delete(res);
216
+ });
217
+ return;
218
+ }
219
+
220
+ if (method === "GET" && path === "/api/state") {
221
+ const prefs = {
222
+ replyFromStart: cfg.replyFromStart === true,
223
+ workingBrightness: [0, 1, 2, 3].includes(cfg.workingBrightness) ? cfg.workingBrightness : 4,
224
+ latestOnTalk: cfg.latestOnTalk === true,
225
+ toolLines: [1, 2, 3, 4, 5, 6].includes(cfg.toolLines) ? cfg.toolLines : 2,
226
+ latestOnPrompt: cfg.latestOnPrompt === true,
227
+ showSuggestions: cfg.showSuggestions === true,
228
+ sendSuggestionOnTap: cfg.sendSuggestionOnTap === true,
229
+ };
230
+ return send(res, 200, { seq, agents, prefs, sessions: registry.list().map((s) => s.summaryJSON()) });
231
+ }
232
+
233
+ if (method === "GET" && path === "/api/recent") {
234
+ const liveIds = new Set(registry.list().filter((s) => s.state !== "ended").map((s) => s.id));
235
+ const sessions = recentTranscripts({ liveIds, limit: 20 }).map((t) => ({ ...t, agent: "claude" }));
236
+ return send(res, 200, { agents, projects: recentProjects(15), sessions });
237
+ }
238
+
239
+ if (method === "POST" && path === "/api/log") {
240
+ const { message } = await readJSON(req);
241
+ log(`app: ${String(message || "").slice(0, 300)}`);
242
+ return send(res, 200, { ok: true });
243
+ }
244
+
245
+ if (method === "POST" && path === "/api/presence") {
246
+ const now = Date.now();
247
+ if (lastPresenceAt && now - lastPresenceAt > 75_000 && now - lastPresenceAt < 30 * 60_000) {
248
+ log(`app: no heartbeat for ${Math.round((now - lastPresenceAt) / 1000)}s (the app was suspended or offline)`);
249
+ }
250
+ lastPresenceAt = now;
251
+ notifier.markForeground();
252
+ return send(res, 200, { ok: true });
253
+ }
254
+
255
+ if (method === "POST" && path === "/api/stt") {
256
+ const pcm = await readBody(req, 16000 * 2 * 120); // two minutes max
257
+ const result = await transcriber.transcribe(pcm, vocabulary());
258
+ // Partials arrive about once a second while a hold is in progress; only log finals.
259
+ if (url.searchParams.get("partial") !== "1") log(`stt ${(pcm.length / 32000).toFixed(1)}s -> "${result.text}"${result.ms ? ` (${result.ms}ms)` : ""}`);
260
+ return send(res, 200, result);
261
+ }
262
+
263
+ if (method === "POST" && path === "/api/sessions") {
264
+ const body = await readJSON(req);
265
+ const { target } = await launch(body);
266
+ const session = await waitForSessionOnPane(target);
267
+ if (!session) throw new HttpError(504, `Claude Code started but did not report in; is the hook installed? (${BRAND.name} install)`);
268
+ if (body.prompt) {
269
+ await paneCtl.waitForInput(session.pane, 20000);
270
+ await paneCtl.sendPrompt(session.pane, body.prompt);
271
+ }
272
+ return send(res, 200, { session: session.summaryJSON() });
273
+ }
274
+
275
+ const m = /^\/api\/sessions\/([0-9a-f-]{36})(?:\/([a-z]+))?$/.exec(path);
276
+ if (m) {
277
+ const s = sessionOr404(m[1]);
278
+ const action = m[2];
279
+ if (method === "GET" && !action) {
280
+ const limit = Math.min(Number(url.searchParams.get("items") || 150), 300);
281
+ return send(res, 200, { seq, session: s.summaryJSON(), items: s.items.slice(-limit) });
282
+ }
283
+ if (method === "GET" && action === "models") return send(res, 200, { models: CLAUDE_MODELS });
284
+ if (method === "POST" && action === "prompt") {
285
+ const { text } = await readJSON(req);
286
+ if (!text || typeof text !== "string") throw new HttpError(400, "text required");
287
+ await refuseIfDialog(s);
288
+ await paneCtl.sendPrompt(controllable(s), text);
289
+ if (!(await confirmDelivered(s, text))) {
290
+ log(`✗ ${s.project}: typed but not seen in the terminal or transcript: ${text.slice(0, 80)}`);
291
+ throw new HttpError(502, "Typed it, but Claude didn't show it. Is that terminal in another mode?");
292
+ }
293
+ log(`→ ${s.project}: ${text}`);
294
+ return send(res, 200, { ok: true });
295
+ }
296
+ if (method === "POST" && action === "interrupt") {
297
+ await paneCtl.sendKey(controllable(s), "Escape");
298
+ return send(res, 200, { ok: true });
299
+ }
300
+ if (method === "POST" && action === "choose") {
301
+ const { index, kind } = await readJSON(req);
302
+ const chosen = await paneCtl.chooseOption(controllable(s), kind === "question" ? "question" : "permission", Number(index));
303
+ log(`→ ${s.project}: chose "${chosen}"`);
304
+ if (kind === "question" && s.waiting?.kind === "question") {
305
+ s.waiting.questionIndex = (s.waiting.questionIndex || 0) + 1;
306
+ if (s.waiting.questionIndex >= (s.waiting.questions?.length || 1)) s.waiting = null;
307
+ } else if (kind !== "question") {
308
+ s.waiting = null;
309
+ }
310
+ if (!s.waiting && s.state === "waiting") s.state = "working";
311
+ registry.changed(s);
312
+ return send(res, 200, { ok: true, chosen });
313
+ }
314
+ if (method === "POST" && action === "answer") {
315
+ const { text } = await readJSON(req);
316
+ await paneCtl.answerWithText(controllable(s), String(text || ""));
317
+ return send(res, 200, { ok: true });
318
+ }
319
+ if (method === "POST" && action === "screen") {
320
+ return send(res, 200, { dialog: await paneCtl.readDialogStable(controllable(s)) });
321
+ }
322
+ if (method === "POST" && action === "command") {
323
+ const { command } = await readJSON(req);
324
+ const allowed = /^\/(model (opus|sonnet|haiku|fable)(\[1m\])?|compact|clear|cost|context)$/;
325
+ if (!allowed.test(String(command))) throw new HttpError(400, "command not allowed");
326
+ await refuseIfDialog(s);
327
+ const model = /^\/model (\S+)$/.exec(command)?.[1];
328
+ if (model) {
329
+ const withWindow = !model.startsWith("haiku") && (/\[1m\]$/.test(model) || (s.context || 0) > 150_000) ? model.replace(/(\[1m\])?$/, "[1m]") : model;
330
+ await paneCtl.switchModel(controllable(s), withWindow, CLAUDE_SETTINGS);
331
+ log(`→ ${s.project}: /model ${withWindow} (default left unchanged)`);
332
+ return send(res, 200, { ok: true });
333
+ }
334
+ await paneCtl.sendPrompt(controllable(s), command);
335
+ log(`→ ${s.project}: ${command}`);
336
+ return send(res, 200, { ok: true });
337
+ }
338
+ }
339
+ throw new HttpError(404, "not found");
340
+ }
341
+
342
+ function serveStatic(req, res, url) {
343
+ if (!existsSync(APP_DIST)) return send(res, 404, "App not built. Run: npm run build:app");
344
+ let rel = decodeURIComponent(url.pathname);
345
+ if (rel === "/" || !extname(rel)) rel = "/index.html";
346
+ const file = normalize(join(APP_DIST, rel));
347
+ if (!file.startsWith(APP_DIST) || !existsSync(file)) return send(res, 404, "not found");
348
+ res.writeHead(200, { "Content-Type": MIME[extname(file)] || "application/octet-stream", "Cache-Control": rel === "/index.html" ? "no-store" : "public, max-age=3600" });
349
+ res.end(readFileSync(file));
350
+ }
351
+
352
+ function handler(req, res) {
353
+ const url = new URL(req.url, "http://hub");
354
+ res.setHeader("Access-Control-Allow-Origin", "*");
355
+ res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Last-Event-ID");
356
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
357
+ if (req.method === "OPTIONS") return res.writeHead(204).end();
358
+ const done = url.pathname.startsWith("/api/") ? api(req, res, url) : Promise.resolve(serveStatic(req, res, url));
359
+ done.catch((err) => {
360
+ const status = err.status || 500;
361
+ if (status >= 500) log(`error ${req.method} ${url.pathname}: ${err.stack || err.message}`);
362
+ if (!res.headersSent) send(res, status, { error: err.message });
363
+ else res.end();
364
+ });
365
+ }
366
+
367
+ // ---------- hook intake (127.0.0.1 only) ----------
368
+ const pidLookups = new Set(); // sessions whose Claude pid is being resolved
369
+ async function enrichFromHook(session, { shellPid }) {
370
+ if (!session) return;
371
+ // Claude Code's pid, for sessions outside a host: PowerShell's parent, while it still runs.
372
+ if (!session.pane && !session.pid && shellPid > 1 && !pidLookups.has(session.id)) {
373
+ pidLookups.add(session.id);
374
+ const pid = await parentPid(shellPid).catch(() => null);
375
+ pidLookups.delete(session.id);
376
+ if (pid && !session.pid) {
377
+ session.pid = pid;
378
+ registry.scheduleSave();
379
+ }
380
+ }
381
+ // The host's name for the pane, for sessions started at the desk.
382
+ if (session.pane && !session.paneName) {
383
+ const info = await paneCtl.paneInfo(session.pane);
384
+ if (info?.name && !session.paneName) {
385
+ session.paneName = info.name;
386
+ registry.changed(session);
387
+ }
388
+ }
389
+ }
390
+
391
+ const hookServer = createServer(async (req, res) => {
392
+ if (req.method !== "POST" || req.url !== "/hook") return res.writeHead(404).end();
393
+ try {
394
+ const raw = await readBody(req, 4 * 1024 * 1024);
395
+ const payload = JSON.parse(raw.toString("utf8"));
396
+ const shellPid = Number(req.headers["x-shell-pid"]) || 0;
397
+ const session = registry.handleHook(payload, { host: req.headers["x-host"], pane: req.headers["x-pane"] });
398
+ // The hook's PowerShell is alive only until we answer, and it is the way to
399
+ // Claude's pid for a view-only session, so look that up before replying.
400
+ if (session && !session.pane && !session.pid && shellPid) await enrichFromHook(session, { shellPid });
401
+ res.writeHead(204).end();
402
+ enrichFromHook(session, { shellPid }).catch(() => {});
403
+ } catch {
404
+ res.writeHead(400).end();
405
+ }
406
+ });
407
+ hookServer.listen(cfg.hookPort, "127.0.0.1");
408
+
409
+ const apiServers = [];
410
+ // Loopback only by default: the phone reaches the hub through `tailscale serve`
411
+ // (HTTPS on the machine's *.ts.net name). The raw Tailscale IP is opt-in.
412
+ const hosts = ["127.0.0.1"];
413
+ const ts = cfg.bindTailscaleIP ? tailscaleAddress() : null;
414
+ if (ts) hosts.push(ts);
415
+ for (const host of hosts) {
416
+ const srv = createServer(handler);
417
+ srv.listen(cfg.port, host);
418
+ srv.on("error", (err) => log(`could not listen on ${host}:${cfg.port}: ${err.message}`));
419
+ apiServers.push(srv);
420
+ }
421
+
422
+ log(`hub on ${hosts.map((h) => `http://${h}:${cfg.port}`).join(" and ")}; hooks on 127.0.0.1:${cfg.hookPort}; host pipe ${cfg.hostPipe}`);
423
+ if (!transcriber.available) log(`voice: speech model missing, run \`${BRAND.name} setup-voice\``);
424
+ else transcriber.ensure().then(() => log("voice: whisper ready")).catch((err) => log(`voice: ${err.message}`));
425
+ if (notifier.enabled) log(`phone push: ntfy topic set`);
426
+ if (awake) log("holding the PC awake while on AC power");
427
+
428
+ return {
429
+ cfg,
430
+ registry,
431
+ close() {
432
+ clearInterval(sweepTimer);
433
+ awake?.kill();
434
+ for (const res of clients) res.end();
435
+ hookServer.close();
436
+ for (const s of apiServers) s.close();
437
+ transcriber.stop();
438
+ for (const s of registry.sessions.values()) s.tail?.close();
439
+ },
440
+ };
441
+ }
@@ -0,0 +1,181 @@
1
+ // The hub as a background service on Windows: a Task Scheduler task that starts at
2
+ // logon, runs hidden, and is restarted when it fails. Also the file logger the hub
3
+ // uses in that mode, since a hidden process has nowhere else to write.
4
+ import { execFileSync, spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, renameSync, statSync, appendFileSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { BRAND } from "./brand.mjs";
8
+
9
+ const SYSTEM32 = join(process.env.SystemRoot || "C:\\Windows", "System32");
10
+ const SCHTASKS = join(SYSTEM32, "schtasks.exe");
11
+ const WSCRIPT = join(SYSTEM32, "wscript.exe");
12
+ const POWERSHELL = join(SYSTEM32, "WindowsPowerShell", "v1.0", "powershell.exe");
13
+ export const TASK_NAME = BRAND.serviceLabel;
14
+ const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
15
+
16
+ const xmlEscape = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
17
+ const vbsQuote = (s) => `""${String(s).replace(/"/g, '""')}""`; // a quoted argument inside a VBS string literal
18
+
19
+ /** DOMAIN\user for the signed-in user, as Task Scheduler wants it. */
20
+ export function currentUser() {
21
+ const domain = process.env.USERDOMAIN || process.env.COMPUTERNAME || ".";
22
+ return `${domain}\\${process.env.USERNAME || "user"}`;
23
+ }
24
+
25
+ /**
26
+ * A console program started by a logon task gets a console window. wscript.exe is
27
+ * a GUI program, so a three-line script that starts the hub hidden and waits for
28
+ * it, passing its exit code on, keeps Task Scheduler in charge without a window.
29
+ */
30
+ export function hubLauncherScript({ nodePath, cliPath }) {
31
+ return `Set sh = CreateObject("WScript.Shell")\r\nWScript.Quit sh.Run("${vbsQuote(nodePath)} ${vbsQuote(cliPath)} hub --service", 0, True)\r\n`;
32
+ }
33
+
34
+ /** Same trick for the session host, without waiting: the host outlives its starter. */
35
+ export function hostLauncherScript({ nodePath, hostPath, pipe, logFile }) {
36
+ return `Set sh = CreateObject("WScript.Shell")\r\nsh.Run "${vbsQuote(nodePath)} ${vbsQuote(hostPath)} --pipe ${vbsQuote(pipe)} --log ${vbsQuote(logFile)}", 0, False\r\n`;
37
+ }
38
+
39
+ export function taskXml({ launcher, user }) {
40
+ return `<?xml version="1.0" encoding="UTF-16"?>
41
+ <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
42
+ <RegistrationInfo>
43
+ <Description>${xmlEscape(BRAND.displayName)} hub: follows Claude Code sessions for the glasses. Managed by \`${xmlEscape(BRAND.name)} service\`.</Description>
44
+ <URI>\\${xmlEscape(TASK_NAME)}</URI>
45
+ </RegistrationInfo>
46
+ <Triggers>
47
+ <LogonTrigger>
48
+ <Enabled>true</Enabled>
49
+ <UserId>${xmlEscape(user)}</UserId>
50
+ </LogonTrigger>
51
+ </Triggers>
52
+ <Principals>
53
+ <Principal id="Author">
54
+ <UserId>${xmlEscape(user)}</UserId>
55
+ <LogonType>InteractiveToken</LogonType>
56
+ <RunLevel>LeastPrivilege</RunLevel>
57
+ </Principal>
58
+ </Principals>
59
+ <Settings>
60
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
61
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
62
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
63
+ <AllowHardTerminate>true</AllowHardTerminate>
64
+ <StartWhenAvailable>true</StartWhenAvailable>
65
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
66
+ <IdleSettings>
67
+ <StopOnIdleEnd>false</StopOnIdleEnd>
68
+ <RestartOnIdle>false</RestartOnIdle>
69
+ </IdleSettings>
70
+ <AllowStartOnDemand>true</AllowStartOnDemand>
71
+ <Enabled>true</Enabled>
72
+ <Hidden>false</Hidden>
73
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
74
+ <DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
75
+ <UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
76
+ <WakeToRun>false</WakeToRun>
77
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
78
+ <Priority>7</Priority>
79
+ <RestartOnFailure>
80
+ <Interval>PT1M</Interval>
81
+ <Count>999</Count>
82
+ </RestartOnFailure>
83
+ </Settings>
84
+ <Actions Context="Author">
85
+ <Exec>
86
+ <Command>${xmlEscape(WSCRIPT)}</Command>
87
+ <Arguments>"${xmlEscape(launcher)}"</Arguments>
88
+ </Exec>
89
+ </Actions>
90
+ </Task>
91
+ `;
92
+ }
93
+
94
+ function schtasks(args) {
95
+ return spawnSync(SCHTASKS, args, { encoding: "utf8", windowsHide: true });
96
+ }
97
+
98
+ /**
99
+ * Register (or replace) the task and start it now.
100
+ * @returns {{launcher: string, xml: string}}
101
+ */
102
+ export function installService({ nodePath, cliPath, dataDir }) {
103
+ mkdirSync(dataDir, { recursive: true });
104
+ const launcher = join(dataDir, "hub-launcher.vbs");
105
+ writeFileSync(launcher, hubLauncherScript({ nodePath, cliPath }));
106
+ const xmlPath = join(dataDir, "hub-task.xml");
107
+ const xml = taskXml({ launcher, user: currentUser() });
108
+ // schtasks reads the XML in the encoding it declares; UTF-16 LE with a BOM is the safe form.
109
+ writeFileSync(xmlPath, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(xml, "utf16le")]));
110
+ stopService({ quiet: true });
111
+ const r = schtasks(["/Create", "/TN", TASK_NAME, "/XML", xmlPath, "/F"]);
112
+ if (r.status !== 0) throw new Error(`schtasks /Create failed: ${(r.stderr || r.stdout || "").trim()}`);
113
+ const run = schtasks(["/Run", "/TN", TASK_NAME]);
114
+ if (run.status !== 0) throw new Error(`schtasks /Run failed: ${(run.stderr || run.stdout || "").trim()}`);
115
+ return { launcher, xml: xmlPath };
116
+ }
117
+
118
+ /** End the task (so Task Scheduler doesn't restart it) and stop the hub process it started. */
119
+ export function stopService({ quiet = false } = {}) {
120
+ const ended = schtasks(["/End", "/TN", TASK_NAME]);
121
+ const killed = killHubProcesses();
122
+ if (!quiet && ended.status !== 0 && !killed) return false;
123
+ return true;
124
+ }
125
+
126
+ export function startService() {
127
+ const r = schtasks(["/Run", "/TN", TASK_NAME]);
128
+ if (r.status !== 0) throw new Error(`schtasks /Run failed: ${(r.stderr || r.stdout || "").trim()}`);
129
+ }
130
+
131
+ export function uninstallService() {
132
+ stopService({ quiet: true });
133
+ const r = schtasks(["/Delete", "/TN", TASK_NAME, "/F"]);
134
+ return r.status === 0;
135
+ }
136
+
137
+ /**
138
+ * Hub processes started by the service (`hub --service` on their command line).
139
+ * Ending the task stops its launcher; the hub itself is a separate process.
140
+ */
141
+ function killHubProcesses() {
142
+ const script = `Get-CimInstance Win32_Process -Filter "Name='node.exe'" | Where-Object { $_.CommandLine -like '*${BRAND.name}* hub --service*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force; $_.ProcessId }`;
143
+ const r = spawnSync(POWERSHELL, ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", windowsHide: true, timeout: 15000 });
144
+ return (r.stdout || "").trim().length > 0;
145
+ }
146
+
147
+ /**
148
+ * @returns {{installed: boolean, state?: string, lastRun?: string, lastResult?: number, nextRun?: string}}
149
+ */
150
+ export function serviceStatus() {
151
+ const script = `$t = Get-ScheduledTask -TaskName '${TASK_NAME.replace(/'/g, "''")}' -ErrorAction SilentlyContinue; if (-not $t) { '{"installed":false}' } else { $i = $t | Get-ScheduledTaskInfo; @{ installed = $true; state = [string]$t.State; lastRun = [string]$i.LastRunTime; lastResult = $i.LastTaskResult; nextRun = [string]$i.NextRunTime } | ConvertTo-Json -Compress }`;
152
+ try {
153
+ const out = execFileSync(POWERSHELL, ["-NoProfile", "-NonInteractive", "-Command", script], { encoding: "utf8", windowsHide: true, timeout: 15000 });
154
+ return JSON.parse(out.trim() || '{"installed":false}');
155
+ } catch {
156
+ return { installed: false };
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Send console output to a file, rotating once at `LOG_ROTATE_BYTES`. For the
162
+ * hidden service process; a foreground hub keeps writing to the terminal.
163
+ */
164
+ export function installFileLogger(file) {
165
+ mkdirSync(dirname(file), { recursive: true });
166
+ const write = (level, args) => {
167
+ const line = `${new Date().toISOString()} ${level} ${args.map((a) => (typeof a === "string" ? a : a instanceof Error ? a.stack || a.message : JSON.stringify(a))).join(" ")}\n`;
168
+ try {
169
+ if (existsSync(file) && statSync(file).size > LOG_ROTATE_BYTES) renameSync(file, `${file}.1`);
170
+ appendFileSync(file, line);
171
+ } catch {
172
+ /* nowhere to log */
173
+ }
174
+ };
175
+ console.log = (...a) => write("info", a);
176
+ console.warn = (...a) => write("warn", a);
177
+ console.error = (...a) => write("error", a);
178
+ process.on("uncaughtException", (err) => write("fatal", [err]));
179
+ process.on("unhandledRejection", (err) => write("fatal", [err instanceof Error ? err : new Error(String(err))]));
180
+ return file;
181
+ }