agentlane 0.0.0 → 0.4.0-rc.2

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.
Files changed (146) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/LICENSE +27 -0
  3. package/README.md +167 -2
  4. package/dist/agents/claude-plugin.js +79 -0
  5. package/dist/agents/cli.js +258 -0
  6. package/dist/agents/detect.js +88 -0
  7. package/dist/agents/init.js +251 -0
  8. package/dist/agents/launcher.js +32 -0
  9. package/dist/agents/package.js +119 -0
  10. package/dist/agents/skills.js +59 -0
  11. package/dist/agents/toml.js +325 -0
  12. package/dist/agents/wiring-check.js +117 -0
  13. package/dist/agents/wiring.js +374 -0
  14. package/dist/bench/host.js +104 -0
  15. package/dist/bench/live.js +511 -0
  16. package/dist/bench/mcp-client.js +91 -0
  17. package/dist/bench/model.js +15 -0
  18. package/dist/bench/report.js +162 -0
  19. package/dist/bench/run.js +121 -0
  20. package/dist/bench/schedule.js +140 -0
  21. package/dist/bench/stats.js +59 -0
  22. package/dist/bench-cli.js +167 -0
  23. package/dist/browser/aria.js +184 -0
  24. package/dist/browser/control.js +203 -0
  25. package/dist/browser/env.js +118 -0
  26. package/dist/browser/evidence.js +44 -0
  27. package/dist/browser/install.js +361 -0
  28. package/dist/browser/kinds.js +10 -0
  29. package/dist/browser/lane-browser.js +224 -0
  30. package/dist/browser/libraries.js +56 -0
  31. package/dist/browser/paths.js +29 -0
  32. package/dist/browser/release.js +121 -0
  33. package/dist/browser/screen.js +19 -0
  34. package/dist/browser/signin.js +154 -0
  35. package/dist/browser/stop.js +163 -0
  36. package/dist/browser/tools.js +25 -0
  37. package/dist/cache/build.js +154 -0
  38. package/dist/cache/config.js +186 -0
  39. package/dist/cache/index.js +4 -0
  40. package/dist/cache/key.js +196 -0
  41. package/dist/cache/store.js +303 -0
  42. package/dist/cli.js +178 -0
  43. package/dist/clock.js +4 -0
  44. package/dist/devices/adb.js +160 -0
  45. package/dist/devices/android.js +214 -0
  46. package/dist/devices/backend.js +7 -0
  47. package/dist/devices/bundler.js +46 -0
  48. package/dist/devices/common.js +51 -0
  49. package/dist/devices/controls.js +65 -0
  50. package/dist/devices/dial.js +56 -0
  51. package/dist/devices/emulator.js +396 -0
  52. package/dist/devices/hygiene.js +202 -0
  53. package/dist/devices/index.js +5 -0
  54. package/dist/devices/launch.js +76 -0
  55. package/dist/devices/simctl.js +119 -0
  56. package/dist/devices/tools.js +1 -0
  57. package/dist/devices/variant.js +99 -0
  58. package/dist/devices/xcrun.js +265 -0
  59. package/dist/driver/absence.js +54 -0
  60. package/dist/driver/caller.js +51 -0
  61. package/dist/driver/client.js +312 -0
  62. package/dist/driver/diff.js +180 -0
  63. package/dist/driver/elements.js +70 -0
  64. package/dist/driver/engine-main.js +13 -0
  65. package/dist/driver/engine.js +499 -0
  66. package/dist/driver/errors.js +11 -0
  67. package/dist/driver/exec.js +66 -0
  68. package/dist/driver/failure.js +156 -0
  69. package/dist/driver/flow.js +94 -0
  70. package/dist/driver/idle.js +100 -0
  71. package/dist/driver/images.js +68 -0
  72. package/dist/driver/install.js +272 -0
  73. package/dist/driver/lock.js +101 -0
  74. package/dist/driver/look.js +223 -0
  75. package/dist/driver/maestro-child.js +194 -0
  76. package/dist/driver/maestro-runs.js +46 -0
  77. package/dist/driver/paths.js +105 -0
  78. package/dist/driver/pixels.js +144 -0
  79. package/dist/driver/plan.js +108 -0
  80. package/dist/driver/release.js +7 -0
  81. package/dist/driver/runner.js +42 -0
  82. package/dist/driver/selector.js +91 -0
  83. package/dist/driver/session.js +474 -0
  84. package/dist/driver/suggest.js +86 -0
  85. package/dist/driver/supervisor.js +251 -0
  86. package/dist/driver/tree.js +426 -0
  87. package/dist/driver-cli.js +865 -0
  88. package/dist/evidence/device.js +177 -0
  89. package/dist/evidence/evidence.js +304 -0
  90. package/dist/evidence/files.js +92 -0
  91. package/dist/hooks/env.js +81 -0
  92. package/dist/hooks/run.js +101 -0
  93. package/dist/mcp/server.js +69 -0
  94. package/dist/mcp/tools.js +246 -0
  95. package/dist/name.js +22 -0
  96. package/dist/plugin/aims.js +465 -0
  97. package/dist/plugin/conventions.js +73 -0
  98. package/dist/plugin/guard.js +163 -0
  99. package/dist/plugin/hook-cli.js +216 -0
  100. package/dist/plugin/session-name.js +28 -0
  101. package/dist/plugin/shell.js +254 -0
  102. package/dist/processes.js +77 -0
  103. package/dist/project/config.js +316 -0
  104. package/dist/project/schema.js +335 -0
  105. package/dist/project/validate.js +224 -0
  106. package/dist/registry/config.js +142 -0
  107. package/dist/registry/format.js +22 -0
  108. package/dist/registry/owner.js +265 -0
  109. package/dist/registry/paths.js +50 -0
  110. package/dist/registry/ports.js +26 -0
  111. package/dist/registry/prune.js +160 -0
  112. package/dist/registry/refusal.js +53 -0
  113. package/dist/registry/registry.js +1027 -0
  114. package/dist/registry/resources.js +117 -0
  115. package/dist/registry/rows.js +115 -0
  116. package/dist/registry/status.js +85 -0
  117. package/dist/registry/store.js +274 -0
  118. package/dist/registry/types.js +1 -0
  119. package/dist/registry-cli.js +544 -0
  120. package/dist/services/services.js +268 -0
  121. package/dist/services/system.js +189 -0
  122. package/dist/up/deps.js +1 -0
  123. package/dist/up/doctor.js +424 -0
  124. package/dist/up/exec.js +133 -0
  125. package/dist/up/lane-files.js +75 -0
  126. package/dist/up/lane-services.js +38 -0
  127. package/dist/up/maestro-env.js +172 -0
  128. package/dist/up/preflight.js +232 -0
  129. package/dist/up/release.js +148 -0
  130. package/dist/up/resources.js +178 -0
  131. package/dist/up/restart.js +87 -0
  132. package/dist/up/setup.js +28 -0
  133. package/dist/up/up.js +610 -0
  134. package/dist/up-cli.js +258 -0
  135. package/dist/usage.js +16 -0
  136. package/package.json +58 -3
  137. package/schema/agentlane.schema.json +675 -0
  138. package/skills/create-verification-skill/LICENSE +21 -0
  139. package/skills/create-verification-skill/SKILL.md +88 -0
  140. package/skills/dev-loop/LICENSE +21 -0
  141. package/skills/dev-loop/SKILL.md +61 -0
  142. package/skills/device/SKILL.md +8 -0
  143. package/skills/drive/SKILL.md +64 -0
  144. package/skills/maintain-verification-skill/LICENSE +21 -0
  145. package/skills/maintain-verification-skill/SKILL.md +42 -0
  146. package/skills/setup/SKILL.md +80 -0
