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
@@ -25,9 +25,10 @@ import { MAESTRO_RELEASE } from "./driver/release.js";
25
25
  import { serveMcp } from "./mcp/server.js";
26
26
  import { createToolHandler, TOOLS } from "./mcp/tools.js";
27
27
  import { CLI, TOOL } from "./name.js";
28
- import { tcpProbe } from "./registry/ports.js";
29
28
  import { NotClaimed, Refusal, UsageError } from "./registry/refusal.js";
30
- import { Registry } from "./registry/registry.js";
29
+ import { touchLane } from "./registry/touch.js";
30
+ import { SWEEP_INTERVAL_MS } from "./up/sweep.js";
31
+ import { enterLane } from "./up/wake.js";
31
32
  import { groupUsage, helpOf } from "./usage.js";
32
33
  export const DRIVER_COMMANDS = ['look', 'run', 'screenshot', 'record', 'evidence', 'driver', 'browser', 'device', 'mcp'];
33
34
  export const DRIVER_HELP = {
@@ -101,6 +102,14 @@ function stamp() {
101
102
  function laneFor(deps, worktree, need = 'device') {
102
103
  return resolveCallerLane({ env: deps.env, cwd: deps.cwd, worktree, processes: deps.processes, need });
103
104
  }
105
+ /** The caller's lane for a call on it: the call is recorded, and a parked lane is brought back first. */
106
+ async function enter(deps, worktree, need = 'device') {
107
+ const resolved = resolveCallerLane({ env: deps.env, cwd: deps.cwd, worktree, processes: deps.processes, need, counts: true });
108
+ const lane = await enterLane({ stateDir: resolved.stateDir, processes: deps.processes }, resolved.lane, resolved.park, deps.wake, line => {
109
+ deps.stderr(`${TOOL}: ${line}\n`);
110
+ });
111
+ return { ...resolved, lane, park: null };
112
+ }
104
113
  /** The lane's browser when asked for, or when the lane holds no device; else null, for the device. */
105
114
  function browserTarget(deps, resolved, asked) {
106
115
  const { lane } = resolved;
@@ -194,16 +203,16 @@ async function look(args, deps) {
194
203
  throw new UsageError(`--depth ${values.depth} is not a level count`, 'pass --depth 2');
195
204
  lookArgs.depth = depth;
196
205
  }
197
- const resolved = laneFor(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
206
+ const resolved = await enter(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
198
207
  const browser = values.device ? null : browserTarget(deps, resolved, values.browser);
199
208
  if (browser) {
200
209
  notOnBrowser({ bounds: values.bounds, raw: values.raw }, 'look');
210
+ touch(deps, resolved, 'look: browser');
201
211
  const page = await lookAtBrowser(browser, {
202
212
  interactiveOnly: values.interactive,
203
213
  ...(lookArgs.within === undefined ? {} : { within: lookArgs.within }),
204
214
  ...(lookArgs.depth === undefined ? {} : { depth: lookArgs.depth }),
205
215
  });
206
- touch(deps, resolved, 'look: browser');
207
216
  if (values.json) {
208
217
  deps.stdout(`${JSON.stringify({ ok: true, text: page.text, url: page.url, title: page.title, driver: page.driver, shown: page.shown, interactive: page.interactive }, null, 2)}\n`);
209
218
  }
@@ -265,7 +274,7 @@ async function run(args, deps) {
265
274
  throw new UsageError(`no flow file at ${file}`, 'pass the path of a Maestro flow');
266
275
  runArgs.file = file;
267
276
  }
268
- const resolved = laneFor(deps, values.worktree);
277
+ const resolved = await enter(deps, values.worktree);
269
278
  const driverLogFrom = sizeOf(enginePaths(resolved.stateDir, resolved.lane.id).log);
270
279
  const response = await callEngine(targetOf(deps, resolved), { op: 'run', args: runArgs });
271
280
  let screenshot;
@@ -310,12 +319,12 @@ async function screenshot(args, deps) {
310
319
  }
311
320
  if (values.crop !== undefined)
312
321
  shotArgs.crop = parseCrop(values.crop);
313
- const resolved = laneFor(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
322
+ const resolved = await enter(deps, values.worktree, values.device ? 'device' : values.browser ? 'browser' : 'either');
314
323
  const browser = values.device ? null : browserTarget(deps, resolved, values.browser);
315
324
  if (browser) {
316
325
  notOnBrowser({ scale: values.scale, crop: values.crop }, 'screenshot');
317
- const file = await screenshotBrowser(browser, values.out === undefined ? undefined : path.resolve(deps.cwd, values.out));
318
326
  touch(deps, resolved, 'screenshot: browser');
327
+ const file = await screenshotBrowser(browser, values.out === undefined ? undefined : path.resolve(deps.cwd, values.out));
319
328
  if (values.json)
320
329
  deps.stdout(`${JSON.stringify({ ok: true, file, mimeType: 'image/png' }, null, 2)}\n`);
321
330
  else
@@ -342,7 +351,7 @@ async function record(args, deps) {
342
351
  (action === 'save') !== (file !== undefined)) {
343
352
  throw new UsageError('record takes save <file>, show or clear', `${CLI} record save flows/probe.yaml`);
344
353
  }
345
- const resolved = laneFor(deps, values.worktree);
354
+ const resolved = await enter(deps, values.worktree);
346
355
  const response = await callEngine(targetOf(deps, resolved), {
347
356
  op: 'record',
348
357
  args: { action, ...(file === undefined ? {} : { file: path.resolve(deps.cwd, file) }) },
@@ -390,7 +399,7 @@ async function driver(args, deps) {
390
399
  return 0;
391
400
  }
392
401
  case 'start': {
393
- const resolved = laneFor(deps, values.worktree);
402
+ const resolved = await enter(deps, values.worktree);
394
403
  const started = Date.now();
395
404
  const response = await callEngine(targetOf(deps, resolved), { op: 'look', args: { interactiveOnly: true } });
396
405
  const seconds = (Date.now() - started) / 1000;
@@ -422,6 +431,7 @@ async function driver(args, deps) {
422
431
  }
423
432
  case 'stop': {
424
433
  const resolved = laneFor(deps, values.worktree);
434
+ touch(deps, resolved, 'driver stop');
425
435
  const stopped = await stopEngine(resolved.stateDir, resolved.lane);
426
436
  deps.stdout(stopped ? `Stopped the driver for lane ${resolved.lane.id}.\n` : `No driver ran for lane ${resolved.lane.id}.\n`);
427
437
  return 0;
@@ -483,7 +493,9 @@ async function evidence(args, deps) {
483
493
  if (rest.length > 0)
484
494
  throw new UsageError(`unexpected ${rest.join(' ')}`, EVIDENCE_FIX);
485
495
  const asked = values.browser ? 'browser' : values.device ? 'device' : undefined;
486
- const resolved = laneFor(deps, values.worktree, asked ?? 'either');
496
+ const resolved = what === 'list' ? laneFor(deps, values.worktree, asked ?? 'either') : await enter(deps, values.worktree, asked ?? 'either');
497
+ if (what !== 'list')
498
+ touch(deps, resolved, `evidence ${what}${action ? ` ${action}` : ''}`);
487
499
  const ctx = evidenceContext(deps, resolved);
488
500
  const folder = laneEvidence(resolved.stateDir, resolved.lane.id);
489
501
  let kept;
@@ -530,7 +542,6 @@ async function evidence(args, deps) {
530
542
  default:
531
543
  throw new UsageError(`'evidence ${what}' is not an evidence command`, EVIDENCE_FIX);
532
544
  }
533
- touch(deps, resolved, `evidence ${what}${action ? ` ${action}` : ''}`);
534
545
  if (values.json)
535
546
  deps.stdout(`${JSON.stringify({ ok: kept.problems.length === 0, ...kept }, null, 2)}\n`);
536
547
  else {
@@ -603,7 +614,8 @@ async function device(args, deps) {
603
614
  options: { worktree: { type: 'string' } },
604
615
  });
605
616
  const [control, ...rest] = positionals;
606
- const resolved = laneFor(deps, values.worktree);
617
+ const resolved = await enter(deps, values.worktree);
618
+ touch(deps, resolved, control === undefined ? 'device' : `device ${control}`);
607
619
  const claimed = resolved.lane.device;
608
620
  if (claimed?.platform === 'android') {
609
621
  if (!claimed.serial)
@@ -611,7 +623,6 @@ async function device(args, deps) {
611
623
  const adb = adbTools(deps, claimed.serial);
612
624
  await requireEmulatorBooted(adb);
613
625
  const said = await androidControl(adb, positionals);
614
- touch(deps, resolved, `device ${control ?? ''}`);
615
626
  deps.stdout(`${said}\n`);
616
627
  return 0;
617
628
  }
@@ -685,7 +696,6 @@ async function device(args, deps) {
685
696
  const [action, ...words] = rest;
686
697
  if (action === 'get' && words.length === 0) {
687
698
  deps.stdout(await controls.readClipboard(udid));
688
- touch(deps, resolved, 'device clipboard');
689
699
  return 0;
690
700
  }
691
701
  if (action !== 'set' || words.length === 0)
@@ -709,7 +719,6 @@ async function device(args, deps) {
709
719
  default:
710
720
  notAControl(positionals, `${CLI} device location|permission|appearance|push|clipboard|open ...`);
711
721
  }
712
- touch(deps, resolved, `device ${control}`);
713
722
  deps.stdout(`${said}\n`);
714
723
  return 0;
715
724
  }
@@ -798,13 +807,7 @@ async function androidControl(adb, positionals) {
798
807
  }
799
808
  }
800
809
  function touch(deps, resolved, action) {
801
- const registry = Registry.open({ dir: resolved.stateDir, processes: deps.processes, ports: tcpProbe, devices: {} });
802
- try {
803
- registry.touch({ id: resolved.lane.id, token: resolved.lane.token }, action);
804
- }
805
- finally {
806
- registry.close();
807
- }
810
+ touchLane({ dir: resolved.stateDir, processes: deps.processes }, { id: resolved.lane.id, token: resolved.lane.token }, action);
808
811
  }
809
812
  async function mcp(args, deps) {
810
813
  if (args.length > 0)
@@ -814,7 +817,13 @@ async function mcp(args, deps) {
814
817
  output: deps.output,
815
818
  info: { name: TOOL, version: packageVersion() },
816
819
  tools: TOOLS,
817
- call: createToolHandler({ env: deps.env, cwd: deps.cwd, processes: deps.processes }),
820
+ call: createToolHandler({
821
+ env: deps.env,
822
+ cwd: deps.cwd,
823
+ processes: deps.processes,
824
+ ...(deps.wake ? { wake: deps.wake } : {}),
825
+ }),
826
+ ...(deps.sweep ? { every: { ms: SWEEP_INTERVAL_MS, ...deps.sweep } } : {}),
818
827
  });
819
828
  return 0;
820
829
  }
@@ -3,6 +3,7 @@ import fs from 'node:fs';
3
3
  import { DriverError } from "../driver/errors.js";
4
4
  import { isAlive, runCommand, tail } from "../driver/exec.js";
5
5
  import { TOOL } from "../name.js";
6
+ import { runningStartTimes } from "../processes.js";
6
7
  export const realEvidenceSystem = {
7
8
  run: (command, args, timeoutMs) => runCommand(command, args, { timeoutMs }),
8
9
  start(command, args, log) {
@@ -27,6 +28,7 @@ export const realEvidenceSystem = {
27
28
  });
28
29
  return result.status === 0 && result.stdout.trim() !== '' ? result.stdout.trim() : undefined;
29
30
  },
31
+ startTimes: runningStartTimes,
30
32
  signal(pid, signal) {
31
33
  try {
32
34
  process.kill(pid, signal);
@@ -70,6 +72,7 @@ export async function startDeviceVideo(system, target, file, clock) {
70
72
  const said = fs.existsSync(log) ? tail(fs.readFileSync(log, 'utf8'), 6) : '';
71
73
  throw new DriverError(`the screen recording stopped as it started${said ? `:\n${said}` : ''}`, target.platform === 'ios' ? 'check that the simulator is booted' : 'check that the emulator is booted');
72
74
  }
75
+ const start = system.startTimes([pid])?.get(pid);
73
76
  return {
74
77
  version: 1,
75
78
  target: 'device',
@@ -77,6 +80,7 @@ export async function startDeviceVideo(system, target, file, clock) {
77
80
  file,
78
81
  pid,
79
82
  command: running,
83
+ ...(start === undefined ? {} : { start }),
80
84
  platform: target.platform,
81
85
  device: target.device,
82
86
  ...(target.platform === 'android' ? { remote } : {}),
@@ -9,7 +9,7 @@ import { CLI } from "../name.js";
9
9
  import { UsageError } from "../registry/refusal.js";
10
10
  import { laneDir, readUpRecord } from "../up/lane-files.js";
11
11
  import { startDeviceVideo, stopDeviceVideo, writeDeviceLog } from "./device.js";
12
- import { clearInProgress, copyNewer, newEvidenceFile, newEvidenceFolder, readFrom, readInProgress, sizeOf, writeInProgress, } from "./files.js";
12
+ import { clearInProgress, copyNewer, inodeOf, newEvidenceFile, newEvidenceFolder, readFrom, readInProgress, runsSince, sizeOf, writeInProgress, } from "./files.js";
13
13
  export function laneEvidence(stateDir, laneId) {
14
14
  return evidenceDir(laneDir(stateDir, laneId));
15
15
  }
@@ -134,12 +134,14 @@ export async function startTrace(ctx, target) {
134
134
  return { path: evidence, files: [], notes: [`tracing the ${control.driver} browser's actions`], problems: [] };
135
135
  }
136
136
  const files = driverFiles(ctx);
137
+ const stepsIno = inodeOf(files.steps);
137
138
  writeInProgress(evidence, 'trace', {
138
139
  version: 1,
139
140
  target,
140
141
  startedAt,
141
142
  driverLogBytes: sizeOf(files.log),
142
143
  stepsBytes: sizeOf(files.steps),
144
+ ...(stepsIno === undefined ? {} : { stepsIno }),
143
145
  });
144
146
  return { path: evidence, files: [], notes: ["tracing the driver's calls, the flows run and the device's log"], problems: [] };
145
147
  }
@@ -187,7 +189,7 @@ export async function stopTrace(ctx, target) {
187
189
  kept.files.push(file);
188
190
  };
189
191
  write('driver.log', readFrom(files.log, started.driverLogBytes ?? 0));
190
- write('flows.jsonl', readFrom(files.steps, started.stepsBytes ?? 0));
192
+ write('flows.jsonl', runsSince(files.steps, { bytes: started.stepsBytes ?? 0, ino: started.stepsIno, startedAt: started.startedAt }));
191
193
  kept.files.push(...copyNewer(files.shots, path.join(dir, 'screenshots'), started.startedAt));
192
194
  try {
193
195
  const file = path.join(dir, 'device.log');
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ const NEWLINE = 0x0a;
3
4
  export function evidenceStamp(at = new Date()) {
4
5
  return at
5
6
  .toISOString()
@@ -46,6 +47,10 @@ export function writeInProgress(evidence, kind, state) {
46
47
  fs.mkdirSync(evidence, { recursive: true, mode: 0o700 });
47
48
  fs.writeFileSync(stateFile(evidence, kind, state.target), `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
48
49
  }
50
+ /** Whether a device recording in the evidence folder is marked as running: its recorder may still write there. */
51
+ export function deviceRecordingMarked(evidence) {
52
+ return fs.existsSync(stateFile(evidence, 'video', 'device'));
53
+ }
49
54
  export function clearInProgress(evidence, kind, target) {
50
55
  fs.rmSync(stateFile(evidence, kind, target), { force: true });
51
56
  }
@@ -60,6 +65,69 @@ export function readFrom(file, from) {
60
65
  }
61
66
  return data.subarray(data.length >= from ? from : 0).toString('utf8');
62
67
  }
68
+ /**
69
+ * The recorded runs, one JSON line each, that were recorded since `mark`. While the file is the one the trace saw,
70
+ * those are the lines past its offset. Once it was replaced (a cut, a clear), they are the whole lines after the last
71
+ * one whose `at` is before the trace's start; with none before it, the lines from the first that has an `at`, or every
72
+ * line when none has one, since a 0.4.1 engine of the lane records no `at`.
73
+ */
74
+ export function runsSince(file, mark) {
75
+ let data;
76
+ let ino;
77
+ try {
78
+ const fd = fs.openSync(file, 'r');
79
+ try {
80
+ ino = fs.fstatSync(fd).ino;
81
+ data = fs.readFileSync(fd);
82
+ }
83
+ finally {
84
+ fs.closeSync(fd);
85
+ }
86
+ }
87
+ catch {
88
+ return '';
89
+ }
90
+ const same = (mark.ino === undefined || mark.ino === ino) &&
91
+ data.length >= mark.bytes &&
92
+ (mark.bytes === 0 || data[mark.bytes - 1] === NEWLINE);
93
+ if (same)
94
+ return data.subarray(mark.bytes).toString('utf8');
95
+ const runs = data
96
+ .toString('utf8')
97
+ .split('\n')
98
+ .slice(0, -1)
99
+ .flatMap(line => {
100
+ const at = recordedAt(line);
101
+ return at === null ? [] : [{ line, at }];
102
+ });
103
+ const before = runs.findLastIndex(run => run.at !== undefined && run.at < mark.startedAt);
104
+ const timed = runs.findIndex(run => run.at !== undefined);
105
+ const from = before !== -1 ? before + 1 : Math.max(timed, 0);
106
+ return runs
107
+ .slice(from)
108
+ .map(run => `${run.line}\n`)
109
+ .join('');
110
+ }
111
+ function recordedAt(line) {
112
+ try {
113
+ const run = JSON.parse(line);
114
+ if (typeof run !== 'object' || run === null)
115
+ return null;
116
+ const { at } = run;
117
+ return typeof at === 'number' ? at : undefined;
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ export function inodeOf(file) {
124
+ try {
125
+ return fs.statSync(file).ino;
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ }
63
131
  export function sizeOf(file) {
64
132
  try {
65
133
  return fs.statSync(file).size;
@@ -0,0 +1,107 @@
1
+ import { describeStart, startMs } from "../processes.js";
2
+ import { stopDeviceVideo } from "./device.js";
3
+ import { clearInProgress, deviceRecordingMarked, readInProgress, writeInProgress } from "./files.js";
4
+ /** How long after a sweep left an ended lane's recorder running, unproven, the next sweep looks at it again. */
5
+ export const STRAY_RETRY_MS = 5 * 60_000;
6
+ /** How long before its marker's `startedAt` a recorder may have started: ps reports a start to the second, and spawn takes time. */
7
+ const RECORDER_START_MS = 2000;
8
+ function startedAround(start, startedAt) {
9
+ const at = startMs(start);
10
+ if (Number.isNaN(at))
11
+ return { kind: 'cant-tell', reason: `ps gave its start time as '${start}'` };
12
+ if (at <= startedAt && at > startedAt - RECORDER_START_MS)
13
+ return { kind: 'ours' };
14
+ return {
15
+ kind: 'not-ours',
16
+ reason: `it started ${describeStart(start)}, not as the recording began at ${new Date(startedAt).toISOString()}`,
17
+ };
18
+ }
19
+ /**
20
+ * Whether the process at the recording's pid is its recorder: the command it ran, and the start time recorded with it
21
+ * or, in a marker written before start times were, a start in the second the recording began.
22
+ */
23
+ function judgeRecorder(system, recording) {
24
+ const starts = system.startTimes([recording.pid]);
25
+ if (!starts)
26
+ return { kind: 'cant-tell', reason: 'ps could not read when it started' };
27
+ const start = starts.get(recording.pid);
28
+ if (start === undefined)
29
+ return { kind: 'gone' };
30
+ const command = system.commandOf(recording.pid);
31
+ if (command === undefined)
32
+ return { kind: 'gone' };
33
+ if (recording.command !== undefined && command !== recording.command)
34
+ return { kind: 'not-ours', reason: `it runs ${command.slice(0, 80)}, not ${recording.command.slice(0, 80)}` };
35
+ if (recording.start === undefined)
36
+ return startedAround(start, recording.startedAt);
37
+ if (start === recording.start)
38
+ return { kind: 'ours' };
39
+ return { kind: 'not-ours', reason: `it started ${describeStart(start)}, not ${describeStart(recording.start)}` };
40
+ }
41
+ function deviceRecording(evidence) {
42
+ const recording = readInProgress(evidence, 'video', 'device');
43
+ return recording?.pid === undefined ? null : { ...recording, pid: recording.pid };
44
+ }
45
+ /** Whether the evidence folder of an ended lane marks a device recorder a sweep is to look at now. */
46
+ export function strayDue(evidence, now) {
47
+ if (!deviceRecordingMarked(evidence))
48
+ return false;
49
+ const recording = deviceRecording(evidence);
50
+ return recording !== null && (recording.leftAt === undefined || recording.leftAt <= now - STRAY_RETRY_MS);
51
+ }
52
+ /**
53
+ * Stops the device recorder an ended lane left running, once its pid is proven to be that recorder, so its file is
54
+ * complete. Signals only the recorder on this Mac, never the device, which another lane may hold now. A process the
55
+ * pid names that is not the recorder is left running; one it can't tell about is left marked for a later sweep.
56
+ */
57
+ export async function stopStrayRecorder(system, evidence, lane, clock) {
58
+ const recording = deviceRecording(evidence);
59
+ if (!recording)
60
+ return null;
61
+ const { pid } = recording;
62
+ const leave = () => {
63
+ writeInProgress(evidence, 'video', { ...recording, leftAt: clock.now() });
64
+ };
65
+ const verdict = judgeRecorder(system, recording);
66
+ if (verdict.kind === 'cant-tell') {
67
+ leave();
68
+ return { kind: 'cant-tell', lane, pid, reason: `${verdict.reason}, so it was sent nothing` };
69
+ }
70
+ if (verdict.kind !== 'ours') {
71
+ clearInProgress(evidence, 'video', 'device');
72
+ return verdict.kind === 'gone' ? { kind: 'exited', lane, pid } : { kind: 'not-ours', lane, pid, reason: verdict.reason };
73
+ }
74
+ const stopped = await stopDeviceVideo(system, recording, clock);
75
+ const problems = [
76
+ ...stopped.problems,
77
+ ...(recording.platform === 'android' && recording.remote !== undefined
78
+ ? [`the video stays at ${recording.remote} on emulator ${recording.device ?? '(unknown)'}, which may be another lane's now`]
79
+ : []),
80
+ ];
81
+ const after = judgeRecorder(system, recording);
82
+ if (after.kind === 'ours') {
83
+ leave();
84
+ return { kind: 'survived', lane, pid, problems };
85
+ }
86
+ if (after.kind === 'cant-tell') {
87
+ leave();
88
+ return { kind: 'cant-tell', lane, pid, reason: `it was sent SIGINT, but then ${after.reason}` };
89
+ }
90
+ clearInProgress(evidence, 'video', 'device');
91
+ return { kind: 'stopped', lane, pid, file: stopped.file, problems };
92
+ }
93
+ export function describeStray(stray) {
94
+ const who = `the device recorder (pid ${String(stray.pid)}) lane ${stray.lane} left running`;
95
+ switch (stray.kind) {
96
+ case 'stopped':
97
+ return stray.file ? `stopped ${who}; its video is ${stray.file}` : `stopped ${who}`;
98
+ case 'exited':
99
+ return `${who} had already exited`;
100
+ case 'not-ours':
101
+ return `left pid ${String(stray.pid)} alone: it is not ${who}, since ${stray.reason}`;
102
+ case 'cant-tell':
103
+ return `could not prove pid ${String(stray.pid)} is ${who}: ${stray.reason}; a later sweep looks again`;
104
+ case 'survived':
105
+ return `${who} is still running after SIGINT and SIGKILL`;
106
+ }
107
+ }
package/dist/hooks/env.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { ENV_PREFIX, envName } from "../name.js";
3
3
  import { BUILT_IN_SERVICE_TYPES, WEB_PLATFORM } from "../project/schema.js";
4
+ import { USER_TEMP_ENV } from "../driver/paths.js";
4
5
  import { OWNER_PID_ENV } from "../registry/owner.js";
5
6
  import { STATE_DIR_ENV } from "../registry/paths.js";
6
7
  /** glibc has C.UTF-8 built in, but en_US.UTF-8 only where the locales package generated it; macOS has no C.UTF-8. */
@@ -19,7 +20,7 @@ export const EVIDENCE_ENV = envName('EVIDENCE');
19
20
  export function evidenceDir(logsDir) {
20
21
  return path.join(logsDir, 'evidence');
21
22
  }
22
- const SETTINGS = new Set([STATE_DIR_ENV, OWNER_PID_ENV, JAVA_HOME_ENV]);
23
+ const SETTINGS = new Set([STATE_DIR_ENV, USER_TEMP_ENV, OWNER_PID_ENV, JAVA_HOME_ENV]);
23
24
  export function portVariable(service) {
24
25
  return envName(`${service.toUpperCase().replaceAll('-', '_')}_PORT`);
25
26
  }
@@ -1,10 +1,24 @@
1
1
  import { createInterface } from 'node:readline';
2
2
  const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
3
+ function unrefSleep(ms) {
4
+ return new Promise(resolve => setTimeout(resolve, ms).unref());
5
+ }
6
+ async function repeat(every, open) {
7
+ const wait = every.wait ?? unrefSleep;
8
+ while (open()) {
9
+ await wait(every.ms);
10
+ if (open())
11
+ every.run();
12
+ }
13
+ }
3
14
  /** A stdio MCP server: newline-delimited JSON-RPC, tools only. Resolves when the input closes and every call has answered. */
4
15
  export function serveMcp(options) {
5
16
  const send = (message) => options.output.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`);
6
17
  const lines = createInterface({ input: options.input });
7
18
  const inFlight = new Set();
19
+ let open = true;
20
+ if (options.every)
21
+ void repeat(options.every, () => open);
8
22
  lines.on('line', line => {
9
23
  if (!line.trim())
10
24
  return;
@@ -61,6 +75,7 @@ export function serveMcp(options) {
61
75
  });
62
76
  return new Promise(resolve => {
63
77
  lines.on('close', () => {
78
+ open = false;
64
79
  void Promise.allSettled([...inFlight]).then(() => {
65
80
  resolve();
66
81
  });
package/dist/mcp/tools.js CHANGED
@@ -9,6 +9,8 @@ import { DriverError, messageOf } from "../driver/errors.js";
9
9
  import { CLI, TOOL } from "../name.js";
10
10
  import { resolveOwner } from "../registry/owner.js";
11
11
  import { NotClaimed, Refusal, UsageError } from "../registry/refusal.js";
12
+ import { LaneToucher } from "../registry/touch.js";
13
+ import { enterLane } from "../up/wake.js";
12
14
  export const TOOLS = [
13
15
  {
14
16
  name: 'look',
@@ -205,6 +207,7 @@ function errorResult(text) {
205
207
  /** The MCP tools' handler. It resolves the owner once, and the lane on every call, so a new lane is picked up. */
206
208
  export function createToolHandler(context) {
207
209
  let owner;
210
+ let toucher;
208
211
  return async (name, args) => {
209
212
  try {
210
213
  owner ??= resolveOwner(context.env, context.processes);
@@ -216,9 +219,14 @@ export function createToolHandler(context) {
216
219
  processes: context.processes,
217
220
  owner,
218
221
  need: !screen ? 'device' : asked ? 'browser' : 'either',
222
+ counts: true,
219
223
  };
220
- const { lane, stateDir } = resolveCallerLane(caller);
224
+ const resolved = resolveCallerLane(caller);
225
+ const { stateDir } = resolved;
226
+ const lane = await enterLane({ stateDir, processes: context.processes }, resolved.lane, resolved.park, context.wake, line => process.stderr.write(`${TOOL}: ${line}\n`));
221
227
  if (screen && hasBrowser(lane) && (asked || lane.device === null)) {
228
+ toucher ??= new LaneToucher({ dir: stateDir, processes: context.processes }, context.touchRetryMs);
229
+ toucher.touch({ id: lane.id, token: lane.token }, `${name}: browser`);
222
230
  const browser = { tools: context.browser ?? realBrowserTools, stateDir, lane, env: context.env };
223
231
  return name === 'look'
224
232
  ? await browserLook(browser, lookArgs(args))
@@ -74,6 +74,27 @@ class Judge {
74
74
  return this.browsers.filter(c => c.browser?.driver === aim.driver && theirs(c));
75
75
  }
76
76
  }
77
+ /** The caller's own lanes the command aims at, here. */
78
+ aimedOwn(aimed) {
79
+ const { aim, cwd } = aimed;
80
+ const own = (lanes) => lanes.filter(c => this.mine(c, cwd));
81
+ switch (aim.kind) {
82
+ case 'device':
83
+ return own(this.held.filter(c => matches(c, aim.platform, aim.ref)));
84
+ case 'booted':
85
+ return own(this.held.filter(c => c.device?.platform === 'ios'));
86
+ case 'every':
87
+ return own(this.held.filter(c => c.device?.platform === aim.platform));
88
+ case 'unselected':
89
+ return own(this.held.filter(c => c.device?.platform === 'android'));
90
+ case 'browser-session':
91
+ return own(this.browsers.filter(c => c.browser?.session === aim.session));
92
+ case 'browser-port':
93
+ return own(this.browsers.filter(c => c.browser?.debugPort === aim.port || c.browser?.streamPort === aim.port));
94
+ case 'every-browser':
95
+ return own(this.browsers.filter(c => c.browser?.driver === aim.driver));
96
+ }
97
+ }
77
98
  holder(lane, aim) {
78
99
  const name = this.ctx.sessionName(lane);
79
100
  const who = `${describeOwner(lane.owner)}${name ? ` "${name}"` : ''}`;
@@ -141,6 +162,15 @@ function recovery(aimed, holders, judge, self) {
141
162
  lines.push(`${CLI} status (every lane with its owner)`);
142
163
  return lines;
143
164
  }
165
+ /** The caller's own lanes a command the guard allows aims at: the command is a call on each of them. */
166
+ export function aimedOwnLanes(script, env, ctx) {
167
+ const judge = new Judge(ctx);
168
+ const found = new Map();
169
+ for (const aimed of aimsOf(script, env, ctx.cwd))
170
+ for (const lane of judge.aimedOwn(aimed))
171
+ found.set(lane.id, lane);
172
+ return [...found.values()];
173
+ }
144
174
  export function guard(script, env, ctx) {
145
175
  const aims = aimsOf(script, env, ctx.cwd);
146
176
  if (aims.length === 0)