@anupha/claude-bridge 0.0.0-stage → 1.0.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,35 @@
1
+ // Shared pairing-code format for onboarding a phone. A pairing code bundles the
2
+ // daemon host + auth token into one string so a teammate pastes (or scans) it
3
+ // once instead of typing a URL and a 20-char token by hand.
4
+ //
5
+ // Format: "CR1|<host>|<token>" — host has no "|", token is hex, so the app just
6
+ // splits on "|". Deliberately not base64 so both the daemon and the apps decode
7
+ // it with a plain string split (no Buffer/atob needed in React Native / Swift).
8
+
9
+ export const PAIR_SCHEME = 'claude-remote';
10
+
11
+ export function pairingCode(host, token) {
12
+ return `CR1|${host}|${token}`;
13
+ }
14
+
15
+ // Deep link the phone's Camera app can open directly (no in-app scanner needed):
16
+ // scanning the QR opens the app already pointed at this daemon.
17
+ export function pairingLink(host, token) {
18
+ return `${PAIR_SCHEME}://pair?h=${encodeURIComponent(host)}&t=${encodeURIComponent(token)}`;
19
+ }
20
+
21
+ // Accept either the "CR1|host|token" paste code or the deep link.
22
+ export function parsePairingCode(code) {
23
+ const s = String(code || '').trim();
24
+ if (s.startsWith(`${PAIR_SCHEME}://`)) {
25
+ try {
26
+ const u = new URL(s);
27
+ const host = u.searchParams.get('h');
28
+ const token = u.searchParams.get('t');
29
+ return host && token ? { host, token } : null;
30
+ } catch { return null; }
31
+ }
32
+ const parts = s.split('|');
33
+ if (parts.length !== 3 || parts[0] !== 'CR1' || !parts[1] || !parts[2]) return null;
34
+ return { host: parts[1], token: parts[2] };
35
+ }
package/src/qr.mjs ADDED
@@ -0,0 +1,296 @@
1
+ // Minimal, dependency-free QR encoder — just enough to render a pairing link as
2
+ // a scannable code in the terminal. Byte mode, EC level L, versions 1–9 (8-bit
3
+ // char-count indicator throughout), with standard mask-penalty selection.
4
+ //
5
+ // Not a general QR library; scoped to short ASCII payloads (a pairing deep link).
6
+
7
+ // ---- GF(256) arithmetic (generator polynomial 0x11d) -----------------------
8
+ const EXP = new Array(512);
9
+ const LOG = new Array(256);
10
+ (function initGF() {
11
+ let x = 1;
12
+ for (let i = 0; i < 255; i++) {
13
+ EXP[i] = x;
14
+ LOG[x] = i;
15
+ x <<= 1;
16
+ if (x & 0x100) x ^= 0x11d;
17
+ }
18
+ for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
19
+ })();
20
+ const gfMul = (a, b) => (a === 0 || b === 0 ? 0 : EXP[LOG[a] + LOG[b]]);
21
+
22
+ // Reed–Solomon EC codewords for one block.
23
+ function rsEncode(data, ecLen) {
24
+ // Build the generator polynomial for ecLen EC codewords.
25
+ let gen = [1];
26
+ for (let i = 0; i < ecLen; i++) {
27
+ const next = new Array(gen.length + 1).fill(0);
28
+ for (let j = 0; j < gen.length; j++) {
29
+ next[j] ^= gen[j];
30
+ next[j + 1] ^= gfMul(gen[j], EXP[i]);
31
+ }
32
+ gen = next;
33
+ }
34
+ const res = new Array(ecLen).fill(0);
35
+ for (const d of data) {
36
+ const factor = d ^ res[0];
37
+ res.shift();
38
+ res.push(0);
39
+ // gen has ecLen+1 coefficients and gen[0] is the leading 1, which the
40
+ // shift above already accounts for — the remainder takes gen[1..ecLen].
41
+ // Using gen[j] here drops the last coefficient and shifts the rest,
42
+ // producing EC codewords that no scanner can verify.
43
+ for (let j = 0; j < ecLen; j++) res[j] ^= gfMul(gen[j + 1], factor);
44
+ }
45
+ return res;
46
+ }
47
+
48
+ // ---- Version tables (EC level L) -------------------------------------------
49
+ // [dataCodewords, ecPerBlock, numBlocks] — versions 1..9 are all single-group.
50
+ const L = {
51
+ 1: [19, 7, 1], 2: [34, 10, 1], 3: [55, 15, 1], 4: [80, 20, 1], 5: [108, 26, 1],
52
+ 6: [136, 18, 2], 7: [156, 20, 2], 8: [194, 24, 2], 9: [232, 30, 2],
53
+ };
54
+ const ALIGN = {
55
+ 1: [], 2: [6, 18], 3: [6, 22], 4: [6, 26], 5: [6, 30],
56
+ 6: [6, 34], 7: [6, 22, 38], 8: [6, 24, 42], 9: [6, 26, 46],
57
+ };
58
+
59
+ function chooseVersion(len) {
60
+ for (let v = 1; v <= 9; v++) if (L[v][0] >= len + 2) return v; // +2: mode+count overhead in codewords (approx, checked below)
61
+ throw new Error('pairing payload too long for a v1–9 QR');
62
+ }
63
+
64
+ // ---- Bit stream ------------------------------------------------------------
65
+ function encodeData(bytes, version) {
66
+ const dataCw = L[version][0];
67
+ const bits = [];
68
+ const push = (val, n) => { for (let i = n - 1; i >= 0; i--) bits.push((val >> i) & 1); };
69
+ push(0b0100, 4); // byte mode
70
+ push(bytes.length, 8); // char count (8-bit for v1–9)
71
+ for (const b of bytes) push(b, 8);
72
+ // terminator
73
+ const cap = dataCw * 8;
74
+ for (let i = 0; i < 4 && bits.length < cap; i++) bits.push(0);
75
+ while (bits.length % 8 !== 0) bits.push(0);
76
+ // to codewords, then pad
77
+ const cw = [];
78
+ for (let i = 0; i < bits.length; i += 8) {
79
+ let b = 0;
80
+ for (let j = 0; j < 8; j++) b = (b << 1) | bits[i + j];
81
+ cw.push(b);
82
+ }
83
+ const pads = [0xec, 0x11];
84
+ let p = 0;
85
+ while (cw.length < dataCw) cw.push(pads[p++ % 2]);
86
+ return cw;
87
+ }
88
+
89
+ // Split data codewords into blocks, add EC, interleave.
90
+ function buildCodewords(dataCw, version) {
91
+ const [total, ecLen, blocks] = L[version];
92
+ const per = total / blocks;
93
+ const dataBlocks = [];
94
+ const ecBlocks = [];
95
+ for (let i = 0; i < blocks; i++) {
96
+ const chunk = dataCw.slice(i * per, (i + 1) * per);
97
+ dataBlocks.push(chunk);
98
+ ecBlocks.push(rsEncode(chunk, ecLen));
99
+ }
100
+ const out = [];
101
+ for (let i = 0; i < per; i++) for (const b of dataBlocks) if (i < b.length) out.push(b[i]);
102
+ for (let i = 0; i < ecLen; i++) for (const b of ecBlocks) out.push(b[i]);
103
+ return out;
104
+ }
105
+
106
+ // ---- Matrix ----------------------------------------------------------------
107
+ function sizeFor(version) { return version * 4 + 17; }
108
+
109
+ function makeMatrix(version) {
110
+ const n = sizeFor(version);
111
+ const m = Array.from({ length: n }, () => new Array(n).fill(null));
112
+ const reserved = Array.from({ length: n }, () => new Array(n).fill(false));
113
+
114
+ const placeFinder = (r, c) => {
115
+ for (let dr = -1; dr <= 7; dr++) for (let dc = -1; dc <= 7; dc++) {
116
+ const rr = r + dr, cc = c + dc;
117
+ if (rr < 0 || rr >= n || cc < 0 || cc >= n) continue;
118
+ const inRing = dr >= 0 && dr <= 6 && dc >= 0 && dc <= 6;
119
+ const dark = inRing && ((dr === 0 || dr === 6 || dc === 0 || dc === 6) ||
120
+ (dr >= 2 && dr <= 4 && dc >= 2 && dc <= 4));
121
+ m[rr][cc] = dark ? 1 : 0;
122
+ reserved[rr][cc] = true;
123
+ }
124
+ };
125
+ placeFinder(0, 0);
126
+ placeFinder(0, n - 7);
127
+ placeFinder(n - 7, 0);
128
+
129
+ // timing patterns
130
+ for (let i = 0; i < n; i++) {
131
+ if (m[6][i] === null) { m[6][i] = i % 2 === 0 ? 1 : 0; reserved[6][i] = true; }
132
+ if (m[i][6] === null) { m[i][6] = i % 2 === 0 ? 1 : 0; reserved[i][6] = true; }
133
+ }
134
+
135
+ // alignment patterns
136
+ const pos = ALIGN[version];
137
+ for (const r of pos) for (const c of pos) {
138
+ if (reserved[r][c]) continue; // overlaps a finder
139
+ for (let dr = -2; dr <= 2; dr++) for (let dc = -2; dc <= 2; dc++) {
140
+ const rr = r + dr, cc = c + dc;
141
+ const dark = Math.max(Math.abs(dr), Math.abs(dc)) !== 1;
142
+ m[rr][cc] = dark ? 1 : 0;
143
+ reserved[rr][cc] = true;
144
+ }
145
+ }
146
+
147
+ // dark module
148
+ m[n - 8][8] = 1; reserved[n - 8][8] = true;
149
+
150
+ // reserve format-info areas
151
+ for (let i = 0; i < 9; i++) {
152
+ if (!reserved[8][i]) reserved[8][i] = 'fmt';
153
+ if (!reserved[i][8]) reserved[i][8] = 'fmt';
154
+ }
155
+ for (let i = 0; i < 8; i++) {
156
+ if (!reserved[8][n - 1 - i]) reserved[8][n - 1 - i] = 'fmt';
157
+ if (!reserved[n - 1 - i][8]) reserved[n - 1 - i][8] = 'fmt';
158
+ }
159
+
160
+ return { m, reserved, n };
161
+ }
162
+
163
+ function placeData(m, reserved, n, codewords) {
164
+ const bits = [];
165
+ for (const cw of codewords) for (let i = 7; i >= 0; i--) bits.push((cw >> i) & 1);
166
+ let idx = 0;
167
+ let up = true;
168
+ for (let col = n - 1; col > 0; col -= 2) {
169
+ if (col === 6) col--; // skip the timing column
170
+ for (let i = 0; i < n; i++) {
171
+ const row = up ? n - 1 - i : i;
172
+ for (let c = 0; c < 2; c++) {
173
+ const cc = col - c;
174
+ if (reserved[row][cc]) continue;
175
+ m[row][cc] = idx < bits.length ? bits[idx++] : 0;
176
+ }
177
+ }
178
+ up = !up;
179
+ }
180
+ }
181
+
182
+ const MASKS = [
183
+ (r, c) => (r + c) % 2 === 0,
184
+ (r) => r % 2 === 0,
185
+ (_, c) => c % 3 === 0,
186
+ (r, c) => (r + c) % 3 === 0,
187
+ (r, c) => (Math.floor(r / 2) + Math.floor(c / 3)) % 2 === 0,
188
+ (r, c) => ((r * c) % 2) + ((r * c) % 3) === 0,
189
+ (r, c) => (((r * c) % 2) + ((r * c) % 3)) % 2 === 0,
190
+ (r, c) => (((r + c) % 2) + ((r * c) % 3)) % 2 === 0,
191
+ ];
192
+
193
+ function applyMask(m, reserved, n, maskFn) {
194
+ const out = m.map((row) => row.slice());
195
+ for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) {
196
+ if (reserved[r][c]) continue;
197
+ if (maskFn(r, c)) out[r][c] ^= 1;
198
+ }
199
+ return out;
200
+ }
201
+
202
+ // BCH(15,5) format info; EC level L = 0b01.
203
+ function formatBits(mask) {
204
+ const data = (0b01 << 3) | mask; // 5 bits
205
+ let rem = data << 10;
206
+ const g = 0b10100110111;
207
+ for (let i = 14; i >= 10; i--) if ((rem >> i) & 1) rem ^= g << (i - 10);
208
+ let bits = ((data << 10) | rem) ^ 0b101010000010010;
209
+ return bits & 0x7fff;
210
+ }
211
+
212
+ function placeFormat(m, n, mask) {
213
+ const bits = formatBits(mask);
214
+ const get = (i) => (bits >> i) & 1;
215
+ // Around top-left. Indices here are [row][col]; the spec's own diagram is
216
+ // written (x, y) = (col, row), so transcribing it literally transposes this
217
+ // copy — bits 0-5 belong in COLUMN 8 going down, not row 8 going right.
218
+ for (let i = 0; i <= 5; i++) m[i][8] = get(i);
219
+ m[7][8] = get(6); m[8][8] = get(7); m[8][7] = get(8);
220
+ for (let i = 9; i <= 14; i++) m[8][14 - i] = get(i);
221
+ // around top-right / bottom-left
222
+ for (let i = 0; i <= 7; i++) m[8][n - 1 - i] = get(i);
223
+ for (let i = 8; i <= 14; i++) m[n - 15 + i][8] = get(i);
224
+ }
225
+
226
+ function penalty(m, n) {
227
+ let score = 0;
228
+ // rule 1: runs of >=5 same colour
229
+ for (let r = 0; r < n; r++) for (const line of [m[r], m.map((x) => x[r])]) {
230
+ let run = 1;
231
+ for (let c = 1; c < n; c++) {
232
+ if (line[c] === line[c - 1]) { run++; if (run === 5) score += 3; else if (run > 5) score += 1; }
233
+ else run = 1;
234
+ }
235
+ }
236
+ // rule 2: 2x2 blocks
237
+ for (let r = 0; r < n - 1; r++) for (let c = 0; c < n - 1; c++) {
238
+ const v = m[r][c];
239
+ if (v === m[r][c + 1] && v === m[r + 1][c] && v === m[r + 1][c + 1]) score += 3;
240
+ }
241
+ // rule 3: finder-like pattern
242
+ const pat = [1, 0, 1, 1, 1, 0, 1];
243
+ const has = (line, i) => pat.every((p, k) => line[i + k] === p);
244
+ for (let r = 0; r < n; r++) for (let c = 0; c <= n - 7; c++) {
245
+ if (has(m[r], c)) score += 40;
246
+ const col = m.map((x) => x[r]);
247
+ if (has(col, c)) score += 40;
248
+ }
249
+ // rule 4: dark proportion
250
+ let dark = 0;
251
+ for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) dark += m[r][c];
252
+ const pct = (dark * 100) / (n * n);
253
+ score += Math.floor(Math.abs(pct - 50) / 5) * 10;
254
+ return score;
255
+ }
256
+
257
+ // Encode `text` and return an array of terminal lines (2 rows per char row,
258
+ // using half-block glyphs so the code stays roughly square).
259
+ export function qrLines(text) {
260
+ const bytes = [...Buffer.from(text, 'utf8')];
261
+ const version = chooseVersion(bytes.length);
262
+ const dataCw = encodeData(bytes, version);
263
+ const codewords = buildCodewords(dataCw, version);
264
+ const base = makeMatrix(version);
265
+
266
+ let best = null;
267
+ for (let mask = 0; mask < 8; mask++) {
268
+ const { m, reserved, n } = base;
269
+ placeData(m, reserved, n, codewords);
270
+ const masked = applyMask(m, reserved, n, MASKS[mask]);
271
+ placeFormat(masked, n, mask);
272
+ const p = penalty(masked, n);
273
+ if (!best || p < best.p) best = { m: masked, n, p };
274
+ // reset data cells for the next mask trial
275
+ for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if (!reserved[r][c]) m[r][c] = null;
276
+ }
277
+
278
+ const { m, n } = best;
279
+ const quiet = 4;
280
+ const N = n + quiet * 2;
281
+ const grid = Array.from({ length: N }, () => new Array(N).fill(0));
282
+ for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) grid[r + quiet][c + quiet] = m[r][c];
283
+
284
+ const lines = [];
285
+ for (let r = 0; r < N; r += 2) {
286
+ let line = '';
287
+ for (let c = 0; c < N; c++) {
288
+ const top = grid[r][c] === 1;
289
+ const bot = r + 1 < N && grid[r + 1][c] === 1;
290
+ // dark module -> black; render black as space, light as block (terminal is dark-on-light for scanners)
291
+ line += top && bot ? ' ' : top ? '▄' : bot ? '▀' : '█';
292
+ }
293
+ lines.push(line);
294
+ }
295
+ return lines;
296
+ }
package/src/sysmon.mjs ADDED
@@ -0,0 +1,98 @@
1
+ // System monitor for the Mac the daemon runs on — CPU / memory / disk / battery
2
+ // and identity, for the app's "Mac" dashboard. Zero deps: Node's os module plus
3
+ // a few macOS CLIs. Results are cached briefly so polling stays cheap.
4
+
5
+ import os from 'node:os';
6
+ import { execFileSync } from 'node:child_process';
7
+
8
+ const sh = (cmd, args) => {
9
+ try { return execFileSync(cmd, args, { encoding: 'utf8', timeout: 4000 }).trim(); }
10
+ catch { return ''; }
11
+ };
12
+
13
+ // Identity rarely changes — read it once.
14
+ let identity = null;
15
+ function readIdentity() {
16
+ if (identity) return identity;
17
+ identity = {
18
+ host: os.hostname().replace(/\.local$/, ''),
19
+ chip: sh('sysctl', ['-n', 'machdep.cpu.brand_string']) || sh('sysctl', ['-n', 'hw.model']),
20
+ model: sh('sysctl', ['-n', 'hw.model']),
21
+ os: sh('sw_vers', ['-productVersion']),
22
+ cores: os.cpus().length,
23
+ };
24
+ return identity;
25
+ }
26
+
27
+ // Overall CPU busy %. `top -l 2` takes a ~1s delta sample, so the second
28
+ // "CPU usage" line is a real reading rather than a since-boot average.
29
+ function cpuPercent() {
30
+ const out = sh('top', ['-l', '2', '-n', '0']);
31
+ const lines = out.split('\n').filter((l) => l.includes('CPU usage'));
32
+ const last = lines[lines.length - 1] || '';
33
+ const idle = /(\d+\.?\d*)%\s*idle/.exec(last);
34
+ if (!idle) return null;
35
+ return Math.round((100 - parseFloat(idle[1])) * 10) / 10;
36
+ }
37
+
38
+ // "App memory" (active + wired + compressed), matching Activity Monitor's feel.
39
+ function memory() {
40
+ const total = os.totalmem();
41
+ const vm = sh('vm_stat');
42
+ const pageSize = parseInt(/page size of (\d+)/.exec(vm)?.[1] || '4096', 10);
43
+ const pages = (name) => parseInt(new RegExp(`${name}:\\s+(\\d+)`).exec(vm)?.[1] || '0', 10);
44
+ const used = (pages('Pages active') + pages('Pages wired down') + pages('Pages occupied by compressor')) * pageSize;
45
+ return {
46
+ usedGB: Math.round((used / 1e9) * 10) / 10,
47
+ totalGB: Math.round((total / 1e9) * 10) / 10,
48
+ pct: Math.min(100, Math.round((used / total) * 100)),
49
+ };
50
+ }
51
+
52
+ function disk() {
53
+ // df -k / -> "Filesystem 1024-blocks Used Available Capacity ... /"
54
+ const out = sh('df', ['-k', '/']);
55
+ const row = out.split('\n')[1]?.split(/\s+/) || [];
56
+ const totalKB = parseInt(row[1] || '0', 10);
57
+ const usedKB = parseInt(row[2] || '0', 10);
58
+ if (!totalKB) return null;
59
+ return {
60
+ usedGB: Math.round((usedKB / 1e6) * 10) / 10,
61
+ totalGB: Math.round((totalKB / 1e6) * 10) / 10,
62
+ pct: Math.round((usedKB / totalKB) * 100),
63
+ };
64
+ }
65
+
66
+ function battery() {
67
+ const out = sh('pmset', ['-g', 'batt']);
68
+ const pct = /(\d+)%/.exec(out);
69
+ if (!pct) return null; // desktop Mac / no battery
70
+ const charging = /AC Power|charging/i.test(out) && !/discharging/i.test(out);
71
+ return { pct: parseInt(pct[1], 10), charging };
72
+ }
73
+
74
+ function uptimeText() {
75
+ let s = os.uptime();
76
+ const d = Math.floor(s / 86400); s -= d * 86400;
77
+ const h = Math.floor(s / 3600); s -= h * 3600;
78
+ const m = Math.floor(s / 60);
79
+ return d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
80
+ }
81
+
82
+ let cache = { at: 0, value: null };
83
+ export function systemStats() {
84
+ const now = Date.now();
85
+ if (cache.value && now - cache.at < 4000) return cache.value;
86
+ const [one, five, fifteen] = os.loadavg();
87
+ const value = {
88
+ ...readIdentity(),
89
+ cpuPct: cpuPercent(),
90
+ load: [one, five, fifteen].map((n) => Math.round(n * 100) / 100),
91
+ memory: memory(),
92
+ disk: disk(),
93
+ battery: battery(),
94
+ uptime: uptimeText(),
95
+ };
96
+ cache = { at: now, value };
97
+ return value;
98
+ }