agentlane 0.4.1 → 0.5.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.
Files changed (75) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/agents/claude-plugin.js +69 -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/hygiene.js +20 -4
  17. package/dist/devices/simctl.js +15 -3
  18. package/dist/disk-limits.js +134 -0
  19. package/dist/driver/caller.js +21 -6
  20. package/dist/driver/client.js +9 -5
  21. package/dist/driver/engine.js +29 -14
  22. package/dist/driver/install.js +88 -36
  23. package/dist/driver/paths.js +15 -11
  24. package/dist/driver/session.js +4 -1
  25. package/dist/driver/superseded.js +378 -0
  26. package/dist/driver-cli.js +32 -23
  27. package/dist/evidence/device.js +4 -0
  28. package/dist/evidence/evidence.js +4 -2
  29. package/dist/evidence/files.js +68 -0
  30. package/dist/evidence/strays.js +107 -0
  31. package/dist/hooks/env.js +2 -1
  32. package/dist/mcp/server.js +15 -0
  33. package/dist/mcp/tools.js +9 -1
  34. package/dist/plugin/guard.js +30 -0
  35. package/dist/plugin/hook-cli.js +101 -6
  36. package/dist/plugin/hook-mark.js +73 -0
  37. package/dist/plugin/hook-once.js +78 -0
  38. package/dist/plugin/shell.js +109 -8
  39. package/dist/processes.js +52 -2
  40. package/dist/registry/config.js +12 -8
  41. package/dist/registry/holds.js +37 -0
  42. package/dist/registry/leases.js +109 -0
  43. package/dist/registry/owner-checks.js +55 -0
  44. package/dist/registry/owner.js +18 -0
  45. package/dist/registry/parks.js +60 -0
  46. package/dist/registry/paths.js +28 -4
  47. package/dist/registry/ports.js +5 -1
  48. package/dist/registry/prune.js +643 -24
  49. package/dist/registry/refusal.js +1 -0
  50. package/dist/registry/registry.js +1261 -236
  51. package/dist/registry/rows.js +18 -4
  52. package/dist/registry/status.js +51 -8
  53. package/dist/registry/store.js +65 -2
  54. package/dist/registry/touch.js +180 -0
  55. package/dist/registry-cli.js +197 -36
  56. package/dist/services/services.js +227 -56
  57. package/dist/services/system.js +2 -1
  58. package/dist/up/answers.js +124 -0
  59. package/dist/up/doctor.js +29 -4
  60. package/dist/up/exec.js +29 -4
  61. package/dist/up/lane-files.js +26 -8
  62. package/dist/up/lane-services.js +8 -3
  63. package/dist/up/park.js +146 -0
  64. package/dist/up/preflight.js +2 -10
  65. package/dist/up/release.js +20 -24
  66. package/dist/up/restart.js +9 -2
  67. package/dist/up/sweep.js +437 -0
  68. package/dist/up/up.js +38 -15
  69. package/dist/up/wake.js +124 -0
  70. package/dist/up/waker.js +49 -0
  71. package/dist/up-cli.js +6 -1
  72. package/package.json +2 -2
  73. package/skills/dev-loop/SKILL.md +7 -5
  74. package/skills/drive/SKILL.md +4 -0
  75. 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,
@@ -31,6 +31,7 @@ export const STATUS_BAR_PIN_FIELDS = {
31
31
  'Battery Level': '100',
32
32
  };
33
33
  const LOCATION_FRESH_MS = 3000;
34
+ const LOCATION_UNHEARD = 'locationd reports a location only while an app is receiving one';
34
35
  const LOCATION_HEARD_MS = 300_000;
35
36
  const COORDINATE_TOLERANCE = 5e-8;
36
37
  export class HygieneError extends DeviceStateError {
@@ -62,6 +63,9 @@ function formatStatusBar(fields) {
62
63
  const entries = Object.entries(fields ?? {});
63
64
  return entries.length === 0 ? 'no overrides' : entries.map(([key, value]) => `${key} ${value}`).join(', ');
64
65
  }
66
+ function formatWindow(ms) {
67
+ return ms % 60_000 === 0 ? `${String(ms / 60_000)} min` : `${String(Math.round(ms / 1000))} s`;
68
+ }
65
69
  function message(error) {
66
70
  return error instanceof Error ? error.message : String(error);
67
71
  }
@@ -103,6 +107,7 @@ function steps(tools, udid, options) {
103
107
  }
104
108
  },
105
109
  tries: () => `after setting it ${String(sets)} time${sets === 1 ? '' : 's'} over ${String(Math.round((tools.now().getTime() - locationSetAt.getTime()) / 1000))} s`,
110
+ unheard: LOCATION_UNHEARD,
106
111
  };
107
112
  const keyboardStep = {
108
113
  name: 'keyboard',
@@ -147,10 +152,18 @@ function steps(tools, udid, options) {
147
152
  export async function checkHygiene(tools, udid, options = {}) {
148
153
  await requireBooted(tools, udid);
149
154
  const checks = [];
150
- for (const step of steps(tools, udid, { locationLookbackMs: LOCATION_HEARD_MS, ...options })) {
155
+ const lookbackMs = options.locationLookbackMs ?? LOCATION_HEARD_MS;
156
+ for (const step of steps(tools, udid, { ...options, locationLookbackMs: lookbackMs })) {
151
157
  try {
152
158
  const got = await step.read();
153
- checks.push({ step: step.name, wanted: step.wanted, got: step.format(got), ok: step.matches(got) });
159
+ const unheard = got === undefined ? step.unheard : undefined;
160
+ checks.push({
161
+ step: step.name,
162
+ wanted: step.wanted,
163
+ got: step.format(got),
164
+ ok: step.matches(got) || unheard !== undefined,
165
+ ...(unheard ? { unconfirmed: `nothing read back in the last ${formatWindow(lookbackMs)}; ${unheard}` } : {}),
166
+ });
154
167
  }
155
168
  catch (error) {
156
169
  checks.push({ step: step.name, wanted: step.wanted, got: `unreadable (${message(error)})`, ok: false });
@@ -172,7 +185,9 @@ export async function applyHygiene(tools, udid, options = {}) {
172
185
  }
173
186
  await step.apply();
174
187
  const after = await step.readBack();
175
- const ok = step.matches(after);
188
+ const unheard = after === undefined ? step.unheard : undefined;
189
+ const ok = step.matches(after) || unheard !== undefined;
190
+ const tries = step.tries?.();
176
191
  reports.push({
177
192
  step: step.name,
178
193
  wanted: step.wanted,
@@ -180,7 +195,8 @@ export async function applyHygiene(tools, udid, options = {}) {
180
195
  after: step.format(after),
181
196
  changed: true,
182
197
  ok,
183
- ...(!ok && step.tries ? { tries: step.tries() } : {}),
198
+ ...(!ok && tries ? { tries } : {}),
199
+ ...(unheard ? { unconfirmed: `nothing read back${tries ? ` ${tries}` : ''}; ${unheard}` } : {}),
184
200
  });
185
201
  }
186
202
  catch (error) {
@@ -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;