@@ -0,0 +1,194 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { killGroup } from "./exec.js";
6
+ export class ChildGone extends Error {
7
+ name = 'ChildGone';
8
+ }
9
+ export class CallTimeout extends Error {
10
+ name = 'CallTimeout';
11
+ }
12
+ export function textOf(result) {
13
+ return result.content
14
+ .filter(item => item.type === 'text')
15
+ .map(item => item.text ?? '')
16
+ .join('\n');
17
+ }
18
+ export function imageOf(result) {
19
+ const item = result.content.find(entry => entry.type === 'image' && entry.data);
20
+ return item?.data === undefined ? undefined : { data: item.data, mimeType: item.mimeType ?? 'image/jpeg' };
21
+ }
22
+ export const RUNNER_TOKEN_ENV = 'MAESTRO_RUNNER_TOKEN';
23
+ /**
24
+ * The environment Maestro runs in: JDK 17 first on PATH, the lane's runner token, and for a simulator an `adb` that
25
+ * fails fast ahead of any real one; for an emulator, the SDK's own adb, emulator and avdmanager instead.
26
+ */
27
+ export function maestroEnv(options, stubDir, tempDir) {
28
+ const sdk = options.androidSdk;
29
+ const head = sdk
30
+ ? [
31
+ path.join(options.javaHome, 'bin'),
32
+ path.join(sdk, 'platform-tools'),
33
+ path.join(sdk, 'emulator'),
34
+ path.join(sdk, 'cmdline-tools', 'latest', 'bin'),
35
+ ]
36
+ : [stubDir, path.join(options.javaHome, 'bin')];
37
+ const env = {
38
+ ...options.env,
39
+ JAVA_HOME: options.javaHome,
40
+ PATH: [...head, options.env.PATH ?? '/usr/bin:/bin'].join(path.delimiter),
41
+ MAESTRO_CLI_NO_ANALYTICS: '1',
42
+ MAESTRO_DISABLE_UPDATE_CHECK: 'true',
43
+ [RUNNER_TOKEN_ENV]: options.token,
44
+ ...(sdk ? { ANDROID_HOME: sdk, ANDROID_SDK_ROOT: sdk } : {}),
45
+ };
46
+ env.MAESTRO_OPTS = [options.env.MAESTRO_OPTS, `-Djava.io.tmpdir=${tempDir}`].filter(Boolean).join(' ');
47
+ return env;
48
+ }
49
+ // Maestro lists adb devices during device discovery even when it drives iOS, and a hung adb stalls the session:
50
+ // https://github.com/mobile-dev-inc/Maestro/issues/3635
51
+ function writeAdbStub(dir) {
52
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
53
+ const temp = path.join(dir, `adb.${String(process.pid)}.tmp`);
54
+ fs.writeFileSync(temp, '#!/bin/sh\nexit 1\n', { mode: 0o755 });
55
+ fs.renameSync(temp, path.join(dir, 'adb'));
56
+ }
57
+ /** One `maestro mcp --no-viewer` process, spoken to over stdio JSON-RPC, in its own process group. */
58
+ export class MaestroChild {
59
+ process;
60
+ stdin;
61
+ exited;
62
+ pending = new Map();
63
+ nextId = 0;
64
+ gone;
65
+ tempDir;
66
+ constructor(options) {
67
+ fs.mkdirSync(options.workDir, { recursive: true, mode: 0o700 });
68
+ const stubDir = path.join(options.workDir, 'bin');
69
+ if (!options.androidSdk)
70
+ writeAdbStub(stubDir);
71
+ this.tempDir = fs.mkdtempSync(path.join(options.workDir, `tmp-${String(process.pid)}-`));
72
+ const args = ['mcp', '--no-viewer', '--working-dir', options.workDir];
73
+ this.process = spawn(options.maestro, args, {
74
+ cwd: options.workDir,
75
+ env: maestroEnv(options, stubDir, this.tempDir),
76
+ stdio: ['pipe', 'pipe', options.logFd],
77
+ detached: true,
78
+ });
79
+ const { stdin, stdout } = this.process;
80
+ if (!stdin || !stdout)
81
+ throw new Error('spawn gave Maestro no stdin or stdout pipe');
82
+ this.stdin = stdin;
83
+ options.log(`maestro ${String(this.process.pid)}: ${options.maestro} ${args.join(' ')}`);
84
+ stdin.on('error', () => undefined);
85
+ createInterface({ input: stdout }).on('line', line => {
86
+ this.onLine(line, options.log);
87
+ });
88
+ this.exited = new Promise(resolve => {
89
+ const finish = (why) => {
90
+ if (this.gone !== undefined)
91
+ return;
92
+ this.gone = why;
93
+ options.log(`maestro ${String(this.process.pid)} ${why}`);
94
+ for (const waiter of this.pending.values()) {
95
+ clearTimeout(waiter.timer);
96
+ waiter.reject(new ChildGone(`Maestro ${why}`));
97
+ }
98
+ this.pending.clear();
99
+ killGroup(this.process.pid);
100
+ fs.rmSync(this.tempDir, { recursive: true, force: true });
101
+ resolve(why);
102
+ };
103
+ this.process.on('exit', (code, signal) => {
104
+ finish(`exited (${signal ?? `code ${String(code)}`})`);
105
+ });
106
+ this.process.on('error', error => {
107
+ finish(`failed to start: ${error.message}`);
108
+ });
109
+ });
110
+ }
111
+ static async start(options, timeoutMs = 60_000) {
112
+ const child = new MaestroChild(options);
113
+ try {
114
+ await child.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'agentlane-driver', version: '1' } }, timeoutMs);
115
+ child.write({ jsonrpc: '2.0', method: 'notifications/initialized' });
116
+ return child;
117
+ }
118
+ catch (error) {
119
+ await child.kill();
120
+ throw error;
121
+ }
122
+ }
123
+ get pid() {
124
+ return this.process.pid;
125
+ }
126
+ get alive() {
127
+ return this.gone === undefined;
128
+ }
129
+ onLine(line, log) {
130
+ let message;
131
+ try {
132
+ message = JSON.parse(line);
133
+ }
134
+ catch {
135
+ log(`maestro stdout: ${line.slice(0, 500)}`);
136
+ return;
137
+ }
138
+ if (message.method !== undefined && message.id !== undefined) {
139
+ this.write(message.method === 'ping'
140
+ ? { jsonrpc: '2.0', id: message.id, result: {} }
141
+ : { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'not supported' } });
142
+ return;
143
+ }
144
+ if (typeof message.id !== 'number')
145
+ return;
146
+ const waiter = this.pending.get(message.id);
147
+ if (!waiter)
148
+ return;
149
+ this.pending.delete(message.id);
150
+ clearTimeout(waiter.timer);
151
+ if (message.error)
152
+ waiter.reject(new Error(message.error.message ?? JSON.stringify(message.error)));
153
+ else
154
+ waiter.resolve(message.result);
155
+ }
156
+ write(message) {
157
+ if (this.gone === undefined)
158
+ this.stdin.write(`${JSON.stringify(message)}\n`);
159
+ }
160
+ request(method, params, timeoutMs) {
161
+ if (this.gone !== undefined)
162
+ return Promise.reject(new ChildGone(`Maestro ${this.gone}`));
163
+ const id = ++this.nextId;
164
+ return new Promise((resolve, reject) => {
165
+ const timer = setTimeout(() => {
166
+ this.pending.delete(id);
167
+ reject(new CallTimeout(`Maestro didn't answer ${method} within ${String(Math.round(timeoutMs / 1000))} s`));
168
+ }, timeoutMs);
169
+ this.pending.set(id, { resolve, reject, timer });
170
+ this.write({ jsonrpc: '2.0', id, method, params });
171
+ });
172
+ }
173
+ async callTool(name, args, timeoutMs) {
174
+ const result = (await this.request('tools/call', { name, arguments: args }, timeoutMs));
175
+ return { content: Array.isArray(result?.content) ? result.content : [], isError: result?.isError === true };
176
+ }
177
+ /** Closes stdin so Maestro shuts its sessions down (runner, xcodebuild, port); kills the group if it takes too long. */
178
+ async stop(graceMs = 5000) {
179
+ if (this.gone !== undefined)
180
+ return;
181
+ this.stdin.end();
182
+ const timer = setTimeout(() => {
183
+ killGroup(this.process.pid);
184
+ }, graceMs);
185
+ await this.exited;
186
+ clearTimeout(timer);
187
+ }
188
+ async kill() {
189
+ if (this.gone !== undefined)
190
+ return;
191
+ killGroup(this.process.pid);
192
+ await this.exited;
193
+ }
194
+ }
@@ -0,0 +1,46 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ /**
5
+ * Where `maestro test` writes a run's output when no option moves it: `$XDG_STATE_HOME/maestro/tests` when that is set,
6
+ * else `~/.maestro/tests` (Maestro's `EnvUtils.xdgStateHome`).
7
+ */
8
+ export function maestroRunsDir(env) {
9
+ const xdg = env.XDG_STATE_HOME;
10
+ return xdg ? path.join(xdg, 'maestro', 'tests') : path.join(env.HOME ?? os.homedir(), '.maestro', 'tests');
11
+ }
12
+ function inside(child, parent) {
13
+ const relative = path.relative(parent, child);
14
+ return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
15
+ }
16
+ /**
17
+ * Removes the links in Maestro's runs folder that point into `lanes` at a run that is gone, the ones the lane's
18
+ * maestro made for runs whose lane folder was pruned. Every other entry stays.
19
+ */
20
+ export function sweepMaestroRunLinks(env, lanes) {
21
+ const dir = maestroRunsDir(env);
22
+ let names;
23
+ try {
24
+ names = fs.readdirSync(dir);
25
+ }
26
+ catch {
27
+ return [];
28
+ }
29
+ const removed = [];
30
+ for (const name of names) {
31
+ const link = path.join(dir, name);
32
+ try {
33
+ if (!fs.lstatSync(link).isSymbolicLink())
34
+ continue;
35
+ const target = path.resolve(dir, fs.readlinkSync(link));
36
+ if (!inside(target, lanes) || fs.existsSync(target))
37
+ continue;
38
+ fs.unlinkSync(link);
39
+ removed.push(link);
40
+ }
41
+ catch {
42
+ continue;
43
+ }
44
+ }
45
+ return removed;
46
+ }
@@ -0,0 +1,105 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import crypto from 'node:crypto';
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { diskNames, lanesRoot } from "../registry/paths.js";
6
+ import { DriverError } from "./errors.js";
7
+ import { isAlive } from "./exec.js";
8
+ import { lockHolder } from "./lock.js";
9
+ // sockaddr_un.sun_path holds 104 bytes on macOS and 108 on Linux, terminator included.
10
+ export const SUN_PATH_LIMIT = 100;
11
+ let cachedTemp;
12
+ export function perUserTemp() {
13
+ if (cachedTemp !== undefined)
14
+ return cachedTemp;
15
+ let dir = '/tmp';
16
+ if (process.platform === 'darwin') {
17
+ const result = spawnSync('getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8' });
18
+ const found = result.status === 0 ? result.stdout.trim() : '';
19
+ if (found)
20
+ dir = found;
21
+ }
22
+ cachedTemp = dir;
23
+ return dir;
24
+ }
25
+ export function ensurePrivateDir(dir) {
26
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
27
+ const stat = fs.lstatSync(dir);
28
+ const uid = process.getuid?.();
29
+ if (!stat.isDirectory() || (uid !== undefined && stat.uid !== uid) || (stat.mode & 0o077) !== 0) {
30
+ throw new DriverError(`${dir} holds the driver's sockets, so it must be a directory only you can open (mode 700, owned by you)`, `remove ${dir} and retry`);
31
+ }
32
+ return dir;
33
+ }
34
+ /**
35
+ * Where a lane's driver engine keeps its socket, lock, log and recorded steps. Everything sits in the registry's
36
+ * state dir, except a socket whose path there would be too long for a Unix socket: that goes in a per-user temp
37
+ * folder named by a hash of the state dir, so each registry still gets its own sockets.
38
+ */
39
+ export function enginePaths(stateDir, laneId, temp = perUserTemp()) {
40
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(laneId))
41
+ throw new Error(`'${laneId}' is not a lane id`);
42
+ const dir = path.join(stateDir, 'driver');
43
+ let sockets = dir;
44
+ if (Buffer.byteLength(path.join(sockets, `${laneId}.sock`)) > SUN_PATH_LIMIT) {
45
+ const digest = crypto.createHash('sha256').update(path.resolve(stateDir)).digest('hex').slice(0, 16);
46
+ sockets = path.join(temp, `${diskNames(stateDir).tool}-${digest}`);
47
+ }
48
+ return {
49
+ dir,
50
+ socket: path.join(sockets, `${laneId}.sock`),
51
+ stoppingSocket: path.join(sockets, `${laneId}.stop`),
52
+ lock: path.join(dir, `${laneId}.lock`),
53
+ log: path.join(dir, `${laneId}.log`),
54
+ steps: path.join(dir, `${laneId}.steps.jsonl`),
55
+ work: path.join(dir, laneId),
56
+ releasing: path.join(dir, `${laneId}.releasing`),
57
+ volatile: path.join(dir, `${laneId}.volatile.json`),
58
+ idle: path.join(dir, `${laneId}.idle.json`),
59
+ shots: path.join(lanesRoot(stateDir), laneId, 'shots'),
60
+ };
61
+ }
62
+ const LANE_FILE = /^([0-9a-f]{8})(?:\.[A-Za-z0-9.]+)?$/;
63
+ /**
64
+ * Removes the driver files of lanes that are no longer live (logs, recorded steps, learned labels, stale locks
65
+ * and working folders) once none of a lane's files has changed for `keepMs`. A lane whose engine still holds
66
+ * its lock is left alone.
67
+ */
68
+ export function pruneDriverFiles(stateDir, liveIds, now, keepMs) {
69
+ const dir = path.join(stateDir, 'driver');
70
+ let names;
71
+ try {
72
+ names = fs.readdirSync(dir);
73
+ }
74
+ catch {
75
+ return [];
76
+ }
77
+ const byLane = new Map();
78
+ for (const name of names) {
79
+ const id = LANE_FILE.exec(name)?.[1];
80
+ if (id === undefined || liveIds.has(id))
81
+ continue;
82
+ byLane.set(id, [...(byLane.get(id) ?? []), name]);
83
+ }
84
+ const removed = [];
85
+ for (const [id, files] of byLane) {
86
+ let newest = 0;
87
+ try {
88
+ for (const name of files)
89
+ newest = Math.max(newest, fs.statSync(path.join(dir, name)).mtimeMs);
90
+ }
91
+ catch {
92
+ continue;
93
+ }
94
+ if (now - newest < keepMs)
95
+ continue;
96
+ const lock = path.join(dir, `${id}.lock`);
97
+ const holder = lockHolder(lock);
98
+ if (holder && isAlive(holder.pid))
99
+ continue;
100
+ for (const name of files)
101
+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });
102
+ removed.push(id);
103
+ }
104
+ return removed;
105
+ }
@@ -0,0 +1,144 @@
1
+ import zlib from 'node:zlib';
2
+ import { contentElements } from "./look.js";
3
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
4
+ const CHANNELS = { 0: 1, 2: 3, 4: 2, 6: 4 };
5
+ function paeth(a, b, c) {
6
+ const p = a + b - c;
7
+ const pa = Math.abs(p - a);
8
+ const pb = Math.abs(p - b);
9
+ const pc = Math.abs(p - c);
10
+ if (pa <= pb && pa <= pc)
11
+ return a;
12
+ return pb <= pc ? b : c;
13
+ }
14
+ /** Decodes an 8-bit, non-interlaced PNG (grey, grey+alpha, RGB or RGBA), which is what sips writes. */
15
+ export function decodePng(png) {
16
+ if (png.length < 8 || !png.subarray(0, 8).equals(PNG_SIGNATURE))
17
+ throw new Error('not a PNG');
18
+ let offset = 8;
19
+ let width = 0;
20
+ let height = 0;
21
+ let channels = 0;
22
+ const idat = [];
23
+ while (offset + 8 <= png.length) {
24
+ const length = png.readUInt32BE(offset);
25
+ const type = png.toString('latin1', offset + 4, offset + 8);
26
+ const body = png.subarray(offset + 8, offset + 8 + length);
27
+ offset += 12 + length;
28
+ if (type === 'IHDR') {
29
+ width = body.readUInt32BE(0);
30
+ height = body.readUInt32BE(4);
31
+ const depth = body[8];
32
+ const colorType = body[9] ?? -1;
33
+ const interlace = body[12];
34
+ channels = CHANNELS[colorType] ?? 0;
35
+ if (depth !== 8 || channels === 0 || interlace !== 0) {
36
+ throw new Error(`unsupported PNG (bit depth ${String(depth)}, color type ${String(colorType)}, interlace ${String(interlace)})`);
37
+ }
38
+ }
39
+ else if (type === 'IDAT') {
40
+ idat.push(body);
41
+ }
42
+ else if (type === 'IEND') {
43
+ break;
44
+ }
45
+ }
46
+ if (width === 0 || height === 0)
47
+ throw new Error('PNG has no IHDR');
48
+ const raw = zlib.inflateSync(Buffer.concat(idat));
49
+ const stride = width * channels;
50
+ const data = new Uint8Array(height * stride);
51
+ for (let y = 0; y < height; y++) {
52
+ const filter = raw[y * (stride + 1)];
53
+ const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1));
54
+ for (let i = 0; i < stride; i++) {
55
+ const left = i >= channels ? (data[y * stride + i - channels] ?? 0) : 0;
56
+ const up = y > 0 ? (data[(y - 1) * stride + i] ?? 0) : 0;
57
+ const upLeft = y > 0 && i >= channels ? (data[(y - 1) * stride + i - channels] ?? 0) : 0;
58
+ const value = line[i] ?? 0;
59
+ let out;
60
+ switch (filter) {
61
+ case 0:
62
+ out = value;
63
+ break;
64
+ case 1:
65
+ out = value + left;
66
+ break;
67
+ case 2:
68
+ out = value + up;
69
+ break;
70
+ case 3:
71
+ out = value + ((left + up) >> 1);
72
+ break;
73
+ case 4:
74
+ out = value + paeth(left, up, upLeft);
75
+ break;
76
+ default:
77
+ throw new Error(`PNG row ${String(y)} has unknown filter ${String(filter)}`);
78
+ }
79
+ data[y * stride + i] = out & 0xff;
80
+ }
81
+ }
82
+ return { width, height, channels, data };
83
+ }
84
+ export const EDGE_DELTA = 48;
85
+ export const BLANK_EDGE_SHARE = 0.004;
86
+ const COVER_PAD_POINTS = 3;
87
+ /**
88
+ * How much drawn detail the screenshot shows where the accessibility tree has nothing. Covered areas are the readable
89
+ * elements' bounds (plus a small pad for anti-aliasing) and the status bar; everything else is scanned for sharp edges.
90
+ * Flat fills and soft gradients (a short page's empty space, a dimmed backdrop) have none; text, map tiles and drawn
91
+ * rows have many.
92
+ */
93
+ export function uncoveredDetail(image, screen, covered) {
94
+ const { width, height, channels, data } = image;
95
+ const sx = width / Math.max(1, screen.x2 - screen.x1);
96
+ const sy = height / Math.max(1, screen.y2 - screen.y1);
97
+ const mask = new Uint8Array(width * height);
98
+ for (const rect of covered) {
99
+ const x1 = Math.max(0, Math.floor((rect.x1 - screen.x1 - COVER_PAD_POINTS) * sx));
100
+ const x2 = Math.min(width, Math.ceil((rect.x2 - screen.x1 + COVER_PAD_POINTS) * sx));
101
+ const y1 = Math.max(0, Math.floor((rect.y1 - screen.y1 - COVER_PAD_POINTS) * sy));
102
+ const y2 = Math.min(height, Math.ceil((rect.y2 - screen.y1 + COVER_PAD_POINTS) * sy));
103
+ for (let y = y1; y < y2; y++)
104
+ mask.fill(1, y * width + x1, y * width + x2);
105
+ }
106
+ const colors = Math.min(channels, 3);
107
+ const at = (x, y, c) => data[(y * width + x) * channels + Math.min(c, channels - 1)] ?? 0;
108
+ let free = 0;
109
+ let edges = 0;
110
+ for (let y = 0; y < height - 1; y++) {
111
+ for (let x = 0; x < width - 1; x++) {
112
+ const index = y * width + x;
113
+ if (mask[index] || mask[index + 1] || mask[index + width])
114
+ continue;
115
+ free += 1;
116
+ let delta = 0;
117
+ for (let c = 0; c < colors; c++) {
118
+ const here = at(x, y, c);
119
+ delta = Math.max(delta, Math.abs(here - at(x + 1, y, c)), Math.abs(here - at(x, y + 1, c)));
120
+ }
121
+ if (delta > EDGE_DELTA)
122
+ edges += 1;
123
+ }
124
+ }
125
+ return { uncovered: free / Math.max(1, (width - 1) * (height - 1)), edges: free === 0 ? 0 : edges / free };
126
+ }
127
+ export function judgeUncovered(detail) {
128
+ return detail.edges < BLANK_EDGE_SHARE ? 'blank' : 'drawn';
129
+ }
130
+ /** The rects that count as read: the status bar band and every content element of the read. */
131
+ export function coveredRects(read) {
132
+ const { statusBar, elements } = contentElements(read);
133
+ return [statusBar, ...elements.flatMap(element => (element.node.bounds ? [element.node.bounds] : []))];
134
+ }
135
+ /**
136
+ * Re-judges a sparse read with its screenshot. When the parts of the screen the tree doesn't explain are blank, the
137
+ * screen really is short (a short page, a small sheet over a plain backdrop), so the read is complete after all.
138
+ */
139
+ export function refineSparseness(read, sparseness, image) {
140
+ const pixels = uncoveredDetail(image, read.screen, coveredRects(read));
141
+ if (!sparseness.sparse || judgeUncovered(pixels) === 'drawn')
142
+ return { ...sparseness, pixels };
143
+ return { ...sparseness, sparse: false, reason: undefined, pixels };
144
+ }
@@ -0,0 +1,108 @@
1
+ import { stringify } from 'yaml';
2
+ import { parseFlow } from "./flow.js";
3
+ import { selectorsOfStep } from "./selector.js";
4
+ function isRecord(value) {
5
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ }
7
+ /** Gives a bare command list the `appId` header Maestro requires, from the caller or the session's last flow. */
8
+ export function prepareFlow(yaml, appId) {
9
+ const flow = parseFlow(yaml);
10
+ if (flow.error !== undefined || flow.config !== undefined || appId === undefined) {
11
+ return { source: yaml, flow, appId: flow.appId, headerAdded: false };
12
+ }
13
+ const source = `${stringify({ appId })}---\n${yaml}`;
14
+ return { source, flow: parseFlow(source), appId, headerAdded: true };
15
+ }
16
+ function headerOf(flow) {
17
+ return `${stringify(flow.config ?? {})}---\n`;
18
+ }
19
+ const QUICK_COMMANDS = new Set(['tapOn', 'doubleTapOn', 'longPressOn']);
20
+ /** A tap that neither waits for the screen to settle nor taps again when nothing seems to change. */
21
+ export function quickBody(body) {
22
+ if (!isRecord(body))
23
+ return body;
24
+ const [command] = Object.keys(body);
25
+ if (command === undefined || !QUICK_COMMANDS.has(command))
26
+ return body;
27
+ let target = body[command];
28
+ if (typeof target === 'string')
29
+ target = { text: target };
30
+ if (!isRecord(target))
31
+ return body;
32
+ return { [command]: { ...target, waitToSettleTimeoutMs: target.waitToSettleTimeoutMs ?? 0, retryTapIfNoChange: false } };
33
+ }
34
+ export function flowYaml(flow, steps, quick) {
35
+ return `${headerOf(flow)}${stringify(steps.map(step => (quick ? quickBody(step.body) : step.body)))}`;
36
+ }
37
+ // Maestro keeps script outputs, copied text, recordings and loop state inside one `run` call, so only commands that
38
+ // use none of them behave the same when each runs in a call of its own.
39
+ const STATELESS_COMMANDS = new Set([
40
+ 'addMedia',
41
+ 'assertNotVisible',
42
+ 'assertVisible',
43
+ 'back',
44
+ 'clearKeychain',
45
+ 'clearState',
46
+ 'doubleTapOn',
47
+ 'eraseText',
48
+ 'extendedWaitUntil',
49
+ 'hideKeyboard',
50
+ 'inputRandomEmail',
51
+ 'inputRandomNumber',
52
+ 'inputRandomPersonName',
53
+ 'inputRandomText',
54
+ 'inputText',
55
+ 'killApp',
56
+ 'launchApp',
57
+ 'longPressOn',
58
+ 'openLink',
59
+ 'pressKey',
60
+ 'scroll',
61
+ 'scrollUntilVisible',
62
+ 'setAirplaneMode',
63
+ 'setLocation',
64
+ 'setOrientation',
65
+ 'setPermissions',
66
+ 'stopApp',
67
+ 'swipe',
68
+ 'takeScreenshot',
69
+ 'tapOn',
70
+ 'toggleAirplaneMode',
71
+ 'waitForAnimationToEnd',
72
+ ]);
73
+ /** Whether the flow can run one step per Maestro call, so a failure names its step and absence checks read the screen. */
74
+ export function splittable(flow) {
75
+ if (flow.error !== undefined || flow.steps.length < 2)
76
+ return false;
77
+ const config = flow.config ?? {};
78
+ if ('onFlowStart' in config || 'onFlowComplete' in config)
79
+ return false;
80
+ return flow.steps.every(step => STATELESS_COMMANDS.has(step.command) && !/\boutput\.|copiedText/.test(step.source));
81
+ }
82
+ export function absenceSelectors(step) {
83
+ return selectorsOfStep(step)
84
+ .filter(entry => entry.expect === 'absent')
85
+ .map(entry => entry.selector);
86
+ }
87
+ const READ_ONLY_COMMANDS = new Set([
88
+ 'assertVisible',
89
+ 'assertNotVisible',
90
+ 'assertTrue',
91
+ 'extendedWaitUntil',
92
+ 'takeScreenshot',
93
+ 'waitForAnimationToEnd',
94
+ ]);
95
+ /**
96
+ * The absence steps of a flow run in one Maestro call whose screen is still the one after the flow: those followed only
97
+ * by steps that read the screen. An earlier absence step was judged on a screen that is gone.
98
+ */
99
+ export function finalAbsenceSteps(steps) {
100
+ const out = [];
101
+ for (const step of steps.toReversed()) {
102
+ if (!READ_ONLY_COMMANDS.has(step.command))
103
+ break;
104
+ if (absenceSelectors(step).length > 0)
105
+ out.unshift(step);
106
+ }
107
+ return out;
108
+ }
@@ -0,0 +1,7 @@
1
+ export const MAESTRO_RELEASE = {
2
+ version: '2.11.0-agentlane.1',
3
+ asset: 'maestro-2.11.0-agentlane.1.zip',
4
+ size: 314_868_792,
5
+ sha256: 'c79f6b2960eb2af7cb39953b1f9a8c77cd068d9c5b95d6a49f29eccc47e5f308',
6
+ url: 'https://github.com/north-star-hq/agentlane/releases/download/maestro-v2.11.0-agentlane.1/maestro-2.11.0-agentlane.1.zip',
7
+ };
@@ -0,0 +1,42 @@
1
+ import { runCommand } from "./exec.js";
2
+ export function parseProcessRows(text) {
3
+ const rows = [];
4
+ for (const line of text.split('\n')) {
5
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
6
+ if (!match)
7
+ continue;
8
+ rows.push({
9
+ pid: Number(match[1]),
10
+ ppid: Number(match[2]),
11
+ pgid: Number(match[3]),
12
+ rssKb: Number(match[4]),
13
+ command: match[5] ?? '',
14
+ });
15
+ }
16
+ return rows;
17
+ }
18
+ export async function processRows() {
19
+ const ran = await runCommand('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,rss=,command='], {
20
+ env: { PATH: `${process.env.PATH ?? ''}:/bin:/usr/bin`, LC_ALL: 'C' },
21
+ timeoutMs: 10_000,
22
+ });
23
+ return parseProcessRows(ran.stdout);
24
+ }
25
+ export const RUNNER_EXECUTABLE = 'maestro-driver-iosUITests-Runner';
26
+ /** The XCTest runner Maestro installs on this simulator: its executable lives in the simulator's data folder. */
27
+ export function runnersOn(rows, udid) {
28
+ return rows.filter(row => row.command.includes(`/CoreSimulator/Devices/${udid}/`) && row.command.includes(RUNNER_EXECUTABLE));
29
+ }
30
+ export async function listeningPorts(pid) {
31
+ const ran = await runCommand('lsof', ['-nP', '-a', '-p', String(pid), '-iTCP', '-sTCP:LISTEN', '-Fn'], {
32
+ env: { PATH: `${process.env.PATH ?? ''}:/usr/sbin:/usr/bin`, LC_ALL: 'C' },
33
+ timeoutMs: 10_000,
34
+ });
35
+ const ports = new Set();
36
+ for (const line of ran.stdout.split('\n')) {
37
+ const port = /^n.*:(\d+)$/.exec(line)?.[1];
38
+ if (port !== undefined)
39
+ ports.add(Number(port));
40
+ }
41
+ return [...ports];
42
+ }