agentlane 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/agents/claude-plugin.js +69 -8
  3. package/dist/agents/cli.js +11 -4
  4. package/dist/agents/hook-check.js +290 -0
  5. package/dist/agents/launcher.js +34 -6
  6. package/dist/agents/wiring-check.js +10 -4
  7. package/dist/agents/wiring.js +6 -33
  8. package/dist/browser/env.js +27 -7
  9. package/dist/browser/install.js +144 -6
  10. package/dist/browser/lane-browser.js +6 -3
  11. package/dist/browser/stop.js +2 -17
  12. package/dist/cache/key.js +23 -11
  13. package/dist/cli.js +63 -23
  14. package/dist/devices/backend.js +6 -0
  15. package/dist/devices/emulator.js +15 -5
  16. package/dist/devices/hygiene.js +20 -4
  17. package/dist/devices/simctl.js +15 -3
  18. package/dist/disk-limits.js +134 -0
  19. package/dist/driver/caller.js +21 -6
  20. package/dist/driver/client.js +9 -5
  21. package/dist/driver/engine.js +29 -14
  22. package/dist/driver/install.js +88 -36
  23. package/dist/driver/paths.js +15 -11
  24. package/dist/driver/session.js +4 -1
  25. package/dist/driver/superseded.js +378 -0
  26. package/dist/driver-cli.js +32 -23
  27. package/dist/evidence/device.js +4 -0
  28. package/dist/evidence/evidence.js +4 -2
  29. package/dist/evidence/files.js +68 -0
  30. package/dist/evidence/strays.js +107 -0
  31. package/dist/hooks/env.js +2 -1
  32. package/dist/mcp/server.js +15 -0
  33. package/dist/mcp/tools.js +9 -1
  34. package/dist/plugin/guard.js +30 -0
  35. package/dist/plugin/hook-cli.js +101 -6
  36. package/dist/plugin/hook-mark.js +73 -0
  37. package/dist/plugin/hook-once.js +78 -0
  38. package/dist/plugin/shell.js +109 -8
  39. package/dist/processes.js +52 -2
  40. package/dist/registry/config.js +12 -8
  41. package/dist/registry/holds.js +37 -0
  42. package/dist/registry/leases.js +109 -0
  43. package/dist/registry/owner-checks.js +55 -0
  44. package/dist/registry/owner.js +18 -0
  45. package/dist/registry/parks.js +60 -0
  46. package/dist/registry/paths.js +28 -4
  47. package/dist/registry/ports.js +5 -1
  48. package/dist/registry/prune.js +643 -24
  49. package/dist/registry/refusal.js +1 -0
  50. package/dist/registry/registry.js +1261 -236
  51. package/dist/registry/rows.js +18 -4
  52. package/dist/registry/status.js +51 -8
  53. package/dist/registry/store.js +65 -2
  54. package/dist/registry/touch.js +180 -0
  55. package/dist/registry-cli.js +197 -36
  56. package/dist/services/services.js +227 -56
  57. package/dist/services/system.js +2 -1
  58. package/dist/up/answers.js +124 -0
  59. package/dist/up/doctor.js +29 -4
  60. package/dist/up/exec.js +29 -4
  61. package/dist/up/lane-files.js +26 -8
  62. package/dist/up/lane-services.js +8 -3
  63. package/dist/up/park.js +146 -0
  64. package/dist/up/preflight.js +2 -10
  65. package/dist/up/release.js +20 -24
  66. package/dist/up/restart.js +9 -2
  67. package/dist/up/sweep.js +437 -0
  68. package/dist/up/up.js +38 -15
  69. package/dist/up/wake.js +124 -0
  70. package/dist/up/waker.js +49 -0
  71. package/dist/up-cli.js +6 -1
  72. package/package.json +2 -2
  73. package/skills/dev-loop/SKILL.md +7 -5
  74. package/skills/drive/SKILL.md +4 -0
  75. package/skills/setup/SKILL.md +2 -2
