@rootnative/loupe 0.0.0-alpha.0 → 0.0.0-alpha.1

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,24 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@rootnative/loupe` are in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versions follow modified semver: a breaking change bumps the middle digit (`0.1.0`), and fixes and additions bump the last digit (`0.0.2`).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.0.0-alpha.1] - 2026-11-24
8
+
9
+ loupe drives an Android emulator or device, measures each screen of your app in dp, and gives your agent "pass" or "fail" with the numbers. It works on Android 11 (API level 30) and later.
10
+
11
+ ### Added
12
+
13
+ - **The CLI**, `loupe`. It prints JSON through a pipe and text in a terminal. Exit codes: 0 passed, 1 failed, 2 a wrong command or flag, 130 cancelled.
14
+ - **The MCP server**, `loupe mcp`. Each command is a tool, with the schemas of its input and its output. A sweep sends its progress, and a cancelled call stops at a safe point. `screenshot` and `sweep` also give their images in the result.
15
+ - **The skill**, `skills/loupe/SKILL.md`: the workflow, the rules, and what to do for each error. It tells your agent to ask you before it starts an emulator or opens an app. The MCP server serves it too.
16
+ - **`check`**, with five rules: `inset`, `overflow`, `centred`, `touch-target`, and `mirrored`. Each finding gives the element and its numbers in dp.
17
+ - **`sweep`**: it checks each link in each orientation and theme, and with `scroll` once more after a scroll down. It writes `report.json`, a screenshot of each screen, and a contact sheet of each variant. Then it puts the orientation and the theme back.
18
+ - **Reads:** `screenshot` (upright, with a crop and a scale), `ui` (the accessibility tree, with frames in dp), `insets` (the system bars, the cutout, and the safe area), `measure` (the colour runs along a row or a column, and where an element sits), and `wait`.
19
+ - **Touches:** `tap`, `double-tap`, `hold`, `swipe`, `drag`, `pinch`, `type`, `key`, and `scroll-to`. `tap`, `double-tap`, `hold`, and `pinch` aim at a point in dp, or at an element by its text, label, or id. Each touch but `scroll-to` can then wait for a text or a still screen.
20
+ - **The device:** `devices`, `open-url`, `rotate`, `theme`, `background`, `foreground`, and `dismiss`. `dismiss` closes a system sheet, a dialog, the keyboard, or an overlay of your app.
21
+ - **The probe:** when your app renders `<LoupeProbe />` from `@rootnative/loupe-probe`, `insets` and the rules use the app's own safe area.
22
+
23
+ [unreleased]: https://github.com/rootnative/loupe/compare/loupe@0.0.0-alpha.1...HEAD
24
+ [0.0.0-alpha.1]: https://github.com/rootnative/loupe/releases/tag/loupe@0.0.0-alpha.1
package/README.md CHANGED
@@ -1,8 +1,178 @@
1
1
  # @rootnative/loupe
2
2
 
3
- loupe by Root Native: layout checks for iOS and Android, built for AI agents.
3
+ Layout checks for iOS and Android, built for AI agents.
4
4
 
5
- This version, `0.0.0-alpha.0`, is empty. It has no code. Use a later
6
- version.
5
+ loupe drives an emulator or a device, opens each screen of your app, and
6
+ gives your agent exact numbers: element frames, safe areas, cutouts, and
7
+ edges, in dp. Your agent can then say "pass" or "fail" with evidence, not
8
+ with a guess from a screenshot.
7
9
 
8
- Source and docs: https://github.com/rootnative/loupe
10
+ > loupe is in alpha, and it drives Android only for now. A new version can
11
+ > change the commands, their options, and their JSON.
12
+
13
+ ## What you need
14
+
15
+ - Node.js 20.19 or later.
16
+ - `adb` from the Android SDK platform tools, on your `PATH` or in
17
+ `$ANDROID_HOME/platform-tools`.
18
+ - An emulator or a device with Android 11 (API level 30) or later.
19
+
20
+ ## Use it with an agent
21
+
22
+ ### The MCP server
23
+
24
+ `loupe mcp` serves each loupe command as an MCP tool, over stdin and stdout.
25
+
26
+ In Claude Code:
27
+
28
+ ```sh
29
+ claude mcp add loupe -- npx -y @rootnative/loupe mcp
30
+ ```
31
+
32
+ In VS Code, add it to `.vscode/mcp.json`:
33
+
34
+ ```json
35
+ {
36
+ "servers": {
37
+ "loupe": {
38
+ "type": "stdio",
39
+ "command": "npx",
40
+ "args": ["-y", "@rootnative/loupe", "mcp"]
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ In another MCP client:
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "loupe": {
52
+ "command": "npx",
53
+ "args": ["-y", "@rootnative/loupe", "mcp"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ When adb isn't on your `PATH`, set `ANDROID_HOME` in the server's `env`.
60
+ With more than one device, set `ANDROID_SERIAL`, or let the agent give
61
+ `device` in each call.
62
+
63
+ The server runs one call at a time, because two touches at the same time
64
+ lose events. A sweep sends its progress, and a cancelled call stops at a
65
+ safe point. `screenshot` and `sweep` also give their images in the result.
66
+
67
+ ### The skill
68
+
69
+ `skills/loupe/SKILL.md` tells your agent how to use loupe: the workflow, the
70
+ rules, and what to do for each error. It also tells the agent to ask you
71
+ before it starts an emulator or opens an app.
72
+
73
+ A client with the MCP skills extension gets the skill from the server. For
74
+ another agent, copy the skill into the agent's skills folder. For Claude
75
+ Code:
76
+
77
+ ```sh
78
+ npm install --save-dev @rootnative/loupe
79
+ cp -R node_modules/@rootnative/loupe/skills/loupe .claude/skills/
80
+ ```
81
+
82
+ ## Use it from the command line
83
+
84
+ ```sh
85
+ npx @rootnative/loupe devices
86
+ npx @rootnative/loupe open-url "exp://127.0.0.1:8081/--/settings" --app host.exp.exponent --wait-still
87
+ npx @rootnative/loupe check --app host.exp.exponent
88
+ npx @rootnative/loupe rotate landscape-left
89
+ npx @rootnative/loupe check --app host.exp.exponent
90
+ ```
91
+
92
+ Run `loupe --help` for the commands, and `loupe <command> --help` for the
93
+ options of one command.
94
+
95
+ To check many screens in one call:
96
+
97
+ ```sh
98
+ npx @rootnative/loupe sweep \
99
+ --url "exp://127.0.0.1:8081/--/settings" \
100
+ --url "exp://127.0.0.1:8081/--/profile" \
101
+ --orientation portrait,landscape-left \
102
+ --theme light,dark \
103
+ --app host.exp.exponent
104
+ ```
105
+
106
+ A sweep writes `loupe-sweep/report.json`, a screenshot of each screen, and a
107
+ contact sheet of each variant. A red frame on the contact sheet marks a
108
+ screen that failed. At the end, loupe puts the orientation and the theme
109
+ back.
110
+
111
+ ## The output
112
+
113
+ - Each position and size is in dp, from the top-left corner of the current
114
+ orientation. Each reading gives `scale`, the pixels in one dp.
115
+ - Through a pipe, each command prints JSON: `{ "ok": true, "command": …,
116
+ "data": … }`, or `"ok": false` with `"error": { "code": …, "message": …
117
+ }`. In a terminal, it prints text. `--json` and `--no-json` choose.
118
+ - Exit codes: 0 passed, 1 failed (also a check that ran and found a
119
+ defect), 2 a wrong command or option, 130 cancelled.
120
+
121
+ ## The rules
122
+
123
+ `check` and `sweep` run these rules:
124
+
125
+ | Rule | Fails when |
126
+ | --- | --- |
127
+ | `inset` | An element with text, a label, or a touch sits under a system bar or the cutout, or outside the safe area. |
128
+ | `overflow` | An element at a screen edge is shorter than the elements like it in its row or column: the edge cuts it. |
129
+ | `centred` | A text with an element on each side is more than 4 dp from the centre of its container. |
130
+ | `touch-target` | An element that you can press is smaller than 48 × 48 dp. From 40 dp, loupe gives a warning: a `hitSlop` can make it whole. |
131
+ | `mirrored` | In RTL, an element sits where LTR puts it. Save the other direction with `ui --out <file>`, then run `check --mirror-of <file>`. |
132
+
133
+ Each finding gives the element and its numbers in dp.
134
+
135
+ ## The commands
136
+
137
+ | Command | What it does |
138
+ | --- | --- |
139
+ | `devices` | List the Android emulators and devices, and the AVDs that don't run. |
140
+ | `open-url` | Open a link (a deep link or a web page), and wait until it opens. |
141
+ | `check` | Check the screen for layout defects with the rules above. |
142
+ | `sweep` | Open each link in each orientation and theme, check each screen, and write a report, the screenshots, and a contact sheet of each variant. |
143
+ | `screenshot` | Save the screen as a PNG file, upright in each orientation. |
144
+ | `ui` | Read the accessibility tree of the screen, with frames in dp. |
145
+ | `insets` | Read the safe-area insets and the cutout of the current orientation. |
146
+ | `measure` | Measure the colour runs along a row or a column, or where an element sits on the screen and in the safe area. |
147
+ | `wait` | Wait until the screen keeps still, or until an element is on the screen. |
148
+ | `rotate` | Turn the screen, and wait until it has turned. |
149
+ | `theme` | Set the system theme to light or dark, and wait until the app shows it. With no theme, read it. |
150
+ | `tap` | Tap one point, or the element with a text, label, or id. |
151
+ | `double-tap` | Tap one point or element twice. |
152
+ | `hold` | Touch one point or element and hold it: a long press. |
153
+ | `swipe` | Move one touch in a straight line from one point to another. |
154
+ | `drag` | Touch, hold, move, hold, and lift, with a screenshot while the touch is down. |
155
+ | `pinch` | Pinch or spread two fingers around a point or an element, and turn them. On an emulator only. |
156
+ | `scroll-to` | Scroll until the element with a text, label, or id is in view, and give its frame. |
157
+ | `type` | Type text into the field that has the focus. |
158
+ | `key` | Press one key, for example `back`, `home`, or `enter`. |
159
+ | `dismiss` | Close the top layer over the app: the keyboard, a dialog, a menu or a sheet of the app, a system sheet, or the notification shade. |
160
+ | `background` | Send the app in front to the background. With `--for`, bring it back after that time. |
161
+ | `foreground` | Bring an app back to the front, as a person does from Recents. |
162
+ | `version` | Print the loupe version and the host it runs on. |
163
+
164
+ ## The probe
165
+
166
+ With [`@rootnative/loupe-probe`](https://github.com/rootnative/loupe/tree/main/packages/probe#readme)
167
+ in your app, `insets` and the rules use the app's own safe area. Without it,
168
+ loupe takes the safe area from Android.
169
+
170
+ ## Privacy
171
+
172
+ - On a real phone, give `--app`. loupe then reads the screen only while that
173
+ app is in front, so it never shows another app to your agent.
174
+ - loupe makes no network call. It talks to the device through adb only.
175
+
176
+ ## License
177
+
178
+ MIT
package/dist/bin.js ADDED
@@ -0,0 +1,315 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ LoupeError,
4
+ createContext,
5
+ inputJsonSchema,
6
+ registry,
7
+ runCommand,
8
+ version
9
+ } from "./chunk-JDX6L5K6.js";
10
+
11
+ // src/cli/flags.ts
12
+ import { parseArgs } from "util";
13
+ var RESERVED = /* @__PURE__ */ new Set(["help", "json"]);
14
+ function kebab(key) {
15
+ return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
16
+ }
17
+ function kindOf(node) {
18
+ switch (node?.type) {
19
+ case "string":
20
+ return "string";
21
+ case "number":
22
+ case "integer":
23
+ return "number";
24
+ case "boolean":
25
+ return "boolean";
26
+ default:
27
+ return void 0;
28
+ }
29
+ }
30
+ function flagsOf(command) {
31
+ const schema = inputJsonSchema(command);
32
+ const required = new Set(schema.required);
33
+ const positionals = new Set(command.positionals);
34
+ const flags = Object.entries(schema.properties ?? {}).map(
35
+ ([key, node]) => {
36
+ const name = kebab(key);
37
+ const multiple = node.type === "array";
38
+ const leaf = multiple ? node.items : node;
39
+ const kind = kindOf(leaf);
40
+ const positional = positionals.has(key);
41
+ if (RESERVED.has(name)) {
42
+ throw new Error(
43
+ `${command.name}: the field "${key}" has the name of a CLI flag.`
44
+ );
45
+ }
46
+ if (!kind) {
47
+ throw new Error(
48
+ `${command.name}: the field "${key}" must be a string, a number, a boolean, or a list of these.`
49
+ );
50
+ }
51
+ if (positional && (multiple || kind === "boolean")) {
52
+ throw new Error(
53
+ `${command.name}: the positional field "${key}" must be one string or one number.`
54
+ );
55
+ }
56
+ return {
57
+ key,
58
+ name,
59
+ kind,
60
+ multiple,
61
+ required: required.has(key),
62
+ positional,
63
+ description: typeof node.description === "string" ? node.description : void 0,
64
+ choices: Array.isArray(leaf?.enum) ? leaf.enum.map(String) : void 0,
65
+ defaultValue: node.default
66
+ };
67
+ }
68
+ );
69
+ for (const key of positionals) {
70
+ if (!flags.some((flag) => flag.key === key)) {
71
+ throw new Error(
72
+ `${command.name}: the positional "${key}" is not an input field.`
73
+ );
74
+ }
75
+ }
76
+ return flags;
77
+ }
78
+ function convert(flag, raw) {
79
+ if (flag.kind !== "number" || typeof raw !== "string") return raw;
80
+ const value = raw.trim() === "" ? Number.NaN : Number(raw);
81
+ return Number.isNaN(value) ? raw : value;
82
+ }
83
+ function parseCommandArgs(command, args) {
84
+ const flags = flagsOf(command);
85
+ let parsed;
86
+ try {
87
+ parsed = parseArgs({
88
+ args: [...args],
89
+ options: {
90
+ help: { type: "boolean", short: "h" },
91
+ ...Object.fromEntries(
92
+ flags.map((flag) => [
93
+ flag.name,
94
+ {
95
+ type: flag.kind === "boolean" ? "boolean" : "string",
96
+ multiple: flag.multiple
97
+ }
98
+ ])
99
+ )
100
+ },
101
+ allowPositionals: true,
102
+ allowNegative: true,
103
+ strict: true
104
+ });
105
+ } catch (error) {
106
+ throw new LoupeError(
107
+ "invalid_input",
108
+ error instanceof Error ? error.message : String(error)
109
+ );
110
+ }
111
+ const values = parsed.values;
112
+ const input = {};
113
+ for (const flag of flags) {
114
+ const raw = values[flag.name];
115
+ if (raw === void 0) continue;
116
+ input[flag.key] = Array.isArray(raw) ? raw.map((item) => convert(flag, item)) : convert(flag, raw);
117
+ }
118
+ const order = command.positionals ?? [];
119
+ if (parsed.positionals.length > order.length) {
120
+ const extra = parsed.positionals[order.length];
121
+ throw new LoupeError(
122
+ "invalid_input",
123
+ `"${extra}" is one argument too many for ${command.name}.`
124
+ );
125
+ }
126
+ parsed.positionals.forEach((raw, index) => {
127
+ const flag = flags.find((item) => item.key === order[index]);
128
+ if (!flag) return;
129
+ if (flag.key in input) {
130
+ throw new LoupeError(
131
+ "invalid_input",
132
+ `${flag.key} has two values: one by position and one from --${flag.name}.`
133
+ );
134
+ }
135
+ input[flag.key] = convert(flag, raw);
136
+ });
137
+ return { help: parsed.values.help === true, input };
138
+ }
139
+
140
+ // src/cli/help.ts
141
+ function columns(rows) {
142
+ const width = Math.max(0, ...rows.map(([left]) => left.length));
143
+ return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`.trimEnd()).join("\n");
144
+ }
145
+ var SHARED_OPTIONS = [
146
+ ["--json", "Print JSON. The default when the output is not a terminal"],
147
+ ["--no-json", "Print text for a person"],
148
+ ["-h, --help", "Print this help"]
149
+ ];
150
+ function globalHelp(registry2) {
151
+ const commands = columns(
152
+ registry2.list().map((command) => [command.name, command.summary])
153
+ );
154
+ return `Usage: loupe <command> [options]
155
+ loupe mcp
156
+
157
+ Commands:
158
+ ${commands}
159
+
160
+ Options:
161
+ ${columns([...SHARED_OPTIONS, ["-v, --version", "Print the version"]])}
162
+
163
+ Run "loupe <command> --help" for the options of one command.
164
+ Run "loupe mcp" to serve each command as an MCP tool, over stdin and stdout.`;
165
+ }
166
+ function mcpHelp() {
167
+ return `Usage: loupe mcp
168
+
169
+ Serve each loupe command as an MCP tool, over stdin and stdout. An MCP client starts this server. For example, its config runs "npx -y @rootnative/loupe mcp".
170
+
171
+ Options:
172
+ ${columns([["-h, --help", "Print this help"]])}`;
173
+ }
174
+ function flagLeft(flag) {
175
+ if (flag.kind === "boolean") return `--${flag.name}`;
176
+ const value = flag.choices ? flag.choices.join("|") : `<${flag.kind}>`;
177
+ return `--${flag.name} ${value}`;
178
+ }
179
+ function flagRight(flag) {
180
+ const notes = [];
181
+ if (flag.required) notes.push("required");
182
+ if (flag.multiple) notes.push("can repeat");
183
+ if (flag.defaultValue !== void 0 && !(Array.isArray(flag.defaultValue) && flag.defaultValue.length === 0)) {
184
+ notes.push(`default: ${JSON.stringify(flag.defaultValue)}`);
185
+ }
186
+ const note = notes.length > 0 ? `(${notes.join(", ")})` : "";
187
+ return [flag.description, note].filter(Boolean).join(" ");
188
+ }
189
+ function commandHelp(command) {
190
+ const flags = flagsOf(command);
191
+ const positionals = (command.positionals ?? []).map((key) => flags.find((flag) => flag.key === key)).filter((flag) => flag !== void 0).map((flag) => flag.required ? `<${flag.name}>` : `[${flag.name}]`);
192
+ const usage = ["loupe", command.name, ...positionals, "[options]"].join(" ");
193
+ const options = columns([
194
+ ...flags.map((flag) => [flagLeft(flag), flagRight(flag)]),
195
+ ...SHARED_OPTIONS
196
+ ]);
197
+ return `Usage: ${usage}
198
+
199
+ ${command.summary}
200
+
201
+ Options:
202
+ ${options}`;
203
+ }
204
+
205
+ // src/cli/run.ts
206
+ var defaultIO = {
207
+ out: (text) => process.stdout.write(`${text}
208
+ `),
209
+ err: (text) => process.stderr.write(`${text}
210
+ `),
211
+ isTTY: process.stdout.isTTY === true,
212
+ // `once`: a second Ctrl-C finds no listener, and Node quits at once.
213
+ onInterrupt: (listener) => {
214
+ process.once("SIGINT", listener);
215
+ return () => process.off("SIGINT", listener);
216
+ }
217
+ };
218
+ var EXIT_OK = 0;
219
+ var EXIT_FAILED = 1;
220
+ var EXIT_USAGE = 2;
221
+ var EXIT_CANCELLED = 130;
222
+ var JSON_FLAGS = /* @__PURE__ */ new Set(["--json", "--no-json"]);
223
+ async function mcp(args, io, registry2, context) {
224
+ if (args.some((arg) => arg === "--help" || arg === "-h")) {
225
+ io.out(mcpHelp());
226
+ return EXIT_OK;
227
+ }
228
+ if (args.length > 0) {
229
+ io.err(`loupe mcp: "${args[0]}" is not an option of mcp.`);
230
+ io.err('Run "loupe mcp --help" for its use.');
231
+ return EXIT_USAGE;
232
+ }
233
+ const { serveMcp } = await import("./server-BTS4TOGF.js");
234
+ await serveMcp({
235
+ registry: registry2,
236
+ context,
237
+ onerror: (error) => io.err(`loupe mcp: ${error.message}`)
238
+ });
239
+ return EXIT_OK;
240
+ }
241
+ function exitCodeOf(result) {
242
+ if (result.ok) return EXIT_OK;
243
+ const { code } = result.error;
244
+ if (code === "cancelled") return EXIT_CANCELLED;
245
+ return code === "unknown_command" || code === "invalid_input" ? EXIT_USAGE : EXIT_FAILED;
246
+ }
247
+ async function run(argv, io = defaultIO, registry2 = registry, context = createContext()) {
248
+ const jsonFlag = argv.findLast((arg) => JSON_FLAGS.has(arg));
249
+ const json = jsonFlag ? jsonFlag === "--json" : !io.isTTY;
250
+ const [first, ...rest] = argv.filter((arg) => !JSON_FLAGS.has(arg));
251
+ if (first === void 0 || first === "--help" || first === "-h") {
252
+ io.out(globalHelp(registry2));
253
+ return EXIT_OK;
254
+ }
255
+ if (first === "--version" || first === "-v") {
256
+ io.out(version);
257
+ return EXIT_OK;
258
+ }
259
+ if (first === "mcp") return mcp(rest, io, registry2, context);
260
+ const report = (result) => {
261
+ const definition = registry2.get(result.command);
262
+ if (json) {
263
+ io.out(JSON.stringify(result));
264
+ } else if (result.ok) {
265
+ const format = definition?.format;
266
+ io.out(format?.(result.data) ?? JSON.stringify(result.data, null, 2));
267
+ } else {
268
+ io.err(`loupe ${result.command}: ${result.error.message}`);
269
+ if (exitCodeOf(result) === EXIT_USAGE) {
270
+ io.err('Run "loupe --help" for the commands and their options.');
271
+ }
272
+ }
273
+ if (result.ok && definition?.passed?.(result.data) === false) {
274
+ return EXIT_FAILED;
275
+ }
276
+ return exitCodeOf(result);
277
+ };
278
+ const command = registry2.get(first);
279
+ if (!command) return report(await runCommand(registry2, first, {}));
280
+ let parsed;
281
+ try {
282
+ parsed = parseCommandArgs(command, rest);
283
+ } catch (error) {
284
+ if (!(error instanceof LoupeError)) throw error;
285
+ return report({
286
+ ok: false,
287
+ command: command.name,
288
+ error: { code: error.code, message: error.message }
289
+ });
290
+ }
291
+ if (parsed.help) {
292
+ io.out(commandHelp(command));
293
+ return EXIT_OK;
294
+ }
295
+ const controller = new AbortController();
296
+ const stopListening = io.onInterrupt?.(() => {
297
+ io.err(
298
+ `loupe ${command.name}: stopping at the next safe point. Press Ctrl-C again to quit now.`
299
+ );
300
+ controller.abort();
301
+ });
302
+ try {
303
+ return report(
304
+ await runCommand(registry2, command.name, parsed.input, {
305
+ ...context,
306
+ signal: controller.signal
307
+ })
308
+ );
309
+ } finally {
310
+ stopListening?.();
311
+ }
312
+ }
313
+
314
+ // src/bin.ts
315
+ process.exitCode = await run(process.argv.slice(2));