@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/awake.mjs ADDED
@@ -0,0 +1,45 @@
1
+ // Keep the PC awake while the hub runs, so the glasses never see a sleeping hub.
2
+ // Windows' SetThreadExecutionState holds the system (not the display) awake for as
3
+ // long as the calling thread keeps asking, so a small PowerShell helper asks every
4
+ // half minute, only while on AC power, and leaves when the hub is gone.
5
+ import { spawn } from "node:child_process";
6
+ import { join } from "node:path";
7
+
8
+ const POWERSHELL = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
9
+
10
+ /** The helper's script. `hubPid` is who it works for; it exits when that process ends. */
11
+ export function keepAwakeScript(hubPid) {
12
+ return `
13
+ Add-Type -Namespace Glance -Name Power -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint esFlags);'
14
+ Add-Type -AssemblyName System.Windows.Forms
15
+ $continuous = [uint32]0x80000000
16
+ $systemRequired = [uint32]0x00000001
17
+ $held = $false
18
+ while ($true) {
19
+ if (-not (Get-Process -Id ${Number(hubPid)} -ErrorAction SilentlyContinue)) { break }
20
+ $onAc = [System.Windows.Forms.SystemInformation]::PowerStatus.PowerLineStatus -ne 'Offline'
21
+ if ($onAc) { [void][Glance.Power]::SetThreadExecutionState($continuous -bor $systemRequired); $held = $true }
22
+ elseif ($held) { [void][Glance.Power]::SetThreadExecutionState($continuous); $held = $false }
23
+ Start-Sleep -Seconds 30
24
+ }
25
+ [void][Glance.Power]::SetThreadExecutionState($continuous)
26
+ `;
27
+ }
28
+
29
+ /**
30
+ * Start the helper. Returns something with kill(), or null off Windows.
31
+ */
32
+ export function startKeepAwake({ hubPid = process.pid, log = () => {} } = {}) {
33
+ if (process.platform !== "win32") return null;
34
+ const child = spawn(POWERSHELL, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", keepAwakeScript(hubPid)], {
35
+ stdio: ["ignore", "ignore", "pipe"],
36
+ windowsHide: true,
37
+ });
38
+ let stderr = "";
39
+ child.stderr.on("data", (d) => (stderr += d.toString()));
40
+ child.on("exit", (code) => {
41
+ if (code) log(`keep-awake helper exited (${code}): ${stderr.trim().split("\n")[0] || ""}`);
42
+ });
43
+ child.on("error", (err) => log(`could not start the keep-awake helper: ${err.message}`));
44
+ return child;
45
+ }
package/hub/brand.mjs ADDED
@@ -0,0 +1,17 @@
1
+ // Every user-visible and on-disk name lives here, so a rename is a one-file change.
2
+ export const BRAND = {
3
+ name: "codeaside", // CLI command, npm package, config and data folder names
4
+ displayName: "CodeAside", // Even Hub listing and glasses header (20 chars max)
5
+ tagline: "Claude Code sessions on your Even Realities G2 glasses, from Windows",
6
+ serviceLabel: "CodeAside Hub", // Task Scheduler task name
7
+ envPrefix: "CODEASIDE", // CODEASIDE_CONFIG_DIR, CODEASIDE_HOOK_PORT, ...
8
+ // Earlier names this project used on disk, migrated on first run. Add the old
9
+ // values here when renaming, so existing installs carry over.
10
+ legacy: {
11
+ configDirs: [],
12
+ serviceLabels: [],
13
+ hookScripts: [],
14
+ },
15
+ };
16
+
17
+ export const env = (key) => process.env[`${BRAND.envPrefix}_${key}`];
package/hub/config.mjs ADDED
@@ -0,0 +1,129 @@
1
+ // Hub configuration and on-disk locations.
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { cpus, homedir, networkInterfaces } from "node:os";
5
+ import { join } from "node:path";
6
+ import { BRAND, env } from "./brand.mjs";
7
+ import { defaultPipe } from "../host/client.mjs";
8
+
9
+ const WIN = process.platform === "win32";
10
+ // Windows: config in Roaming AppData, big files (speech model, binaries, logs) in Local.
11
+ // Elsewhere (tests, CI): the XDG folders upstream uses.
12
+ const CONFIG_BASE = WIN ? process.env.APPDATA || join(homedir(), "AppData", "Roaming") : process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
13
+ const DATA_BASE = WIN ? process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local") : process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
14
+
15
+ export const CONFIG_DIR = env("CONFIG_DIR") || join(CONFIG_BASE, BRAND.name);
16
+ export const DATA_DIR = env("DATA_DIR") || join(DATA_BASE, BRAND.name);
17
+ export const LOG_DIR = join(DATA_DIR, "logs");
18
+ export const CONFIG_FILE = join(CONFIG_DIR, "config.json");
19
+ export const STATE_FILE = join(CONFIG_DIR, "sessions.json");
20
+ // Claude Code's own folder; CLAUDE_CONFIG_DIR moves it.
21
+ export const CLAUDE_DIR = process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
22
+ export const CLAUDE_SETTINGS = join(CLAUDE_DIR, "settings.json");
23
+ export const CLAUDE_PROJECTS_DIR = join(CLAUDE_DIR, "projects");
24
+
25
+ const DEFAULTS = {
26
+ port: 7717, // API + glasses app, 127.0.0.1 (reached from the phone through `tailscale serve`)
27
+ hookPort: 7718, // hook intake, 127.0.0.1 only, never exposed
28
+ whisperPort: 7719, // local whisper-server, 127.0.0.1 only
29
+ httpsPort: 7443, // tailscale serve HTTPS port on the machine's *.ts.net name
30
+ // Also listen on the raw Tailscale IP over plain HTTP. Only for development
31
+ // sideloads; store builds must use HTTPS through tailscale serve.
32
+ bindTailscaleIP: false,
33
+ // The session host's named pipe. One host per Windows user by default.
34
+ hostPipe: defaultPipe(),
35
+ whisperBin: WIN ? join(DATA_DIR, "whisper", "whisper-server.exe") : "whisper-server",
36
+ whisperModel: join(DATA_DIR, "models", "ggml-large-v3-turbo-q5_0.bin"),
37
+ // CPU threads for whisper-server: about the physical cores, capped so the PC stays usable.
38
+ whisperThreads: Math.max(2, Math.min(8, Math.floor(cpus().length / 2))),
39
+ // Words whisper should expect: project names get appended at runtime.
40
+ sttVocabulary: "Claude, Claude Code, Opus, Sonnet, Haiku, commit, deploy, npm, git",
41
+ // Optional phone push through ntfy (https://ntfy.sh). Off unless a topic is set.
42
+ ntfyTopic: "",
43
+ ntfyServer: "https://ntfy.sh",
44
+ // Extra arguments for sessions the glasses start (for example ["--model", "sonnet"]).
45
+ claudeArgs: [],
46
+ // Keep the machine awake while the hub runs, so the glasses can reach it. Later milestone.
47
+ preventSleep: true,
48
+ // The rest are for the glasses display, and only this fork's build of the glasses
49
+ // app reads them; upstream's build in Even Hub behaves as it always has.
50
+ // Hold a reply too long for the screen at its first line instead of showing its end.
51
+ replyFromStart: true,
52
+ // The text brightness while a session works, from 0 (dimmest) to 4 (full, which
53
+ // means no dimming).
54
+ workingBrightness: 0,
55
+ // Jump to a session's latest lines when a hold to talk starts in it.
56
+ latestOnTalk: true,
57
+ // Lines a tool call's description may take, 1 to 6. It is cut where the display
58
+ // runs out, measured in pixels.
59
+ toolLines: 2,
60
+ // Jump to a session's latest lines when a prompt is sent to it or a dialog in it
61
+ // is answered, whether from the glasses or at the desk.
62
+ latestOnPrompt: true,
63
+ // Show the next prompt Claude Code suggests in its input box, when it suggests
64
+ // one, under an idle session's latest lines. The hub reads it off the screen.
65
+ showSuggestions: true,
66
+ // Let a tap on a shown suggestion send it as the next prompt, once a second tap
67
+ // confirms it.
68
+ sendSuggestionOnTap: true,
69
+ };
70
+
71
+ /** Read the raw config file without generating tokens (used at import time). */
72
+ function readConfigFile() {
73
+ if (!existsSync(CONFIG_FILE)) return {};
74
+ try {
75
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
76
+ } catch {
77
+ return {};
78
+ }
79
+ }
80
+
81
+ export const HOST_PIPE = env("HOST_PIPE") || readConfigFile().hostPipe || DEFAULTS.hostPipe;
82
+
83
+ export function loadConfig() {
84
+ mkdirSync(CONFIG_DIR, { recursive: true });
85
+ let cfg = {};
86
+ if (existsSync(CONFIG_FILE)) {
87
+ try {
88
+ cfg = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
89
+ } catch (err) {
90
+ throw new Error(`could not parse ${CONFIG_FILE}: ${err.message}`);
91
+ }
92
+ }
93
+ let changed = false;
94
+ if (!cfg.token) {
95
+ cfg.token = randomBytes(24).toString("base64url");
96
+ changed = true;
97
+ }
98
+ const merged = { ...DEFAULTS, ...cfg };
99
+ if (changed) saveConfig(cfg);
100
+ return merged;
101
+ }
102
+
103
+ export function saveConfig(cfg) {
104
+ mkdirSync(CONFIG_DIR, { recursive: true });
105
+ writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n");
106
+ // The profile folders are already private to the user on Windows; elsewhere, make the file so.
107
+ if (!WIN) chmodSync(CONFIG_FILE, 0o600);
108
+ }
109
+
110
+ /** Update individual keys in the config file, keeping everything else. */
111
+ export function updateConfig(patch) {
112
+ const cfg = readConfigFile();
113
+ Object.assign(cfg, patch);
114
+ saveConfig(cfg);
115
+ return cfg;
116
+ }
117
+
118
+ /** The machine's Tailscale IPv4 address, if Tailscale is up. */
119
+ export function tailscaleAddress() {
120
+ for (const addrs of Object.values(networkInterfaces())) {
121
+ for (const a of addrs || []) {
122
+ if (a.family === "IPv4" && !a.internal && a.address.startsWith("100.")) {
123
+ const second = Number(a.address.split(".")[1]);
124
+ if (second >= 64 && second <= 127) return a.address; // CGNAT range Tailscale uses
125
+ }
126
+ }
127
+ }
128
+ return null;
129
+ }
package/hub/feed.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Readable one-line-per-event feed of all sessions, for the terminal.
2
+ export function color(s, code) {
3
+ return process.stdout.isTTY ? `\x1b[${code}m${s}\x1b[0m` : s;
4
+ }
5
+
6
+ export function printFeed(session, items) {
7
+ const tag = color(String(session.project).padEnd(14).slice(0, 14), 36);
8
+ for (const it of items) {
9
+ const first = it.text.split("\n").find((l) => l.trim()) || "";
10
+ const line = first.length > 110 ? first.slice(0, 109) + "…" : first;
11
+ if (it.kind === "user") console.log(`${tag} ${color("›", 32)} ${color(line, 1)}`);
12
+ else if (it.kind === "assistant") console.log(`${tag} ${line}`);
13
+ else if (it.kind === "tool") console.log(`${tag} ${color(`▷ ${it.tool} ${it.text}`, 2)}`);
14
+ else if (it.kind === "error") console.log(`${tag} ${color(`! ${line}`, 31)}`);
15
+ else console.log(`${tag} ${color(`◇ ${line}`, 35)}`);
16
+ }
17
+ }
18
+
19
+ export function printState(session, previous) {
20
+ if (!previous || previous.state === session.state) return;
21
+ const tag = color(String(session.project).padEnd(14).slice(0, 14), 36);
22
+ if (session.state === "waiting") {
23
+ const what = session.waiting?.kind === "question" ? "has a question" : `needs approval: ${session.waiting?.detail || ""}`;
24
+ console.log(`${tag} ${color(`◆ ${what}`, 33)}`);
25
+ } else if (session.state === "idle" && previous.state !== "starting") {
26
+ console.log(`${tag} ${color("○ done", 2)}`);
27
+ } else if (session.state === "ended") {
28
+ console.log(`${tag} ${color("× ended", 2)}`);
29
+ }
30
+ }
package/hub/notify.mjs ADDED
@@ -0,0 +1,39 @@
1
+ // Optional phone push via ntfy. The Even app mirrors iPhone notifications to the
2
+ // glasses, which is the only way to reach you while another glasses app is open.
3
+ export class Notifier {
4
+ constructor({ server, topic, log = () => {} }) {
5
+ this.server = (server || "https://ntfy.sh").replace(/\/$/, "");
6
+ this.topic = topic;
7
+ this.log = log;
8
+ this.glassesForegroundUntil = 0;
9
+ this.lastSent = new Map();
10
+ }
11
+
12
+ get enabled() {
13
+ return !!this.topic;
14
+ }
15
+
16
+ /** The glasses app pings while it is open; no pushes while you are looking at it. */
17
+ markForeground(ms = 45_000) {
18
+ this.glassesForegroundUntil = Date.now() + ms;
19
+ }
20
+
21
+ async send(key, title, message) {
22
+ if (!this.enabled || Date.now() < this.glassesForegroundUntil) return false;
23
+ const last = this.lastSent.get(key) || 0;
24
+ if (Date.now() - last < 20_000) return false; // one push per session event burst
25
+ this.lastSent.set(key, Date.now());
26
+ try {
27
+ const res = await fetch(`${this.server}/${encodeURIComponent(this.topic)}`, {
28
+ method: "POST",
29
+ headers: { Title: title, Tags: "robot" },
30
+ body: message.slice(0, 180),
31
+ signal: AbortSignal.timeout(5000),
32
+ });
33
+ return res.ok;
34
+ } catch (err) {
35
+ this.log(`ntfy failed: ${err.message}`);
36
+ return false;
37
+ }
38
+ }
39
+ }
package/hub/pane.mjs ADDED
@@ -0,0 +1,326 @@
1
+ // Session control through the host: find panes, type into Claude Code, read the
2
+ // screen, launch sessions. The host replaces tmux on Windows; see host/host.mjs.
3
+ import { basename } from "node:path";
4
+ import { join } from "node:path";
5
+ import { DATA_DIR, HOST_PIPE } from "./config.mjs";
6
+ import { HostClient, defaultPipe, ensureHost, resolveClaude, styledScreen } from "../host/client.mjs";
7
+
8
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
9
+ const HOST_LOG = join(DATA_DIR, "logs", "host.log");
10
+
11
+ /** One control connection per host pipe, reused across calls. */
12
+ const clients = new Map();
13
+ function clientFor(pipe = HOST_PIPE) {
14
+ let c = clients.get(pipe);
15
+ if (!c) {
16
+ c = new HostClient(pipe);
17
+ clients.set(pipe, c);
18
+ }
19
+ return c;
20
+ }
21
+
22
+ /**
23
+ * A pane is identified by its host's pipe plus the host's session id, the way a
24
+ * tmux pane is identified by socket path plus pane id.
25
+ * @typedef {{host: string, pane: string}} Target
26
+ */
27
+ export function paneKey(target) {
28
+ if (!target?.pane || !target?.host) return null;
29
+ return `${target.host.toLowerCase()}|${target.pane}`;
30
+ }
31
+
32
+ /** Target for the pane a hook reported, or null when it didn't run in a host. */
33
+ export function targetFromHook({ host, pane }) {
34
+ if (!host || !pane) return null;
35
+ return { host, pane };
36
+ }
37
+
38
+ async function host(target, op, params = {}, opts) {
39
+ return clientFor(target.host).request(op, { session: target.pane, ...params }, opts);
40
+ }
41
+
42
+ /** True when the session still exists in its host. A host that's gone means no. */
43
+ export async function paneAlive(target) {
44
+ try {
45
+ return (await host(target, "alive")).alive === true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ /** Name and process id the host has for a pane, if it still has it. */
52
+ export async function paneInfo(target) {
53
+ try {
54
+ const r = await host(target, "alive");
55
+ return r.alive ? { name: r.name, pid: r.pid } : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ export async function capture(target, lines = 60) {
62
+ const { text } = await host(target, "screen", { lines });
63
+ return text.replace(/\s+$/gm, "");
64
+ }
65
+
66
+ /**
67
+ * What is Claude Code showing at the bottom of the pane?
68
+ * @returns {{kind: "permission"|"question"|"trust"|"input"|"unknown", options: string[]}}
69
+ */
70
+ export function readDialog(screen) {
71
+ const tail = screen.split("\n").filter((l) => l.trim()).slice(-30);
72
+ const joined = tail.join("\n");
73
+ const options = [];
74
+ for (const l of tail) {
75
+ const m = /^\s*(?:❯\s*)?(\d+)\.\s+(.+?)\s*$/.exec(l);
76
+ if (m) options[Number(m[1]) - 1] = m[2];
77
+ }
78
+ // The UI redraws constantly, and a read taken mid-redraw can miss a line. A
79
+ // numbered list with a hole is such a read: compacting it would shift every
80
+ // index after the hole, so the dialog isn't ready rather than wrong.
81
+ const complete = options.length > 0 && Array.from(options).every(Boolean); // from(): holes become undefined, every() alone skips them
82
+ const clean = complete ? options : [];
83
+ if (/Yes, I trust this folder/.test(joined)) return { kind: "trust", options: clean };
84
+ const asked = /^\s*(Do you want to [^?]*\?)/im.exec(joined)?.[1];
85
+ if (asked && /Do you want to (proceed|make this edit|create|allow)/i.test(asked) && clean.length) return { kind: "permission", options: clean, prompt: asked };
86
+ if (/Enter to select/.test(joined) && clean.length) return { kind: "question", options: clean };
87
+ if (!complete && options.length) return { kind: "unknown", options: [] };
88
+ if (/^\s*❯\s*/m.test(tail.slice(-4).join("\n"))) return { kind: "input", options: [] };
89
+ return { kind: "unknown", options: clean };
90
+ }
91
+
92
+ /** Whether text is dim after an SGR sequence with these parameters. */
93
+ function dimAfter(params, dim) {
94
+ const p = params.split(";");
95
+ for (let i = 0; i < p.length; i++) {
96
+ if (p[i] === "" || p[i] === "0" || p[i] === "22") dim = false;
97
+ else if (p[i] === "2") dim = true;
98
+ else if (p[i] === "38" || p[i] === "48") i += p[i + 1] === "2" ? 4 : p[i + 1] === "5" ? 2 : 0; // a colour's own numbers
99
+ }
100
+ return dim;
101
+ }
102
+
103
+ /**
104
+ * The prompt Claude Code suggests, read from a styled screen (see styledScreen):
105
+ * dim text alone in the input box. Text the user typed isn't dim, so a box with
106
+ * any of it holds no suggestion.
107
+ */
108
+ export function suggestionIn(styled) {
109
+ // What an attaching client is sent ends with terminal modes and then live output.
110
+ const cells = String(styled || "").split("\x1b[?")[0];
111
+ // The box sits under a full-width rule, and the two arrive as one wrapped row.
112
+ const boxes = [...cells.matchAll(/─{20,}(?:\x1b\[[0-9;]*m)*❯([\s\S]*?)(?=(?:\x1b\[[0-9;]*m)*─{20,}|$)/g)];
113
+ const input = boxes.at(-1)?.[1];
114
+ if (!input) return null;
115
+ let dim = false;
116
+ let text = "";
117
+ for (const m of input.matchAll(/\x1b\[([0-9;]*)([A-Za-z])|([^\x1b])/g)) {
118
+ if (m[3] !== undefined) {
119
+ if (/\s/.test(m[3])) text += " ";
120
+ else if (dim) text += m[3];
121
+ else return null; // typed text
122
+ } else if (m[2] === "m") dim = dimAfter(m[1], dim);
123
+ else if (m[2] === "C") text += " ".repeat(Number(m[1]) || 1); // cursor forward stands in for spaces
124
+ }
125
+ text = text.replace(/\s+/g, " ").trim();
126
+ // A new session's box holds an example prompt in the same style.
127
+ if (!text || /^Try "/.test(text)) return null;
128
+ return text;
129
+ }
130
+
131
+ /** The prompt Claude Code is suggesting in this pane right now, or null. */
132
+ export async function readSuggestion(target) {
133
+ return suggestionIn(await styledScreen(target.host, target.pane));
134
+ }
135
+
136
+ /**
137
+ * Read the dialog until two consecutive reads agree and neither is a mid-redraw
138
+ * miss, so a glasses tap lands on the option the glasses showed.
139
+ */
140
+ export async function readDialogStable(target, { lines = 40, attempts = 6, gapMs = 70 } = {}) {
141
+ let previous = null;
142
+ let last = null;
143
+ for (let i = 0; i < attempts; i++) {
144
+ last = readDialog(await capture(target, lines));
145
+ const key = JSON.stringify(last);
146
+ if (last.kind !== "unknown" && key === previous) return last;
147
+ previous = key;
148
+ await sleep(gapMs);
149
+ }
150
+ return last;
151
+ }
152
+
153
+ /** Type a prompt into Claude Code's input box and submit it. */
154
+ export async function sendPrompt(target, text) {
155
+ const flat = String(text).replace(/\r?\n+/g, " ").trim();
156
+ if (!flat) return;
157
+ await host(target, "write", { data: flat });
158
+ await sleep(120); // let the TUI absorb a paste-sized burst before submitting
159
+ await host(target, "key", { key: "Enter" });
160
+ }
161
+
162
+ const KEY_WHITELIST = new Set(["Escape", "Enter", "Up", "Down", "MenuUp", "MenuDown", "Tab", "BTab", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
163
+
164
+ export async function sendKey(target, key) {
165
+ if (!KEY_WHITELIST.has(key)) throw new Error(`key not allowed: ${key}`);
166
+ await host(target, "key", { key });
167
+ }
168
+
169
+ /**
170
+ * Press an option number only if the expected dialog is on screen, so a digit
171
+ * never lands in the prompt box by accident.
172
+ */
173
+ export async function chooseOption(target, expectedKind, index) {
174
+ const dialog = await readDialogStable(target);
175
+ if (dialog.kind !== expectedKind) {
176
+ throw Object.assign(new Error(`no ${expectedKind} dialog on screen (saw ${dialog.kind})`), { status: 409 });
177
+ }
178
+ if (index < 0 || index >= dialog.options.length || index > 8) {
179
+ throw Object.assign(new Error(`option ${index + 1} not available`), { status: 400 });
180
+ }
181
+ await sendKey(target, String(index + 1));
182
+ return dialog.options[index];
183
+ }
184
+
185
+ /**
186
+ * Switch the session's model with /model, confirm the cache-reset dialog if it
187
+ * appears, and put the user's saved default back: /model also rewrites the
188
+ * default in settings.json, and a glasses switch should only change this session.
189
+ */
190
+ export async function switchModel(target, model, settingsPath) {
191
+ const { readFileSync, writeFileSync } = await import("node:fs");
192
+ const readModel = () => {
193
+ try {
194
+ return JSON.parse(readFileSync(settingsPath, "utf8")).model;
195
+ } catch {
196
+ return undefined;
197
+ }
198
+ };
199
+ const before = readModel();
200
+ await sendPrompt(target, `/model ${model}`);
201
+ const until = Date.now() + 4000;
202
+ let confirmed = false;
203
+ while (Date.now() < until) {
204
+ await sleep(300);
205
+ const screen = await capture(target, 30);
206
+ const m = /(\d+)\.\s+Yes, switch to/.exec(screen);
207
+ if (m && !confirmed) {
208
+ await sendKey(target, m[1]);
209
+ confirmed = true;
210
+ continue;
211
+ }
212
+ if (/Set model to/.test(screen.split("\n").slice(-12).join("\n"))) break;
213
+ }
214
+ await sleep(300);
215
+ const after = readModel();
216
+ if (after !== before) {
217
+ const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
218
+ if (before === undefined) delete settings.model;
219
+ else settings.model = before;
220
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
221
+ }
222
+ return { restoredDefault: after !== before ? before ?? null : null };
223
+ }
224
+
225
+ /** Answer a question with free text via its "Type something" option. */
226
+ export async function answerWithText(target, text) {
227
+ const dialog = await readDialogStable(target);
228
+ if (dialog.kind !== "question") throw Object.assign(new Error("no question on screen"), { status: 409 });
229
+ const idx = dialog.options.findIndex((o) => /^Type something/i.test(o));
230
+ if (idx < 0) throw Object.assign(new Error("question has no free-text option"), { status: 400 });
231
+ await sendKey(target, String(idx + 1));
232
+ await sleep(250);
233
+ await sendPrompt(target, text);
234
+ }
235
+
236
+ export function sessionNameFor(cwd, taken) {
237
+ const base = (basename(cwd || "") || "claude").replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 24) || "claude";
238
+ let name = base;
239
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
240
+ return name;
241
+ }
242
+
243
+ /** Sessions in our host, by name. */
244
+ export async function listOurSessions(pipe = HOST_PIPE) {
245
+ try {
246
+ const { sessions } = await clientFor(pipe).request("list");
247
+ return sessions;
248
+ } catch {
249
+ return []; // no host running
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Start Claude Code in a detached session on our host, starting the host if needed.
255
+ * @returns {Promise<{name: string, target: Target}>}
256
+ */
257
+ export async function launchClaude({ cwd, args = [], claudeBin = "claude", env = {}, pipe = HOST_PIPE }) {
258
+ const claude = resolveClaude(claudeBin);
259
+ if (!claude) throw Object.assign(new Error("Claude Code not found on PATH"), { status: 503 });
260
+ await ensureHost(pipe, { logFile: HOST_LOG, launcherDir: DATA_DIR });
261
+ const taken = new Set((await listOurSessions(pipe)).map((s) => s.name));
262
+ const name = sessionNameFor(cwd, taken);
263
+ const r = await clientFor(pipe).request("new", { name, cwd, cmd: claude.cmd, args: [...claude.args, ...args], env, cols: 200, rows: 50 });
264
+ return { name: r.name, target: { host: pipe, pane: r.id } };
265
+ }
266
+
267
+ /** Accept the folder-trust dialog if it appears within `waitMs`. */
268
+ export async function acceptTrustIfShown(target, waitMs = 8000) {
269
+ const until = Date.now() + waitMs;
270
+ while (Date.now() < until) {
271
+ let dialog;
272
+ try {
273
+ dialog = readDialog(await capture(target));
274
+ } catch {
275
+ return false;
276
+ }
277
+ if (dialog.kind === "trust") {
278
+ // The trust dialog is an unnumbered two-item menu with "No, exit" focused.
279
+ // Arrow keys don't move it through ConPTY; the vi key does (see KEYS). A key
280
+ // sent while the dialog is still mounting is dropped, so move, check that
281
+ // "Yes" has the focus, and only then confirm.
282
+ for (let attempt = 0; attempt < 4; attempt++) {
283
+ await sleep(attempt ? 400 : 600);
284
+ await sendKey(target, "MenuDown");
285
+ await sleep(400);
286
+ const focused = (await capture(target, 20)).split("\n").find((l) => /❯/.test(l)) || "";
287
+ if (/Yes, I trust/.test(focused)) {
288
+ await sendKey(target, "Enter");
289
+ return true;
290
+ }
291
+ }
292
+ return false; // leave it for the user rather than guess
293
+ }
294
+ if (dialog.kind === "input") return false;
295
+ await sleep(400);
296
+ }
297
+ return false;
298
+ }
299
+
300
+ /** Wait until Claude Code shows its input prompt. */
301
+ export async function waitForInput(target, waitMs = 20000) {
302
+ const until = Date.now() + waitMs;
303
+ while (Date.now() < until) {
304
+ try {
305
+ if (readDialog(await capture(target)).kind === "input") return true;
306
+ } catch {
307
+ /* pane not ready */
308
+ }
309
+ await sleep(400);
310
+ }
311
+ return false;
312
+ }
313
+
314
+ /** Whitespace-insensitive snippet used to confirm a prompt reached Claude Code. */
315
+ export function promptSnippet(text) {
316
+ return String(text).replace(/\s+/g, " ").trim().slice(0, 40);
317
+ }
318
+
319
+ export function screenHasSnippet(screen, snippet) {
320
+ if (!snippet) return true;
321
+ const flat = screen.replace(/\s+/g, " ");
322
+ // Wrapped lines add spaces at arbitrary points, so also compare with spaces removed.
323
+ return flat.includes(snippet) || flat.replace(/ /g, "").includes(snippet.replace(/ /g, ""));
324
+ }
325
+
326
+ export { defaultPipe };
package/hub/procs.mjs ADDED
@@ -0,0 +1,24 @@
1
+ // Process lookups Windows doesn't give Node directly.
2
+ import { execFile } from "node:child_process";
3
+
4
+ const POWERSHELL = process.env.SystemRoot ? `${process.env.SystemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe";
5
+
6
+ /**
7
+ * The parent of a process, or null. Used once per view-only session: the hook
8
+ * script runs under PowerShell, whose parent is Claude Code, and the hub wants
9
+ * Claude's pid to notice when it exits. About 400 ms, so never on a hot path.
10
+ */
11
+ export function parentPid(pid) {
12
+ if (!pid || process.platform !== "win32") return Promise.resolve(null);
13
+ return new Promise((resolve) => {
14
+ execFile(
15
+ POWERSHELL,
16
+ ["-NoProfile", "-NonInteractive", "-Command", `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").ParentProcessId`],
17
+ { encoding: "utf8", timeout: 5000, windowsHide: true },
18
+ (err, stdout) => {
19
+ const n = Number(String(stdout || "").trim());
20
+ resolve(!err && n > 0 ? n : null);
21
+ },
22
+ );
23
+ });
24
+ }