@@ -3,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 { readRegistryStatus } from "../registry/registry.js";
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 verdict = guard(command, deps.env, {
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
- return verdict.allow ? convention.allow : convention.deny(verdict.reason);
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
+ }
@@ -1,12 +1,107 @@
1
1
  const SEPARATORS = new Set([';', '&', '|', '(', ')', '\n']);
2
2
  const RESERVED = new Set(['if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', '!', '{', '}', 'time']);
3
3
  const HEADERS = new Set(['for', 'case', 'select', 'function']);
4
+ const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
5
+ const MAX_EXPANSIONS = 1000;
6
+ const OPEN = Symbol('{');
7
+ const COMMA = Symbol(',');
8
+ const CLOSE = Symbol('}');
9
+ function piecesOf(text, braces) {
10
+ const unquoted = new Set(braces);
11
+ return text.split('').map((c, i) => {
12
+ if (!unquoted.has(i))
13
+ return c;
14
+ return c === '{' ? OPEN : c === ',' ? COMMA : CLOSE;
15
+ });
16
+ }
17
+ function textOf(pieces) {
18
+ return pieces.map(p => (p === OPEN ? '{' : p === COMMA ? ',' : p === CLOSE ? '}' : p)).join('');
19
+ }
20
+ function groupAt(pieces, open) {
21
+ let depth = 0;
22
+ const commas = [];
23
+ for (let i = open + 1; i < pieces.length; i++) {
24
+ const p = pieces[i];
25
+ if (p === OPEN)
26
+ depth++;
27
+ else if (p === CLOSE) {
28
+ if (depth === 0)
29
+ return { close: i, commas };
30
+ depth--;
31
+ }
32
+ else if (p === COMMA && depth === 0)
33
+ commas.push(i);
34
+ }
35
+ return null;
36
+ }
37
+ function sequence(body, limit) {
38
+ if (!body.every(p => typeof p === 'string'))
39
+ return null;
40
+ const text = body.join('');
41
+ const numbers = /^([-+]?\d+)\.\.([-+]?\d+)(?:\.\.([-+]?\d+))?$/.exec(text);
42
+ const letters = /^([A-Za-z])\.\.([A-Za-z])(?:\.\.([-+]?\d+))?$/.exec(text);
43
+ const [, from = '', to = '', by = '1'] = numbers ?? letters ?? [];
44
+ if (from === '')
45
+ return null;
46
+ const start = numbers ? Number(from) : from.charCodeAt(0);
47
+ const end = numbers ? Number(to) : to.charCodeAt(0);
48
+ const step = (Math.abs(Number(by)) || 1) * (end < start ? -1 : 1);
49
+ const width = /^[-+]?0\d/.test(from) || /^[-+]?0\d/.test(to) ? Math.max(from.length, to.length) : 0;
50
+ const term = (n) => !numbers ? String.fromCharCode(n) : n < 0 ? `-${String(-n).padStart(width - 1, '0')}` : String(n).padStart(width, '0');
51
+ const terms = [];
52
+ for (let n = start; (step > 0 ? n <= end : n >= end) && terms.length <= limit; n += step)
53
+ terms.push([term(n)]);
54
+ return terms;
55
+ }
56
+ function alternativesOf(pieces, open, close, commas, limit) {
57
+ if (commas.length === 0)
58
+ return sequence(pieces.slice(open + 1, close), limit);
59
+ const cuts = [open, ...commas, close];
60
+ return cuts.slice(1).map((cut, i) => pieces.slice((cuts[i] ?? open) + 1, cut));
61
+ }
62
+ function expand(pieces, budget) {
63
+ for (let open = pieces.indexOf(OPEN); open !== -1; open = pieces.indexOf(OPEN, open + 1)) {
64
+ const group = groupAt(pieces, open);
65
+ if (group === null)
66
+ continue;
67
+ const alternatives = alternativesOf(pieces, open, group.close, group.commas, budget.left);
68
+ if (alternatives === null)
69
+ continue;
70
+ const words = [];
71
+ for (const alternative of alternatives) {
72
+ const expanded = expand([...pieces.slice(0, open), ...alternative, ...pieces.slice(group.close + 1)], budget);
73
+ if (expanded === null)
74
+ return null;
75
+ words.push(...expanded);
76
+ }
77
+ return words;
78
+ }
79
+ budget.left -= 1;
80
+ return budget.left < 0 ? null : [[...pieces]];
81
+ }
82
+ function expandBraces({ word, braces }) {
83
+ if (braces.length === 0)
84
+ return [word];
85
+ const expanded = expand(piecesOf(word.text, braces), { left: MAX_EXPANSIONS });
86
+ if (expanded === null)
87
+ return [word];
88
+ return expanded.map(textOf).flatMap(text => (text === '' ? [] : [{ text, literal: word.literal }]));
89
+ }
90
+ /** Bash and zsh brace-expand every word of a simple command except the assignments that lead it. */
91
+ function expandWords(lexed) {
92
+ let assigning = true;
93
+ return lexed.flatMap(entry => {
94
+ assigning &&= ASSIGNMENT_WORD.test(entry.word.text);
95
+ return assigning ? [entry.word] : expandBraces(entry);
96
+ });
97
+ }
4
98
  class Lexer {
5
99
  src;
6
100
  pos = 0;
7
101
  commands = [];
8
102
  words = [];
9
103
  word = null;
104
+ braces = [];
10
105
  heredocs = [];
11
106
  skipNextWord = false;
12
107
  constructor(src) {
@@ -33,13 +128,15 @@ class Lexer {
33
128
  if (this.skipNextWord)
34
129
  this.skipNextWord = false;
35
130
  else
36
- this.words.push(this.word);
131
+ this.words.push({ word: this.word, braces: this.braces });
37
132
  this.word = null;
133
+ this.braces = [];
38
134
  }
39
135
  endCommand() {
40
136
  this.endWord();
41
- if (this.words.length > 0)
42
- this.commands.push({ words: this.words });
137
+ const words = expandWords(this.words);
138
+ if (words.length > 0)
139
+ this.commands.push({ words });
43
140
  this.words = [];
44
141
  }
45
142
  nested(script) {
@@ -90,6 +187,10 @@ class Lexer {
90
187
  this.pos += 2;
91
188
  return;
92
189
  }
190
+ if (c === '$' && (this.peek(1) === "'" || this.peek(1) === '"')) {
191
+ this.pos++;
192
+ return;
193
+ }
93
194
  if (c === '$') {
94
195
  this.dollar();
95
196
  return;
@@ -98,13 +199,17 @@ class Lexer {
98
199
  this.backtick();
99
200
  return;
100
201
  }
202
+ if (c === '{' || c === ',' || c === '}')
203
+ this.braces.push(this.word?.text.length ?? 0);
101
204
  this.append(c);
102
205
  this.pos++;
103
206
  }
104
207
  redirection() {
105
208
  const fd = this.word !== null && /^\d+$/.test(this.word.text) ? this.word : null;
106
- if (fd)
209
+ if (fd) {
107
210
  this.word = null;
211
+ this.braces = [];
212
+ }
108
213
  else
109
214
  this.endWord();
110
215
  const c = this.peek();
@@ -185,10 +290,6 @@ class Lexer {
185
290
  this.pos = stop + 1;
186
291
  return;
187
292
  }
188
- if (next === "'") {
189
- this.pos++;
190
- return;
191
- }
192
293
  const name = /^[A-Za-z_][A-Za-z0-9_]*|^[0-9@*#?$!-]/.exec(this.src.slice(this.pos + 1));
193
294
  if (name) {
194
295
  this.append(`$${name[0]}`, false);
package/dist/processes.js CHANGED
@@ -2,13 +2,20 @@ import { spawnSync } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  const LSTART = String.raw `[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d{2}:\d{2}:\d{2} \d{4}`;
4
4
  const START_LINE = new RegExp(String.raw `^\s*(\d+)\s+(${LSTART})\s*$`);
5
+ const RUNNING_LINE = new RegExp(String.raw `^\s*(\d+)\s+(\S+)\s+(${LSTART})\s*$`);
5
6
  const INFO_LINE = new RegExp(String.raw `^\s*(\d+)\s+(\d+)\s+(${LSTART})\s?(.*)$`);
7
+ const START_ONLY = new RegExp(`^${LSTART}$`);
6
8
  function normalizeStart(lstart) {
7
9
  return lstart.replace(/\s+/g, ' ');
8
10
  }
9
11
  export function describeStart(start) {
10
12
  return `${start} UTC`;
11
13
  }
14
+ /** The start time as milliseconds since the epoch, to the second `ps` reports; NaN when it isn't a `ps` start time. */
15
+ export function startMs(start) {
16
+ const normal = normalizeStart(start);
17
+ return START_ONLY.test(normal) ? Date.parse(describeStart(normal)) : Number.NaN;
18
+ }
12
19
  function ps(columns, pids) {
13
20
  const result = spawnSync('ps', ['-o', columns, '-p', pids.join(',')], {
14
21
  encoding: 'utf8',
@@ -24,6 +31,11 @@ function ps(columns, pids) {
24
31
  return [];
25
32
  return undefined;
26
33
  }
34
+ // Linux appends " (deleted)" to the /proc/<pid>/cwd link once the directory is removed (proc(5)).
35
+ const DELETED_SUFFIX = ' (deleted)';
36
+ export function cwdOfProcLink(link) {
37
+ return link.endsWith(DELETED_SUFFIX) ? link.slice(0, -DELETED_SUFFIX.length) : link;
38
+ }
27
39
  function lsofCwd(pid) {
28
40
  const result = spawnSync('lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], {
29
41
  encoding: 'utf8',
@@ -35,9 +47,30 @@ function lsofCwd(pid) {
35
47
  const line = result.stdout.split('\n').find(l => l.startsWith('n'));
36
48
  return line?.slice(1);
37
49
  }
50
+ function wantedPids(pids) {
51
+ return [...new Set(pids)].filter(pid => Number.isInteger(pid) && pid > 0);
52
+ }
53
+ /** The start times of those of `pids` still running. A zombie has exited, though ps lists it until it is reaped. */
54
+ export function runningStartTimes(pids) {
55
+ const wanted = wantedPids(pids);
56
+ if (wanted.length === 0)
57
+ return new Map();
58
+ const lines = ps('pid=,stat=,lstart=', wanted);
59
+ if (!lines)
60
+ return undefined;
61
+ const table = new Map();
62
+ for (const line of lines) {
63
+ const m = RUNNING_LINE.exec(line);
64
+ if (!m?.[1] || !m[2] || !m[3])
65
+ return undefined;
66
+ if (!m[2].startsWith('Z'))
67
+ table.set(Number(m[1]), normalizeStart(m[3]));
68
+ }
69
+ return table;
70
+ }
38
71
  export const systemProcesses = {
39
72
  startTimes(pids) {
40
- const wanted = [...new Set(pids)].filter(pid => Number.isInteger(pid) && pid > 0);
73
+ const wanted = wantedPids(pids);
41
74
  if (wanted.length === 0)
42
75
  return new Map();
43
76
  const lines = ps('pid=,lstart=', wanted);
@@ -62,7 +95,7 @@ export const systemProcesses = {
62
95
  cwd(pid) {
63
96
  if (process.platform === 'linux') {
64
97
  try {
65
- return fs.readlinkSync(`/proc/${String(pid)}/cwd`);
98
+ return cwdOfProcLink(fs.readlinkSync(`/proc/${String(pid)}/cwd`));
66
99
  }
67
100
  catch {
68
101
  return undefined;
@@ -71,6 +104,23 @@ export const systemProcesses = {
71
104
  return lsofCwd(pid);
72
105
  },
73
106
  };
107
+ /** A process's environment, where the OS shows it to its owner; undefined when it can't be read. */
108
+ export function environmentOf(pid) {
109
+ if (process.platform === 'linux') {
110
+ try {
111
+ return fs.readFileSync(`/proc/${String(pid)}/environ`, 'utf8').replaceAll('\0', ' ');
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ }
117
+ const result = spawnSync('ps', ['eww', '-o', 'command=', '-p', String(pid)], {
118
+ encoding: 'utf8',
119
+ env: { PATH: `${process.env.PATH ?? ''}:/usr/bin:/bin`, LC_ALL: 'C' },
120
+ timeout: 10_000,
121
+ });
122
+ return result.status === 0 ? result.stdout : undefined;
123
+ }
74
124
  export function identityOf(table, pid) {
75
125
  const start = table.startTimes([pid])?.get(pid);
76
126
  return start === undefined ? undefined : { pid, start };
@@ -3,6 +3,7 @@ import { BROWSER_PORT_TYPE } from "../browser/kinds.js";
3
3
  import { configPath } from "./paths.js";
4
4
  import { UsageError } from "./refusal.js";
5
5
  export const HOUR_MS = 3_600_000;
6
+ export const MINUTE_MS = 60_000;
6
7
  export const DEVICE_MEMORY_MB = { ios: 4000, android: 3400 };
7
8
  export const EMULATOR_PORTS = { first: 5554, last: 5585 };
8
9
  export const EMULATOR_SERVICE = 'emulator';
@@ -16,7 +17,7 @@ export const DEFAULT_CONFIG = {
16
17
  poolSize: 5,
17
18
  emulatorPoolSize: 5,
18
19
  memoryBudgetMb: 5 * DEVICE_MEMORY_MB.ios,
19
- idleMs: 2 * HOUR_MS,
20
+ parkMs: 30 * MINUTE_MS,
20
21
  blocks: {
21
22
  metro: { first: 41100, last: 41119 },
22
23
  api: { first: 41200, last: 41219 },
@@ -34,7 +35,7 @@ export function parseConfig(raw, source) {
34
35
  const bad = (problem, fix) => new UsageError(`${source}: ${problem}`, fix);
35
36
  if (!isRecord(raw))
36
37
  throw bad('the file is not a JSON object', `write an object such as {"poolSize": 5}`);
37
- const known = ['poolSize', 'emulatorPoolSize', 'memoryBudgetGB', 'idleHours', 'ports'];
38
+ const known = ['poolSize', 'emulatorPoolSize', 'memoryBudgetGB', 'parkMinutes', 'idleHours', 'ports'];
38
39
  for (const key of Object.keys(raw)) {
39
40
  if (!known.includes(key))
40
41
  throw bad(`unknown setting '${key}'`, `use only ${known.join(', ')}`);
@@ -58,12 +59,15 @@ export function parseConfig(raw, source) {
58
59
  }
59
60
  memoryBudgetMb = Math.round(raw.memoryBudgetGB * 1000);
60
61
  }
61
- let idleMs = DEFAULT_CONFIG.idleMs;
62
- if (raw.idleHours !== undefined) {
63
- if (typeof raw.idleHours !== 'number' || !(raw.idleHours > 0)) {
64
- throw bad('idleHours must be a positive number', 'set "idleHours": 2 (the default)');
62
+ let parkMs = DEFAULT_CONFIG.parkMs;
63
+ if (raw.parkMinutes !== undefined) {
64
+ if (typeof raw.parkMinutes !== 'number' || !(raw.parkMinutes > 0)) {
65
+ throw bad('parkMinutes must be a positive number', `set "parkMinutes": ${String(DEFAULT_CONFIG.parkMs / MINUTE_MS)} (the default)`);
65
66
  }
66
- idleMs = raw.idleHours * HOUR_MS;
67
+ parkMs = Math.round(raw.parkMinutes * MINUTE_MS);
68
+ }
69
+ if (raw.idleHours !== undefined && (typeof raw.idleHours !== 'number' || !(raw.idleHours > 0))) {
70
+ throw bad('idleHours must be a positive number', 'set "idleHours": 2, or remove it: only 0.4.1 and earlier read it');
67
71
  }
68
72
  const blocks = { ...DEFAULT_CONFIG.blocks };
69
73
  if (raw.ports !== undefined) {
@@ -85,7 +89,7 @@ export function parseConfig(raw, source) {
85
89
  const onEmulators = emulatorOverlap(blocks);
86
90
  if (onEmulators)
87
91
  throw bad(emulatorOverlapProblem(onEmulators), 'move that block clear of 5554-5585');
88
- return { poolSize, emulatorPoolSize, memoryBudgetMb, idleMs, blocks };
92
+ return { poolSize, emulatorPoolSize, memoryBudgetMb, parkMs, blocks };
89
93
  }
90
94
  function emulatorOverlap(blocks) {
91
95
  const hit = Object.entries(blocks).find(([, b]) => b.first <= EMULATOR_PORTS.last && b.last >= EMULATOR_PORTS.first);