@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 iBiztech Co., Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @anupha/claude-bridge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Companion daemon for the **Claude Remote Control** app. It mirrors every Claude Code
4
+ terminal session to your phone: live session registry, remote permission
5
+ approval, and terminal preview/typing over tmux.
6
+
7
+ ## Requirements
8
+
9
+ - macOS (the daemon uses `launchctl`, `screencapture`, and `osascript`)
10
+ - Node.js 18 or newer
11
+ - `tmux` (`brew install tmux`) — required; it is what lets the phone see and
12
+ type into a session
13
+ - Claude Code installed and on your `PATH`
14
+ - [Tailscale](https://tailscale.com) if you want to reach the daemon from
15
+ outside your local network
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npm i -g @anupha/claude-bridge
21
+ bridge install
22
+ ```
23
+
24
+ `bridge install` runs preflight checks, adds claude-bridge hooks to
25
+ `~/.claude/settings.json` (merging with any hooks you already have and keeping a
26
+ timestamped backup), aliases `claude` to a tmux wrapper in your shell config, and
27
+ installs a LaunchAgent so the daemon starts at login.
28
+
29
+ Use `bridge install --local` to install hooks into the current project's
30
+ `.claude/settings.json` only, with no LaunchAgent and no shell alias.
31
+
32
+ ## Pair with the app
33
+
34
+ ```sh
35
+ bridge pair
36
+ ```
37
+
38
+ Scan the QR code with the Claude Remote Control app.
39
+
40
+ ## Other commands
41
+
42
+ ```sh
43
+ bridge status # sessions + pending approvals
44
+ bridge approve <id|latest> # or: bridge deny <id|latest>
45
+ bridge remote on|off # remote approval mode
46
+ bridge watch # live event stream
47
+ bridge daemon # run the daemon in the foreground
48
+ bridge uninstall [--local] # remove hooks, alias, and LaunchAgent
49
+ ```
50
+
51
+ ## App
52
+
53
+ Claude Remote Control for iOS and Android — link coming soon.
54
+
55
+ ## License
56
+
57
+ MIT
package/SETUP.md ADDED
@@ -0,0 +1,157 @@
1
+ # Claude Remote Control — Setup Guide
2
+
3
+ Control every Claude Code terminal session on your computer, from your phone.
4
+ There are two pieces:
5
+
6
+ - **The daemon** — a small Node service that runs on your computer, watches your
7
+ Claude Code sessions (via tmux + Claude hooks), and exposes a local HTTP/SSE API.
8
+ - **The app** — iOS (SwiftUI) or the cross-platform React Native build — that
9
+ connects to the daemon over your private network and mirrors/controls sessions.
10
+
11
+ They find each other over **Tailscale**, which gives both devices a stable
12
+ private IP that works anywhere (home, hotspot, different networks) without port
13
+ forwarding.
14
+
15
+ ---
16
+
17
+ ## 1. Tailscale (both devices)
18
+
19
+ Tailscale creates a private mesh network so the phone can reach your computer by
20
+ a fixed IP (`100.x.x.x`) no matter where either one is.
21
+
22
+ 1. Install Tailscale on **your computer**: <https://tailscale.com/download> and sign in.
23
+ 2. Install the **Tailscale** app on **your phone** (App Store / Play Store) and
24
+ sign in with the **same account**.
25
+ 3. On the computer, note its Tailscale IP:
26
+ ```
27
+ tailscale ip -4
28
+ ```
29
+ (`bridge pair` prints this for you automatically — see below.)
30
+
31
+ ---
32
+
33
+ ## 2. The daemon
34
+
35
+ ### macOS / Linux
36
+
37
+ Requirements: **Node 18+** and **tmux** (`brew install tmux` / `apt install tmux`).
38
+
39
+ ```bash
40
+ npm i -g @anupha/claude-bridge
41
+ bridge install # Claude Code hooks + launch agent (daemon runs from login)
42
+ ```
43
+
44
+ (Developing from a clone instead? `npm run daemon` starts it in the foreground,
45
+ and `node src/cli.mjs …` is the uninstalled equivalent of `bridge …`.)
46
+
47
+ Then pair (exposes the daemon on the network + prints the connection info):
48
+
49
+ ```bash
50
+ bridge pair
51
+ # █▀▀▀▀▀█ ... ← a QR code
52
+ # ...
53
+ # …or paste this code in Settings → “Quick pair”:
54
+ # CR1|http://100.x.x.x:8787|<access token>
55
+ # host : http://100.x.x.x:8787 ← your Tailscale IP
56
+ # token: <access token>
57
+ ```
58
+
59
+ You get three ways to connect the phone (pick one):
60
+
61
+ - **Scan the QR** printed in the terminal with the phone's **Camera app** — it
62
+ opens the app already paired. Nothing to type.
63
+ - **Paste the pairing code** (`CR1|…`) into the app under Settings → **Quick pair**.
64
+ - **Type the host + token** manually under Settings → Computer connection.
65
+
66
+ Run Claude Code as usual inside a **tmux** session; it registers itself with the
67
+ daemon through Claude's hooks, and shows up in the app.
68
+
69
+ ### Windows
70
+
71
+ Windows has no native tmux, so you have two options:
72
+
73
+ **Option A — WSL2 (recommended, works today).** Run everything inside WSL2 Ubuntu,
74
+ exactly like Linux:
75
+
76
+ 1. Install WSL2: in PowerShell (admin) run `wsl --install`, reboot, open **Ubuntu**.
77
+ 2. Inside Ubuntu: install Node 18+ and tmux (`sudo apt install tmux`).
78
+ 3. Clone the repo, `npm run daemon`, `node src/cli.mjs pair`.
79
+ 4. Install Tailscale **inside WSL** (`curl -fsSL https://tailscale.com/install.sh | sh`)
80
+ so the daemon gets its own Tailscale IP, and use that as the host.
81
+ 5. Run Claude Code inside the same WSL Ubuntu (inside tmux).
82
+
83
+ **Option B — native Windows (not built yet).** Attaching to an already-open
84
+ Windows Terminal window is not reliable (no tmux; Win32 console scraping is
85
+ fragile). True native support would require swapping the tmux backend for a
86
+ `node-pty` (ConPTY) backend where the daemon *spawns and owns* the Claude
87
+ session — meaning you'd launch Claude from the app rather than mirror a terminal
88
+ you opened yourself, and the daemon gains a native dependency. Ask if you want
89
+ this; for now, use WSL2.
90
+
91
+ ---
92
+
93
+ ## 3. The app
94
+
95
+ 1. Open the app. On first launch it opens **Settings**.
96
+ 2. Fastest: **scan the QR** from `bridge pair` with your phone's Camera app — the
97
+ app opens already paired. Or paste the `CR1|…` code into **Quick pair**.
98
+ 3. You should see “Connected — N sessions”.
99
+
100
+ To point the app at a different computer later: Settings → **Forget this
101
+ computer**, then scan/paste a new pairing code.
102
+
103
+ If the connection drops (the computer sleeps, Tailscale reconnects), the app
104
+ shows **Reconnecting…** and retries on its own — no need to re-pair.
105
+
106
+ ---
107
+
108
+ ## 4. Distributing to teammates
109
+
110
+ Pushing to git does **not** install anything on a teammate's phone. Each
111
+ teammate needs three things:
112
+
113
+ 1. **Their own computer** running the daemon (they clone this repo and start it —
114
+ the app talks to *their* machine, not yours) + `bridge pair` on it.
115
+ 2. **Tailscale** on their phone and computer, same account.
116
+ 3. **The app** on their phone — see below, per platform.
117
+
118
+ ### Android (easiest — one file for everyone)
119
+
120
+ Build once, share the APK with every Android teammate:
121
+
122
+ ```bash
123
+ cd app-rn
124
+ npm install -g eas-cli # first time only
125
+ eas login # interactive — you must run this yourself
126
+ eas build -p android --profile preview
127
+ ```
128
+
129
+ EAS returns a download URL for a `.apk`. Send it to teammates; they enable
130
+ "install unknown apps" and tap it. No expiry, no per-device registration.
131
+
132
+ ### iOS
133
+
134
+ Free provisioning only signs the developer's own device, so an iPhone teammate
135
+ can't just install your build. Options:
136
+
137
+ - **TestFlight** (best for non-devs): needs an Apple Developer account
138
+ ($99/yr). `eas build -p ios --profile production` then `eas submit`, invite
139
+ teammates by email.
140
+ - **Expo Go** (works today, no cost, for dev teammates): they clone `app-rn`,
141
+ run `npm install` then `npx expo start`, and open it in the **Expo Go** app.
142
+ Runs on both iOS and Android with no build.
143
+
144
+ ### Then, on the teammate's phone
145
+
146
+ Open the app → run `bridge pair` on their computer → **scan the QR** with the
147
+ Camera app (or paste the `CR1|…` code into Settings → Quick pair). Done.
148
+
149
+ ---
150
+
151
+ ## Notes
152
+
153
+ - The daemon is auth'd by the bearer **token** from `bridge pair`; keep it private.
154
+ - Push notifications use **ntfy** (free, no Apple Developer account): install the
155
+ ntfy app, subscribe to a unique topic, enter the same topic in Settings.
156
+ - The account name and 5h/7d usage shown in the app are read from the computer
157
+ the daemon runs on.
@@ -0,0 +1,27 @@
1
+ #!/bin/bash
2
+ # claude-bridge hook shim. Forwards the hook event (JSON on stdin) to the local
3
+ # daemon and prints its response, which for pre-tool-use may contain a
4
+ # permissionDecision. Fails open: if the daemon is down or slow to accept the
5
+ # connection, we print nothing and exit 0 so Claude Code behaves exactly as if
6
+ # the hook were not installed.
7
+ EVENT="$1"
8
+ PORT="${BRIDGE_PORT:-8787}"
9
+
10
+ # When claude runs inside tmux, report the pane so the phone can type into this
11
+ # terminal and capture its screen. TMUX_PANE looks like "%12" -> url-encode %.
12
+ PANE="${TMUX_PANE//\%/%25}"
13
+
14
+ # Shared secret written by the daemon (owner-only): proves this request comes
15
+ # from the hook shim, not from some other process talking to the local port.
16
+ SECRET="$(cat "${BRIDGE_DATA_DIR:-$HOME/.claude-bridge}/hook-secret" 2>/dev/null)"
17
+
18
+ # --max-time must exceed the daemon's approval wait. waitSeconds defaults to 100
19
+ # and the daemon clamps it to 110, so 115 always outlives the wait: the daemon
20
+ # gets to answer (allow/deny/timeout) rather than curl cutting the reply off.
21
+ # Either way this fails open — curl errors print nothing and we exit 0.
22
+ curl -s --connect-timeout 1 --max-time 115 \
23
+ -X POST "http://127.0.0.1:${PORT}/hook/${EVENT}?pane=${PANE}" \
24
+ -H 'Content-Type: application/json' \
25
+ -H "X-Bridge-Hook: ${SECRET}" \
26
+ --data-binary @- 2>/dev/null
27
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "@anupha/claude-bridge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Mirror every Claude Code terminal session to mobile: session registry, remote permission approval, auto-sync daemon. Companion daemon for the Claude Remote app.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "iBiztech",
8
+ "homepage": "https://ibiztech.co.th",
9
+ "os": [
10
+ "darwin"
11
+ ],
12
+ "bin": {
13
+ "bridge": "src/cli.mjs",
14
+ "claude-bridge": "src/cli.mjs"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "hooks",
19
+ "scripts/install.mjs",
20
+ "scripts/claude-tmux.sh",
21
+ "scripts/kitty-passthrough.py",
22
+ "SETUP.md",
23
+ "LICENSE",
24
+ "README.md"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "keywords": [
30
+ "claude-code",
31
+ "remote-control",
32
+ "tmux",
33
+ "daemon",
34
+ "mobile"
35
+ ],
36
+ "scripts": {
37
+ "daemon": "node src/daemon.mjs",
38
+ "test": "node tests/parsers.test.mjs && node tests/loop.test.mjs && node tests/terminal.test.mjs && node tests/apns.test.mjs && node tests/qr.test.mjs"
39
+ },
40
+ "engines": {
41
+ "node": ">=18"
42
+ }
43
+ }
@@ -0,0 +1,52 @@
1
+ #!/bin/bash
2
+ # Transparent tmux wrapper for claude. Installed as `alias claude=.../claude-tmux.sh`
3
+ # so every session runs inside tmux — which is what lets the phone type into the
4
+ # terminal (tmux send-keys) and render View Preview (tmux capture-pane).
5
+ # Inside tmux already (or tmux missing): behaves exactly like plain claude.
6
+
7
+ # Inside tmux the PATH is the tmux server's (it may have been started by the
8
+ # launchd daemon with a minimal PATH), so prefer the path resolved outside.
9
+ REAL_CLAUDE="${CLAUDE_BRIDGE_REAL:-$(command -v claude)}"
10
+ if [ -z "$REAL_CLAUDE" ]; then
11
+ echo "claude not found in PATH" >&2
12
+ exit 127
13
+ fi
14
+
15
+ # Pasted-image thumbnails (kitty graphics) only survive tmux when each image
16
+ # escape is rewrapped as a tmux passthrough; kitty-passthrough.py does that.
17
+ # Only turned on when the outer terminal can draw them (Ghostty, kitty) —
18
+ # everywhere else this runs plain claude, exactly as before.
19
+ SHIM="$(dirname "$0")/kitty-passthrough.py"
20
+
21
+ if [ -n "$TMUX" ]; then
22
+ OUTER_TERM="${CLAUDE_BRIDGE_OUTER_TERM:-$(tmux display-message -p '#{client_termname}' 2>/dev/null)}"
23
+ case "$OUTER_TERM" in
24
+ xterm-ghostty|xterm-kitty)
25
+ # Interactive only: piped/redirected runs (echo x | claude -p, claude -p >
26
+ # file) must keep real pipes, and the shim would hang on stdin EOF.
27
+ # `python3 -c` rather than `command -v`: macOS ships a stub that only
28
+ # offers to install the Command Line Tools.
29
+ if [ -t 0 ] && [ -t 1 ] && [ -f "$SHIM" ] && python3 -c '' >/dev/null 2>&1; then
30
+ tmux set-option -p allow-passthrough on 2>/dev/null
31
+ export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
32
+ exec python3 "$SHIM" "$REAL_CLAUDE" "$@"
33
+ fi
34
+ ;;
35
+ esac
36
+ exec "$REAL_CLAUDE" "$@"
37
+ fi
38
+
39
+ if ! command -v tmux >/dev/null; then
40
+ echo "tmux not found — Claude Remote can't mirror this session; install tmux (brew install tmux)" >&2
41
+ exec "$REAL_CLAUDE" "$@"
42
+ fi
43
+
44
+ SESSION="claude-$(basename "$PWD" | tr -cd '[:alnum:]-')-$$"
45
+ # Re-enter this script inside tmux (it then takes the branch above). Hand the
46
+ # outer terminal's name over with -e (tmux 3.2+); older tmux just runs plain
47
+ # claude, exactly as before the image shim existed.
48
+ SELF="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
49
+ if tmux -V 2>/dev/null | awk '{ split($2, v, /[.a-z]/); exit !(v[1] > 3 || (v[1] == 3 && v[2] >= 2)) }'; then
50
+ exec tmux new-session -s "$SESSION" -e "CLAUDE_BRIDGE_OUTER_TERM=$TERM" -e "CLAUDE_BRIDGE_REAL=$REAL_CLAUDE" "$SELF" "$@"
51
+ fi
52
+ exec tmux new-session -s "$SESSION" "$REAL_CLAUDE" "$@"
@@ -0,0 +1,282 @@
1
+ #!/usr/bin/env node
2
+ // Installs claude-bridge hooks into Claude Code settings (merging with any
3
+ // existing hooks, never replacing them) and, with --global, a launchd agent so
4
+ // the daemon starts at login. A timestamped backup of the settings file is
5
+ // written next to it before any change.
6
+ //
7
+ // node scripts/install.mjs --local -> this project's .claude/settings.json
8
+ // node scripts/install.mjs --global -> ~/.claude/settings.json + LaunchAgent
9
+ // node scripts/install.mjs --uninstall [--local|--global]
10
+ //
11
+ // Everything the settings file and shell rc files point at lives under
12
+ // ~/.claude-bridge, not inside this package, so hooks keep working when the
13
+ // package is upgraded, moved, or installed globally from npm.
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import os from 'node:os';
18
+ import { execFileSync } from 'node:child_process';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
22
+ const HOME = os.homedir();
23
+ const MARKER = 'claude-bridge'; // identifies our entries for clean uninstall
24
+
25
+ const BRIDGE_DIR = path.join(HOME, '.claude-bridge');
26
+ const HOOK = path.join(BRIDGE_DIR, 'hook-handler.sh');
27
+ const TMUX_WRAPPER = path.join(BRIDGE_DIR, 'claude-tmux.sh');
28
+
29
+ const args = process.argv.slice(2);
30
+ const isGlobal = args.includes('--global');
31
+ const uninstall = args.includes('--uninstall');
32
+
33
+ const settingsFile = isGlobal
34
+ ? path.join(HOME, '.claude', 'settings.json')
35
+ : path.join(process.cwd(), '.claude', 'settings.json');
36
+ const otherSettingsFile = isGlobal
37
+ ? path.join(process.cwd(), '.claude', 'settings.json')
38
+ : path.join(HOME, '.claude', 'settings.json');
39
+
40
+ // Every event here must have a matching POST /hook/<name> case in the daemon,
41
+ // and every case the daemon handles must be listed here — a handler with no
42
+ // installer entry silently stops firing on a fresh install. Notification is the
43
+ // one that tells the daemon a terminal is parked on a permission prompt.
44
+ const EVENTS = [
45
+ { event: 'SessionStart', matcher: undefined, timeout: 5 },
46
+ { event: 'SessionEnd', matcher: undefined, timeout: 5 },
47
+ { event: 'Stop', matcher: undefined, timeout: 5 },
48
+ { event: 'PreToolUse', matcher: '.*', timeout: 180 },
49
+ { event: 'Notification', matcher: undefined, timeout: 5 },
50
+ ];
51
+
52
+ const hookEventName = { SessionStart: 'session-start', SessionEnd: 'session-end', Stop: 'stop', PreToolUse: 'pre-tool-use', Notification: 'notification' };
53
+
54
+ // Paths are quoted: a home directory with a space in it would otherwise split
55
+ // into two shell words when Claude Code runs the hook.
56
+ function ourCommand(event) {
57
+ return `"${HOOK}" ${hookEventName[event]} # ${MARKER}`;
58
+ }
59
+
60
+ // `command -v` rather than `which`: it is a shell builtin, so it also finds
61
+ // binaries the user only has via a function or alias-free PATH entry.
62
+ function have(bin) {
63
+ try {
64
+ return execFileSync('/bin/sh', ['-c', 'command -v "$1"', 'sh', bin], { encoding: 'utf8' }).trim();
65
+ } catch {
66
+ return '';
67
+ }
68
+ }
69
+
70
+ // --------------------------------------------------------------- preflight
71
+
72
+ function preflight() {
73
+ const major = Number(process.versions.node.split('.')[0]);
74
+ if (major < 18) {
75
+ console.error(`error: node >= 18 required, found ${process.version}`);
76
+ process.exit(1);
77
+ }
78
+ console.log(`node ${process.version} ok`);
79
+
80
+ const tmux = have('tmux');
81
+ if (!tmux) {
82
+ console.error('error: tmux not found — install with: brew install tmux');
83
+ console.error(' claude-bridge needs tmux to mirror sessions to your phone.');
84
+ process.exit(1);
85
+ }
86
+ console.log(`tmux ${tmux} ok`);
87
+
88
+ const claude = have('claude');
89
+ if (!claude) console.warn('warning: `claude` not found in PATH — install Claude Code before using the bridge');
90
+ else console.log(`claude ${claude} ok`);
91
+ }
92
+
93
+ if (!uninstall) preflight();
94
+
95
+ // ------------------------------------------------- stable script location
96
+ // The clone/npm-install directory is not a stable address: a global npm upgrade
97
+ // replaces it and a moved checkout breaks it. Copy the scripts that get
98
+ // referenced from long-lived config into ~/.claude-bridge instead.
99
+
100
+ function stableHookIsStillReferenced() {
101
+ try {
102
+ if (!fs.existsSync(otherSettingsFile)) return false;
103
+ return fs.readFileSync(otherSettingsFile, 'utf8').includes(MARKER);
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ if (uninstall) {
110
+ if (fs.existsSync(HOOK)) {
111
+ if (stableHookIsStillReferenced()) {
112
+ console.log(`kept (still referenced by ${otherSettingsFile}): ${HOOK}`);
113
+ } else {
114
+ fs.unlinkSync(HOOK);
115
+ console.log(`removed: ${HOOK}`);
116
+ }
117
+ }
118
+ if (isGlobal && fs.existsSync(TMUX_WRAPPER)) {
119
+ fs.unlinkSync(TMUX_WRAPPER);
120
+ console.log(`removed: ${TMUX_WRAPPER}`);
121
+ fs.rmSync(path.join(BRIDGE_DIR, 'kitty-passthrough.py'), { force: true }); // the wrapper's image shim
122
+ fs.rmSync(path.join(BRIDGE_DIR, 'hook-secret'), { force: true }); // daemon makes a new one on next start
123
+ }
124
+ } else {
125
+ fs.mkdirSync(BRIDGE_DIR, { recursive: true });
126
+ fs.copyFileSync(path.join(ROOT, 'hooks', 'hook-handler.sh'), HOOK);
127
+ fs.chmodSync(HOOK, 0o755);
128
+ fs.copyFileSync(path.join(ROOT, 'scripts', 'claude-tmux.sh'), TMUX_WRAPPER);
129
+ fs.chmodSync(TMUX_WRAPPER, 0o755);
130
+ // claude-tmux.sh runs this next to itself to carry pasted-image thumbnails through tmux
131
+ fs.copyFileSync(path.join(ROOT, 'scripts', 'kitty-passthrough.py'), path.join(BRIDGE_DIR, 'kitty-passthrough.py'));
132
+ console.log(`hook handler: ${HOOK}`);
133
+ }
134
+
135
+ // ---------------------------------------------------------------- settings
136
+
137
+ fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
138
+
139
+ let settings = {};
140
+ if (fs.existsSync(settingsFile)) {
141
+ const raw = fs.readFileSync(settingsFile, 'utf8');
142
+ try {
143
+ settings = raw.trim() ? JSON.parse(raw) : {};
144
+ } catch (err) {
145
+ console.error(`error: ${settingsFile} is not valid JSON (${err.message}).`);
146
+ console.error(' Nothing was changed. Fix or move that file, then run this installer again.');
147
+ process.exit(1);
148
+ }
149
+
150
+ const backup = `${settingsFile}.bak-${Date.now()}`;
151
+ fs.copyFileSync(settingsFile, backup);
152
+ console.log(`backup: ${backup}`);
153
+ pruneBackups(settingsFile, 3);
154
+ }
155
+
156
+ // Every run used to leave another .bak behind; keep only the newest few.
157
+ function pruneBackups(file, keep) {
158
+ const dir = path.dirname(file);
159
+ const prefix = `${path.basename(file)}.bak-`;
160
+ const old = fs
161
+ .readdirSync(dir)
162
+ .filter((n) => n.startsWith(prefix))
163
+ .sort()
164
+ .slice(0, -keep);
165
+ for (const name of old) {
166
+ try { fs.unlinkSync(path.join(dir, name)); } catch {}
167
+ }
168
+ if (old.length) console.log(`pruned ${old.length} old backup(s)`);
169
+ }
170
+
171
+ settings.hooks = settings.hooks || {};
172
+
173
+ for (const { event, matcher, timeout } of EVENTS) {
174
+ const list = settings.hooks[event] || [];
175
+ // remove any previous claude-bridge entries
176
+ const cleaned = list
177
+ .map((group) => ({
178
+ ...group,
179
+ hooks: (group.hooks || []).filter((h) => !String(h.command).includes(MARKER)),
180
+ }))
181
+ .filter((group) => group.hooks.length > 0);
182
+
183
+ if (!uninstall) {
184
+ const entry = { type: 'command', command: ourCommand(event), timeout };
185
+ cleaned.push(matcher !== undefined ? { matcher, hooks: [entry] } : { hooks: [entry] });
186
+ }
187
+ if (cleaned.length) settings.hooks[event] = cleaned;
188
+ else delete settings.hooks[event];
189
+ }
190
+
191
+ fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2));
192
+ console.log(`${uninstall ? 'removed hooks from' : 'hooks installed in'}: ${settingsFile}`);
193
+
194
+ // ------------------------------------------------------------ shell alias
195
+ // Global install also aliases `claude` to the tmux wrapper so the phone can
196
+ // type into sessions. Marker-delimited block, removed cleanly on uninstall.
197
+ // Written to whichever rc file the user's login shell actually reads.
198
+
199
+ function rcTargets() {
200
+ const shell = path.basename(process.env.SHELL || '');
201
+ if (shell === 'zsh') return { shell, files: [path.join(HOME, '.zshrc')] };
202
+ if (shell === 'bash') {
203
+ const files = [path.join(HOME, '.bashrc'), path.join(HOME, '.bash_profile')].filter((f) => fs.existsSync(f));
204
+ return { shell, files: files.length ? files : [path.join(HOME, '.bash_profile')] };
205
+ }
206
+ if (shell === 'fish') return { shell, files: [path.join(HOME, '.config', 'fish', 'config.fish')] };
207
+ return { shell, files: [] };
208
+ }
209
+
210
+ function aliasBlock(shell) {
211
+ const line = shell === 'fish' ? `alias claude "${TMUX_WRAPPER}"` : `alias claude="${TMUX_WRAPPER}"`;
212
+ return [`# >>> ${MARKER} >>>`, line, `# <<< ${MARKER} <<<`].join('\n');
213
+ }
214
+
215
+ if (isGlobal) {
216
+ const { shell, files } = rcTargets();
217
+ if (!files.length) {
218
+ console.warn(`warning: unrecognized shell "${shell || '(unset $SHELL)'}" — add this alias to your shell config manually:`);
219
+ console.warn(` alias claude="${TMUX_WRAPPER}"`);
220
+ }
221
+ for (const rcFile of files) {
222
+ fs.mkdirSync(path.dirname(rcFile), { recursive: true });
223
+ let rc = fs.existsSync(rcFile) ? fs.readFileSync(rcFile, 'utf8') : '';
224
+ rc = rc.replace(new RegExp(`\\n?# >>> ${MARKER} >>>[\\s\\S]*?# <<< ${MARKER} <<<\\n?`, 'g'), '\n');
225
+ if (!uninstall) rc = `${rc.trimEnd()}\n\n${aliasBlock(shell)}\n`;
226
+ fs.writeFileSync(rcFile, rc);
227
+ console.log(`${uninstall ? 'alias removed from' : 'claude->tmux alias added to'}: ${rcFile}`);
228
+ }
229
+ }
230
+
231
+ // -------------------------------------------------------------- launchd
232
+
233
+ // process.execPath under nvm/fnm points at a version-specific directory that
234
+ // disappears on the next node upgrade, taking the daemon with it.
235
+ function stableNode() {
236
+ for (const candidate of ['/usr/local/bin/node', '/opt/homebrew/bin/node']) {
237
+ if (fs.existsSync(candidate)) return candidate;
238
+ }
239
+ return process.execPath;
240
+ }
241
+
242
+ if (isGlobal) {
243
+ const plistFile = path.join(HOME, 'Library', 'LaunchAgents', 'com.claude-bridge.daemon.plist');
244
+ const label = 'com.claude-bridge.daemon';
245
+ const uid = process.getuid();
246
+
247
+ const bootout = () => {
248
+ try { execFileSync('launchctl', ['bootout', `gui/${uid}/${label}`], { stdio: 'ignore' }); } catch {}
249
+ };
250
+
251
+ if (uninstall) {
252
+ bootout();
253
+ if (fs.existsSync(plistFile)) fs.unlinkSync(plistFile);
254
+ console.log('LaunchAgent removed');
255
+ } else {
256
+ const node = stableNode();
257
+ // launchd starts with a bare PATH; the daemon shells out to tmux and claude.
258
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
259
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
260
+ <plist version="1.0"><dict>
261
+ <key>Label</key><string>${label}</string>
262
+ <key>ProgramArguments</key><array>
263
+ <string>${node}</string>
264
+ <string>${path.join(ROOT, 'src', 'daemon.mjs')}</string>
265
+ </array>
266
+ <key>EnvironmentVariables</key><dict>
267
+ <key>PATH</key><string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
268
+ </dict>
269
+ <key>RunAtLoad</key><true/>
270
+ <key>KeepAlive</key><true/>
271
+ <key>StandardOutPath</key><string>${path.join(BRIDGE_DIR, 'launchd.log')}</string>
272
+ <key>StandardErrorPath</key><string>${path.join(BRIDGE_DIR, 'launchd.err')}</string>
273
+ </dict></plist>
274
+ `;
275
+ fs.mkdirSync(path.dirname(plistFile), { recursive: true });
276
+ fs.writeFileSync(plistFile, plist);
277
+ bootout();
278
+ execFileSync('launchctl', ['bootstrap', `gui/${uid}`, plistFile]);
279
+ console.log(`LaunchAgent installed + started: ${plistFile}`);
280
+ console.log(` node: ${node}`);
281
+ }
282
+ }