agentlane 0.4.1 → 0.5.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/agents/claude-plugin.js +54 -8
  3. package/dist/agents/cli.js +11 -4
  4. package/dist/agents/hook-check.js +290 -0
  5. package/dist/agents/launcher.js +34 -6
  6. package/dist/agents/wiring-check.js +10 -4
  7. package/dist/agents/wiring.js +6 -33
  8. package/dist/browser/env.js +27 -7
  9. package/dist/browser/install.js +144 -6
  10. package/dist/browser/lane-browser.js +6 -3
  11. package/dist/browser/stop.js +2 -17
  12. package/dist/cache/key.js +23 -11
  13. package/dist/cli.js +63 -23
  14. package/dist/devices/backend.js +6 -0
  15. package/dist/devices/emulator.js +15 -5
  16. package/dist/devices/simctl.js +15 -3
  17. package/dist/disk-limits.js +134 -0
  18. package/dist/driver/caller.js +21 -6
  19. package/dist/driver/client.js +9 -5
  20. package/dist/driver/engine.js +29 -14
  21. package/dist/driver/install.js +88 -36
  22. package/dist/driver/paths.js +15 -11
  23. package/dist/driver/session.js +4 -1
  24. package/dist/driver/superseded.js +378 -0
  25. package/dist/driver-cli.js +32 -23
  26. package/dist/evidence/device.js +4 -0
  27. package/dist/evidence/evidence.js +4 -2
  28. package/dist/evidence/files.js +68 -0
  29. package/dist/evidence/strays.js +107 -0
  30. package/dist/hooks/env.js +2 -1
  31. package/dist/mcp/server.js +15 -0
  32. package/dist/mcp/tools.js +9 -1
  33. package/dist/plugin/guard.js +30 -0
  34. package/dist/plugin/hook-cli.js +101 -6
  35. package/dist/plugin/hook-mark.js +73 -0
  36. package/dist/plugin/hook-once.js +78 -0
  37. package/dist/plugin/shell.js +109 -8
  38. package/dist/processes.js +52 -2
  39. package/dist/registry/config.js +12 -8
  40. package/dist/registry/holds.js +37 -0
  41. package/dist/registry/leases.js +109 -0
  42. package/dist/registry/owner-checks.js +55 -0
  43. package/dist/registry/owner.js +18 -0
  44. package/dist/registry/parks.js +60 -0
  45. package/dist/registry/paths.js +28 -4
  46. package/dist/registry/ports.js +5 -1
  47. package/dist/registry/prune.js +643 -24
  48. package/dist/registry/refusal.js +1 -0
  49. package/dist/registry/registry.js +1258 -235
  50. package/dist/registry/rows.js +18 -4
  51. package/dist/registry/status.js +51 -8
  52. package/dist/registry/store.js +63 -1
  53. package/dist/registry/touch.js +180 -0
  54. package/dist/registry-cli.js +197 -36
  55. package/dist/services/services.js +223 -54
  56. package/dist/services/system.js +2 -1
  57. package/dist/up/answers.js +124 -0
  58. package/dist/up/doctor.js +27 -3
  59. package/dist/up/exec.js +29 -4
  60. package/dist/up/lane-files.js +26 -8
  61. package/dist/up/lane-services.js +8 -3
  62. package/dist/up/park.js +146 -0
  63. package/dist/up/preflight.js +2 -10
  64. package/dist/up/release.js +20 -24
  65. package/dist/up/restart.js +9 -2
  66. package/dist/up/sweep.js +437 -0
  67. package/dist/up/up.js +33 -12
  68. package/dist/up/wake.js +124 -0
  69. package/dist/up/waker.js +49 -0
  70. package/dist/up-cli.js +6 -1
  71. package/package.json +2 -2
  72. package/skills/dev-loop/SKILL.md +7 -5
  73. package/skills/drive/SKILL.md +4 -0
  74. package/skills/setup/SKILL.md +2 -2
@@ -3,17 +3,19 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { promisify } from 'node:util';
6
+ import { rotateLog } from "../disk-limits.js";
6
7
  import { JAVA_HOME_ENV } from "../hooks/env.js";
7
8
  import { EMULATOR_NAME_PREFIX, FORMER } from "../name.js";
8
9
  import { emulatorSerial } from "../registry/config.js";
9
10
  import { isPoolName } from "../registry/paths.js";
10
11
  import { UsageError } from "../registry/refusal.js";
11
- import { DeviceBackendError } from "./backend.js";
12
+ import { DeviceBackendError, DeviceRunningError } from "./backend.js";
12
13
  export const MAESTRO_DRIVER_PACKAGE = 'dev.mobile.maestro';
