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.
- package/CHANGELOG.md +76 -0
- package/dist/agents/claude-plugin.js +54 -8
- package/dist/agents/cli.js +11 -4
- package/dist/agents/hook-check.js +290 -0
- package/dist/agents/launcher.js +34 -6
- package/dist/agents/wiring-check.js +10 -4
- package/dist/agents/wiring.js +6 -33
- package/dist/browser/env.js +27 -7
- package/dist/browser/install.js +144 -6
- package/dist/browser/lane-browser.js +6 -3
- package/dist/browser/stop.js +2 -17
- package/dist/cache/key.js +23 -11
- package/dist/cli.js +63 -23
- package/dist/devices/backend.js +6 -0
- package/dist/devices/emulator.js +15 -5
- package/dist/devices/simctl.js +15 -3
- package/dist/disk-limits.js +134 -0
- package/dist/driver/caller.js +21 -6
- package/dist/driver/client.js +9 -5
- package/dist/driver/engine.js +29 -14
- package/dist/driver/install.js +88 -36
- package/dist/driver/paths.js +15 -11
- package/dist/driver/session.js +4 -1
- package/dist/driver/superseded.js +378 -0
- package/dist/driver-cli.js +32 -23
- package/dist/evidence/device.js +4 -0
- package/dist/evidence/evidence.js +4 -2
- package/dist/evidence/files.js +68 -0
- package/dist/evidence/strays.js +107 -0
- package/dist/hooks/env.js +2 -1
- package/dist/mcp/server.js +15 -0
- package/dist/mcp/tools.js +9 -1
- package/dist/plugin/guard.js +30 -0
- package/dist/plugin/hook-cli.js +101 -6
- package/dist/plugin/hook-mark.js +73 -0
- package/dist/plugin/hook-once.js +78 -0
- package/dist/plugin/shell.js +109 -8
- package/dist/processes.js +52 -2
- package/dist/registry/config.js +12 -8
- package/dist/registry/holds.js +37 -0
- package/dist/registry/leases.js +109 -0
- package/dist/registry/owner-checks.js +55 -0
- package/dist/registry/owner.js +18 -0
- package/dist/registry/parks.js +60 -0
- package/dist/registry/paths.js +28 -4
- package/dist/registry/ports.js +5 -1
- package/dist/registry/prune.js +643 -24
- package/dist/registry/refusal.js +1 -0
- package/dist/registry/registry.js +1258 -235
- package/dist/registry/rows.js +18 -4
- package/dist/registry/status.js +51 -8
- package/dist/registry/store.js +63 -1
- package/dist/registry/touch.js +180 -0
- package/dist/registry-cli.js +197 -36
- package/dist/services/services.js +223 -54
- package/dist/services/system.js +2 -1
- package/dist/up/answers.js +124 -0
- package/dist/up/doctor.js +27 -3
- package/dist/up/exec.js +29 -4
- package/dist/up/lane-files.js +26 -8
- package/dist/up/lane-services.js +8 -3
- package/dist/up/park.js +146 -0
- package/dist/up/preflight.js +2 -10
- package/dist/up/release.js +20 -24
- package/dist/up/restart.js +9 -2
- package/dist/up/sweep.js +437 -0
- package/dist/up/up.js +33 -12
- package/dist/up/wake.js +124 -0
- package/dist/up/waker.js +49 -0
- package/dist/up-cli.js +6 -1
- package/package.json +2 -2
- package/skills/dev-loop/SKILL.md +7 -5
- package/skills/drive/SKILL.md +4 -0
- package/skills/setup/SKILL.md +2 -2
package/dist/evidence/files.js
CHANGED
|
@@ -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
|
}
|
package/dist/mcp/server.js
CHANGED
|
@@ -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
|
|
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))
|
package/dist/plugin/guard.js
CHANGED
|
@@ -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)
|
package/dist/plugin/hook-cli.js
CHANGED
|
@@ -3,15 +3,21 @@ import fs from 'node:fs';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { parseArgs } from 'node:util';
|
|
5
5
|
import { systemClock } from "../clock.js";
|
|
6
|
+
import { rotateLog } from "../disk-limits.js";
|
|
6
7
|
import { envName, TOOL } from "../name.js";
|
|
7
8
|
import { AGENTS, describeOwner, judgeProcess, ownerKey, resolveOwner } from "../registry/owner.js";
|
|
8
9
|
import { stateDir } from "../registry/paths.js";
|
|
9
|
-
import {
|
|
10
|
+
import { tcpProbe } from "../registry/ports.js";
|
|
11
|
+
import { readRegistryStatus, Registry } from "../registry/registry.js";
|
|
12
|
+
import { recordCall, TOUCH_WAIT_MS } from "../registry/touch.js";
|
|
10
13
|
import { releaseEveryLaneOf, resolveFolder } from "../registry-cli.js";
|
|
11
14
|
import { commandUsage, groupUsage } from "../usage.js";
|
|
15
|
+
import { toolVersion } from "../agents/package.js";
|
|
12
16
|
import { aimsOf } from "./aims.js";
|
|
13
17
|
import { CONVENTIONS, readHookInput } from "./conventions.js";
|
|
14
|
-
import { guard } from "./guard.js";
|
|
18
|
+
import { aimedOwnLanes, guard } from "./guard.js";
|
|
19
|
+
import { HOOK_PROBE_ENV, writeHookMark } from "./hook-mark.js";
|
|
20
|
+
import { claimOnce } from "./hook-once.js";
|
|
15
21
|
import { claudeSessionName } from "./session-name.js";
|
|
16
22
|
export const HOOK_COMMANDS = ['hook'];
|
|
17
23
|
export const HOOK_HELP = {
|
|
@@ -29,8 +35,11 @@ export const HOOK_HELP = {
|
|
|
29
35
|
export const HOOK_USAGE = groupUsage(HOOK_HELP);
|
|
30
36
|
export const SESSION_END_OWNER_ENV = envName('SESSION_END_OWNER');
|
|
31
37
|
export const SESSION_END_WAIT_ENV = envName('SESSION_END_WAIT_MS');
|
|
38
|
+
export const SESSION_END_ONCE_ENV = envName('SESSION_END_ONCE');
|
|
32
39
|
const OWNER_EXIT_WAIT_MS = 30_000;
|
|
33
40
|
const OWNER_EXIT_POLL_MS = 250;
|
|
41
|
+
const PLUGIN_AND_SETTINGS = new Set(['claude']);
|
|
42
|
+
export const SESSION_END_LOG_MAX_BYTES = 1024 * 1024;
|
|
34
43
|
function selfOwner(deps) {
|
|
35
44
|
try {
|
|
36
45
|
return resolveOwner(deps.env, deps.processes, deps.selfPid);
|
|
@@ -61,15 +70,47 @@ function guardReply(raw, agent, deps) {
|
|
|
61
70
|
devices: deps.devices,
|
|
62
71
|
...(deps.clock ? { clock: deps.clock } : {}),
|
|
63
72
|
});
|
|
64
|
-
const
|
|
73
|
+
const context = {
|
|
65
74
|
self: owner ? ownerKey(owner) : null,
|
|
66
75
|
cwd,
|
|
67
76
|
lanes: report.lanes,
|
|
68
77
|
now: report.now,
|
|
69
78
|
worktreeOf,
|
|
70
79
|
sessionName: lane => claudeSessionName(lane.owner, deps.env),
|
|
71
|
-
}
|
|
72
|
-
|
|
80
|
+
};
|
|
81
|
+
const verdict = guard(command, deps.env, context);
|
|
82
|
+
if (!verdict.allow)
|
|
83
|
+
return convention.deny(verdict.reason);
|
|
84
|
+
if (owner)
|
|
85
|
+
recordCalls(owner, aimedOwnLanes(command, deps.env, context), deps);
|
|
86
|
+
return convention.allow;
|
|
87
|
+
}
|
|
88
|
+
/** Records an allowed simctl, adb, playwright-cli or agent-browser command on the caller's own lanes as a call on each. */
|
|
89
|
+
function recordCalls(owner, lanes, deps) {
|
|
90
|
+
if (lanes.length === 0)
|
|
91
|
+
return;
|
|
92
|
+
const dir = stateDir(deps.env);
|
|
93
|
+
let registry;
|
|
94
|
+
try {
|
|
95
|
+
registry = Registry.open({ dir, processes: deps.processes, ports: tcpProbe, devices: {}, lockWaitMs: TOUCH_WAIT_MS });
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const at = (deps.clock ?? systemClock).now();
|
|
102
|
+
for (const lane of lanes) {
|
|
103
|
+
const found = registry.find(owner, lane.worktree);
|
|
104
|
+
if (found?.id === lane.id)
|
|
105
|
+
recordCall(dir, { id: found.id, token: found.token }, at);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
finally {
|
|
112
|
+
registry.close();
|
|
113
|
+
}
|
|
73
114
|
}
|
|
74
115
|
function preToolUse(raw, agent, deps) {
|
|
75
116
|
let reply;
|
|
@@ -121,11 +162,13 @@ function sessionEnd(input, agent, deps) {
|
|
|
121
162
|
const held = readRegistryStatus({ dir, processes: deps.processes, devices: {} }).lanes.filter(c => c.ownerKey === key);
|
|
122
163
|
if (held.length === 0)
|
|
123
164
|
return 0;
|
|
165
|
+
const once = PLUGIN_AND_SETTINGS.has(agent) ? ['session-end', input.sessionId ?? '', key] : null;
|
|
124
166
|
const log = path.join(dir, 'session-end.log');
|
|
125
167
|
const waits = convention.release !== 'at-once' && convention.release !== 'by-thread' && owner.process !== null;
|
|
126
168
|
deps.startWorker({
|
|
127
169
|
...deps.env,
|
|
128
170
|
[SESSION_END_OWNER_ENV]: JSON.stringify(owner),
|
|
171
|
+
[SESSION_END_ONCE_ENV]: once ? JSON.stringify(once) : undefined,
|
|
129
172
|
...(waits ? { [SESSION_END_WAIT_ENV]: String(OWNER_EXIT_WAIT_MS) } : {}),
|
|
130
173
|
}, log);
|
|
131
174
|
const when = waits ? ' once that process exits' : '';
|
|
@@ -135,6 +178,7 @@ function sessionEnd(input, agent, deps) {
|
|
|
135
178
|
export function detachedWorker(cli) {
|
|
136
179
|
return (env, log) => {
|
|
137
180
|
fs.mkdirSync(path.dirname(log), { recursive: true });
|
|
181
|
+
rotateLog(log, SESSION_END_LOG_MAX_BYTES);
|
|
138
182
|
const fd = fs.openSync(log, 'a');
|
|
139
183
|
try {
|
|
140
184
|
const child = spawn(process.execPath, [cli, 'hook', 'session-end'], {
|
|
@@ -149,6 +193,41 @@ export function detachedWorker(cli) {
|
|
|
149
193
|
}
|
|
150
194
|
};
|
|
151
195
|
}
|
|
196
|
+
const PROJECT_ENV = { claude: 'CLAUDE_PROJECT_DIR', cursor: 'CURSOR_PROJECT_DIR' };
|
|
197
|
+
function realEntry(file) {
|
|
198
|
+
try {
|
|
199
|
+
return fs.realpathSync(file);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return file;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
function leaveMark(agent, event, deps) {
|
|
206
|
+
try {
|
|
207
|
+
let cwd = null;
|
|
208
|
+
try {
|
|
209
|
+
cwd = readHookInput(deps.stdin).cwd;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
cwd = null;
|
|
213
|
+
}
|
|
214
|
+
const named = PROJECT_ENV[agent];
|
|
215
|
+
const project = named ? deps.env[named] : undefined;
|
|
216
|
+
writeHookMark(stateDir(deps.env), {
|
|
217
|
+
agent,
|
|
218
|
+
event,
|
|
219
|
+
project: project !== undefined && project !== '' ? project : (cwd ?? deps.cwd),
|
|
220
|
+
at: (deps.clock ?? systemClock).now(),
|
|
221
|
+
toolkit: realEntry(deps.toolkit ?? process.argv[1] ?? ''),
|
|
222
|
+
version: toolVersion(),
|
|
223
|
+
probe: deps.env[HOOK_PROBE_ENV] ?? null,
|
|
224
|
+
node: realEntry(process.execPath),
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
152
231
|
async function ownerExited(owner, waitMs, deps) {
|
|
153
232
|
const identity = owner.process;
|
|
154
233
|
if (identity === null)
|
|
@@ -164,10 +243,23 @@ async function ownerExited(owner, waitMs, deps) {
|
|
|
164
243
|
await clock.sleep(deps.pollMs ?? OWNER_EXIT_POLL_MS);
|
|
165
244
|
}
|
|
166
245
|
}
|
|
246
|
+
function onceParts(raw) {
|
|
247
|
+
if (raw === undefined)
|
|
248
|
+
return null;
|
|
249
|
+
const parts = JSON.parse(raw);
|
|
250
|
+
if (!Array.isArray(parts) || !parts.every(part => typeof part === 'string'))
|
|
251
|
+
throw new Error(`${SESSION_END_ONCE_ENV} is not a list of strings`);
|
|
252
|
+
return parts;
|
|
253
|
+
}
|
|
167
254
|
async function releaseWorker(raw, deps) {
|
|
168
255
|
const owner = parseOwner(raw);
|
|
169
256
|
const clock = deps.clock ?? systemClock;
|
|
170
257
|
const stamp = () => new Date(clock.now()).toISOString();
|
|
258
|
+
const once = onceParts(deps.env[SESSION_END_ONCE_ENV]);
|
|
259
|
+
if (once && !claimOnce(stateDir(deps.env), once, clock.now())) {
|
|
260
|
+
deps.stderr(`${stamp()} session end: another copy of this hook is already releasing the lanes of ${describeOwner(owner)}\n`);
|
|
261
|
+
return 0;
|
|
262
|
+
}
|
|
171
263
|
const waitMs = Number(deps.env[SESSION_END_WAIT_ENV] ?? 0);
|
|
172
264
|
if (waitMs > 0 && !(await ownerExited(owner, waitMs, deps))) {
|
|
173
265
|
deps.stderr(`${stamp()} session end: ${describeOwner(owner)} is still running after ${String(waitMs / 1000)} s (a cleared session, or another conversation in the same app), so its lanes stay; they are freed once it exits\n`);
|
|
@@ -207,10 +299,13 @@ export async function runHookCommand(args, deps) {
|
|
|
207
299
|
const owner = deps.env[SESSION_END_OWNER_ENV];
|
|
208
300
|
if (owner)
|
|
209
301
|
return releaseWorker(owner, deps);
|
|
302
|
+
leaveMark(agent, event, deps);
|
|
210
303
|
return sessionEnd(readHookInput(deps.stdin), agent, deps);
|
|
211
304
|
}
|
|
212
|
-
if (event === 'pre-tool-use')
|
|
305
|
+
if (event === 'pre-tool-use') {
|
|
306
|
+
leaveMark(agent, event, deps);
|
|
213
307
|
return preToolUse(deps.stdin, agent, deps);
|
|
308
|
+
}
|
|
214
309
|
deps.stderr(`${TOOL} hook: '${event ?? ''}' is not a hook\n\n${HOOK_USAGE}`);
|
|
215
310
|
return 2;
|
|
216
311
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { envName } from "../name.js";
|
|
5
|
+
import { AGENTS } from "../registry/owner.js";
|
|
6
|
+
export const HOOK_PROBE_ENV = envName('HOOK_PROBE');
|
|
7
|
+
function marksDir(stateDir) {
|
|
8
|
+
return path.join(stateDir, 'hook-marks');
|
|
9
|
+
}
|
|
10
|
+
function real(dir) {
|
|
11
|
+
try {
|
|
12
|
+
return fs.realpathSync(dir);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return path.resolve(dir);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function markFile(stateDir, agent, project) {
|
|
19
|
+
const key = crypto.createHash('sha256').update(project).digest('hex').slice(0, 16);
|
|
20
|
+
return path.join(marksDir(stateDir), `${agent}-${key}.json`);
|
|
21
|
+
}
|
|
22
|
+
export function writeHookMark(stateDir, mark) {
|
|
23
|
+
const dir = marksDir(stateDir);
|
|
24
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
25
|
+
const project = real(mark.project);
|
|
26
|
+
const file = markFile(stateDir, mark.agent, project);
|
|
27
|
+
const temp = `${file}.${String(process.pid)}.tmp`;
|
|
28
|
+
fs.writeFileSync(temp, `${JSON.stringify({ ...mark, project })}\n`);
|
|
29
|
+
fs.renameSync(temp, file);
|
|
30
|
+
}
|
|
31
|
+
function parseMark(text) {
|
|
32
|
+
let value;
|
|
33
|
+
try {
|
|
34
|
+
value = JSON.parse(text);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
if (typeof value !== 'object' || value === null)
|
|
40
|
+
return null;
|
|
41
|
+
const m = value;
|
|
42
|
+
if (typeof m.agent !== 'string' ||
|
|
43
|
+
!AGENTS.includes(m.agent) ||
|
|
44
|
+
(m.event !== 'pre-tool-use' && m.event !== 'session-end') ||
|
|
45
|
+
typeof m.project !== 'string' ||
|
|
46
|
+
typeof m.at !== 'number' ||
|
|
47
|
+
typeof m.toolkit !== 'string' ||
|
|
48
|
+
typeof m.version !== 'string')
|
|
49
|
+
return null;
|
|
50
|
+
return {
|
|
51
|
+
agent: m.agent,
|
|
52
|
+
event: m.event,
|
|
53
|
+
project: m.project,
|
|
54
|
+
at: m.at,
|
|
55
|
+
toolkit: m.toolkit,
|
|
56
|
+
version: m.version,
|
|
57
|
+
probe: typeof m.probe === 'string' ? m.probe : null,
|
|
58
|
+
node: typeof m.node === 'string' ? m.node : null,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** The latest mark the agent's hook left for exactly this project folder. */
|
|
62
|
+
export function readHookMark(stateDir, agent, project) {
|
|
63
|
+
const root = real(project);
|
|
64
|
+
let text;
|
|
65
|
+
try {
|
|
66
|
+
text = fs.readFileSync(markFile(stateDir, agent, root), 'utf8');
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const mark = parseMark(text);
|
|
72
|
+
return mark?.agent === agent && mark.project === root ? mark : null;
|
|
73
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export const ONCE_WINDOW_MS = 60_000;
|
|
5
|
+
const KEEP_MS = 24 * 60 * 60 * 1000;
|
|
6
|
+
const ATTEMPTS = 5;
|
|
7
|
+
function claimsDir(stateDir) {
|
|
8
|
+
return path.join(stateDir, 'hook-once');
|
|
9
|
+
}
|
|
10
|
+
function keyOf(parts) {
|
|
11
|
+
return crypto.createHash('sha256').update(parts.join('\0')).digest('hex').slice(0, 32);
|
|
12
|
+
}
|
|
13
|
+
function claims(dir) {
|
|
14
|
+
return fs.readdirSync(dir).flatMap(name => {
|
|
15
|
+
const match = /^([0-9a-f]{32})\.(\d{1,15})$/.exec(name);
|
|
16
|
+
return match?.[1] && match[2] ? [{ key: match[1], n: Number(match[2]), file: path.join(dir, name) }] : [];
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function top(all, key) {
|
|
20
|
+
return all.reduce((best, c) => (c.key === key && (best === null || c.n > best.n) ? c : best), null);
|
|
21
|
+
}
|
|
22
|
+
function dated(file) {
|
|
23
|
+
try {
|
|
24
|
+
return fs.statSync(file).mtimeMs;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function sweep(all, mine, now) {
|
|
31
|
+
for (const c of all) {
|
|
32
|
+
const latest = top(all, c.key);
|
|
33
|
+
const old = c.key !== mine.key && latest !== null && (dated(latest.file) ?? 0) < now - KEEP_MS;
|
|
34
|
+
if ((c.key === mine.key && c.n < mine.n) || old)
|
|
35
|
+
fs.rmSync(c.file, { force: true });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Whether this caller wins the work named by `parts`: one caller per window wins, however many race, and a claim
|
|
40
|
+
* left by a caller that died counts only until the window passes. A claim that can't be written counts as won.
|
|
41
|
+
*/
|
|
42
|
+
export function claimOnce(stateDir, parts, now) {
|
|
43
|
+
try {
|
|
44
|
+
const dir = claimsDir(stateDir);
|
|
45
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
46
|
+
const key = keyOf(parts);
|
|
47
|
+
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
|
48
|
+
const last = top(claims(dir), key);
|
|
49
|
+
if (last !== null) {
|
|
50
|
+
const at = dated(last.file);
|
|
51
|
+
if (at === null)
|
|
52
|
+
continue;
|
|
53
|
+
if (now - at <= ONCE_WINDOW_MS)
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
const n = (last?.n ?? -1) + 1;
|
|
57
|
+
const mine = { key, n, file: path.join(dir, `${key}.${String(n)}`) };
|
|
58
|
+
try {
|
|
59
|
+
fs.writeFileSync(mine.file, '', { flag: 'wx' });
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === 'EEXIST')
|
|
63
|
+
continue;
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
fs.utimesSync(mine.file, now / 1000, now / 1000);
|
|
67
|
+
const all = claims(dir);
|
|
68
|
+
if ((top(all, key)?.n ?? n) > n)
|
|
69
|
+
return false;
|
|
70
|
+
sweep(all, mine, now);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
}
|