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.
- package/CHANGELOG.md +118 -0
- package/LICENSE +27 -0
- package/README.md +167 -2
- package/dist/agents/claude-plugin.js +79 -0
- package/dist/agents/cli.js +258 -0
- package/dist/agents/detect.js +88 -0
- package/dist/agents/init.js +251 -0
- package/dist/agents/launcher.js +32 -0
- package/dist/agents/package.js +119 -0
- package/dist/agents/skills.js +59 -0
- package/dist/agents/toml.js +325 -0
- package/dist/agents/wiring-check.js +117 -0
- package/dist/agents/wiring.js +374 -0
- package/dist/bench/host.js +104 -0
- package/dist/bench/live.js +511 -0
- package/dist/bench/mcp-client.js +91 -0
- package/dist/bench/model.js +15 -0
- package/dist/bench/report.js +162 -0
- package/dist/bench/run.js +121 -0
- package/dist/bench/schedule.js +140 -0
- package/dist/bench/stats.js +59 -0
- package/dist/bench-cli.js +167 -0
- package/dist/browser/aria.js +184 -0
- package/dist/browser/control.js +203 -0
- package/dist/browser/env.js +118 -0
- package/dist/browser/evidence.js +44 -0
- package/dist/browser/install.js +361 -0
- package/dist/browser/kinds.js +10 -0
- package/dist/browser/lane-browser.js +224 -0
- package/dist/browser/libraries.js +56 -0
- package/dist/browser/paths.js +29 -0
- package/dist/browser/release.js +121 -0
- package/dist/browser/screen.js +19 -0
- package/dist/browser/signin.js +154 -0
- package/dist/browser/stop.js +163 -0
- package/dist/browser/tools.js +25 -0
- package/dist/cache/build.js +154 -0
- package/dist/cache/config.js +186 -0
- package/dist/cache/index.js +4 -0
- package/dist/cache/key.js +196 -0
- package/dist/cache/store.js +303 -0
- package/dist/cli.js +178 -0
- package/dist/clock.js +4 -0
- package/dist/devices/adb.js +160 -0
- package/dist/devices/android.js +214 -0
- package/dist/devices/backend.js +7 -0
- package/dist/devices/bundler.js +46 -0
- package/dist/devices/common.js +51 -0
- package/dist/devices/controls.js +65 -0
- package/dist/devices/dial.js +56 -0
- package/dist/devices/emulator.js +396 -0
- package/dist/devices/hygiene.js +202 -0
- package/dist/devices/index.js +5 -0
- package/dist/devices/launch.js +76 -0
- package/dist/devices/simctl.js +119 -0
- package/dist/devices/tools.js +1 -0
- package/dist/devices/variant.js +99 -0
- package/dist/devices/xcrun.js +265 -0
- package/dist/driver/absence.js +54 -0
- package/dist/driver/caller.js +51 -0
- package/dist/driver/client.js +312 -0
- package/dist/driver/diff.js +180 -0
- package/dist/driver/elements.js +70 -0
- package/dist/driver/engine-main.js +13 -0
- package/dist/driver/engine.js +499 -0
- package/dist/driver/errors.js +11 -0
- package/dist/driver/exec.js +66 -0
- package/dist/driver/failure.js +156 -0
- package/dist/driver/flow.js +94 -0
- package/dist/driver/idle.js +100 -0
- package/dist/driver/images.js +68 -0
- package/dist/driver/install.js +272 -0
- package/dist/driver/lock.js +101 -0
- package/dist/driver/look.js +223 -0
- package/dist/driver/maestro-child.js +194 -0
- package/dist/driver/maestro-runs.js +46 -0
- package/dist/driver/paths.js +105 -0
- package/dist/driver/pixels.js +144 -0
- package/dist/driver/plan.js +108 -0
- package/dist/driver/release.js +7 -0
- package/dist/driver/runner.js +42 -0
- package/dist/driver/selector.js +91 -0
- package/dist/driver/session.js +474 -0
- package/dist/driver/suggest.js +86 -0
- package/dist/driver/supervisor.js +251 -0
- package/dist/driver/tree.js +426 -0
- package/dist/driver-cli.js +865 -0
- package/dist/evidence/device.js +177 -0
- package/dist/evidence/evidence.js +304 -0
- package/dist/evidence/files.js +92 -0
- package/dist/hooks/env.js +81 -0
- package/dist/hooks/run.js +101 -0
- package/dist/mcp/server.js +69 -0
- package/dist/mcp/tools.js +246 -0
- package/dist/name.js +22 -0
- package/dist/plugin/aims.js +465 -0
- package/dist/plugin/conventions.js +73 -0
- package/dist/plugin/guard.js +163 -0
- package/dist/plugin/hook-cli.js +216 -0
- package/dist/plugin/session-name.js +28 -0
- package/dist/plugin/shell.js +254 -0
- package/dist/processes.js +77 -0
- package/dist/project/config.js +316 -0
- package/dist/project/schema.js +335 -0
- package/dist/project/validate.js +224 -0
- package/dist/registry/config.js +142 -0
- package/dist/registry/format.js +22 -0
- package/dist/registry/owner.js +265 -0
- package/dist/registry/paths.js +50 -0
- package/dist/registry/ports.js +26 -0
- package/dist/registry/prune.js +160 -0
- package/dist/registry/refusal.js +53 -0
- package/dist/registry/registry.js +1027 -0
- package/dist/registry/resources.js +117 -0
- package/dist/registry/rows.js +115 -0
- package/dist/registry/status.js +85 -0
- package/dist/registry/store.js +274 -0
- package/dist/registry/types.js +1 -0
- package/dist/registry-cli.js +544 -0
- package/dist/services/services.js +268 -0
- package/dist/services/system.js +189 -0
- package/dist/up/deps.js +1 -0
- package/dist/up/doctor.js +424 -0
- package/dist/up/exec.js +133 -0
- package/dist/up/lane-files.js +75 -0
- package/dist/up/lane-services.js +38 -0
- package/dist/up/maestro-env.js +172 -0
- package/dist/up/preflight.js +232 -0
- package/dist/up/release.js +148 -0
- package/dist/up/resources.js +178 -0
- package/dist/up/restart.js +87 -0
- package/dist/up/setup.js +28 -0
- package/dist/up/up.js +610 -0
- package/dist/up-cli.js +258 -0
- package/dist/usage.js +16 -0
- package/package.json +58 -3
- package/schema/agentlane.schema.json +675 -0
- package/skills/create-verification-skill/LICENSE +21 -0
- package/skills/create-verification-skill/SKILL.md +88 -0
- package/skills/dev-loop/LICENSE +21 -0
- package/skills/dev-loop/SKILL.md +61 -0
- package/skills/device/SKILL.md +8 -0
- package/skills/drive/SKILL.md +64 -0
- package/skills/maintain-verification-skill/LICENSE +21 -0
- package/skills/maintain-verification-skill/SKILL.md +42 -0
- package/skills/setup/SKILL.md +80 -0
|
@@ -0,0 +1,499 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline';
|
|
6
|
+
import { adbPath, createAdbTools, forceStopMaestro } from "../devices/adb.js";
|
|
7
|
+
import { findAndroidSdk } from "../devices/emulator.js";
|
|
8
|
+
import { identityOf, systemProcesses } from "../processes.js";
|
|
9
|
+
import { isProven, judgeProcess, worktreeState } from "../registry/owner.js";
|
|
10
|
+
import { tcpProbe } from "../registry/ports.js";
|
|
11
|
+
import { Refusal } from "../registry/refusal.js";
|
|
12
|
+
import { Registry } from "../registry/registry.js";
|
|
13
|
+
import { messageOf } from "./errors.js";
|
|
14
|
+
import { IdleWatch, writeIdleStop, describeIdle } from "./idle.js";
|
|
15
|
+
import { sipsImages } from "./images.js";
|
|
16
|
+
import { liveHolder, tryLock, unlock } from "./lock.js";
|
|
17
|
+
import { enginePaths, ensurePrivateDir } from "./paths.js";
|
|
18
|
+
import { DriverSession } from "./session.js";
|
|
19
|
+
import { SessionFailure, Supervisor } from "./supervisor.js";
|
|
20
|
+
const LOG_LIMIT_BYTES = 5 * 1024 * 1024;
|
|
21
|
+
function canConnect(socket) {
|
|
22
|
+
return new Promise(resolve => {
|
|
23
|
+
const probe = net.connect(socket);
|
|
24
|
+
probe.once('connect', () => {
|
|
25
|
+
probe.destroy();
|
|
26
|
+
resolve(true);
|
|
27
|
+
});
|
|
28
|
+
probe.once('error', () => {
|
|
29
|
+
resolve(false);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const ANSWER_WAIT_MS = 2000;
|
|
34
|
+
function actsOnDevice(op) {
|
|
35
|
+
return op === 'look' || op === 'screenshot' || op === 'run';
|
|
36
|
+
}
|
|
37
|
+
function onlyReads(op) {
|
|
38
|
+
return op === 'ping' || op === 'status' || op === 'look' || op === 'screenshot';
|
|
39
|
+
}
|
|
40
|
+
const ACTIONS = {
|
|
41
|
+
ping: 'driver ping',
|
|
42
|
+
status: 'driver status',
|
|
43
|
+
look: 'look',
|
|
44
|
+
screenshot: 'screenshot',
|
|
45
|
+
run: 'run',
|
|
46
|
+
record: 'record',
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* The long-lived driver engine of one lane. It owns the lane's `maestro mcp` session, answers tool calls on a Unix
|
|
50
|
+
* socket one at a time, records activity on the lane, and stops (freeing Maestro, its xcodebuild and its runner)
|
|
51
|
+
* when the lane ends or its owner is proven gone.
|
|
52
|
+
*/
|
|
53
|
+
export async function runEngine(config, deps = {}) {
|
|
54
|
+
const processes = deps.processes ?? systemProcesses;
|
|
55
|
+
const paths = enginePaths(config.stateDir, config.laneId);
|
|
56
|
+
ensurePrivateDir(paths.dir);
|
|
57
|
+
ensurePrivateDir(path.dirname(paths.socket));
|
|
58
|
+
const me = identityOf(processes, process.pid);
|
|
59
|
+
if (!me)
|
|
60
|
+
return `ps could not read this engine's start time (pid ${String(process.pid)})`;
|
|
61
|
+
if (!tryLock(paths.lock, me, processes).acquired)
|
|
62
|
+
return 'another engine holds the lock';
|
|
63
|
+
const releaser = liveHolder(paths.releasing, processes);
|
|
64
|
+
if (releaser) {
|
|
65
|
+
unlock(paths.lock, me);
|
|
66
|
+
return `lane ${config.laneId} is being released (by pid ${String(releaser.pid)})`;
|
|
67
|
+
}
|
|
68
|
+
const logFd = fs.openSync(paths.log, 'a', 0o600);
|
|
69
|
+
if (fs.fstatSync(logFd).size > LOG_LIMIT_BYTES)
|
|
70
|
+
fs.ftruncateSync(logFd, 0);
|
|
71
|
+
let logOpen = true;
|
|
72
|
+
const log = (line) => {
|
|
73
|
+
const entry = `${new Date().toISOString()} [engine ${String(process.pid)}] ${line}\n`;
|
|
74
|
+
if (logOpen)
|
|
75
|
+
fs.writeSync(logFd, entry);
|
|
76
|
+
else
|
|
77
|
+
process.stderr.write(entry);
|
|
78
|
+
};
|
|
79
|
+
const closeLog = () => {
|
|
80
|
+
logOpen = false;
|
|
81
|
+
fs.closeSync(logFd);
|
|
82
|
+
};
|
|
83
|
+
const device = config.serial ?? config.deviceId;
|
|
84
|
+
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 });
|
|
86
|
+
const held = () => {
|
|
87
|
+
const lane = registry.find(config.owner, config.worktree);
|
|
88
|
+
return (lane?.id === config.laneId &&
|
|
89
|
+
lane.token === config.token &&
|
|
90
|
+
lane.device?.id === config.deviceId &&
|
|
91
|
+
(lane.device.serial ?? null) === config.serial);
|
|
92
|
+
};
|
|
93
|
+
if (!held()) {
|
|
94
|
+
registry.close();
|
|
95
|
+
unlock(paths.lock, me);
|
|
96
|
+
closeLog();
|
|
97
|
+
return `lane ${config.laneId} is not held for ${device}`;
|
|
98
|
+
}
|
|
99
|
+
const androidSdk = config.platform === 'android' ? (findAndroidSdk(config.env)?.root ?? undefined) : undefined;
|
|
100
|
+
const adb = config.platform === 'android' && config.serial !== null
|
|
101
|
+
? (deps.adb ?? createAdbTools(config.serial, { adb: adbPath(config.env) }))
|
|
102
|
+
: undefined;
|
|
103
|
+
const stillHeld = () => {
|
|
104
|
+
try {
|
|
105
|
+
return held();
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
log(`lane check failed: ${messageOf(error)}`);
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const cleanup = async () => {
|
|
113
|
+
if (!adb || !stillHeld())
|
|
114
|
+
return;
|
|
115
|
+
await forceStopMaestro(adb);
|
|
116
|
+
log(`force-stopped Maestro's driver on ${adb.serial}`);
|
|
117
|
+
};
|
|
118
|
+
if (fs.existsSync(paths.socket)) {
|
|
119
|
+
if (await canConnect(paths.socket)) {
|
|
120
|
+
registry.close();
|
|
121
|
+
unlock(paths.lock, me);
|
|
122
|
+
closeLog();
|
|
123
|
+
return 'an engine already answers on the socket';
|
|
124
|
+
}
|
|
125
|
+
fs.rmSync(paths.socket, { force: true });
|
|
126
|
+
}
|
|
127
|
+
const supervisor = new Supervisor({
|
|
128
|
+
platform: config.platform,
|
|
129
|
+
deviceId: device,
|
|
130
|
+
androidSdk,
|
|
131
|
+
cleanup,
|
|
132
|
+
maestro: config.maestro,
|
|
133
|
+
javaHome: config.javaHome,
|
|
134
|
+
token: config.token,
|
|
135
|
+
workDir: paths.work,
|
|
136
|
+
env: config.env,
|
|
137
|
+
logFd,
|
|
138
|
+
log,
|
|
139
|
+
...(config.runnerWatchMs === undefined ? {} : { runnerWatchMs: config.runnerWatchMs }),
|
|
140
|
+
...(deps.rows ? { rows: deps.rows } : {}),
|
|
141
|
+
});
|
|
142
|
+
const session = new DriverSession(supervisor, deps.images ?? sipsImages(path.join(paths.work, 'images')), { steps: paths.steps, volatile: paths.volatile, work: paths.work, shots: paths.shots }, log);
|
|
143
|
+
const idle = new IdleWatch(config.idleMs ?? 0, { now: () => Date.now() });
|
|
144
|
+
const startedAt = Date.now();
|
|
145
|
+
let stopping;
|
|
146
|
+
let tail = Promise.resolve();
|
|
147
|
+
let pendingTouch;
|
|
148
|
+
let lastTouch = 0;
|
|
149
|
+
let resolveDone = () => undefined;
|
|
150
|
+
const done = new Promise(resolve => {
|
|
151
|
+
resolveDone = resolve;
|
|
152
|
+
});
|
|
153
|
+
const timers = [];
|
|
154
|
+
const flushTouch = () => {
|
|
155
|
+
if (pendingTouch === undefined || stopping !== undefined)
|
|
156
|
+
return;
|
|
157
|
+
const action = pendingTouch;
|
|
158
|
+
try {
|
|
159
|
+
registry.touch({ id: config.laneId, token: config.token }, action);
|
|
160
|
+
pendingTouch = undefined;
|
|
161
|
+
lastTouch = Date.now();
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (error instanceof Refusal && error.code === 'registry-busy')
|
|
165
|
+
return;
|
|
166
|
+
if (!stillHeld())
|
|
167
|
+
endLane();
|
|
168
|
+
else
|
|
169
|
+
void shutdown(`the lane can't be touched: ${messageOf(error).split('\n')[0] ?? ''}`);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const touchSoon = (action) => {
|
|
173
|
+
pendingTouch = action;
|
|
174
|
+
if (Date.now() - lastTouch >= (config.touchEveryMs ?? 5000))
|
|
175
|
+
setImmediate(flushTouch);
|
|
176
|
+
};
|
|
177
|
+
let laneEnded = false;
|
|
178
|
+
const laneGone = () => ({
|
|
179
|
+
pid: process.pid,
|
|
180
|
+
ok: false,
|
|
181
|
+
error: `lane ${config.laneId} no longer holds ${device}, so the driver stopped without acting`,
|
|
182
|
+
});
|
|
183
|
+
const stoppingAnswer = (reason) => ({
|
|
184
|
+
pid: process.pid,
|
|
185
|
+
ok: false,
|
|
186
|
+
error: `the driver is stopping (${reason})`,
|
|
187
|
+
stopping: reason,
|
|
188
|
+
});
|
|
189
|
+
const endLane = () => {
|
|
190
|
+
laneEnded = true;
|
|
191
|
+
void shutdown(`lane ${config.laneId} has ended`);
|
|
192
|
+
};
|
|
193
|
+
const refusal = (request, reason) => laneEnded && actsOnDevice(request.op) ? laneGone() : stoppingAnswer(reason);
|
|
194
|
+
const cutShort = (request, reason) => onlyReads(request.op)
|
|
195
|
+
? { pid: process.pid, ok: false, error: `the driver stopped during ${request.op} (${reason})`, stopping: reason }
|
|
196
|
+
: {
|
|
197
|
+
pid: process.pid,
|
|
198
|
+
ok: false,
|
|
199
|
+
error: `the driver stopped partway through ${request.op} (${reason}). Some of it may have run on the device, so it was not sent again; read the screen before you repeat it`,
|
|
200
|
+
interrupted: reason,
|
|
201
|
+
};
|
|
202
|
+
const perform = async (request) => {
|
|
203
|
+
const base = { pid: process.pid };
|
|
204
|
+
if (actsOnDevice(request.op) && !stillHeld()) {
|
|
205
|
+
endLane();
|
|
206
|
+
return laneGone();
|
|
207
|
+
}
|
|
208
|
+
switch (request.op) {
|
|
209
|
+
case 'ping':
|
|
210
|
+
return { ...base, ok: true };
|
|
211
|
+
case 'status':
|
|
212
|
+
return {
|
|
213
|
+
...base,
|
|
214
|
+
ok: true,
|
|
215
|
+
status: {
|
|
216
|
+
...(await supervisor.status()),
|
|
217
|
+
enginePid: process.pid,
|
|
218
|
+
device,
|
|
219
|
+
laneId: config.laneId,
|
|
220
|
+
startedAt,
|
|
221
|
+
log: paths.log,
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
case 'look':
|
|
225
|
+
return { ...base, ...(await session.look(request.args)) };
|
|
226
|
+
case 'screenshot':
|
|
227
|
+
return { ...base, ...(await session.screenshot(request.args)) };
|
|
228
|
+
case 'run':
|
|
229
|
+
return { ...base, ...(await session.run(request.args)) };
|
|
230
|
+
case 'record':
|
|
231
|
+
return { ...base, ...session.recording(request.args) };
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
let sampleTimer;
|
|
235
|
+
let idleTimer;
|
|
236
|
+
const scheduleIdleCheck = () => {
|
|
237
|
+
clearTimeout(idleTimer);
|
|
238
|
+
const remaining = idle.remainingMs();
|
|
239
|
+
if (remaining === undefined || stopping !== undefined)
|
|
240
|
+
return;
|
|
241
|
+
idleTimer = setTimeout(() => {
|
|
242
|
+
if (stopping !== undefined)
|
|
243
|
+
return;
|
|
244
|
+
if (idle.remainingMs() !== 0) {
|
|
245
|
+
scheduleIdleCheck();
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const idleMs = config.idleMs ?? 0;
|
|
249
|
+
try {
|
|
250
|
+
writeIdleStop(paths.idle, { version: 1, stoppedAt: Date.now(), idleMs });
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
log(`could not note the idle stop: ${messageOf(error)}`);
|
|
254
|
+
}
|
|
255
|
+
void shutdown(`no tool call for ${describeIdle(idleMs)}; the lane stays, and the next call starts the driver again`);
|
|
256
|
+
}, remaining);
|
|
257
|
+
idleTimer.unref();
|
|
258
|
+
};
|
|
259
|
+
const sampleWhenIdle = () => {
|
|
260
|
+
clearTimeout(sampleTimer);
|
|
261
|
+
sampleTimer = setTimeout(() => {
|
|
262
|
+
if (stopping !== undefined)
|
|
263
|
+
return;
|
|
264
|
+
tail = tail
|
|
265
|
+
.then(() => session.idleSample())
|
|
266
|
+
.catch((error) => {
|
|
267
|
+
log(`idle read failed: ${messageOf(error)}`);
|
|
268
|
+
});
|
|
269
|
+
}, config.idleSampleMs ?? 1500);
|
|
270
|
+
sampleTimer.unref();
|
|
271
|
+
};
|
|
272
|
+
const isToolCall = (op) => op === 'look' || op === 'run' || op === 'screenshot' || op === 'record';
|
|
273
|
+
const serialized = (request) => {
|
|
274
|
+
clearTimeout(sampleTimer);
|
|
275
|
+
const tool = isToolCall(request.op);
|
|
276
|
+
if (tool)
|
|
277
|
+
idle.begin();
|
|
278
|
+
const job = tail.then(() => (stopping === undefined ? perform(request) : refusal(request, stopping)));
|
|
279
|
+
tail = job.catch(() => undefined);
|
|
280
|
+
return job
|
|
281
|
+
.then((response) => {
|
|
282
|
+
touchSoon(ACTIONS[request.op]);
|
|
283
|
+
if (request.op === 'look' || request.op === 'run' || request.op === 'screenshot')
|
|
284
|
+
sampleWhenIdle();
|
|
285
|
+
return response;
|
|
286
|
+
}, (error) => {
|
|
287
|
+
log(`${request.op} failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
|
|
288
|
+
if (stopping !== undefined)
|
|
289
|
+
return cutShort(request, stopping);
|
|
290
|
+
if (error instanceof SessionFailure) {
|
|
291
|
+
return {
|
|
292
|
+
pid: process.pid,
|
|
293
|
+
ok: false,
|
|
294
|
+
error: `Maestro's session failed (${error.kind}) and failed again after a restart: ${error.message}. The driver's log: ${paths.log}`,
|
|
295
|
+
sessionFailure: { kind: error.kind, attempts: error.attempts },
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
return { pid: process.pid, ok: false, error: messageOf(error) };
|
|
299
|
+
})
|
|
300
|
+
.finally(() => {
|
|
301
|
+
if (tool) {
|
|
302
|
+
idle.end();
|
|
303
|
+
scheduleIdleCheck();
|
|
304
|
+
}
|
|
305
|
+
});
|
|
306
|
+
};
|
|
307
|
+
const handle = (line) => {
|
|
308
|
+
let request;
|
|
309
|
+
try {
|
|
310
|
+
request = JSON.parse(line);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
return Promise.resolve({ pid: process.pid, ok: false, error: 'the driver got a request that is not JSON' });
|
|
314
|
+
}
|
|
315
|
+
const ours = request.lane.id === config.laneId && request.lane.token === config.token;
|
|
316
|
+
if (stopping !== undefined)
|
|
317
|
+
return Promise.resolve(ours ? refusal(request, stopping) : stoppingAnswer(stopping));
|
|
318
|
+
if (!ours) {
|
|
319
|
+
return Promise.resolve({
|
|
320
|
+
pid: process.pid,
|
|
321
|
+
ok: false,
|
|
322
|
+
error: `this driver serves lane ${config.laneId}, with its own token`,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
if (request.op === 'stop') {
|
|
326
|
+
void shutdown('asked to stop');
|
|
327
|
+
return Promise.resolve({ pid: process.pid, ok: true, text: 'Stopping the driver.' });
|
|
328
|
+
}
|
|
329
|
+
return serialized(request);
|
|
330
|
+
};
|
|
331
|
+
const drainMark = randomUUID();
|
|
332
|
+
let markAccepted = () => undefined;
|
|
333
|
+
const open = new Set();
|
|
334
|
+
const unread = new Set();
|
|
335
|
+
let allClosed = () => undefined;
|
|
336
|
+
const server = net.createServer(socket => {
|
|
337
|
+
open.add(socket);
|
|
338
|
+
unread.add(socket);
|
|
339
|
+
socket.on('error', () => undefined);
|
|
340
|
+
socket.once('close', () => {
|
|
341
|
+
open.delete(socket);
|
|
342
|
+
unread.delete(socket);
|
|
343
|
+
if (open.size === 0)
|
|
344
|
+
allClosed();
|
|
345
|
+
});
|
|
346
|
+
const lines = createInterface({ input: socket });
|
|
347
|
+
lines.once('line', line => {
|
|
348
|
+
lines.close();
|
|
349
|
+
unread.delete(socket);
|
|
350
|
+
if (line === drainMark) {
|
|
351
|
+
socket.destroy();
|
|
352
|
+
markAccepted();
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
void handle(line).then(response => {
|
|
356
|
+
socket.end(`${JSON.stringify(response)}\n`);
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
});
|
|
360
|
+
const removeOurs = (file) => {
|
|
361
|
+
try {
|
|
362
|
+
if (fs.statSync(file).ino === socketIno)
|
|
363
|
+
fs.rmSync(file);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
log(`${file} was already gone`);
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
// A listener that closes drops the connections it has not accepted yet (Linux resets them, macOS ends them
|
|
370
|
+
// unanswered), and libuv accepts one connection per loop turn. With the socket moved off its public path no new
|
|
371
|
+
// connection arrives, and the kernel accepts in arrival order, so once a mark sent through the moved path is
|
|
372
|
+
// accepted, so is every connection that was waiting before it.
|
|
373
|
+
const acceptQueued = () => new Promise(resolve => {
|
|
374
|
+
let finished = false;
|
|
375
|
+
let moved = false;
|
|
376
|
+
let mark;
|
|
377
|
+
const unmove = () => {
|
|
378
|
+
if (moved)
|
|
379
|
+
removeOurs(paths.stoppingSocket);
|
|
380
|
+
moved = false;
|
|
381
|
+
};
|
|
382
|
+
const finish = () => {
|
|
383
|
+
if (finished)
|
|
384
|
+
return;
|
|
385
|
+
finished = true;
|
|
386
|
+
clearTimeout(deadline);
|
|
387
|
+
mark?.destroy();
|
|
388
|
+
unmove();
|
|
389
|
+
resolve();
|
|
390
|
+
};
|
|
391
|
+
const deadline = setTimeout(() => {
|
|
392
|
+
log('connections queued on the socket were not all accepted in time');
|
|
393
|
+
finish();
|
|
394
|
+
}, ANSWER_WAIT_MS);
|
|
395
|
+
markAccepted = finish;
|
|
396
|
+
try {
|
|
397
|
+
if (fs.statSync(paths.socket).ino !== socketIno)
|
|
398
|
+
throw new Error('replaced');
|
|
399
|
+
fs.renameSync(paths.socket, paths.stoppingSocket);
|
|
400
|
+
moved = true;
|
|
401
|
+
}
|
|
402
|
+
catch {
|
|
403
|
+
log('the socket was already gone');
|
|
404
|
+
finish();
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const sendMark = () => {
|
|
408
|
+
const socket = net.connect(paths.stoppingSocket);
|
|
409
|
+
mark = socket;
|
|
410
|
+
socket.on('connect', () => {
|
|
411
|
+
unmove();
|
|
412
|
+
socket.write(`${drainMark}\n`);
|
|
413
|
+
});
|
|
414
|
+
socket.on('error', (error) => {
|
|
415
|
+
if (finished)
|
|
416
|
+
return;
|
|
417
|
+
if (error.code === 'EAGAIN' || error.code === 'ECONNREFUSED')
|
|
418
|
+
setImmediate(sendMark);
|
|
419
|
+
else
|
|
420
|
+
finish();
|
|
421
|
+
});
|
|
422
|
+
};
|
|
423
|
+
sendMark();
|
|
424
|
+
});
|
|
425
|
+
const connectionsClosed = () => new Promise(resolve => {
|
|
426
|
+
const timer = setTimeout(resolve, ANSWER_WAIT_MS);
|
|
427
|
+
allClosed = () => {
|
|
428
|
+
clearTimeout(timer);
|
|
429
|
+
resolve();
|
|
430
|
+
};
|
|
431
|
+
if (open.size === 0)
|
|
432
|
+
allClosed();
|
|
433
|
+
});
|
|
434
|
+
const shutdown = async (reason) => {
|
|
435
|
+
if (stopping !== undefined)
|
|
436
|
+
return;
|
|
437
|
+
stopping = reason;
|
|
438
|
+
const clean = config.platform !== 'android' || stillHeld();
|
|
439
|
+
log(`stopping: ${reason}`);
|
|
440
|
+
for (const timer of timers)
|
|
441
|
+
clearInterval(timer);
|
|
442
|
+
clearTimeout(sampleTimer);
|
|
443
|
+
clearTimeout(idleTimer);
|
|
444
|
+
const queued = acceptQueued();
|
|
445
|
+
await Promise.race([tail, new Promise(resolve => setTimeout(resolve, 2000))]);
|
|
446
|
+
await supervisor.stop({ clean });
|
|
447
|
+
await queued;
|
|
448
|
+
fs.rmSync(paths.work, { recursive: true, force: true });
|
|
449
|
+
registry.close();
|
|
450
|
+
unlock(paths.lock, me);
|
|
451
|
+
await connectionsClosed();
|
|
452
|
+
for (const socket of unread)
|
|
453
|
+
socket.end(`${JSON.stringify(stoppingAnswer(reason))}\n`);
|
|
454
|
+
log('stopped');
|
|
455
|
+
closeLog();
|
|
456
|
+
server.close();
|
|
457
|
+
resolveDone(reason);
|
|
458
|
+
};
|
|
459
|
+
await new Promise((resolve, reject) => {
|
|
460
|
+
server.once('error', reject);
|
|
461
|
+
server.listen(paths.socket, () => {
|
|
462
|
+
resolve();
|
|
463
|
+
});
|
|
464
|
+
});
|
|
465
|
+
fs.chmodSync(paths.socket, 0o600);
|
|
466
|
+
const socketIno = fs.statSync(paths.socket).ino;
|
|
467
|
+
log(`listening on ${paths.socket}`);
|
|
468
|
+
timers.push(setInterval(() => {
|
|
469
|
+
if (stopping !== undefined)
|
|
470
|
+
return;
|
|
471
|
+
try {
|
|
472
|
+
if (!held())
|
|
473
|
+
endLane();
|
|
474
|
+
}
|
|
475
|
+
catch (error) {
|
|
476
|
+
log(`lane check failed: ${messageOf(error)}`);
|
|
477
|
+
}
|
|
478
|
+
flushTouch();
|
|
479
|
+
}, config.lanePollMs ?? 500), setInterval(() => {
|
|
480
|
+
if (stopping !== undefined)
|
|
481
|
+
return;
|
|
482
|
+
const owner = config.owner.process;
|
|
483
|
+
const verdict = owner ? judgeProcess(owner, processes.startTimes([owner.pid])) : 'cant-tell';
|
|
484
|
+
if (isProven(verdict))
|
|
485
|
+
void shutdown(`the lane's owner (pid ${String(owner?.pid)}) is ${verdict}`);
|
|
486
|
+
else if (worktreeState(config.worktree) === 'gone')
|
|
487
|
+
void shutdown(`the lane's folder ${config.worktree} is gone`);
|
|
488
|
+
}, config.ownerPollMs ?? 2000));
|
|
489
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
|
|
490
|
+
process.on(signal, () => {
|
|
491
|
+
void shutdown(signal);
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
scheduleIdleCheck();
|
|
495
|
+
supervisor.ensure().catch((error) => {
|
|
496
|
+
log(`maestro did not start: ${messageOf(error)}`);
|
|
497
|
+
});
|
|
498
|
+
return done;
|
|
499
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export class DriverError extends Error {
|
|
2
|
+
fix;
|
|
3
|
+
constructor(problem, fix) {
|
|
4
|
+
super(`${problem}\nto fix: ${fix}`);
|
|
5
|
+
this.name = 'DriverError';
|
|
6
|
+
this.fix = fix;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export function messageOf(error) {
|
|
10
|
+
return error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
/** Runs a command to completion, collecting its output; never throws. A timeout kills the command's process group. */
|
|
3
|
+
export function runCommand(command, args, options = {}) {
|
|
4
|
+
return new Promise(resolve => {
|
|
5
|
+
const stdout = [];
|
|
6
|
+
const stderr = [];
|
|
7
|
+
let error;
|
|
8
|
+
const child = spawn(command, [...args], {
|
|
9
|
+
env: options.env ?? process.env,
|
|
10
|
+
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
11
|
+
detached: true,
|
|
12
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
13
|
+
});
|
|
14
|
+
child.stdout.on('data', (chunk) => stdout.push(chunk));
|
|
15
|
+
child.stderr.on('data', (chunk) => stderr.push(chunk));
|
|
16
|
+
child.stdin.on('error', () => undefined);
|
|
17
|
+
child.stdin.end(options.input ?? '');
|
|
18
|
+
const timer = options.timeoutMs === undefined
|
|
19
|
+
? undefined
|
|
20
|
+
: setTimeout(() => {
|
|
21
|
+
error = `timed out after ${String(Math.round((options.timeoutMs ?? 0) / 1000))} s`;
|
|
22
|
+
killGroup(child.pid);
|
|
23
|
+
}, options.timeoutMs);
|
|
24
|
+
child.on('error', failure => {
|
|
25
|
+
error = failure.message;
|
|
26
|
+
});
|
|
27
|
+
child.on('close', (code, signal) => {
|
|
28
|
+
if (timer)
|
|
29
|
+
clearTimeout(timer);
|
|
30
|
+
resolve({
|
|
31
|
+
code,
|
|
32
|
+
signal,
|
|
33
|
+
stdout: Buffer.concat(stdout).toString('utf8'),
|
|
34
|
+
stderr: Buffer.concat(stderr).toString('utf8'),
|
|
35
|
+
error,
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export function killGroup(pid, signal = 'SIGKILL') {
|
|
41
|
+
if (pid === undefined)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
process.kill(-pid, signal);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
try {
|
|
48
|
+
process.kill(pid, signal);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export function isAlive(pid) {
|
|
56
|
+
try {
|
|
57
|
+
process.kill(pid, 0);
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
return error.code === 'EPERM';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
export function tail(text, lines = 15) {
|
|
65
|
+
return text.trimEnd().split('\n').slice(-lines).join('\n');
|
|
66
|
+
}
|