@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.
@@ -0,0 +1,318 @@
1
+ // Read Claude Code session transcripts (~/.claude/projects/<dir>/<id>.jsonl)
2
+ // and turn their entries into small display items for the glasses.
3
+ import { EventEmitter } from "node:events";
4
+ import { closeSync, openSync, readSync, statSync, watch } from "node:fs";
5
+ import { basename } from "node:path";
6
+
7
+ /**
8
+ * @typedef {{
9
+ * key: string, // stable id (entry uuid + block index)
10
+ * kind: "user"|"assistant"|"tool"|"error"|"notice",
11
+ * text: string,
12
+ * full?: string, // for kind "tool": the label before it was cut to a line, when longer
13
+ * tool?: string, // tool name for kind "tool"
14
+ * ts?: string,
15
+ * }} Item
16
+ */
17
+
18
+ const MAX_TEXT = 4000;
19
+
20
+ /** A label no display shows whole; the glasses app cuts it to the lines it has. */
21
+ const FULL_LABEL = 600;
22
+
23
+ /**
24
+ * A short description of a tool call. By default it is cut to about a line.
25
+ * With `full`, it is left long enough for a reader that fits it to its own display.
26
+ */
27
+ export function toolLabel(name, input = {}, { full = false } = {}) {
28
+ const base = (p) => (typeof p === "string" && p ? basename(p) : "");
29
+ const clip = (s, n = 60) => {
30
+ const t = String(s ?? "").replace(/\s+/g, " ").trim();
31
+ const max = full ? FULL_LABEL : n;
32
+ return t.length > max ? t.slice(0, max - 1) + "…" : t;
33
+ };
34
+ switch (name) {
35
+ case "Bash":
36
+ case "PowerShell":
37
+ return clip(input.description || input.command);
38
+ case "Read":
39
+ case "Edit":
40
+ case "Write":
41
+ case "NotebookEdit":
42
+ return base(input.file_path || input.notebook_path);
43
+ case "Grep":
44
+ return clip(input.pattern, 40);
45
+ case "Glob":
46
+ return clip(input.pattern, 40);
47
+ case "WebFetch":
48
+ try {
49
+ return new URL(input.url).host;
50
+ } catch {
51
+ return clip(input.url, 40);
52
+ }
53
+ case "WebSearch":
54
+ return clip(input.query, 50);
55
+ case "Agent":
56
+ case "Task":
57
+ return clip(input.description || input.prompt, 50);
58
+ case "Skill":
59
+ return clip(input.skill, 40);
60
+ case "TodoWrite":
61
+ return "update tasks";
62
+ case "AskUserQuestion":
63
+ return clip(input.questions?.[0]?.question, 60);
64
+ default:
65
+ if (name?.startsWith("mcp__")) return name.split("__").pop();
66
+ return clip(input.description || "", 50);
67
+ }
68
+ }
69
+
70
+ function friendlyToolName(name) {
71
+ if (name?.startsWith("mcp__")) return name.split("__")[1] || name;
72
+ return name;
73
+ }
74
+
75
+ function textOf(content) {
76
+ if (typeof content === "string") return content;
77
+ if (Array.isArray(content)) {
78
+ return content
79
+ .filter((b) => b && b.type === "text")
80
+ .map((b) => b.text)
81
+ .join("\n");
82
+ }
83
+ return "";
84
+ }
85
+
86
+ function clipText(s) {
87
+ return s.length > MAX_TEXT ? s.slice(0, MAX_TEXT) + "…" : s;
88
+ }
89
+
90
+ /** Parse the <task-notification> block Claude Code injects when background work ends. */
91
+ function taskNotice(s) {
92
+ const status = /<status>([^<]*)<\/status>/.exec(s)?.[1];
93
+ const summary = /<summary>([^<]*)<\/summary>/.exec(s)?.[1];
94
+ if (!summary && !status) return "Background task update";
95
+ return summary || `Background task ${status}`;
96
+ }
97
+
98
+ /**
99
+ * Convert one transcript entry into zero or more items.
100
+ * @returns {Item[]}
101
+ */
102
+ export function entryToItems(entry) {
103
+ if (!entry || entry.isSidechain) return [];
104
+ const uuid = entry.uuid || `${entry.type}-${entry.timestamp}`;
105
+ const ts = entry.timestamp;
106
+ const out = [];
107
+
108
+ if (entry.type === "user") {
109
+ if (entry.isMeta || entry.isCompactSummary) return [];
110
+ const content = entry.message?.content;
111
+ if (Array.isArray(content)) {
112
+ content.forEach((b, i) => {
113
+ if (b?.type === "tool_result" && b.is_error) {
114
+ const t = textOf(b.content).split("\n").find((l) => l.trim()) || "tool failed";
115
+ out.push({ key: `${uuid}:${i}`, kind: "error", text: clipText(t.trim()), ts });
116
+ }
117
+ });
118
+ }
119
+ const text = textOf(content).trim();
120
+ if (!text) return out;
121
+ if (text.startsWith("<task-notification>")) {
122
+ out.push({ key: uuid, kind: "notice", text: taskNotice(text), ts });
123
+ } else if (text.startsWith("<command-name>")) {
124
+ const cmd = /<command-name>([^<]*)<\/command-name>/.exec(text)?.[1];
125
+ const args = /<command-args>([^<]*)<\/command-args>/.exec(text)?.[1]?.trim();
126
+ if (cmd) out.push({ key: uuid, kind: "notice", text: [cmd, args].filter(Boolean).join(" "), ts });
127
+ } else if (text.startsWith("<local-command-stdout>")) {
128
+ const s = /<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/.exec(text)?.[1]?.trim();
129
+ if (s) out.push({ key: uuid, kind: "notice", text: clipText(s), ts });
130
+ } else if (/^\[Request interrupted by user/.test(text)) {
131
+ out.push({ key: uuid, kind: "notice", text: "Interrupted", ts });
132
+ } else if (text.startsWith("<")) {
133
+ // system-reminder, local-command-caveat, and other injected context
134
+ } else {
135
+ out.push({ key: uuid, kind: "user", text: clipText(text.replace(/\[Image #\d+\]\s*/g, "[image] ")), ts });
136
+ }
137
+ return out;
138
+ }
139
+
140
+ if (entry.type === "assistant") {
141
+ const msg = entry.message || {};
142
+ const synthetic = msg.model === "<synthetic>";
143
+ (msg.content || []).forEach((b, i) => {
144
+ if (b?.type === "text" && b.text?.trim()) {
145
+ const t = b.text.trim();
146
+ if (synthetic) {
147
+ if (t === "No response requested.") return;
148
+ out.push({ key: `${uuid}:${i}`, kind: "error", text: clipText(t), ts });
149
+ } else {
150
+ out.push({ key: `${uuid}:${i}`, kind: "assistant", text: clipText(t), ts });
151
+ }
152
+ } else if (b?.type === "thinking" && b.thinking?.trim() && !synthetic) {
153
+ // Claude Code shows these as the progress messages between tool calls; most
154
+ // thinking blocks are empty in the transcript and the rest are short narration.
155
+ out.push({ key: `${uuid}:${i}`, kind: "assistant", text: clipText(b.thinking.trim()), ts });
156
+ } else if (b?.type === "tool_use") {
157
+ const text = toolLabel(b.name, b.input || {});
158
+ const full = toolLabel(b.name, b.input || {}, { full: true });
159
+ out.push({
160
+ key: `${uuid}:${i}`,
161
+ kind: "tool",
162
+ tool: friendlyToolName(b.name),
163
+ text,
164
+ ...(full !== text ? { full } : {}),
165
+ ts,
166
+ });
167
+ }
168
+ });
169
+ return out;
170
+ }
171
+
172
+ if (entry.type === "attachment" && entry.attachment?.type === "queued_command") {
173
+ const p = String(entry.attachment.prompt || "").trim();
174
+ if (p && !p.startsWith("<")) out.push({ key: uuid, kind: "user", text: clipText(p), ts });
175
+ return out;
176
+ }
177
+
178
+ if (entry.type === "system") {
179
+ if (entry.subtype === "compact_boundary") out.push({ key: uuid, kind: "notice", text: "Conversation compacted", ts });
180
+ if (entry.subtype === "api_error" && entry.content) out.push({ key: uuid, kind: "error", text: clipText(String(entry.content)), ts });
181
+ return out;
182
+ }
183
+ return out;
184
+ }
185
+
186
+ /** Metadata worth keeping per session: title, model, summaries. */
187
+ export function entryMeta(entry) {
188
+ if (!entry) return null;
189
+ if (entry.type === "ai-title" && entry.aiTitle) return { title: entry.aiTitle };
190
+ if (entry.type === "custom-title" && entry.customTitle) return { title: entry.customTitle };
191
+ if (entry.type === "assistant" && entry.message?.model && entry.message.model !== "<synthetic>") {
192
+ const u = entry.message.usage || {};
193
+ const context = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);
194
+ return { model: entry.message.model, context: context || undefined };
195
+ }
196
+ if (entry.type === "system" && entry.subtype === "away_summary" && entry.content) return { summary: String(entry.content) };
197
+ if (entry.type === "user" && typeof entry.permissionMode === "string") return { permissionMode: entry.permissionMode };
198
+ return null;
199
+ }
200
+
201
+ /** Read the last `maxBytes` of a file and return complete lines. */
202
+ export function readTailLines(path, maxBytes = 2_000_000) {
203
+ const size = statSync(path).size;
204
+ const start = Math.max(0, size - maxBytes);
205
+ const fd = openSync(path, "r");
206
+ try {
207
+ const buf = Buffer.alloc(size - start);
208
+ readSync(fd, buf, 0, buf.length, start);
209
+ let text = buf.toString("utf8");
210
+ if (start > 0) text = text.slice(text.indexOf("\n") + 1); // drop partial first line
211
+ return { lines: text.split("\n").filter(Boolean), end: size };
212
+ } finally {
213
+ closeSync(fd);
214
+ }
215
+ }
216
+
217
+ export function parseLine(line) {
218
+ try {
219
+ return JSON.parse(line);
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Follows a transcript file as it grows, emitting parsed entries.
227
+ * Events: "entry" (entry)
228
+ */
229
+ export class TranscriptTail extends EventEmitter {
230
+ /**
231
+ * @param {string} path
232
+ * @param {{fromOffset?: number, pollMs?: number, resolvePath?: () => string}} [opts]
233
+ * resolvePath: called on every read, for sessions that can move to another file.
234
+ */
235
+ constructor(path, { fromOffset = 0, pollMs = 1000, resolvePath = null } = {}) {
236
+ super();
237
+ this.path = path;
238
+ this.offset = fromOffset;
239
+ this.partial = "";
240
+ this.pollMs = pollMs;
241
+ this.closed = false;
242
+ this.resolvePath = resolvePath;
243
+ this.ino = null;
244
+ }
245
+
246
+ watchPath() {
247
+ this.watcher?.close();
248
+ this.watcher = null;
249
+ try {
250
+ this.watcher = watch(this.path, { persistent: false }, () => this.read());
251
+ } catch {
252
+ /* file may not exist yet; polling covers it */
253
+ }
254
+ }
255
+
256
+ start() {
257
+ this.read();
258
+ this.watchPath();
259
+ this.timer = setInterval(() => this.read(), this.pollMs);
260
+ this.timer.unref?.();
261
+ return this;
262
+ }
263
+
264
+ read() {
265
+ if (this.closed || this.reading) return;
266
+ this.reading = true;
267
+ try {
268
+ const next = this.resolvePath?.();
269
+ if (next && next !== this.path) {
270
+ // The session moved to another file: read that one from the start.
271
+ this.path = next;
272
+ this.offset = 0;
273
+ this.partial = "";
274
+ this.ino = null;
275
+ this.watchPath();
276
+ }
277
+ let size;
278
+ let ino;
279
+ try {
280
+ ({ size, ino } = statSync(this.path));
281
+ } catch {
282
+ return;
283
+ }
284
+ if (size < this.offset || (this.ino !== null && ino !== this.ino)) {
285
+ // Truncated, or replaced by a rewritten file: start over.
286
+ this.offset = 0;
287
+ this.partial = "";
288
+ }
289
+ this.ino = ino;
290
+ if (size === this.offset) return;
291
+ const fd = openSync(this.path, "r");
292
+ try {
293
+ const len = size - this.offset;
294
+ const buf = Buffer.alloc(len);
295
+ readSync(fd, buf, 0, len, this.offset);
296
+ this.offset = size;
297
+ const text = this.partial + buf.toString("utf8");
298
+ const parts = text.split("\n");
299
+ this.partial = parts.pop() ?? "";
300
+ for (const line of parts) {
301
+ if (!line) continue;
302
+ const entry = parseLine(line);
303
+ if (entry) this.emit("entry", entry);
304
+ }
305
+ } finally {
306
+ closeSync(fd);
307
+ }
308
+ } finally {
309
+ this.reading = false;
310
+ }
311
+ }
312
+
313
+ close() {
314
+ this.closed = true;
315
+ this.watcher?.close();
316
+ clearInterval(this.timer);
317
+ }
318
+ }
package/hub/voice.mjs ADDED
@@ -0,0 +1,151 @@
1
+ // Getting whisper.cpp onto a Windows PC: its release zip for this CPU, and the
2
+ // speech model. Downloads resume from a .part file if interrupted.
3
+ import { spawnSync } from "node:child_process";
4
+ import { createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { pipeline } from "node:stream/promises";
8
+ import { Readable } from "node:stream";
9
+
10
+ // whisper.cpp's version tags (v1.x) carry no binaries; its build tags do. This one
11
+ // is the build whose zips were checked to contain whisper-server.exe.
12
+ export const WHISPER_BUILD = "b5454";
13
+ export const MODEL_URL = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main/";
14
+
15
+ /**
16
+ * The release asset for this machine: CPU builds for x64 and arm64, or the CUDA
17
+ * build for x64 with an NVIDIA GPU. The CUDA zip carries the CUDA runtime DLLs
18
+ * (hence its size), so only a driver is needed.
19
+ */
20
+ export function whisperAsset(arch = process.arch, { cuda = false } = {}) {
21
+ if (arch === "arm64") return "whisper-bin-win-cpu-arm64.zip";
22
+ if (arch === "x64") return cuda ? "whisper-bin-win-cuda-12.4.0-x64.zip" : "whisper-bin-x64.zip";
23
+ return null;
24
+ }
25
+
26
+ export function whisperAssetUrl(arch = process.arch, opts = {}) {
27
+ const asset = whisperAsset(arch, opts);
28
+ return asset ? `https://github.com/ggml-org/whisper.cpp/releases/download/${WHISPER_BUILD}/${asset}` : null;
29
+ }
30
+
31
+ /** An NVIDIA driver installs nvidia-smi.exe into System32; that's the sign of a usable GPU. */
32
+ export function hasNvidiaGpu() {
33
+ if (process.platform !== "win32" || process.arch !== "x64") return false;
34
+ return existsSync(join(process.env.SystemRoot || "C:\\Windows", "System32", "nvidia-smi.exe"));
35
+ }
36
+
37
+ /** What `installWhisper` put in `dir`, if anything: {build, asset, cuda}. */
38
+ export function installedWhisper(dir) {
39
+ try {
40
+ return JSON.parse(readFileSync(join(dir, "build.json"), "utf8"));
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Download `url` to `dest`, resuming a partial download when the server allows it.
48
+ * @param {(done: number, total: number|null) => void} [onProgress]
49
+ */
50
+ export async function downloadFile(url, dest, { onProgress = () => {} } = {}) {
51
+ mkdirSync(dirname(dest), { recursive: true });
52
+ const part = dest + ".part";
53
+ let have = existsSync(part) ? statSync(part).size : 0;
54
+ const headers = have ? { Range: `bytes=${have}-` } : {};
55
+ const res = await fetch(url, { headers, redirect: "follow" });
56
+ if (res.status === 416) {
57
+ // Everything was already there.
58
+ renameSync(part, dest);
59
+ return dest;
60
+ }
61
+ if (!res.ok) throw new Error(`download failed: ${res.status} ${res.statusText} for ${url}`);
62
+ const resuming = res.status === 206 && have > 0;
63
+ if (!resuming && have) {
64
+ rmSync(part, { force: true });
65
+ have = 0;
66
+ }
67
+ const length = Number(res.headers.get("content-length")) || null;
68
+ const total = length ? have + length : null;
69
+ let done = have;
70
+ let lastReport = 0;
71
+ const progress = new (await import("node:stream")).Transform({
72
+ transform(chunk, _enc, cb) {
73
+ done += chunk.length;
74
+ if (Date.now() - lastReport > 1000) {
75
+ lastReport = Date.now();
76
+ onProgress(done, total);
77
+ }
78
+ cb(null, chunk);
79
+ },
80
+ });
81
+ await pipeline(Readable.fromWeb(res.body), progress, createWriteStream(part, { flags: resuming ? "a" : "w" }));
82
+ onProgress(done, total);
83
+ renameSync(part, dest);
84
+ return dest;
85
+ }
86
+
87
+ /**
88
+ * Put whisper-server.exe and its DLLs in `dir`. The zip holds them under Release/.
89
+ * Extraction uses PowerShell's Expand-Archive, so there is nothing to install.
90
+ */
91
+ export async function installWhisper(dir, { cuda = false, onProgress, log = () => {} } = {}) {
92
+ const asset = whisperAsset(process.arch, { cuda });
93
+ const url = whisperAssetUrl(process.arch, { cuda });
94
+ if (!url) throw new Error(`no whisper.cpp build for ${process.arch}`);
95
+ mkdirSync(dir, { recursive: true });
96
+ const zip = join(dir, basename(url));
97
+ if (!existsSync(zip)) {
98
+ log(`downloading ${url}`);
99
+ await downloadFile(url, zip, { onProgress });
100
+ }
101
+ const scratch = mkdtempSync(join(tmpdir(), "codeaside-whisper-"));
102
+ try {
103
+ const ps = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
104
+ const r = spawnSync(ps, ["-NoProfile", "-NonInteractive", "-Command", `Expand-Archive -LiteralPath '${zip.replace(/'/g, "''")}' -DestinationPath '${scratch.replace(/'/g, "''")}' -Force`], { encoding: "utf8", windowsHide: true, timeout: 600_000 });
105
+ if (r.status !== 0) throw new Error(`could not unzip ${basename(zip)}: ${(r.stderr || r.stdout || "").trim()}`);
106
+ const release = existsSync(join(scratch, "Release")) ? join(scratch, "Release") : scratch;
107
+ if (!existsSync(join(release, "whisper-server.exe"))) throw new Error(`${basename(zip)} did not contain whisper-server.exe`);
108
+ // A running server holds its files; a build switch has to stop it first, and
109
+ // Windows releases the files a moment after the process ends.
110
+ spawnSync(ps, ["-NoProfile", "-NonInteractive", "-Command", "Get-Process whisper-server -ErrorAction SilentlyContinue | Stop-Process -Force; Wait-Process -Name whisper-server -Timeout 10 -ErrorAction SilentlyContinue"], { windowsHide: true, timeout: 20_000 });
111
+ for (const f of readdirSync(dir)) {
112
+ if (!/\.(exe|dll|json)$/i.test(f)) continue;
113
+ for (let attempt = 0; ; attempt++) {
114
+ try {
115
+ rmSync(join(dir, f), { force: true });
116
+ break;
117
+ } catch (err) {
118
+ if (attempt >= 10) throw err;
119
+ await new Promise((r) => setTimeout(r, 300));
120
+ }
121
+ }
122
+ }
123
+ let moved = 0;
124
+ for (const f of readdirSync(release)) {
125
+ if (!/\.(exe|dll)$/i.test(f)) continue;
126
+ // Only what the server needs: the server, and every DLL it may load.
127
+ if (/\.exe$/i.test(f) && !/^whisper-server\.exe$/i.test(f)) continue;
128
+ renameSync(join(release, f), join(dir, f));
129
+ moved++;
130
+ }
131
+ writeFileSync(join(dir, "build.json"), JSON.stringify({ build: WHISPER_BUILD, asset, cuda }, null, 2) + "\n");
132
+ rmSync(zip, { force: true });
133
+ return { bin: join(dir, "whisper-server.exe"), files: moved, asset };
134
+ } finally {
135
+ rmSync(scratch, { recursive: true, force: true });
136
+ }
137
+ }
138
+
139
+ /** Download the speech model to `modelPath` unless it is already there. */
140
+ export async function installModel(modelPath, { onProgress, log = () => {} } = {}) {
141
+ if (existsSync(modelPath)) return false;
142
+ const url = MODEL_URL + basename(modelPath);
143
+ log(`downloading ${url}`);
144
+ await downloadFile(url, modelPath, { onProgress });
145
+ return true;
146
+ }
147
+
148
+ export function formatProgress(done, total) {
149
+ const mb = (n) => (n / 1e6).toFixed(0);
150
+ return total ? `${mb(done)} / ${mb(total)} MB (${Math.round((100 * done) / total)}%)` : `${mb(done)} MB`;
151
+ }
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@gwro/codeaside",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Drive your Claude Code sessions from Even Realities G2 smart glasses, natively on Windows: live transcript, approvals, and hold-to-talk voice.",
5
+ "type": "module",
6
+ "bin": {
7
+ "codeaside": "bin/codeaside"
8
+ },
9
+ "files": [
10
+ "bin/codeaside",
11
+ "bin/codeaside-hook.mjs",
12
+ "host/",
13
+ "hub/",
14
+ "app/dist/",
15
+ "docs/privacy.md",
16
+ "docs/windows-design.md",
17
+ "README.md",
18
+ "LICENSE",
19
+ "SECURITY.md",
20
+ "CHANGELOG.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "os": [
26
+ "win32"
27
+ ],
28
+ "scripts": {
29
+ "test": "node --test test/*.test.mjs && npm test --prefix app",
30
+ "test:hub": "node --test test/*.test.mjs",
31
+ "build:app": "npm ci --prefix app && npm run build --prefix app",
32
+ "pack:app": "npm run pack:store --prefix app",
33
+ "prepack": "npm run build:app",
34
+ "pack:personal": "npm run pack --prefix app"
35
+ },
36
+ "keywords": [
37
+ "claude-code",
38
+ "even-realities",
39
+ "g2",
40
+ "smart-glasses",
41
+ "windows",
42
+ "conpty",
43
+ "even-hub"
44
+ ],
45
+ "license": "MIT",
46
+ "author": "Grzegorz Wrobel",
47
+ "homepage": "https://github.com/gwro/CodeAside#readme",
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/gwro/CodeAside.git"
51
+ },
52
+ "bugs": {
53
+ "url": "https://github.com/gwro/CodeAside/issues"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "dependencies": {
59
+ "@lydell/node-pty": "1.2.0-beta.18",
60
+ "@xterm/addon-serialize": "0.14.0",
61
+ "@xterm/headless": "6.0.0",
62
+ "qrcode-terminal": "^0.12.0"
63
+ }
64
+ }