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.
@@ -0,0 +1,258 @@
1
+ 'use strict';
2
+ /**
3
+ * platform-tools.js — where adb is, and `brickproof-adb get-adb`.
4
+ *
5
+ * findAdb() only checks that files exist; it never runs adb, so the server
6
+ * starts and lists its tools without adb. Order:
7
+ * adb_path (when set) → <state_dir>/platform-tools → PATH → Android SDK
8
+ * (ANDROID_HOME, ANDROID_SDK_ROOT, the Android Studio default) → WinGet →
9
+ * Homebrew.
10
+ *
11
+ * get-adb downloads Google's platform-tools zip into a temporary directory
12
+ * under state_dir, unpacks it with the ZIP reader of files.js, and replaces
13
+ * <state_dir>/platform-tools as a whole; nothing partial is left behind.
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+ const https = require('https');
20
+ const crypto = require('crypto');
21
+ const { zipEntries, zipRead } = require('./files.js');
22
+
23
+ const PLATFORM_ZIP = {
24
+ win32: 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip',
25
+ darwin: 'https://dl.google.com/android/repository/platform-tools-latest-darwin.zip',
26
+ linux: 'https://dl.google.com/android/repository/platform-tools-latest-linux.zip',
27
+ };
28
+ const LICENSE_URL = 'https://developer.android.com/studio/releases/platform-tools';
29
+
30
+ function exeName(platform = process.platform) {
31
+ return platform === 'win32' ? 'adb.exe' : 'adb';
32
+ }
33
+
34
+ function isExecutableFile(p, platform = process.platform) {
35
+ try {
36
+ if (!fs.statSync(p).isFile()) return false;
37
+ if (platform !== 'win32') fs.accessSync(p, fs.constants.X_OK);
38
+ return true;
39
+ } catch { return false; }
40
+ }
41
+
42
+ // A bare command name on PATH (PATHEXT on Windows).
43
+ function onPath(name, { env = process.env, platform = process.platform, exists = isExecutableFile } = {}) {
44
+ const P = platform === 'win32' ? path.win32 : path.posix;
45
+ const sep = platform === 'win32' ? ';' : ':';
46
+ const exts = platform === 'win32' && !/\.[A-Za-z0-9]+$/.test(name)
47
+ ? (env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(e => /^\.(exe|com)$/i.test(e)).map(e => e.toLowerCase())
48
+ : [''];
49
+ for (const dir of String(env.PATH || env.Path || '').split(sep).filter(Boolean)) {
50
+ for (const ext of exts) {
51
+ const p = P.join(dir, name + ext);
52
+ if (exists(p)) return p;
53
+ }
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Every place adb may be, in order, with what is there: [{ path, source,
60
+ * found }]; one file found by several paths is one place. `chosen` is
61
+ * adb_path when it is set, else the first found; null when none is.
62
+ * `exists`, `list` and `realpath` are the file system, replaceable in tests.
63
+ */
64
+ function findAdb({ adbPath = 'adb', adbPathSource = 'default', stateDir, env = process.env, platform = process.platform,
65
+ homedir = os.homedir(), exists = p => isExecutableFile(p, platform), list = dir => { try { return fs.readdirSync(dir); } catch { return []; } },
66
+ realpath = p => fs.realpathSync.native(p) } = {}) {
67
+ const P = platform === 'win32' ? path.win32 : path.posix;
68
+ const exe = exeName(platform);
69
+ const places = [];
70
+ const add = (p, source) => { if (p) places.push({ path: p, source }); };
71
+
72
+ const userSet = adbPathSource !== 'default';
73
+ if (userSet) {
74
+ if (/[\\/]/.test(adbPath)) add(adbPath, `adb_path (${adbPathSource})`);
75
+ else add(onPath(adbPath, { env, platform, exists }) || adbPath, `adb_path (${adbPathSource}) on PATH`);
76
+ }
77
+ if (stateDir) add(P.join(stateDir, 'platform-tools', exe), 'get-adb');
78
+ const onPathHit = onPath('adb', { env, platform, exists });
79
+ // PATH is a place even without a hit: the list of where adb was looked for
80
+ // names it (lookedIn).
81
+ const pathAt = places.length;
82
+ add(onPathHit, 'PATH');
83
+ const v = name => (env[name] && P.isAbsolute(env[name]) ? env[name] : null);
84
+ for (const [root, source] of [[v('ANDROID_HOME'), 'ANDROID_HOME'], [v('ANDROID_SDK_ROOT'), 'ANDROID_SDK_ROOT']]) {
85
+ if (root) add(P.join(root, 'platform-tools', exe), source);
86
+ }
87
+ const local = v('LOCALAPPDATA') || P.join(homedir, 'AppData', 'Local');
88
+ if (platform === 'win32') add(P.join(local, 'Android', 'Sdk', 'platform-tools', exe), 'Android Studio SDK');
89
+ if (platform === 'darwin') add(P.join(homedir, 'Library', 'Android', 'sdk', 'platform-tools', exe), 'Android Studio SDK');
90
+ if (platform === 'linux') add(P.join(homedir, 'Android', 'Sdk', 'platform-tools', exe), 'Android Studio SDK');
91
+ if (platform === 'win32') {
92
+ add(P.join(local, 'Microsoft', 'WinGet', 'Links', exe), 'WinGet');
93
+ const pkgs = P.join(local, 'Microsoft', 'WinGet', 'Packages');
94
+ for (const d of list(pkgs).filter(n => /^Google\.PlatformTools_/.test(n)).sort())
95
+ add(P.join(pkgs, d, 'platform-tools', exe), 'WinGet');
96
+ }
97
+ if (platform === 'darwin') {
98
+ add('/opt/homebrew/bin/adb', 'Homebrew');
99
+ add('/usr/local/bin/adb', 'Homebrew');
100
+ }
101
+ for (const p of places) p.found = exists(p.path);
102
+ const merged = mergeSameFile(places, { platform, realpath });
103
+ // An adb_path someone set is used as it is, found or not: silently taking
104
+ // another adb instead would bring back the version clash it was set to
105
+ // avoid. Otherwise the first one found.
106
+ const chosen = userSet ? merged[0] : (merged.find(p => p.found) || null);
107
+ // The place that comes right after PATH in the search, for lookedIn().
108
+ const afterPath = onPathHit ? null : places[pathAt] || null;
109
+ return { places: merged, chosen, userSet, pathMissed: !onPathHit, afterPath };
110
+ }
111
+
112
+ /**
113
+ * Where adb was looked for, in the order of the search, for `check`: the
114
+ * paths, with "PATH (no adb there)" in its place when PATH had none.
115
+ */
116
+ function lookedIn(found) {
117
+ const out = found.places.map(p => p.path);
118
+ if (found.pathMissed) {
119
+ const i = found.afterPath ? found.places.indexOf(found.afterPath) : -1;
120
+ out.splice(i === -1 ? out.length : i, 0, 'PATH (no adb there)');
121
+ }
122
+ return out;
123
+ }
124
+
125
+ // One file reached by several paths (another case of the drive letter, a
126
+ // symlink) is one place, at its first path, with every source: "PATH, Android
127
+ // Studio SDK". Compared by realpath; without case on Windows and macOS.
128
+ function mergeSameFile(places, { platform = process.platform, realpath = p => fs.realpathSync.native(p) } = {}) {
129
+ const fold = platform === 'win32' || platform === 'darwin';
130
+ const byKey = new Map();
131
+ const out = [];
132
+ for (const p of places) {
133
+ let key = p.path;
134
+ if (p.found) { try { key = realpath(p.path); } catch {} }
135
+ if (fold) key = key.toLowerCase();
136
+ const first = byKey.get(key);
137
+ if (!first) { byKey.set(key, p); out.push(p); continue; }
138
+ if (!first.source.split(', ').includes(p.source)) first.source += `, ${p.source}`;
139
+ }
140
+ return out;
141
+ }
142
+
143
+ /**
144
+ * The adb the server uses: the first one found, else the setting as it is
145
+ * (so the error says what was looked for).
146
+ */
147
+ function resolveAdbPath(settings, sources, opts = {}) {
148
+ const r = findAdb({ adbPath: settings.adb_path, adbPathSource: sources ? sources.adb_path : 'default', stateDir: settings.state_dir, ...opts });
149
+ return { path: r.chosen ? r.chosen.path : settings.adb_path, source: r.chosen ? r.chosen.source : 'not found', ...r };
150
+ }
151
+
152
+ // ------------------------------------------------------------------ get-adb
153
+
154
+ /** Why get-adb cannot run here, or null. */
155
+ function getAdbRefusal(platform = process.platform, arch = process.arch) {
156
+ if (!PLATFORM_ZIP[platform]) return `Google publishes platform-tools for Windows, macOS and Linux only, not for ${platform}`;
157
+ if (platform === 'linux' && arch !== 'x64')
158
+ return `Google publishes platform-tools for Linux on x86_64 only, this machine is ${arch}. Install your distribution's package instead, ` +
159
+ 'e.g. `sudo apt install adb` (Debian, Ubuntu), `sudo dnf install android-tools` (Fedora) or `sudo pacman -S android-tools` (Arch)';
160
+ return null;
161
+ }
162
+
163
+ /**
164
+ * A safe relative path for a ZIP entry under a directory: forward or back
165
+ * slashes as separators; an absolute name, a drive, "..", ":" or NUL is
166
+ * refused, and the result must stay inside `dir`. null for a directory entry.
167
+ */
168
+ function safeEntryPath(dir, name) {
169
+ const parts = String(name).split(/[\\/]+/);
170
+ const isDirEntry = /[\\/]$/.test(name);
171
+ if (/^[\\/]/.test(name) || parts.some(p => p === '..' || /[:\0]/.test(p)))
172
+ throw new Error(`unsafe file name in the archive: ${JSON.stringify(String(name)).slice(0, 120)}`);
173
+ const clean = parts.filter(p => p && p !== '.');
174
+ if (!clean.length) return null;
175
+ const full = path.join(dir, ...clean);
176
+ const rel = path.relative(dir, full);
177
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) throw new Error(`unsafe file name in the archive: ${JSON.stringify(String(name)).slice(0, 120)}`);
178
+ return { full, isDir: isDirEntry };
179
+ }
180
+
181
+ /**
182
+ * Unpack a ZIP buffer into `dir`. Unix modes of the entries are kept on POSIX
183
+ * (adb needs its execute bit); symlinks are refused. Returns the file count.
184
+ */
185
+ function extractZip(buf, dir, { platform = process.platform } = {}) {
186
+ let files = 0;
187
+ for (const e of zipEntries(buf)) {
188
+ const target = safeEntryPath(dir, e.name);
189
+ if (!target) continue;
190
+ const unixMode = (e.attr >>> 16) & 0xffff;
191
+ if ((unixMode & 0o170000) === 0o120000) throw new Error(`the archive holds a symlink, which is not unpacked: ${e.name}`);
192
+ if (target.isDir || (unixMode & 0o170000) === 0o040000) { fs.mkdirSync(target.full, { recursive: true }); continue; }
193
+ fs.mkdirSync(path.dirname(target.full), { recursive: true });
194
+ fs.writeFileSync(target.full, zipRead(buf, e));
195
+ if (platform !== 'win32') {
196
+ const mode = unixMode & 0o777;
197
+ fs.chmodSync(target.full, mode ? mode | 0o600 : 0o644);
198
+ }
199
+ files++;
200
+ }
201
+ return files;
202
+ }
203
+
204
+ /** GET with redirects, into a Buffer. */
205
+ function download(url, { maxRedirects = 5, timeoutMs = 120000 } = {}) {
206
+ return new Promise((resolve, reject) => {
207
+ const req = https.get(url, { timeout: timeoutMs }, res => {
208
+ if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) {
209
+ res.resume();
210
+ if (!maxRedirects) return reject(new Error('too many redirects'));
211
+ return resolve(download(new URL(res.headers.location, url).href, { maxRedirects: maxRedirects - 1, timeoutMs }));
212
+ }
213
+ if (res.statusCode !== 200) { res.resume(); return reject(new Error(`HTTP ${res.statusCode} from ${url}`)); }
214
+ const chunks = [];
215
+ res.on('data', c => chunks.push(c));
216
+ res.on('end', () => resolve(Buffer.concat(chunks)));
217
+ res.on('error', reject);
218
+ });
219
+ req.on('timeout', () => req.destroy(new Error(`no answer from ${url} within ${timeoutMs / 1000} s`)));
220
+ req.on('error', reject);
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Install platform-tools from a ZIP buffer into <stateDir>/platform-tools:
226
+ * unpack into a temporary directory next to it, check that adb is there, then
227
+ * swap the directories. On any failure the old directory stays as it was and
228
+ * the temporary one is removed.
229
+ */
230
+ function installPlatformTools(buf, stateDir, { platform = process.platform } = {}) {
231
+ fs.mkdirSync(stateDir, { recursive: true });
232
+ const target = path.join(stateDir, 'platform-tools');
233
+ const tmp = fs.mkdtempSync(path.join(stateDir, '.platform-tools-new-'));
234
+ const old = path.join(stateDir, `.platform-tools-old-${crypto.randomBytes(4).toString('hex')}`);
235
+ try {
236
+ const files = extractZip(buf, tmp, { platform });
237
+ const unpacked = path.join(tmp, 'platform-tools');
238
+ const adb = path.join(unpacked, exeName(platform));
239
+ if (!fs.existsSync(adb)) throw new Error('the archive has no platform-tools/' + exeName(platform));
240
+ let moved = false;
241
+ if (fs.existsSync(target)) { fs.renameSync(target, old); moved = true; }
242
+ try {
243
+ fs.renameSync(unpacked, target);
244
+ } catch (e) {
245
+ if (moved) fs.renameSync(old, target);
246
+ throw e;
247
+ }
248
+ if (moved) fs.rmSync(old, { recursive: true, force: true });
249
+ return { dir: target, adb: path.join(target, exeName(platform)), files };
250
+ } finally {
251
+ fs.rmSync(tmp, { recursive: true, force: true });
252
+ }
253
+ }
254
+
255
+ module.exports = {
256
+ PLATFORM_ZIP, LICENSE_URL, exeName, onPath, findAdb, resolveAdbPath, lookedIn,
257
+ getAdbRefusal, safeEntryPath, extractZip, download, installPlatformTools,
258
+ };
@@ -0,0 +1,334 @@
1
+ 'use strict';
2
+ /**
3
+ * registry.js — the tool schemas (tools/list) and the tools/call dispatcher.
4
+ *
5
+ * The registry knows nothing about the transport, and the tool modules know
6
+ * nothing about JSON-RPC.
7
+ */
8
+
9
+ const session = require('./session.js');
10
+ const ui = require('./ui.js');
11
+ const files = require('./files.js');
12
+ const apps = require('./apps.js');
13
+ const { coerceArray } = require('./adb.js');
14
+
15
+ /**
16
+ * Title and MCP annotations. The title goes in twice: top-level `title`
17
+ * (protocol 2025-06-18) and `annotations.title` (2025-03-26, read by older
18
+ * clients). All four hints are explicit booleans: connector catalogues reject
19
+ * a tool with a missing hint, and the schema defaults (destructive=true,
20
+ * openWorld=true) are wrong here. A hint describes the tool's WORST case
21
+ * (adb_app is destructive though list/info only read). Input tools are not
22
+ * destructive; the risk of repeated wrong passwords is handled by the
23
+ * adb_text description, which the model reads.
24
+ */
25
+ function meta(title, h) {
26
+ return {
27
+ title,
28
+ annotations: {
29
+ title,
30
+ readOnlyHint: h.readOnly,
31
+ destructiveHint: h.destructive,
32
+ idempotentHint: h.idempotent,
33
+ openWorldHint: h.openWorld,
34
+ },
35
+ };
36
+ }
37
+
38
+ const SERIAL = { type: 'string', description: 'Device serial from adb_devices. Optional when exactly one device is connected.' };
39
+
40
+ const TOOLS = [
41
+ {
42
+ name: 'adb_devices',
43
+ ...meta('List devices', { readOnly: true, destructive: false, idempotent: true, openWorld: false }),
44
+ description: 'List connected Android devices with serial, state and description (adb devices -l), and remembered addresses that are not connected now. Start here: the other tools take serial from this list. If the device the user means is not in the list, call again with discover=true: it searches the local network for devices to connect (mDNS and port 5555), any time and as often as needed, and connects none of them.',
45
+ inputSchema: { type: 'object', properties: {
46
+ discover: { type: 'boolean', description: 'Search the local network (about 10 s) for devices with network or Wireless debugging on; returns candidates and the next step for each. Default false.' }
47
+ } }
48
+ },
49
+ {
50
+ name: 'adb_connect',
51
+ ...meta('Connect device', { readOnly: false, destructive: false, idempotent: true, openWorld: false }),
52
+ description: 'Connect to a device over network ADB. host is ip or ip:port (default port 5555). An Android 11+ phone with Wireless debugging is paired once with adb_pair first; after that adb_connect is enough. The reverse is adb_disconnect.',
53
+ inputSchema: { type: 'object', properties: {
54
+ host: { type: 'string', description: 'Device address: ip (port 5555 implied) or ip:port, e.g. 192.0.2.50 or 192.0.2.50:5555.' }
55
+ }, required: ['host'] }
56
+ },
57
+ {
58
+ name: 'adb_pair',
59
+ ...meta('Pair device', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
60
+ description: 'Pair with an Android 11+ device over Wireless Debugging, once per device and computer; afterwards adb_connect alone reconnects. On the device: Developer options -> Wireless debugging -> "Pair device with pairing code" shows ip:port and a 6-digit code. The pairing port is random and differs from the connect port; after pairing succeeds, call adb_connect with the ip:port shown on the main Wireless debugging screen.',
61
+ inputSchema: { type: 'object', properties: {
62
+ host: { type: 'string', description: 'ip:port from the pairing dialog (random port, NOT 5555)' },
63
+ code: { type: 'string', description: '6-digit pairing code from the dialog' }
64
+ }, required: ['host', 'code'] }
65
+ },
66
+ {
67
+ name: 'adb_disconnect',
68
+ ...meta('Disconnect device', { readOnly: false, destructive: false, idempotent: true, openWorld: false }),
69
+ description: 'Disconnect a network ADB device, the reverse of adb_connect. Omit host to disconnect every network device. adb_disconnect then adb_connect recovers a device that adb_devices lists as offline. With host the address is also forgotten and not reconnected at start.',
70
+ inputSchema: { type: 'object', properties: {
71
+ host: { type: 'string', description: 'ip:port as listed by adb_devices. Omit to disconnect all network devices.' }
72
+ } }
73
+ },
74
+ {
75
+ name: 'adb_shell',
76
+ ...meta('Run shell command', { readOnly: false, destructive: true, idempotent: false, openWorld: false }),
77
+ description: 'Run a shell command on the device (settings, pm, am, dumpsys, getprop, wm, cmd, svc...) and return stdout. It bypasses every guard rail, so it works only while the server option allow_shell is on. For package changes use adb_app instead: dry runs, a protected set, a network guard and a rollback snapshot.',
78
+ inputSchema: { type: 'object', properties: {
79
+ command: { type: 'string', description: 'Command line for the device shell, e.g. "getprop ro.build.version.release". Logged verbatim with log_requests: type secrets with adb_text instead.' },
80
+ serial: SERIAL,
81
+ timeout_sec: { type: 'number', description: 'Time limit in seconds, default 30, at most 120. Past it the call fails with "timed out".' }
82
+ }, required: ['command'] }
83
+ },
84
+ {
85
+ name: 'adb_screenshot',
86
+ ...meta('Take screenshot', { readOnly: true, destructive: false, idempotent: true, openWorld: false }),
87
+ description: 'Take a screenshot of the device screen. Returns a JPEG image, then a text line with the logical screen size, the image size and the scale between them, e.g. "screen 1080x2340 -> image 473x1024 · scale 2.283/2.285". Pass coords="screenshot" to adb_tap/adb_swipe to tap coordinates read off that image. A near-uniformly dark frame is a warning after the image, not a refusal. To read labels and exact tap points, adb_ui_dump is cheaper and precise; the screenshot shows what the dump cannot (images, video, games).',
88
+ inputSchema: { type: 'object', properties: {
89
+ serial: SERIAL,
90
+ quality: { type: 'number', description: 'JPEG quality 30-95, default 70' },
91
+ max_px: { type: 'number', description: 'Max dimension 320-1920, default 1024' }
92
+ } }
93
+ },
94
+ {
95
+ name: 'adb_ui_dump',
96
+ ...meta('Dump UI hierarchy', { readOnly: true, destructive: false, idempotent: true, openWorld: false }),
97
+ description: 'Dump the current UI hierarchy (uiautomator) as a compact list of interactive/labeled elements with tap coordinates @(x,y). Password fields are marked [PASSWORD] and listed even with no visible text. Use together with adb_tap. Prefer it over adb_screenshot for labels and tap targets; use adb_screenshot for content the dump does not see (images, video, some WebViews and games).',
98
+ inputSchema: { type: 'object', properties: { serial: SERIAL } }
99
+ },
100
+ {
101
+ name: 'adb_tap',
102
+ ...meta('Tap', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
103
+ description: 'Tap at (x, y). coords="screen" (default): coordinates from adb_ui_dump, the logical space input tap uses. coords="screenshot": coordinates off the last adb_screenshot for the SAME serial, rescaled; missing or older than 120s is refused. Rotation between screenshot and tap is not checked. verify="activity"|"ui" reports whether the tap changed anything; a failed verify never turns a performed tap into an error. To activate an element by its label, adb_find_and_tap does it in one call and also works on TV boxes without a touchscreen.',
104
+ inputSchema: { type: 'object', properties: {
105
+ x: { type: 'number', description: 'X in pixels, in the space chosen by coords.' },
106
+ y: { type: 'number', description: 'Y in pixels, same space.' },
107
+ serial: SERIAL,
108
+ coords: { type: 'string', enum: ['screen', 'screenshot'], description: 'Coordinate space, default "screen". "screenshot" = pixels read off the last adb_screenshot image for this serial, rescaled automatically; refused if that screenshot is missing or older than 120s.' },
109
+ verify: { type: 'string', enum: ['none', 'activity', 'ui'], description: 'Default "none". "activity" compares the resumed activity before/after. "ui" also hashes the UI dump (~2-4s); a clock or timer ticking on its own can make it report "changed". "unchanged" is reliable.' },
110
+ }, required: ['x', 'y'] }
111
+ },
112
+ {
113
+ name: 'adb_swipe',
114
+ ...meta('Swipe', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
115
+ description: 'Swipe from (x1,y1) to (x2,y2) over duration_ms (default 300). The same point at both ends with duration_ms >= 800 is a long-press. coords and verify work as in adb_tap and both endpoints share one coordinate space; with verify="ui", an "unchanged" result on a swipe usually means the end of a scrollable list. On a TV box without a touchscreen, move the focus with adb_key DPAD_* instead.',
116
+ inputSchema: { type: 'object', properties: {
117
+ x1: { type: 'number', description: 'Start X in pixels, in the space chosen by coords.' },
118
+ y1: { type: 'number', description: 'Start Y in pixels.' },
119
+ x2: { type: 'number', description: 'End X in pixels.' },
120
+ y2: { type: 'number', description: 'End Y in pixels.' },
121
+ duration_ms: { type: 'number', description: 'Duration in ms, default 300.' },
122
+ serial: SERIAL,
123
+ coords: { type: 'string', enum: ['screen', 'screenshot'], description: 'Coordinate space for BOTH endpoints, default "screen". See adb_tap for the "screenshot" semantics and its 120s TTL.' },
124
+ verify: { type: 'string', enum: ['none', 'activity', 'ui'], description: 'See adb_tap. For a swipe, "ui" reporting "unchanged" usually means you hit the end of a scrollable list rather than that nothing happened.' },
125
+ }, required: ['x1', 'y1', 'x2', 'y2'] }
126
+ },
127
+ {
128
+ name: 'adb_text',
129
+ ...meta('Type text', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
130
+ description: 'Type text into the focused input field. Focus the field first; on a TV box, DPAD_CENTER on the field opens the keyboard. For single keys (ENTER, BACK) use adb_key. ASCII goes through input text; non-ASCII (Cyrillic, emoji, CJK) is sent via the ADBKeyBoard IME, which must be installed on the device (github.com/senzhk/ADBKeyBoard): the current keyboard is switched to it and restored afterwards. The response reports only the character count, never the text itself. Never retry a wrong password or PIN: repeated failures can lock the account or device. Stop and ask the user.',
131
+ inputSchema: { type: 'object', properties: {
132
+ text: { type: 'string', description: 'Text to type into the focused field. Only its length appears in the response and the log.' },
133
+ serial: SERIAL
134
+ }, required: ['text'] }
135
+ },
136
+ {
137
+ name: 'adb_key',
138
+ ...meta('Send key', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
139
+ description: 'Send a keyevent. Accepts names (HOME, BACK, ENTER, DPAD_UP, POWER, VOLUME_UP, MENU, TAB...) or numeric codes. On TV boxes DPAD_UP/DOWN/LEFT/RIGHT move the focus and DPAD_CENTER presses it. verify="activity"|"ui" reports whether the key changed anything; see adb_tap for the same parameter. For text use adb_text; for a labelled element, adb_find_and_tap.',
140
+ inputSchema: { type: 'object', properties: {
141
+ key: { type: 'string', description: 'Key name (HOME, BACK, ENTER, DPAD_CENTER, WAKEUP...; the KEYCODE_ prefix is optional) or a numeric keycode.' },
142
+ serial: SERIAL,
143
+ verify: { type: 'string', enum: ['none', 'activity', 'ui'], description: 'Default "none". See adb_tap.' },
144
+ }, required: ['key'] }
145
+ },
146
+ {
147
+ name: 'adb_find_and_tap',
148
+ ...meta('Find and tap element', { readOnly: false, destructive: false, idempotent: false, openWorld: false }),
149
+ description:
150
+ 'Find an on-screen element by text, resource-id or content-desc and activate it.\n' +
151
+ 'The method is derived from the device: with a touchscreen the element centre is tapped; on leanback without one the focus is walked there with DPAD keys, since a coordinate tap activates whatever has focus.\n' +
152
+ 'If the focus stalls, cycles, or the target is not reached in max_steps or the time budget, nothing is pressed and the tool reports where it stopped.\n' +
153
+ 'Prefer it over adb_ui_dump plus adb_tap when the label is known; use adb_tap for a point that has no label.',
154
+ inputSchema: { type: 'object', properties: {
155
+ text: { type: 'string', description: 'Visible label to match, checked against both the text attribute and content-desc (substring by default, case-insensitive). Some TV launchers put every label in content-desc and leave text empty.' },
156
+ resource_id: { type: 'string', description: 'resource-id; the part after "/" is enough' },
157
+ desc: { type: 'string', description: 'content-desc to match' },
158
+ exact: { type: 'boolean', description: 'Require an exact match instead of substring. Default false.' },
159
+ index: { type: 'number', description: 'Which match to use when several elements match. Without it, several matches are an error listing the candidates.' },
160
+ max_steps: { type: 'number', description: 'Max DPAD steps on leanback devices, default 12, max 40. Each step re-dumps the UI (~1.5-2s) and the walk also stops after an internal ~25s budget, returning a report instead of timing out.' },
161
+ serial: SERIAL
162
+ } }
163
+ },
164
+ {
165
+ name: 'adb_install',
166
+ ...meta('Install app', { readOnly: false, destructive: true, idempotent: false, openWorld: false }),
167
+ description: 'Installs only with dry_run=false; by default it reports what would be installed and installs nothing.\n' +
168
+ 'Installs an APK from the server\'s file roots (file_roots). apk_path takes a single .apk, an array of split-APK paths, or one .apks/.xapk/.apkm bundle.\n' +
169
+ 'Without apk_path it installs nothing and lists the installable files in file_roots, newest first, with the full path to pass as apk_path: start there when the user says "install what I downloaded".\n' +
170
+ 'Bundle splits are chosen from the device ABI list, density and locale. No matching ABI split is a refusal; a density mismatch is not.\n' +
171
+ 'Flags -r, -t and -g are applied by default. The reverse is adb_uninstall, or adb_app for a removal with a backup and a rollback.',
172
+ inputSchema: { type: 'object', properties: {
173
+ apk_path: { type: ['string', 'array'], items: { type: 'string' }, description: 'Single APK path, array of split-APK paths, or one .apks/.xapk/.apkm bundle. Without it: a list of the installable files in file_roots, newest first; nothing is installed.' },
174
+ dir: { type: 'string', description: 'Only without apk_path: the list shows the top level and one level of subfolders; for a deeper folder pass it here, listed the same way. Ignored when apk_path is given.' },
175
+ abi: { type: 'string', description: 'Bundle only: force an ABI instead of the device default (e.g. armeabi-v7a)' },
176
+ density: { type: 'number', description: 'Bundle only: force a screen density in dpi instead of the device value' },
177
+ locales: { type: ['string', 'array'], items: { type: 'string' }, description: 'Bundle only: extra language splits to include alongside the device language (e.g. ["ru"] on an en-US device)' },
178
+ dry_run: { type: 'boolean', default: true, description: 'Default true: report the files, the command and the device (for a bundle, also the chosen splits) and install nothing. Only false installs.' },
179
+ serial: SERIAL
180
+ } }
181
+ },
182
+ {
183
+ name: 'adb_uninstall',
184
+ ...meta('Uninstall app', { readOnly: false, destructive: true, idempotent: true, openWorld: false }),
185
+ description: 'Uninstall an app by package name, at once and without a backup. keep_data=true keeps app data (-k). The reverse is adb_install. For system packages, reversible bulk operations and backups, use adb_app.',
186
+ inputSchema: { type: 'object', properties: {
187
+ package: { type: 'string', description: 'Package name, e.g. com.example.app (adb_app action=list lists them).' },
188
+ keep_data: { type: 'boolean', description: 'Keep the app data and cache (-k). Default false.' },
189
+ serial: SERIAL
190
+ }, required: ['package'] }
191
+ },
192
+ {
193
+ name: 'adb_push',
194
+ ...meta('Push file to device', { readOnly: false, destructive: true, idempotent: true, openWorld: false }),
195
+ description: 'Copy a file from the server\'s file roots (file_roots) to the device, overwriting a file of the same name there. To install an APK use adb_install instead. The reverse is adb_pull.',
196
+ inputSchema: { type: 'object', properties: {
197
+ host_path: { type: 'string', description: 'Absolute path of the file on the server, inside file_roots.' },
198
+ device_path: { type: 'string', description: 'Destination on the device, e.g. /sdcard/Download/file.apk or /data/local/tmp/.' },
199
+ serial: SERIAL
200
+ }, required: ['host_path', 'device_path'] }
201
+ },
202
+ {
203
+ name: 'adb_pull',
204
+ ...meta('Pull file from device', { readOnly: false, destructive: true, idempotent: true, openWorld: false }),
205
+ description: 'Copy a file from the device into the server\'s file roots (file_roots), overwriting a file of the same name and creating missing directories. The reverse is adb_push.',
206
+ inputSchema: { type: 'object', properties: {
207
+ device_path: { type: 'string', description: 'File on the device, e.g. /sdcard/Download/report.pdf.' },
208
+ host_path: { type: 'string', description: 'Absolute destination path on the server, inside file_roots.' },
209
+ serial: SERIAL
210
+ }, required: ['device_path', 'host_path'] }
211
+ },
212
+ {
213
+ name: 'adb_logcat',
214
+ ...meta('Read logcat', { readOnly: true, destructive: false, idempotent: true, openWorld: false }),
215
+ description: 'Read recent logcat lines without waiting for new ones, e.g. to see why an app crashed; unlike adb_shell it works with allow_shell off. filter: either a logcat filterspec like "ActivityManager:I *:S" (contains ":" or "*"; *:S is auto-appended if missing so unmatched tags are silenced) or a plain substring grepped case-insensitively across the whole line. lines limits the result (default 200). Filtering runs on the device.',
216
+ inputSchema: { type: 'object', properties: {
217
+ filter: { type: 'string', description: 'A filterspec such as "ActivityManager:I *:S" (has ":" or "*"), or a plain substring matched case-insensitively. Omit for the last lines unfiltered.' },
218
+ lines: { type: 'number', description: 'How many lines to return, default 200, at most 2000.' },
219
+ serial: SERIAL
220
+ } }
221
+ },
222
+ {
223
+ name: 'adb_app',
224
+ ...meta('Manage packages', { readOnly: false, destructive: true, idempotent: false, openWorld: false }),
225
+ description:
226
+ 'Package operations with guard rails: inspect, launch, stop, clear, disable, uninstall, back up and restore packages. Use it rather than adb_shell or adb_uninstall for package changes.\n' +
227
+ 'Every action that changes packages defaults to dry_run=true. A protected set derived from the device (launcher, active IME, installer, WebView provider, role holders, account packages) aborts the whole call on any overlap, and has no override.\n' +
228
+ 'A network guard refuses disable, uninstall, stop and clear while the package is serving an off-device client, naming the port and the peer. Only force_network=true lifts it; force covers a failed APK backup and nothing else.\n' +
229
+ 'An account canary between batches rolls a batch back and stops on a drop. Everything applied goes into a snapshot, so action=restore undoes it. mode=uninstall also needs the server option allow_uninstall and a successful APK backup.\n' +
230
+ 'action=launch also accepts uri and/or intent_action for an intent or deep link; CALL, CALL_PRIVILEGED and CALL_EMERGENCY are refused while allow_shell is false.',
231
+ inputSchema: {
232
+ type: 'object',
233
+ properties: {
234
+ action: {
235
+ type: 'string',
236
+ enum: ['list', 'info', 'protected', 'launch', 'stop', 'clear', 'disable', 'uninstall', 'enable', 'restore', 'backup', 'state'],
237
+ description: 'list/info/protected/state only read. launch/stop/clear act at once (clear defaults to dry_run), stop/clear under the network guard. disable/uninstall/enable/restore default to dry_run.'
238
+ },
239
+ packages: { type: ['string', 'array'], items: { type: 'string' }, description: 'Package name or array of package names. For action=launch with uri/intent_action, at most one package is accepted (used as -p to narrow the resolver); it is otherwise optional there.' },
240
+ uri: { type: 'string', description: 'action=launch only: deep-link / intent data URI (am start -d). Its presence, together with intent_action, selects the intent-based launch instead of resolving the package\'s main activity.' },
241
+ intent_action: { type: 'string', description: 'action=launch only: intent action, default android.intent.action.VIEW when uri is set. Must match [A-Za-z0-9_.]+. See the CALL refusal note above.' },
242
+ extras: { type: ['object', 'string'], description: 'action=launch only: intent extras. string -> --es, boolean -> --ez, int32 integer -> --ei, larger integer -> --el; anything else is refused by key name. A JSON-stringified object is accepted too.' },
243
+ serial: SERIAL,
244
+ filter: { type: 'string', enum: ['user', 'system', 'disabled', 'all'], description: 'action=list only, default user' },
245
+ q: { type: 'string', description: 'action=list only: case-insensitive substring filter' },
246
+ scope: { type: 'string', enum: ['user', 'all', 'list'], description: 'action=backup only: what to back up when packages is omitted (default user)' },
247
+ mode: { type: 'string', enum: ['disable', 'uninstall'], description: 'How to remove: disable (default) is undone by action=enable or restore; uninstall needs allow_uninstall.' },
248
+ dry_run: { type: 'boolean', description: 'Default true for state-changing actions. Set false to actually apply.' },
249
+ batch_size: { type: 'number', description: 'Packages per batch between canary checks, default 5, max 25' },
250
+ canary: { type: 'boolean', description: 'Check the account count and the launcher between batches, default true. Turning it off removes the only automatic check for a latent breakage.' },
251
+ backup: { type: 'boolean', description: 'Pull APKs before removing. Default true for uninstall, false for disable.' },
252
+ force: { type: 'boolean', description: 'Proceed even if the APK backup failed. Off by default. It does not affect the network guard; see force_network.' },
253
+ force_network: { type: 'boolean', description: 'Override the network guard for disable, uninstall, stop and clear: act on a package that is currently serving an off-device client. It does NOT override the protected set. Off by default.' },
254
+ store: { type: 'string', description: 'Where snapshots and APK backups live: by default the snapshot store (setting store). Another path must be inside file_roots.' }
255
+ },
256
+ required: ['action']
257
+ }
258
+ },
259
+ ];
260
+
261
+ // Tools that may have done part of their work before a connection loss: after
262
+ // a reconnect they are not repeated automatically, unless the call itself
263
+ // changes nothing (repeatable()).
264
+ const NOT_REPEATED = new Set(TOOLS.filter(t => t.annotations.destructiveHint).map(t => t.name));
265
+
266
+ /**
267
+ * Whether this call may be repeated after a reconnect: a tool that is not
268
+ * destructive; adb_app with a reading action, or with the dry_run in force
269
+ * (passed, else the action's default); adb_install without apk_path (the
270
+ * list) or with the dry_run in force.
271
+ */
272
+ function repeatable(name, args = {}) {
273
+ if (!NOT_REPEATED.has(name)) return true;
274
+ const a = args || {};
275
+ if (name === 'adb_app') {
276
+ const action = String(a.action || '').toLowerCase();
277
+ return apps.READ_ONLY_ACTIONS.has(action) || apps.dryRunOf(action, a) === true;
278
+ }
279
+ if (name === 'adb_install') {
280
+ const paths = coerceArray(a.apk_path).filter(p => typeof p === 'string' && p.trim() !== '');
281
+ return !paths.length || files.installDryRun(a.dry_run).dryRun;
282
+ }
283
+ return false;
284
+ }
285
+
286
+ /**
287
+ * A tool call; when it failed because a remembered network device dropped,
288
+ * one reconnect, then the call once more (or, for a tool that may have done
289
+ * part of its work, a note to call again).
290
+ */
291
+ async function callTool(name, args) {
292
+ try {
293
+ return await dispatch(name, args);
294
+ } catch (e) {
295
+ const r = await session.reconnectRemembered(args && args.serial, e.message);
296
+ if (!r) throw e;
297
+ if (!r.ok)
298
+ throw new Error(`${e.message}\nA reconnect to the remembered address ${r.addr} failed: the device may be off or have a new address - adb_devices discover=true finds it again.`);
299
+ if (!repeatable(name, args))
300
+ throw new Error(`${e.message}\nReconnected to ${r.addr}. The call was not repeated, because it may have been partly done: check the state and call it again.`);
301
+ return await dispatch(name, args);
302
+ }
303
+ }
304
+
305
+ async function dispatch(name, args) {
306
+ switch (name) {
307
+ case 'adb_devices': return session.devices(args);
308
+ case 'adb_connect': return session.connect(args);
309
+ case 'adb_pair': return session.pair(args);
310
+ case 'adb_disconnect': return session.disconnect(args);
311
+ case 'adb_shell': return session.shell(args);
312
+ case 'adb_logcat': return session.logcat(args);
313
+
314
+ case 'adb_screenshot': return ui.screenshot(args);
315
+ case 'adb_ui_dump': return ui.uiDump(args);
316
+ case 'adb_tap': return ui.tap(args);
317
+ case 'adb_swipe': return ui.swipe(args);
318
+ case 'adb_text': return ui.typeText(args);
319
+ case 'adb_key': return ui.key(args);
320
+ case 'adb_find_and_tap': return ui.findAndTap(args);
321
+
322
+ case 'adb_install': return files.install(args);
323
+ case 'adb_uninstall': return files.uninstall(args);
324
+ case 'adb_push': return files.push(args);
325
+ case 'adb_pull': return files.pull(args);
326
+
327
+ case 'adb_app': return apps.adbApp(args);
328
+
329
+ default:
330
+ throw new Error(`Unknown tool: ${name}`);
331
+ }
332
+ }
333
+
334
+ module.exports = { TOOLS, callTool, repeatable };