13
14
  export const DEFAULT_DEVICE_PROFILE = 'pixel_8';
14
15
  export const EMULATOR_FLAGS = ['-no-window', '-no-audio', '-no-boot-anim'];
15
16
  const BOOT_TIMEOUT_MS = 300_000;
16
17
  const STOP_TIMEOUT_MS = 60_000;
18
+ export const EMULATOR_LOG_MAX_BYTES = 5 * 1024 * 1024;
17
19
  const execFileAsync = promisify(execFile);
18
20
  function isFile(file) {
19
21
  try {
@@ -168,13 +170,15 @@ export function readAvds(home) {
168
170
  }
169
171
  return files.map(file => {
170
172
  const name = file.slice(0, -'.ini'.length);
171
- const pointer = readProperties(path.join(home, file));
172
- const dir = pointer.get('path') ?? path.join(home, `${name}.avd`);
173
+ const ini = path.join(home, file);
174
+ const dir = readProperties(ini).get('path') ?? path.join(home, `${name}.avd`);
173
175
  const config = readProperties(path.join(dir, 'config.ini'));
174
176
  return {
175
177
  name,
176
178
  deviceType: config.get('hw.device.name') ?? '',
177
179
  runtime: sysdirToImage(config.get('image.sysdir.1') ?? ''),
180
+ ini,
181
+ dir,
178
182
  };
179
183
  });
180
184
  }
@@ -292,6 +296,8 @@ export function createEmulatorBackend(options) {
292
296
  deviceType: avd.deviceType,
293
297
  runtime: avd.runtime,
294
298
  booted: live.has(avd.name),
299
+ stopped: !live.has(avd.name),
300
+ disk: { paths: [avd.ini, avd.dir], bytes: null },
295
301
  ...(serial ? { serial } : {}),
296
302
  };
297
303
  });
@@ -317,9 +323,12 @@ export function createEmulatorBackend(options) {
317
323
  }
318
324
  return name;
319
325
  },
