brickproof-adb 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/CHANGELOG.md ADDED
@@ -0,0 +1,36 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0 — 2026-10-21
4
+
5
+ Continues ha-adb-mcp 1.4.0: the same server and the same 18 tools, now a standalone npm package that runs on Windows, macOS and Linux, in Docker and as the Home Assistant app, with devices over USB and over the network.
6
+
7
+ ### Added
8
+ - **Runs anywhere Node runs.** `brickproof-adb` with no command is an MCP server on stdio for Claude Desktop, Claude Code and other local clients; `brickproof-adb serve` is MCP over Streamable HTTP. Only `adb` is needed next to it: the screenshot pipeline is plain JavaScript, no ImageMagick, no native modules.
9
+ - **Claude Desktop extension.** `brickproof-adb-1.0.0.mcpb` in the release installs with a short form (folders, safety switches, optional TV addresses) and needs no Node.js of its own.
10
+ - **Finding devices.** `adb_devices discover=true` finds phones with Wireless debugging (mDNS, through adb) and TV boxes with network debugging (port 5555 in the home network), and says the next step for each; it connects nothing.
11
+ - **Remembered devices.** A device connected with `adb_connect` is connected again at every start, and a new address of the same device replaces the old one; `adb_disconnect` with its address forgets it. When a remembered device drops during a call, the server reconnects once.
12
+ - **What can be installed.** `adb_install` without a path lists the APKs and bundles in the file folders, newest first, and installs nothing: "install what I just downloaded" works without knowing the file name.
13
+ - **adb found by itself** where Android Studio, WinGet, Homebrew or the system put it; **`brickproof-adb get-adb`** downloads Google's Platform-Tools after asking.
14
+ - **No settings file needed.** Files go to and from the Downloads folder by default. **`brickproof-adb set <key> <value>`** writes a setting; a refusal of a switched-off feature says where to turn it on.
15
+ - **`brickproof-adb check`** prints the settings, every adb on the machine with its version (and warns when they differ), a test run of the image pipeline with its timings, each file root, the snapshot store and the connected devices; `--offline` skips the devices. Exit code 1 on any problem.
16
+ - **Token for HTTP.** Generated on the first start and shown once; `brickproof-adb token` shows it again, `--new` replaces it. Accepted as the secret path `/private_<token>/mcp` or as `Authorization: Bearer <token>` on `/mcp`. A wrong path gets an empty 404, a wrong Bearer token 401. On a localhost bind a foreign `Host` or `Origin` gets 403; `allowed_hosts` names a tunnel's public host.
17
+ - **Protocol version header.** An unsupported `MCP-Protocol-Version` is refused with 400 and JSON-RPC error -32600; no header, or `initialize`, passes.
18
+ - **File roots.** `adb_push`, `adb_pull` and `adb_install` use only the host directories in `file_roots`. A path outside them, a sibling directory whose name starts like a root, or a symlink or junction leading out is refused; Windows and macOS compare without regard to letter case.
19
+ - **Another adb on the machine.** When a different adb restarts the adb server (Android Studio, scrcpy and vendor tools bring their own), the tool result says so and what to do.
20
+ - **Docker image** `ghcr.io/st412m/brickproof-adb` for linux/amd64 and linux/arm64, with adb; `compose.example.yaml` shows a complete setup. USB devices work on a Linux host.
21
+
22
+ ### Changed
23
+ - **Snapshots belong to the device, not to the connection.** One device over USB, over `ip:5555` and over wireless debugging shares one snapshot, so `adb_app action=restore` finds what was done over another connection. Snapshots of ha-adb-mcp 1.x are still read. A device without a usable serial number keeps a snapshot per connection, and the result says so.
24
+ - **`allow_shell` is off by default.** `adb_shell` bypasses every guard rail; turn it on when you need it.
25
+ - **A damaged snapshot file stops the call** before anything happens on the device; it is moved aside and kept, and `adb_app action=state` lists it.
26
+ - **`adb_ui_dump` leaves no files behind** on the device, also after a timeout: dump files older than two minutes are removed before the next dump.
27
+ - **Tool descriptions** say when to use a tool rather than its neighbour, and which tool undoes it; parameters have descriptions.
28
+ - Refusals name this server's settings (`allow_shell`, `allow_uninstall`, `file_roots`, `store`) instead of the Home Assistant options.
29
+
30
+ ### Fixed
31
+ - `adb_text` types quotes, backslashes and shell characters as they are; ha-adb-mcp 1.x put a stray backslash before `'`, `&`, `;` and others.
32
+ - `adb_text` with non-Latin text checks that ADBKeyBoard really became the input method, before and after typing; ha-adb-mcp 1.x reported the text as typed while a connected Google TV remote held the keyboard and nothing arrived.
33
+ - `adb_text` no longer says "Typed" when no on-screen keyboard is shown: the text is still sent, and the answer says it may have gone nowhere.
34
+ - `adb_find_and_tap` on a TV box picks the DPAD axis by where the target lies, not by the centres alone, and tries the other axis once before it gives up.
35
+ - `adb_ui_dump` tries once more after "null root node".
36
+ - `adb_app` and `adb_uninstall` count a change by the package list read afterwards, not by what `pm` prints: some firmware answers `pm disable-user` with a warning and does not always apply it, and ha-adb-mcp 1.x recorded it as applied either way.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 st412m
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,147 @@
1
- # Temporary Holding Version
1
+ <img src="https://raw.githubusercontent.com/st412m/brickproof-adb/main/icon.png" alt="" width="96" height="96">
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
+ # brickproof-adb
4
+
5
+ Let an AI assistant look after your own Android devices — TV boxes first, phones and tablets too — over ADB, without bricking them.
6
+
7
+ brickproof-adb is an MCP server. It gives Claude (or any MCP client) the screen, the input and the package manager of your devices, and puts guard rails where a careless call would hurt: every package change is a dry run first, the packages a device cannot live without are read off the device and refused, a package that serves something on your network right now is not touched, and everything applied goes into a snapshot that one call rolls back.
8
+
9
+ It runs on Windows, macOS and Linux, in Docker, and as a Home Assistant app; devices connect over USB or the network.
10
+
11
+ ## What it looks like
12
+
13
+ **Finding the TV.**
14
+
15
+ > **You:** Find my TV.
16
+ >
17
+ > **Claude** calls `adb_devices discover=true`. Nothing is connected yet; the search looks for devices that announce debugging and for port 5555 on the home network:
18
+ >
19
+ > ```
20
+ > Found:
21
+ > 192.0.2.50:5555 (port 5555 open, network debugging) - adb_connect host=192.0.2.50:5555; if this computer is new to the device, it asks on its screen to allow debugging
22
+ > ```
23
+ >
24
+ > **Claude:** I found one device at 192.0.2.50. Shall I connect? The TV will ask whether to allow debugging.
25
+ >
26
+ > **You:** Yes.
27
+ >
28
+ > **Claude** calls `adb_connect host=192.0.2.50:5555`; you confirm the prompt to allow debugging on the TV screen, with "Always allow" checked. The address is remembered and connected again whenever the server starts.
29
+
30
+ **Installing what you just downloaded.**
31
+
32
+ > **You:** Install on the TV the app I just downloaded.
33
+ >
34
+ > **Claude** calls `adb_install` without a path and gets the newest installable files of your Downloads folder, then `adb_install` with the first one: a report of what would be installed on which device. After your yes, the same call with `dry_run=false` installs it.
35
+
36
+ **Cleaning up a TV box.**
37
+
38
+ > **You:** The box is slow. Turn off the preinstalled junk, but nothing it needs.
39
+ >
40
+ > **Claude** calls `adb_app action=list filter=system`, picks five packages and calls `adb_app action=disable` with them. That is a dry run by default: the plan comes back with the rollback path of each package — and one package refused, because the box uses it as its launcher:
41
+ >
42
+ > ```
43
+ > REFUSED: the list contains protected packages - com.example.launcher.
44
+ > com.example.launcher — launcher, roles (HOME)
45
+ > The full set with every source: adb_app action=protected
46
+ > Nothing was applied. Remove them from the list by hand; the tool has no override.
47
+ > ```
48
+ >
49
+ > **Claude** drops it, runs the plan for the other four, then repeats it with `dry_run=false`. The account count and the launcher are checked after the batch, and the four packages are recorded in the snapshot.
50
+ >
51
+ > **You:** The voice remote stopped working.
52
+ >
53
+ > **Claude** calls `adb_app action=restore`, reads the plan and repeats it with `dry_run=false`: the four packages are enabled again in one call.
54
+
55
+ **Seeing the screen and tapping.**
56
+
57
+ > **You:** Open the network settings on the phone.
58
+ >
59
+ > **Claude** calls `adb_screenshot`, gets the picture and the line under it:
60
+ >
61
+ > ```
62
+ > screen 1080x2340 -> image 473x1024 · scale 2.283/2.285 · pass coords="screenshot" to adb_tap/adb_swipe
63
+ > ```
64
+ >
65
+ > and taps the "Network & internet" row it sees, with `adb_tap coords="screenshot"`, in the image's own coordinates. On a TV box without a touchscreen it uses `adb_find_and_tap text="Network"`, which walks the focus there with the remote's keys.
66
+
67
+ ## Install it where your AI is
68
+
69
+ Details, other setups and checks: [docs/installation.md](docs/installation.md). An AI app without MCP support cannot use this server.
70
+
71
+ - **Home Assistant** — install the [ha-adb-mcp](https://github.com/st412m/ha-adb-mcp) app. It is reachable from a browser chat through your Home Assistant's external address.
72
+ - **Claude Desktop** (Windows, macOS) — download the `.mcpb` file from the [latest release](https://github.com/st412m/brickproof-adb/releases/latest) and drag it into the Claude Desktop window, or choose it in Settings → Extensions → Advanced settings → Install Extension… (a double click works too, unless an archiver opens the file instead); Claude Desktop shows a short form and installs it. No Node.js needed. A JSON configuration instead: [docs/installation.md](docs/installation.md#claude-desktop).
73
+ - **Claude Code**:
74
+
75
+ ```
76
+ claude mcp add brickproof-adb -- npx -y brickproof-adb
77
+ ```
78
+
79
+ - **Other MCP clients on your computer** — the server command is `npx -y brickproof-adb`.
80
+ - **A chat in the browser without Home Assistant** — needs a computer at home that stays on, running `brickproof-adb serve`, behind a public HTTPS address: [docs/installation.md](docs/installation.md#a-browser-chat-without-home-assistant).
81
+ - **Docker** — `ghcr.io/st412m/brickproof-adb`: [docs/installation.md](docs/installation.md#docker).
82
+
83
+ ## First run
84
+
85
+ 1. **Turn on debugging on the device.** Android TV, Google TV, Fire TV and phones hide it under Developer options, which appear after tapping the build number seven times in the About screen of the settings. There: USB debugging for a cable; Network debugging or ADB debugging on many TV boxes; Wireless debugging on a phone with Android 11 or newer.
86
+ 2. **Tell the assistant "find my TV"** (or phone). It searches the network and suggests what to connect; a phone on a cable shows up by itself.
87
+ 3. **Confirm the prompt to allow debugging on the device screen**, with "Always allow" checked. A phone over Wi-Fi asks for the pairing code shown on its screen instead.
88
+
89
+ Defaults that need no setting: files go to and from your Downloads folder, connected devices are remembered, and adb is found by itself (or `brickproof-adb get-adb` downloads it).
90
+
91
+ ## Requirements
92
+
93
+ - Node.js 22.17 or newer — for every setup except the Claude Desktop extension, Home Assistant and Docker.
94
+ - adb (Android SDK Platform-Tools): found by itself where Android Studio, WinGet, Homebrew or your system put it, or downloaded with `brickproof-adb get-adb`. Docker and Home Assistant bring their own.
95
+ - A device with debugging on, over USB or the network.
96
+
97
+ ## Connecting
98
+
99
+ Over stdio (Claude Desktop, Claude Code) there is nothing to connect: the client starts the server. Over HTTP (`brickproof-adb serve`) the token goes either in the path or in a header:
100
+
101
+ ```
102
+ https://<your-host>/private_<token>/mcp
103
+ Authorization: Bearer <token>
104
+ ```
105
+
106
+ The token is generated on the first start; `brickproof-adb token` shows it again, `brickproof-adb token --new` replaces it. See [docs/security.md](docs/security.md).
107
+
108
+ ## Tools
109
+
110
+ 18 tools. Semantics, refusals and time limits: [docs/tools.md](docs/tools.md); screen geometry and input: [docs/screen-and-input.md](docs/screen-and-input.md).
111
+
112
+ - `adb_devices` — connected and remembered devices; `discover=true` searches the network
113
+ - `adb_connect` — connect a network device, `ip` or `ip:port`; remembered for the next start
114
+ - `adb_disconnect` — drop one network device (and forget it), or all
115
+ - `adb_pair` — pair an Android 11+ device over Wireless debugging
116
+ - `adb_shell` — any shell command; off unless `allow_shell` is set
117
+ - `adb_logcat` — recent log lines, filtered on the device
118
+ - `adb_screenshot` — the screen as JPEG, with the scale to tap by
119
+ - `adb_ui_dump` — on-screen elements with tap coordinates
120
+ - `adb_tap` — tap a point, in screen or screenshot coordinates
121
+ - `adb_swipe` — swipe or long-press
122
+ - `adb_key` — a key press (HOME, BACK, DPAD_CENTER…)
123
+ - `adb_text` — type into the focused field, Unicode through ADBKeyBoard
124
+ - `adb_find_and_tap` — find an element by its label and activate it
125
+ - `adb_install` — install an APK, a split set or an `.apks`/`.xapk`/`.apkm` bundle; dry run by default; without a path, lists what can be installed
126
+ - `adb_uninstall` — remove an app by package name
127
+ - `adb_app` — package operations with guard rails, snapshot and rollback
128
+ - `adb_push` — copy a file to the device
129
+ - `adb_pull` — copy a file from the device
130
+
131
+ ## Safety
132
+
133
+ What protects your devices, and what does not: [docs/safety.md](docs/safety.md). In short: dry runs by default, a protected set read off the device, a network guard on live services, an account canary between batches, a snapshot with one-call rollback, and `adb_shell` and uninstalling off until you turn them on. No tool changes these switches; you do, with `brickproof-adb set` or in the settings of your app.
134
+
135
+ ## Limitations
136
+
137
+ - ADB is not a sandbox. With `allow_shell` on, `adb_shell` can do anything the device's shell user can, past every guard.
138
+ - The search finds devices on the same network only: a guest network, Wi-Fi client isolation or separate VLANs hide them. In Docker and Home Assistant only TV boxes on port 5555 are found; phones connect by the address on their screen.
139
+ - The tool list is cached per chat; after an update start a new chat.
140
+ - A screenshot of a sleeping device is a dark frame, and the answer says `screen: Asleep`; `adb_key key=WAKEUP` wakes it, and HDMI-CEC may then switch on the television.
141
+ - Content protected with FLAG_SECURE (streaming players, banking apps) shows as a black frame.
142
+ - Snapshots live on the machine that made them: a rollback has to run where the change was made.
143
+ - USB devices in Docker work only on a Linux host.
144
+
145
+ ## License
146
+
147
+ [MIT](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "brickproof-adb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "mcpName": "io.github.st412m/brickproof-adb",
5
+ "description": "Lets an AI assistant look after your own Android devices over ADB without bricking them.",
6
+ "license": "MIT",
7
+ "author": "st412m",
8
+ "homepage": "https://github.com/st412m/brickproof-adb#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/st412m/brickproof-adb.git"
12
+ },
13
+ "bugs": "https://github.com/st412m/brickproof-adb/issues",
14
+ "keywords": [
15
+ "mcp",
16
+ "model-context-protocol",
17
+ "adb",
18
+ "android",
19
+ "android-tv",
20
+ "claude"
21
+ ],
22
+ "type": "commonjs",
23
+ "bin": {
24
+ "brickproof-adb": "src/main.js"
25
+ },
26
+ "files": [
27
+ "src/",
28
+ "README.md",
29
+ "CHANGELOG.md",
30
+ "LICENSE"
31
+ ],
32
+ "engines": {
33
+ "node": ">=22.17"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test \"test/*.test.js\""
37
+ },
38
+ "dependencies": {
39
+ "jpeg-js": "0.4.4",
40
+ "pngjs": "7.0.0"
41
+ }
42
+ }
package/src/adb.js ADDED
@@ -0,0 +1,376 @@
1
+ 'use strict';
2
+ /**
3
+ * adb.js — the adb binary and everything around it that knows nothing about
4
+ * particular tools: running commands, turning typical failures into advice,
5
+ * quoting for the device shell, client argument coercion, host temp dirs.
6
+ *
7
+ * Every adb call goes through run(): adb() for buffered output, spawnAdb() for
8
+ * a stream (the screenshot). The server never starts, stops or moves the adb
9
+ * server: the first client call starts it on 127.0.0.1:5037 if it is not
10
+ * running, and that server is shared with the user's own adb.
11
+ */
12
+
13
+ const { execFile, spawn } = require('child_process');
14
+ const { AsyncLocalStorage } = require('async_hooks');
15
+ const fs = require('fs');
16
+ const os = require('os');
17
+ const path = require('path');
18
+
19
+ const ADB_TIMEOUT_MS = 30000;
20
+ const ADB_MAX_BUFFER = 16 * 1024 * 1024;
21
+
22
+ // The binary: adb_path, or "adb" looked up on PATH (libuv finds adb.exe on
23
+ // Windows). PREFIX is empty in production; tests put a script there.
24
+ let ADB_BIN = 'adb';
25
+ let ADB_PREFIX = [];
26
+
27
+ function configure({ adbPath } = {}) {
28
+ ADB_BIN = adbPath || 'adb';
29
+ ADB_PREFIX = [];
30
+ }
31
+
32
+ /**
33
+ * Tests only: run `bin prefix... <adb args>` instead of adb, e.g.
34
+ * (process.execPath, ['test/fake-adb.js']). A script cannot be adb_path on
35
+ * Windows (execFile runs no .js or .cmd without a shell), so the fake adb is
36
+ * started through node. Not a setting, not an environment variable.
37
+ */
38
+ function useTestRunner(bin, prefix = []) {
39
+ ADB_BIN = bin;
40
+ ADB_PREFIX = prefix.slice();
41
+ }
42
+
43
+ function adbBinary() {
44
+ return ADB_BIN;
45
+ }
46
+
47
+ // ---------------------------------------------------------------- call notes
48
+ // Warnings that belong to the whole tool call rather than to one adb command
49
+ // (another adb restarted the server). server.js collects them per call and
50
+ // appends them to the result.
51
+
52
+ const callNotes = new AsyncLocalStorage();
53
+
54
+ async function collectNotes(fn) {
55
+ const notes = new Set();
56
+ try {
57
+ const value = await callNotes.run(notes, fn);
58
+ return { value, notes: [...notes] };
59
+ } catch (e) {
60
+ e.adbNotes = [...notes];
61
+ throw e;
62
+ }
63
+ }
64
+
65
+ function addNote(msg) {
66
+ const store = callNotes.getStore();
67
+ if (store) store.add(msg);
68
+ }
69
+
70
+ // The client prints this to stderr when its version differs from the running
71
+ // server's, then kills that server and starts its own; network devices drop.
72
+ // The numbers are the protocol version: two builds of one protocol print the
73
+ // same number twice.
74
+ const FOREIGN_ADB_RE = /adb server version \((\d+)\) doesn't match this client \((\d+)\)/;
75
+
76
+ function foreignAdbWarning(stderr) {
77
+ const m = FOREIGN_ADB_RE.exec(String(stderr || ''));
78
+ if (!m) return null;
79
+ const versions = m[1] !== m[2] ? ` (server version ${m[1]}, client version ${m[2]})` : '';
80
+ return `⚠ the adb server was started by another adb on this machine and this client restarted it${versions}, ` +
81
+ 'so network devices may need adb_connect again. Set adb_path to the same adb your other programs use (Android Studio, scrcpy, vendor tools); `brickproof-adb check` lists every adb it finds.';
82
+ }
83
+
84
+ /**
85
+ * `<bin> version` of any adb found on the machine, for `check`: { ok, build,
86
+ * protocol, error }. The only adb call that does not use the configured
87
+ * binary.
88
+ */
89
+ function adbVersionOf(bin, timeout = 10000) {
90
+ return new Promise(resolve => {
91
+ execFile(bin, ['version'], { timeout, windowsHide: true }, (err, stdout) => {
92
+ if (err) return resolve({ ok: false, error: err.code || err.message });
93
+ const out = String(stdout || '');
94
+ const protocol = (/Android Debug Bridge version (\S+)/.exec(out) || [])[1] || null;
95
+ const build = (/^Version (\S+)/m.exec(out) || [])[1] || null;
96
+ resolve({ ok: true, protocol, build });
97
+ });
98
+ });
99
+ }
100
+
101
+ function noteForeignAdb(stderr) {
102
+ const w = foreignAdbWarning(stderr);
103
+ if (w) addNote(w);
104
+ }
105
+
106
+ // ------------------------------------------------------------------ failures
107
+
108
+ function installHint(platform = process.platform) {
109
+ const cmd = platform === 'win32' ? 'winget install Google.PlatformTools'
110
+ : platform === 'darwin' ? 'brew install --cask android-platform-tools'
111
+ : 'the adb or android-tools package of your distribution';
112
+ return 'Run `brickproof-adb get-adb` to download Google\'s platform-tools, ' +
113
+ `or install them yourself (${cmd}; https://developer.android.com/tools/releases/platform-tools), ` +
114
+ 'or set adb_path to the adb executable.';
115
+ }
116
+
117
+ // Typical adb errors get the action that fixes them.
118
+ function friendlyAdbError(msg) {
119
+ if (/device '.*' not found|no devices\/emulators found/i.test(msg))
120
+ return `${msg}. Call adb_devices to list what is connected; network devices may need adb_connect first (wireless-debug ports change after phone reboot). ` +
121
+ 'A device that is not in that list: adb_devices discover=true searches the network for it.';
122
+ if (/device offline/i.test(msg))
123
+ return `${msg}. The TCP session died (device slept or rebooted) - run adb_disconnect for this host, then adb_connect again.`;
124
+ if (/device unauthorized|failed to authenticate/i.test(msg))
125
+ return `${msg}. Confirm the prompt to allow debugging on the device screen (check "Always allow").`;
126
+ if (/INSTALL_FAILED_VERIFICATION_FAILURE/i.test(msg))
127
+ return `${msg}. The on-device package verifier rejects ADB installs - disable it once via adb_shell (needs allow_shell): settings put global verifier_verify_adb_installs 0`;
128
+ return msg;
129
+ }
130
+
131
+ /**
132
+ * The text of a failed adb call, built from the execFile fields. A non-empty
133
+ * stderr is the message (plus the stdout tail). With an empty stderr only the
134
+ * adb subcommand is named, never the argv: the argv carries call arguments
135
+ * (typed text, pairing codes).
136
+ *
137
+ * ⚠ maxBuffer is checked first: Node reports it as the string code
138
+ * ERR_CHILD_PROCESS_STDIO_MAXBUFFER without `killed`, which would otherwise
139
+ * read as "adb could not start".
140
+ */
141
+ function describeAdbFailure(err, stderr, stdout, args, opts = {}) {
142
+ const raw = (stderr || '').toString();
143
+ // "* daemon not running; starting now", "* daemon started successfully":
144
+ // progress of the adb server start, never the cause of a failure.
145
+ let msg = raw.split(/\r?\n/).filter(l => !/^\s*\* daemon /i.test(l)).join('\n').trim();
146
+ const out = opts.binary ? '' : (stdout || '').toString().trim();
147
+ const a = args || [];
148
+ const sub = (a[0] === '-s' ? a[2] : a[0]) || '(no subcommand)';
149
+ const e = err || {};
150
+ const secs = +((opts.timeout || ADB_TIMEOUT_MS) / 1000).toFixed(3);
151
+ if (e.killed === true && /daemon not running; starting now/i.test(raw))
152
+ msg = `adb ${sub} timed out after ${secs} s: the adb server was still starting (it can take about 20 s on Windows); call again`;
153
+ if (!msg) {
154
+ if (e.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER')
155
+ msg = `adb ${sub} output exceeded ${ADB_MAX_BUFFER / 1024 / 1024} MB and was killed`;
156
+ else if (e.killed === true)
157
+ msg = `adb ${sub} timed out after ${secs} s and was killed${e.signal ? ` (${e.signal})` : ''}`;
158
+ else if (e.signal)
159
+ msg = `adb ${sub} was terminated by ${e.signal}`;
160
+ else if (typeof e.code === 'number')
161
+ msg = out ? `adb ${sub} exited with code ${e.code}` : `adb ${sub} exited with code ${e.code} and printed nothing`;
162
+ else if (e.code === 'ENOENT')
163
+ msg = `adb could not start: ENOENT - adb was not found (adb_path: ${JSON.stringify(ADB_BIN)}). ${installHint()}`;
164
+ else if (e.code === 'EINVAL' && process.platform === 'win32')
165
+ msg = 'adb could not start: EINVAL - adb_path must point to the adb executable (adb.exe), not to a .cmd or .bat file';
166
+ else if (typeof e.code === 'string')
167
+ msg = `adb could not start: ${e.code}`;
168
+ else
169
+ msg = `adb ${sub} failed without output`;
170
+ }
171
+ // stdout is kept on a non-zero exit: a failed device pipeline is unreadable
172
+ // without its output.
173
+ if (out) msg = `${msg}\nstdout (tail): ${out.slice(-2000)}`;
174
+ return friendlyAdbError(msg);
175
+ }
176
+
177
+ // --------------------------------------------------------------------- calls
178
+
179
+ function adb(args, opts = {}) {
180
+ return new Promise((resolve, reject) => {
181
+ execFile(ADB_BIN, [...ADB_PREFIX, ...args], {
182
+ timeout: opts.timeout || ADB_TIMEOUT_MS,
183
+ maxBuffer: ADB_MAX_BUFFER,
184
+ encoding: opts.binary ? 'buffer' : 'utf8',
185
+ windowsHide: true,
186
+ }, (err, stdout, stderr) => {
187
+ noteForeignAdb(stderr);
188
+ if (err) return reject(new Error(describeAdbFailure(err, stderr, stdout, args, opts)));
189
+ resolve(opts.withStderr ? { stdout, stderr } : stdout);
190
+ });
191
+ });
192
+ }
193
+
194
+ /**
195
+ * adb with stdout going straight into a file descriptor (the screenshot PNG):
196
+ * the bytes never pass through this process. Resolves { code, signal,
197
+ * timedOut, stderr }; rejects only when adb cannot be started.
198
+ */
199
+ function spawnAdb(args, outFd, opts = {}) {
200
+ const timeout = opts.timeout || ADB_TIMEOUT_MS;
201
+ return new Promise((resolve, reject) => {
202
+ let child;
203
+ try {
204
+ child = spawn(ADB_BIN, [...ADB_PREFIX, ...args], { stdio: ['ignore', outFd, 'pipe'], windowsHide: true });
205
+ } catch (e) {
206
+ reject(new Error(describeAdbFailure(e, '', '', args, opts)));
207
+ return;
208
+ }
209
+ let stderr = '';
210
+ let timedOut = false;
211
+ let settled = false;
212
+ const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeout);
213
+ child.stderr.on('data', c => { if (stderr.length < 64 * 1024) stderr += c; });
214
+ child.on('error', e => {
215
+ clearTimeout(timer);
216
+ if (settled) return;
217
+ settled = true;
218
+ reject(new Error(describeAdbFailure(e, '', '', args, opts)));
219
+ });
220
+ child.on('close', (code, signal) => {
221
+ clearTimeout(timer);
222
+ if (settled) return;
223
+ settled = true;
224
+ noteForeignAdb(stderr);
225
+ resolve({ code, signal, timedOut, stderr });
226
+ });
227
+ });
228
+ }
229
+
230
+ function withSerial(serial, args) {
231
+ return serial ? ['-s', serial, ...args] : args;
232
+ }
233
+
234
+ // Single quotes for the DEVICE shell.
235
+ function sq(x) {
236
+ return `'${String(x).replace(/'/g, `'\\''`)}'`;
237
+ }
238
+
239
+ /**
240
+ * Run a command in the device shell and return stdout as a string.
241
+ *
242
+ * ⚠ tolerant (on by default) appends `; :`. Without it the last command of a
243
+ * chain sets the exit code, and a grep with no match (exit 1) fails the whole
244
+ * call with a useless "Command failed".
245
+ */
246
+ async function adbSh(serial, cmd, opts = {}) {
247
+ const body = opts.tolerant === false ? cmd : `${cmd}; :`;
248
+ const out = await adb(withSerial(serial, ['shell', body]), opts);
249
+ return out.toString();
250
+ }
251
+
252
+ function text(t) { return [{ type: 'text', text: t }]; }
253
+
254
+ function json(obj) { return text(JSON.stringify(obj, null, 2)); }
255
+
256
+ // The argument of `input text`, before sq() quotes it for the device shell.
257
+ // `input text` (Input.java up to SDK 30, InputShellCommand from SDK 31) has
258
+ // one rule of its own: "%s" is a space. Every other character is typed as it
259
+ // is, so nothing else is escaped; a space becomes %s, as it always worked.
260
+ function escapeInputText(s) {
261
+ return s.replace(/ /g, '%s');
262
+ }
263
+
264
+ // Some MCP clients send array parameters as JSON strings.
265
+ function coerceArray(v) {
266
+ if (v === undefined || v === null) return [];
267
+ if (Array.isArray(v)) return v;
268
+ if (typeof v === 'string') {
269
+ const s = v.trim();
270
+ if (s.startsWith('[') && s.endsWith(']')) {
271
+ try {
272
+ const parsed = JSON.parse(s);
273
+ if (Array.isArray(parsed)) return parsed;
274
+ } catch { /* not JSON: a single value */ }
275
+ }
276
+ }
277
+ return [v];
278
+ }
279
+
280
+ // The same for booleans: "true"/"false" strings.
281
+ function coerceBool(v, dflt) {
282
+ if (v === undefined || v === null || v === '') return dflt;
283
+ if (typeof v === 'boolean') return v;
284
+ return String(v).toLowerCase() === 'true';
285
+ }
286
+
287
+ // The same for objects (adb_app action=launch extras): a JSON string is accepted.
288
+ function coerceObject(v) {
289
+ if (v === undefined || v === null) return {};
290
+ if (typeof v === 'object' && !Array.isArray(v)) return v;
291
+ if (typeof v === 'string') {
292
+ const s = v.trim();
293
+ if (!s) return {};
294
+ if (s.startsWith('{') && s.endsWith('}')) {
295
+ try {
296
+ const parsed = JSON.parse(s);
297
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;
298
+ } catch { /* not JSON: refused below */ }
299
+ }
300
+ }
301
+ throw new Error(`extras: expected a key-value object, got ${JSON.stringify(v).slice(0, 120)}`);
302
+ }
303
+
304
+ function ensureDir(p) {
305
+ fs.mkdirSync(p, { recursive: true });
306
+ return p;
307
+ }
308
+
309
+ // A serial as a directory name: 192.0.2.50:5555 -> 192.0.2.50_5555. Trailing
310
+ // dots are dropped, Windows would drop them silently.
311
+ function sanitizeSerial(serial) {
312
+ const s = String(serial || 'default').replace(/[^\w.\-]+/g, '_').replace(/\.+$/, '');
313
+ return s || '_';
314
+ }
315
+
316
+ const RENAME_RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
317
+ const RENAME_RETRIES = 5;
318
+
319
+ /**
320
+ * rename() with retries for a target held open by another process (an
321
+ * antivirus or indexer on Windows): up to RENAME_RETRIES more attempts with a
322
+ * growing pause, one stderr line per retry. Other errors throw at once.
323
+ */
324
+ async function renameWithRetry(from, to, {
325
+ fsImpl = fs, retries = RENAME_RETRIES, delayMs = 100,
326
+ sleep = ms => new Promise(r => setTimeout(r, ms)),
327
+ log = line => process.stderr.write(line + '\n'),
328
+ } = {}) {
329
+ for (let attempt = 0; ; attempt++) {
330
+ try {
331
+ fsImpl.renameSync(from, to);
332
+ return attempt;
333
+ } catch (e) {
334
+ if (!RENAME_RETRY_CODES.has(e.code) || attempt >= retries) throw e;
335
+ log(`brickproof-adb: rename ${from} -> ${to} failed with ${e.code}, retry ${attempt + 1}/${retries}`);
336
+ await sleep(delayMs * (attempt + 1));
337
+ }
338
+ }
339
+ }
340
+
341
+ // ------------------------------------------------------------ host temp dirs
342
+ // Every temporary directory on the host is <tmpdir>/brickproof-*, removed in
343
+ // a finally; sweepTempDirs() at start removes those left by a killed process.
344
+
345
+ const TEMP_PREFIX = 'brickproof-';
346
+
347
+ function makeTempDir(kind = '') {
348
+ return fs.mkdtempSync(path.join(os.tmpdir(), `${TEMP_PREFIX}${kind}`));
349
+ }
350
+
351
+ function sweepTempDirs({ maxAgeMs = 3600000, dir = os.tmpdir(), now = Date.now() } = {}) {
352
+ const removed = [];
353
+ let names = [];
354
+ try { names = fs.readdirSync(dir); } catch { return removed; }
355
+ for (const n of names) {
356
+ if (!n.startsWith(TEMP_PREFIX)) continue;
357
+ const full = path.join(dir, n);
358
+ try {
359
+ const st = fs.lstatSync(full);
360
+ if (!st.isDirectory() || now - st.mtimeMs < maxAgeMs) continue;
361
+ fs.rmSync(full, { recursive: true, force: true });
362
+ removed.push(full);
363
+ } catch { /* another process, or no permission: leave it */ }
364
+ }
365
+ return removed;
366
+ }
367
+
368
+ module.exports = {
369
+ ADB_TIMEOUT_MS, ADB_MAX_BUFFER, TEMP_PREFIX,
370
+ configure, useTestRunner, adbBinary,
371
+ adb, spawnAdb, adbSh, withSerial, friendlyAdbError, describeAdbFailure, installHint,
372
+ collectNotes, addNote, foreignAdbWarning, FOREIGN_ADB_RE, adbVersionOf,
373
+ sq, text, json, escapeInputText,
374
+ coerceArray, coerceBool, coerceObject,
375
+ ensureDir, sanitizeSerial, makeTempDir, sweepTempDirs, renameWithRetry,
376
+ };