320
- delete(id) {
326
+ delete(id, whenRunning = 'shut-down') {
321
327
  assertPoolAvd(id);
322
- backend.shutdown(id);
328
+ if (whenRunning === 'shut-down')
329
+ backend.shutdown(id);
330
+ else if (!stopped(id))
331
+ throw new DeviceRunningError(id);
323
332
  const tool = sdk().avdmanager;
324
333
  const java = findJavaHome(options.env);
325
334
  if (!tool || !java)
@@ -363,6 +372,7 @@ export function createEmulatorBackend(options) {
363
372
  if (live.has(id))
364
373
  backend.shutdown(id);
365
374
  fs.mkdirSync(options.logDir, { recursive: true, mode: 0o700 });
375
+ rotateLog(log, EMULATOR_LOG_MAX_BYTES);
366
376
  const out = fs.openSync(log, 'a');
367
377
  const started = spawn(sdk().emulator, ['-avd', id, '-port', String(consolePort), ...EMULATOR_FLAGS], {
368
378
  detached: true,
@@ -1,7 +1,8 @@
1
1
  import { execFile, execFileSync } from 'node:child_process';
2
+ import path from 'node:path';
2
3
  import { promisify } from 'node:util';
3
4
  import { UsageError } from "../registry/refusal.js";
4
- import { DeviceBackendError } from "./backend.js";
5
+ import { DeviceBackendError, DeviceRunningError } from "./backend.js";
5
6
  const UDID = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/;
6
7
  const execFileAsync = promisify(execFile);
7
8
  function simctl(args, timeoutMs = 60_000) {
@@ -74,7 +75,15 @@ export function parseDeviceList(json) {
74
75
  if (!runtime.includes('SimRuntime.iOS-'))
75
76
  continue;
76
77
  for (const d of list) {
77
- devices.push({ id: d.udid, name: d.name, deviceType: d.deviceTypeIdentifier ?? '', runtime, booted: d.state === 'Booted' });
78
+ devices.push({
79
+ id: d.udid,
80
+ name: d.name,
81
+ deviceType: d.deviceTypeIdentifier ?? '',
82
+ runtime,
83
+ booted: d.state === 'Booted',
84
+ stopped: d.state === 'Shutdown',
85
+ ...(d.dataPath ? { disk: { paths: [path.dirname(d.dataPath)], bytes: d.dataPathSize ?? null } } : {}),
86
+ });
78
87
  }
79
88
  }
80
89
  return devices;
@@ -94,7 +103,10 @@ export const simctlBackend = {
94
103
  throw new DeviceBackendError(`xcrun simctl create printed '${udid}', not a UDID`);
95
104
  return udid;
96
105
  },
97
- delete(id) {
106
+ delete(id, whenRunning) {
107
+ if (whenRunning === 'refuse' && parseDeviceList(simctl(['list', '-j', 'devices'])).some(d => d.id === id && !d.stopped)) {
108
+ throw new DeviceRunningError(id);
109
+ }
98
110
  simctl(['delete', id], 120_000);
99
111
  },
100
112
  shutdown(id) {
@@ -0,0 +1,134 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ const NEWLINE = 0x0a;
5
+ const STALE_ROTATION_MS = 30_000;
6
+ /**
7
+ * Cuts a line-per-entry file, once it outgrows `maxBytes`, to its newest whole lines within `keepBytes` (the newest
8
+ * line alone when it is longer). The cut replaces the file by rename, so a reader sees the old file or the new one,
9
+ * never half a line. A failed cut leaves the file as it was and returns false.
10
+ */
11
+ export function keepNewestLinesAsSoleWriter(file, limit) {
12
+ let size;
13
+ try {
14
+ size = fs.statSync(file).size;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ if (size <= limit.maxBytes)
20
+ return false;
21
+ const aside = `${file}.cut.${String(process.pid)}`;
22
+ try {
23
+ const data = fs.readFileSync(file);
24
+ let start = data.indexOf(NEWLINE, Math.max(0, data.length - limit.keepBytes - 1)) + 1;
25
+ if (start === 0 || start >= data.length)
26
+ start = data.lastIndexOf(NEWLINE, data.length - 2) + 1;
27
+ fs.writeFileSync(aside, data.subarray(start), { mode: 0o600 });
28
+ fs.renameSync(aside, file);
29
+ return true;
30
+ }
31
+ catch {
32
+ fs.rmSync(aside, { force: true });
33
+ return false;
34
+ }
35
+ }
36
+ function takeRotation(lock) {
37
+ try {
38
+ fs.closeSync(fs.openSync(lock, 'wx', 0o600));
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ if (error.code !== 'EEXIST')
43
+ return false;
44
+ }
45
+ try {
46
+ if (Date.now() - fs.statSync(lock).mtimeMs > STALE_ROTATION_MS)
47
+ fs.rmSync(lock, { force: true });
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ return false;
53
+ }
54
+ /**
55
+ * Moves a log that outgrew `maxBytes` to `<file>.1`, replacing the one before, so the log and its previous
56
+ * generation hold at most about twice that. Writers that opened the log before the move keep writing into `.1`, so
57
+ * a rotation loses only the generation it replaces; one process at a time rotates, under `<file>.rotating`.
58
+ */
59
+ export function rotateLog(file, maxBytes) {
60
+ const over = () => {
61
+ try {
62
+ return fs.statSync(file).size > maxBytes;
63
+ }
64
+ catch {
65
+ return false;
66
+ }
67
+ };
68
+ if (!over())
69
+ return false;
70
+ const lock = `${file}.rotating`;
71
+ if (!takeRotation(lock))
72
+ return false;
73
+ try {
74
+ if (!over())
75
+ return false;
76
+ fs.renameSync(file, `${file}.1`);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ finally {
83
+ fs.rmSync(lock, { force: true });
84
+ }
85
+ }
86
+ const BACKUP_STAMP = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-/;
87
+ /** The part of an init backup's name that says whose it is: the project folder's name and a hash of its real path. */
88
+ export function backupProject(root) {
89
+ let real;
90
+ try {
91
+ real = fs.realpathSync(root);
92
+ }
93
+ catch {
94
+ real = path.resolve(root);
95
+ }
96
+ return `${path.basename(real)}-${crypto.createHash('sha256').update(real).digest('hex').slice(0, 8)}`;
97
+ }
98
+ /**
99
+ * Removes all but the `keep` most recently written `<stamp>-<project>` folders in `dir`, never `written` (the one
100
+ * just made); returns the ones removed.
101
+ */
102
+ export function keepNewestBackups(dir, project, keep, written) {
103
+ const root = path.resolve(dir);
104
+ let names;
105
+ try {
106
+ names = fs.readdirSync(root);
107
+ }
108
+ catch {
109
+ return [];
110
+ }
111
+ const writtenAt = (name) => {
112
+ try {
113
+ return fs.statSync(path.join(root, name)).mtimeMs;
114
+ }
115
+ catch {
116
+ return Number.POSITIVE_INFINITY;
117
+ }
118
+ };
119
+ const ours = names
120
+ .filter(name => BACKUP_STAMP.test(name) && name.replace(BACKUP_STAMP, '') === project)
121
+ .map(name => ({ name, at: name === written ? Number.POSITIVE_INFINITY : writtenAt(name) }))
122
+ .sort((a, b) => b.at - a.at || b.name.localeCompare(a.name));
123
+ const removed = [];
124
+ for (const { name } of ours.slice(keep)) {
125
+ if (name === written)
126
+ continue;
127
+ const at = path.resolve(root, name);
128
+ if (path.dirname(at) !== root)
129
+ throw new Error(`refusing to remove ${at}: it is not in ${root}`);
130
+ fs.rmSync(at, { recursive: true, force: true });
131
+ removed.push(at);
132
+ }
133
+ return removed;
134
+ }
@@ -1,10 +1,12 @@
1
1
  import fs from 'node:fs';
2
+ import { systemClock } from "../clock.js";
2
3
  import { CLI } from "../name.js";
3
4
  import { describeOwner, ownerKey, resolveOwner } from "../registry/owner.js";
4
5
  import { databasePath, stateDir } from "../registry/paths.js";
5
6
  import { tcpProbe } from "../registry/ports.js";
6
7
  import { NotClaimed } from "../registry/refusal.js";
7
8
  import { Registry } from "../registry/registry.js";
9
+ import { recordCall } from "../registry/touch.js";
8
10
  import { resolveFolder } from "../registry-cli.js";
9
11
  function claimCommand(worktree) {
10
12
  return `${CLI} claim --boot (run in ${worktree}; it claims a simulator for this session), then call again`;
@@ -20,14 +22,24 @@ export function resolveCallerLane(caller) {
20
22
  if (!fs.existsSync(databasePath(dir))) {
21
23
  throw new NotClaimed(`${describeOwner(owner)} holds no lane (there is no registry yet)`, claimCommand(folder.worktree));
22
24
  }
23
- const registry = Registry.open({ dir, processes: caller.processes, ports: tcpProbe, devices: {} });
25
+ const registry = Registry.open({
26
+ dir,
27
+ processes: caller.processes,
28
+ ports: tcpProbe,
29
+ devices: {},
30
+ ...(caller.clock ? { clock: caller.clock } : {}),
31
+ });
24
32
  try {
25
33
  const need = caller.need ?? 'device';
26
- const holds = (c) => need === 'device' ? c.device !== null : need === 'browser' ? c.browser !== null : c.device !== null || c.browser !== null;
27
- let lane = registry.find(owner, folder.worktree);
34
+ const holds = (c, parked = null) => {
35
+ const device = c.device !== null || (parked?.device ?? null) !== null;
36
+ const browser = c.browser !== null || (parked?.browser ?? null) !== null;
37
+ return need === 'device' ? device : need === 'browser' ? browser : device || browser;
38
+ };
39
+ let lane = registry.takeBack(owner, folder.worktree);
28
40
  if (!lane && caller.worktree === undefined) {
29
41
  const key = ownerKey(owner);
30
- const own = registry.status().lanes.filter(c => c.ownerKey === key && holds(c));
42
+ const own = registry.status().lanes.filter(c => c.ownerKey === key && holds(c, c.park?.restarts));
31
43
  const only = own.length === 1 ? own[0] : undefined;
32
44
  if (only)
33
45
  lane = registry.find(owner, only.worktree);
@@ -37,13 +49,16 @@ export function resolveCallerLane(caller) {
37
49
  }
38
50
  if (!lane)
39
51
  throw new NotClaimed(`${describeOwner(owner)} holds no lane in ${folder.worktree}`, claimCommand(folder.worktree));
52
+ if (caller.counts)
53
+ recordCall(dir, { id: lane.id, token: lane.token }, (caller.clock ?? systemClock).now());
54
+ const park = registry.parkOf(lane.id);
40
55
  if (need === 'browser' && !lane.browser) {
41
56
  throw new NotClaimed(`lane ${lane.id} in ${lane.worktree} holds no browser`, `${CLI} up --platform web (it claims a browser and opens the web app in it)`);
42
57
  }
43
- if (!holds(lane)) {
58
+ if (!holds(lane, park?.restarts)) {
44
59
  throw new NotClaimed(`lane ${lane.id} in ${lane.worktree} holds ports but no simulator${need === 'either' ? ' and no browser' : ''}`, need === 'either' ? `${CLI} up` : `${CLI} release, then ${CLI} claim --boot`);
45
60
  }
46
- return { lane, stateDir: dir, owner };
61
+ return { lane, stateDir: dir, owner, park };
47
62
  }
48
63
  finally {
49
64
  registry.close();
@@ -87,15 +87,19 @@ function send(paths, request, timeoutMs) {
87
87
  });
88
88
  });
89
89
  }
90
- async function resolveToolchain(target) {
90
+ export async function resolveToolchain(target) {
91
91
  if (target.toolchain)
92
92
  return target.toolchain;
93
- const jdk = await findJdk17(target.env);
93
+ const javaHome = target.javaHome ?? (await findJdk17(target.env, target.install?.searchJdk17)).javaHome;
94
94
  const override = target.env[MAESTRO_OVERRIDE_ENV];
95
95
  if (override)
96
- return { maestro: override, javaHome: jdk.javaHome };
97
- const installed = await ensureMaestro({ env: target.env, ...(target.progress ? { log: target.progress } : {}) });
98
- return { maestro: installed.binary, javaHome: jdk.javaHome };
96
+ return { maestro: override, javaHome };
97
+ const installed = await ensureMaestro({
98
+ ...target.install,
99
+ env: target.javaHome === undefined ? target.env : { ...target.env, JAVA_HOME: javaHome },
100
+ ...(target.progress ? { log: target.progress } : {}),
101
+ });
102
+ return { maestro: installed.binary, javaHome };
99
103
  }
100
104
  function refOf(lane) {
101
105
  return { id: lane.id, token: lane.token };
@@ -8,8 +8,8 @@ import { findAndroidSdk } from "../devices/emulator.js";
8
8
  import { identityOf, systemProcesses } from "../processes.js";
9
9
  import { isProven, judgeProcess, worktreeState } from "../registry/owner.js";
10
10
  import { tcpProbe } from "../registry/ports.js";
11
- import { Refusal } from "../registry/refusal.js";
12
11
  import { Registry } from "../registry/registry.js";
12
+ import { HEARTBEAT_MS, landTouch, laneHasEnded, recordCall, TOUCH_WAIT_MS } from "../registry/touch.js";
13
13
  import { messageOf } from "./errors.js";
14
14
  import { IdleWatch, writeIdleStop, describeIdle } from "./idle.js";
15
15
  import { sipsImages } from "./images.js";
@@ -38,8 +38,6 @@ function onlyReads(op) {
38
38
  return op === 'ping' || op === 'status' || op === 'look' || op === 'screenshot';
39
39
  }
40
40
  const ACTIONS = {
41
- ping: 'driver ping',
42
- status: 'driver status',
43
41
  look: 'look',
44
42
  screenshot: 'screenshot',
45
43
  run: 'run',
@@ -82,7 +80,7 @@ export async function runEngine(config, deps = {}) {
82
80
  };
83
81
  const device = config.serial ?? config.deviceId;
84
82
  log(`starting for lane ${config.laneId} on ${device} in ${config.worktree}`);
85
- const registry = Registry.open({ dir: config.stateDir, processes, ports: tcpProbe, devices: {}, lockWaitMs: 250 });
83
+ const registry = Registry.open({ dir: config.stateDir, processes, ports: tcpProbe, devices: {}, lockWaitMs: TOUCH_WAIT_MS });
86
84
  const held = () => {
87
85
  const lane = registry.find(config.owner, config.worktree);
88
86
  return (lane?.id === config.laneId &&
@@ -146,34 +144,41 @@ export async function runEngine(config, deps = {}) {
146
144
  let tail = Promise.resolve();
147
145
  let pendingTouch;
148
146
  let lastTouch = 0;
147
+ let touchFailing = false;
149
148
  let resolveDone = () => undefined;
150
149
  const done = new Promise(resolve => {
151
150
  resolveDone = resolve;
152
151
  });
153
152
  const timers = [];
153
+ const laneRef = { id: config.laneId, token: config.token };
154
154
  const flushTouch = () => {
155
155
  if (pendingTouch === undefined || stopping !== undefined)
156
156
  return;
157
157
  const action = pendingTouch;
158
158
  try {
159
- registry.touch({ id: config.laneId, token: config.token }, action);
159
+ if (!landTouch({ dir: config.stateDir, processes, waitMs: 0 }, laneRef, action))
160
+ return;
160
161
  pendingTouch = undefined;
161
162
  lastTouch = Date.now();
163
+ touchFailing = false;
162
164
  }
163
165
  catch (error) {
164
- if (error instanceof Refusal && error.code === 'registry-busy')
165
- return;
166
- if (!stillHeld())
166
+ if (laneHasEnded(error))
167
167
  endLane();
168
- else
169
- void shutdown(`the lane can't be touched: ${messageOf(error).split('\n')[0] ?? ''}`);
168
+ else if (!touchFailing) {
169
+ touchFailing = true;
170
+ log(`the touch will be tried again at the next poll: ${messageOf(error).split('\n')[0] ?? ''}`);
171
+ }
170
172
  }
171
173
  };
172
174
  const touchSoon = (action) => {
175
+ recordCall(config.stateDir, laneRef, Date.now());
173
176
  pendingTouch = action;
174
177
  if (Date.now() - lastTouch >= (config.touchEveryMs ?? 5000))
175
178
  setImmediate(flushTouch);
176
179
  };
180
+ const running = new Map();
181
+ let nextCall = 0;
177
182
  let laneEnded = false;
178
183
  const laneGone = () => ({
179
184
  pid: process.pid,
@@ -269,17 +274,21 @@ export async function runEngine(config, deps = {}) {
269
274
  }, config.idleSampleMs ?? 1500);
270
275
  sampleTimer.unref();
271
276
  };
272
- const isToolCall = (op) => op === 'look' || op === 'run' || op === 'screenshot' || op === 'record';
277
+ const isToolCall = (op) => Object.hasOwn(ACTIONS, op);
273
278
  const serialized = (request) => {
274
279
  clearTimeout(sampleTimer);
275
- const tool = isToolCall(request.op);
276
- if (tool)
280
+ const op = request.op;
281
+ const tool = isToolCall(op);
282
+ const call = nextCall++;
283
+ if (tool) {
277
284
  idle.begin();
285
+ touchSoon(ACTIONS[op]);
286
+ running.set(call, ACTIONS[op]);
287
+ }
278
288
  const job = tail.then(() => (stopping === undefined ? perform(request) : refusal(request, stopping)));
279
289
  tail = job.catch(() => undefined);
280
290
  return job
281
291
  .then((response) => {
282
- touchSoon(ACTIONS[request.op]);
283
292
  if (request.op === 'look' || request.op === 'run' || request.op === 'screenshot')
284
293
  sampleWhenIdle();
285
294
  return response;
@@ -299,6 +308,8 @@ export async function runEngine(config, deps = {}) {
299
308
  })
300
309
  .finally(() => {
301
310
  if (tool) {
311
+ running.delete(call);
312
+ touchSoon(ACTIONS[op]);
302
313
  idle.end();
303
314
  scheduleIdleCheck();
304
315
  }
@@ -477,6 +488,10 @@ export async function runEngine(config, deps = {}) {
477
488
  }
478
489
  flushTouch();
479
490
  }, config.lanePollMs ?? 500), setInterval(() => {
491
+ const action = [...running.values()][0];
492
+ if (stopping === undefined && action !== undefined)
493
+ touchSoon(action);
494
+ }, config.heartbeatMs ?? HEARTBEAT_MS), setInterval(() => {
480
495
  if (stopping !== undefined)
481
496
  return;
482
497
  const owner = config.owner.process;
@@ -11,6 +11,7 @@ import { DriverError } from "./errors.js";
11
11
  import { runCommand, tail } from "./exec.js";
12
12
  import { tryLock, unlock } from "./lock.js";
13
13
  import { MAESTRO_RELEASE } from "./release.js";
14
+ import { compareVersions, laneToolsOf, removeOlderVersions, systemCommandLines, } from "./superseded.js";
14
15
  /** A Maestro binary to use instead of the pinned build, such as a local build of `maestro/`. */
15
16
  export const MAESTRO_OVERRIDE_ENV = envName('MAESTRO');
16
17
  const JDK_FIX = `install JDK 17 ('brew install openjdk@17'), or set ${JAVA_HOME_ENV} to a JDK 17 home`;
@@ -20,9 +21,31 @@ export function dataDir(env) {
20
21
  const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(env.HOME ?? os.homedir(), '.local', 'share');
21
22
  return path.join(base, TOOL);
22
23
  }
24
+ /** The data folder when the environment names it, by XDG_DATA_HOME or HOME, rather than by the OS's idea of home. */
25
+ export function namedDataDir(env) {
26
+ const xdg = env.XDG_DATA_HOME;
27
+ return (xdg && path.isAbsolute(xdg)) || env.HOME ? dataDir(env) : undefined;
28
+ }
23
29
  export function maestroHome(env, release = MAESTRO_RELEASE) {
24
30
  return path.join(dataDir(env), 'maestro', release.version);
25
31
  }
32
+ function lockOf(base, version) {
33
+ return path.join(base, `.${version}.lock`);
34
+ }
35
+ /** The builds this toolkit installed beside the pinned one that are older than it. */
36
+ function olderBuilds(base, release) {
37
+ let names;
38
+ try {
39
+ names = fs.readdirSync(base);
40
+ }
41
+ catch {
42
+ return [];
43
+ }
44
+ return names
45
+ .filter(name => !name.startsWith('.') && compareVersions(name, release.version) < 0)
46
+ .filter(name => readMarker(path.join(base, name))?.version === name)
47
+ .map(name => ({ dir: path.join(base, name), lock: lockOf(base, name) }));
48
+ }
26
49
  function binaryIn(home) {
27
50
  return path.join(home, 'maestro', 'bin', 'maestro');
28
51
  }
@@ -63,43 +86,61 @@ async function javaSettings(home) {
63
86
  javaHome: /^\s*java\.home = (.+)$/m.exec(text)?.[1]?.trim(),
64
87
  };
65
88
  }
66
- /** Finds JDK 17: AGENTLANE_JAVA_HOME, then the way maestro/build.sh does, JAVA_HOME, java_home -v 17 and Homebrew's openjdk@17. */
67
- export async function findJdk17(env) {
68
- let candidate;
69
- let origin;
70
- const named = env[JAVA_HOME_ENV] ? JAVA_HOME_ENV : env.JAVA_HOME ? 'JAVA_HOME' : undefined;
71
- if (named) {
72
- candidate = env[named];
73
- origin = `${named}=${candidate ?? ''}`;
89
+ export const JAVA_HOME_TOOL = '/usr/libexec/java_home';
90
+ /** The JDK 17 macOS has registered. Without -F, java_home prints the default JDK when none matches. */
91
+ export async function registeredJdk17(tool = JAVA_HOME_TOOL) {
92
+ const found = await runCommand(tool, ['-F', '-v', '17'], { timeoutMs: 10_000 });
93
+ return found.code === 0 && found.stdout.trim() ? found.stdout.trim() : undefined;
94
+ }
95
+ /** The way maestro/build.sh looks: java_home -F -v 17, then Homebrew's openjdk@17. */
96
+ export const systemJdk17 = async () => {
97
+ const registered = await registeredJdk17();
98
+ if (registered !== undefined)
99
+ return { home: registered, origin: `${JAVA_HOME_TOOL} -F -v 17` };
100
+ const prefixes = ['/opt/homebrew/opt/openjdk@17', '/usr/local/opt/openjdk@17'];
101
+ if (!prefixes.some(prefix => isExecutable(path.join(prefix, 'bin', 'java')))) {
102
+ const brew = await runCommand('brew', ['--prefix', 'openjdk@17'], { timeoutMs: 10_000 });
103
+ if (brew.code === 0 && brew.stdout.trim())
104
+ prefixes.unshift(brew.stdout.trim());
74
105
  }
75
- else {
76
- const javaHome = await runCommand('/usr/libexec/java_home', ['-v', '17'], { timeoutMs: 10_000 });
77
- if (javaHome.code === 0 && javaHome.stdout.trim()) {
78
- candidate = javaHome.stdout.trim();
79
- origin = '/usr/libexec/java_home -v 17';
80
- }
81
- else {
82
- const prefixes = ['/opt/homebrew/opt/openjdk@17', '/usr/local/opt/openjdk@17'];
83
- if (!prefixes.some(prefix => isExecutable(path.join(prefix, 'bin', 'java')))) {
84
- const brew = await runCommand('brew', ['--prefix', 'openjdk@17'], { timeoutMs: 10_000 });
85
- if (brew.code === 0 && brew.stdout.trim())
86
- prefixes.unshift(brew.stdout.trim());
87
- }
88
- candidate = prefixes.find(prefix => isExecutable(path.join(prefix, 'bin', 'java')));
89
- origin = `Homebrew's openjdk@17 (${candidate ?? 'not installed'})`;
106
+ const home = prefixes.find(prefix => isExecutable(path.join(prefix, 'bin', 'java')));
107
+ return home === undefined ? undefined : { home, origin: `Homebrew's openjdk@17 (${home})` };
108
+ };
109
+ function javaProblem(origin, spec) {
110
+ if (spec === undefined)
111
+ return `${origin} has no working bin/java`;
112
+ if (spec !== '17')
113
+ return `${origin} is Java ${spec}`;
114
+ return undefined;
115
+ }
116
+ export async function findJdk17(env, search = systemJdk17) {
117
+ const pinned = env[JAVA_HOME_ENV];
118
+ if (pinned) {
119
+ const origin = `${JAVA_HOME_ENV}=${pinned}`;
120
+ const settings = await javaSettings(pinned);
121
+ const problem = javaProblem(origin, settings.spec);
122
+ if (problem !== undefined) {
123
+ throw new DriverError(`${problem}, and Maestro runs on JDK 17`, `${JDK_FIX}, or unset ${JAVA_HOME_ENV} so ${TOOL} finds one`);
90
124
  }
125
+ return { javaHome: settings.javaHome ?? pinned, origin };
91
126
  }
92
- if (!candidate)
93
- throw new DriverError('no JDK 17 found; Maestro runs on JDK 17', JDK_FIX);
94
- const fix = named ? `${JDK_FIX}, or unset ${named} so ${TOOL} finds one` : JDK_FIX;
95
- const settings = await javaSettings(candidate);
96
- if (settings.spec === undefined) {
97
- throw new DriverError(`${origin} has no working bin/java`, fix);
98
- }
99
- if (settings.spec !== '17') {
100
- throw new DriverError(`${origin} is Java ${settings.spec}, and Maestro runs on JDK 17`, fix);
127
+ let skipped;
128
+ if (env.JAVA_HOME) {
129
+ const origin = `JAVA_HOME=${env.JAVA_HOME}`;
130
+ const settings = await javaSettings(env.JAVA_HOME);
131
+ skipped = javaProblem(origin, settings.spec);
132
+ if (skipped === undefined)
133
+ return { javaHome: settings.javaHome ?? env.JAVA_HOME, origin };
101
134
  }
102
- return { javaHome: settings.javaHome ?? candidate, origin };
135
+ const found = await search();
136
+ const passedOver = skipped === undefined ? '' : ` (${skipped})`;
137
+ if (!found)
138
+ throw new DriverError(`no JDK 17 found${passedOver}; Maestro runs on JDK 17`, JDK_FIX);
139
+ const settings = await javaSettings(found.home);
140
+ const problem = javaProblem(found.origin, settings.spec);
141
+ if (problem !== undefined)
142
+ throw new DriverError(`${problem}${passedOver}, and Maestro runs on JDK 17`, JDK_FIX);
143
+ return { javaHome: settings.javaHome ?? found.home, origin: found.origin };
103
144
  }
104
145
  export async function sha256Of(file) {
105
146
  const hash = crypto.createHash('sha256');
@@ -172,7 +213,10 @@ async function unpack(release, zip, into, jdk) {
172
213
  throw new DriverError(`the unpacked Maestro prints '${printed ?? ''}' for --version (exit ${String(version.code)}), not ${release.version}: ${tail(version.stderr, 5)}`, `check that ${jdk.origin} is a working JDK 17, then retry '${CLI} driver install'`);
173
214
  }
174
215
  }
175
- /** Installs the pinned Maestro build on first use: download, check against the pinned sha256, unpack, check --version. */
216
+ /**
217
+ * Installs the pinned Maestro build on first use: download, check against the pinned sha256, unpack, check --version.
218
+ * Then removes the older builds it installed that no running process or lane uses.
219
+ */
176
220
  export async function ensureMaestro(options) {
177
221
  const release = options.release ?? MAESTRO_RELEASE;
178
222
  const ready = installedMaestro(options.env, release);
@@ -180,7 +224,7 @@ export async function ensureMaestro(options) {
180
224
  return ready;
181
225
  const started = Date.now();
182
226
  const log = options.log ?? (() => undefined);
183
- const jdk = await findJdk17(options.env);
227
+ const jdk = await findJdk17(options.env, options.searchJdk17);
184
228
  const home = maestroHome(options.env, release);
185
229
  const base = path.dirname(home);
186
230
  fs.mkdirSync(base, { recursive: true, mode: 0o700 });
@@ -188,7 +232,7 @@ export async function ensureMaestro(options) {
188
232
  const me = identityOf(processes, process.pid);
189
233
  if (!me)
190
234
  throw new Error(`ps could not read this process's start time (pid ${String(process.pid)})`);
191
- const lock = path.join(base, `.${release.version}.lock`);
235
+ const lock = lockOf(base, release.version);
192
236
  const deadline = Date.now() + (options.lockWaitMs ?? INSTALL_LOCK_WAIT_MS);
193
237
  let announced = false;
194
238
  for (;;) {
@@ -225,6 +269,14 @@ export async function ensureMaestro(options) {
225
269
  fs.renameSync(home, path.join(work, 'previous'));
226
270
  fs.renameSync(unpacked, home);
227
271
  log(`installed Maestro ${release.version} in ${home}`);
272
+ removeOlderVersions(olderBuilds(base, release), {
273
+ root: namedDataDir(options.env),
274
+ me,
275
+ processes,
276
+ commandLines: options.commandLines ?? systemCommandLines,
277
+ laneTools: options.laneTools ?? laneToolsOf(options.env),
278
+ log,
279
+ });
228
280
  return { home, binary: binaryIn(home), version: release.version, installedNow: true, ms: Date.now() - started };
229
281
  }
230
282
  finally {