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.
Files changed (74) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/agents/claude-plugin.js +54 -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/simctl.js +15 -3
  17. package/dist/disk-limits.js +134 -0
  18. package/dist/driver/caller.js +21 -6
  19. package/dist/driver/client.js +9 -5
  20. package/dist/driver/engine.js +29 -14
  21. package/dist/driver/install.js +88 -36
  22. package/dist/driver/paths.js +15 -11
  23. package/dist/driver/session.js +4 -1
  24. package/dist/driver/superseded.js +378 -0
  25. package/dist/driver-cli.js +32 -23
  26. package/dist/evidence/device.js +4 -0
  27. package/dist/evidence/evidence.js +4 -2
  28. package/dist/evidence/files.js +68 -0
  29. package/dist/evidence/strays.js +107 -0
  30. package/dist/hooks/env.js +2 -1
  31. package/dist/mcp/server.js +15 -0
  32. package/dist/mcp/tools.js +9 -1
  33. package/dist/plugin/guard.js +30 -0
  34. package/dist/plugin/hook-cli.js +101 -6
  35. package/dist/plugin/hook-mark.js +73 -0
  36. package/dist/plugin/hook-once.js +78 -0
  37. package/dist/plugin/shell.js +109 -8
  38. package/dist/processes.js +52 -2
  39. package/dist/registry/config.js +12 -8
  40. package/dist/registry/holds.js +37 -0
  41. package/dist/registry/leases.js +109 -0
  42. package/dist/registry/owner-checks.js +55 -0
  43. package/dist/registry/owner.js +18 -0
  44. package/dist/registry/parks.js +60 -0
  45. package/dist/registry/paths.js +28 -4
  46. package/dist/registry/ports.js +5 -1
  47. package/dist/registry/prune.js +643 -24
  48. package/dist/registry/refusal.js +1 -0
  49. package/dist/registry/registry.js +1258 -235
  50. package/dist/registry/rows.js +18 -4
  51. package/dist/registry/status.js +51 -8
  52. package/dist/registry/store.js +63 -1
  53. package/dist/registry/touch.js +180 -0
  54. package/dist/registry-cli.js +197 -36
  55. package/dist/services/services.js +223 -54
  56. package/dist/services/system.js +2 -1
  57. package/dist/up/answers.js +124 -0
  58. package/dist/up/doctor.js +27 -3
  59. package/dist/up/exec.js +29 -4
  60. package/dist/up/lane-files.js +26 -8
  61. package/dist/up/lane-services.js +8 -3
  62. package/dist/up/park.js +146 -0
  63. package/dist/up/preflight.js +2 -10
  64. package/dist/up/release.js +20 -24
  65. package/dist/up/restart.js +9 -2
  66. package/dist/up/sweep.js +437 -0
  67. package/dist/up/up.js +33 -12
  68. package/dist/up/wake.js +124 -0
  69. package/dist/up/waker.js +49 -0
  70. package/dist/up-cli.js +6 -1
  71. package/package.json +2 -2
  72. package/skills/dev-loop/SKILL.md +7 -5
  73. package/skills/drive/SKILL.md +4 -0
  74. package/skills/setup/SKILL.md +2 -2
@@ -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);
@@ -0,0 +1,37 @@
1
+ import { MINUTE_MS } from "./config.js";
2
+ import { UsageError } from "./refusal.js";
3
+ import { int, text } from "./store.js";
4
+ export const DEFAULT_HOLD_MS = 60 * MINUTE_MS;
5
+ export const MAX_HOLD_MS = 24 * 60 * MINUTE_MS;
6
+ const HOLD_FORM = 'minutes or hours, such as 45m, 2h or 1h30m';
7
+ /** A `keep --for` time in milliseconds: `<n>m`, `<n>h` or `<n>h<n>m`, from a minute up to `MAX_HOLD_MS`. */
8
+ export function parseHoldTime(raw) {
9
+ const match = /^(?:(\d+)h)?(?:(\d+)m)?$/.exec(raw.trim());
10
+ if (!match || (match[1] === undefined && match[2] === undefined)) {
11
+ throw new UsageError(`--for ${raw} is not a time`, `write --for as ${HOLD_FORM}`);
12
+ }
13
+ const ms = (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * MINUTE_MS;
14
+ if (ms === 0)
15
+ throw new UsageError(`--for ${raw} holds the lane for no time`, `pass at least 1m, as ${HOLD_FORM}`);
16
+ if (ms > MAX_HOLD_MS) {
17
+ throw new UsageError(`--for ${raw} is longer than a hold can last, which is 24h`, 'pass --for 24h or less');
18
+ }
19
+ return ms;
20
+ }
21
+ /** The lane's hold that counts at `now`: placed by the owner the lane has now, and not yet ended. */
22
+ export function readHold(db, laneId, ownerKey, now) {
23
+ const row = db
24
+ .prepare('SELECT reason, since, until FROM holds WHERE claim_id = ? AND owner_key = ? AND until > ?')
25
+ .get(laneId, ownerKey, now);
26
+ return row ? { reason: text(row, 'reason'), since: int(row, 'since'), until: int(row, 'until') } : null;
27
+ }
28
+ /** Records `hold` as the lane's only hold, in place of any earlier one. */
29
+ export function writeHold(db, laneId, ownerKey, hold) {
30
+ db.prepare(`INSERT INTO holds (claim_id, owner_key, reason, since, until) VALUES (?, ?, ?, ?, ?)
31
+ ON CONFLICT (claim_id) DO UPDATE SET owner_key = excluded.owner_key, reason = excluded.reason,
32
+ since = excluded.since, until = excluded.until`).run(laneId, ownerKey, hold.reason, hold.since, hold.until);
33
+ }
34
+ /** Ends the hold `ownerKey` placed on the lane; true when there was one. */
35
+ export function dropHold(db, laneId, ownerKey) {
36
+ return Number(db.prepare('DELETE FROM holds WHERE claim_id = ? AND owner_key = ?').run(laneId, ownerKey).changes) > 0;
37
+ }
@@ -0,0 +1,109 @@
1
+ import { int, optInt, text } from "./store.js";
2
+ export const KEEPER_PID = 1;
3
+ export function sameProcess(a, b) {
4
+ return a.pid === b.pid && a.start === b.start;
5
+ }
6
+ /**
7
+ * Registries from 0.4.1 and earlier read a device row with no device id and a creator as a device being
8
+ * created: it counts against the pool size and the memory budget while the creator lives, and once their
9
+ * pre-lock snapshot proves the creator dead they adopt the listed device of the same name or drop the row.
10
+ * A leased device's row becomes such a reservation under a name no device has, created by `keeper`, pid 1
11
+ * with its start time, which those versions can't prove dead while the machine stays up. So they hold the
12
+ * device's place until this version ends the lease, judging the lease by its holder. A holder those versions
13
+ * can prove dead would let them drop the row and admit another device while this one still runs.
14
+ */
15
+ function insertLease(db, lease, keeper, now) {
16
+ const creator = keeper ?? lease.holder;
17
+ db.prepare(`INSERT INTO devices (name, platform, device_id, device_type, device_type_name, runtime, runtime_name,
18
+ creator_pid, creator_start, claim_id, created_at)
19
+ VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?, NULL, ?)`).run(lease.reservation, lease.platform, lease.deviceType, lease.deviceTypeName, lease.runtime, lease.runtimeName, creator.pid, creator.start, now);
20
+ db.prepare(`INSERT INTO device_leases (reservation, name, platform, device_id, device_type, device_type_name, runtime, runtime_name,
21
+ created_at, work, holder_pid, holder_start, since, console_port)
22
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(lease.reservation, lease.name, lease.platform, lease.id, lease.deviceType, lease.deviceTypeName, lease.runtime, lease.runtimeName, lease.createdAt, lease.work, lease.holder.pid, lease.holder.start, now, lease.consolePort);
23
+ return lease;
24
+ }
25
+ export function leaseDevice(db, name, terms) {
26
+ const row = db.prepare('SELECT * FROM devices WHERE name = ?').get(name);
27
+ if (!row || row.device_id === null || row.claim_id !== null)
28
+ return null;
29
+ db.prepare('DELETE FROM devices WHERE name = ?').run(name);
30
+ return insertLease(db, {
31
+ reservation: terms.reservation,
32
+ name,
33
+ platform: text(row, 'platform'),
34
+ id: text(row, 'device_id'),
35
+ deviceType: text(row, 'device_type'),
36
+ deviceTypeName: text(row, 'device_type_name'),
37
+ runtime: text(row, 'runtime'),
38
+ runtimeName: text(row, 'runtime_name'),
39
+ createdAt: int(row, 'created_at'),
40
+ work: terms.work,
41
+ holder: terms.holder,
42
+ consolePort: terms.consolePort,
43
+ }, terms.keeper, terms.now);
44
+ }
45
+ function removeLease(db, lease) {
46
+ db.prepare('DELETE FROM devices WHERE name = ? AND device_id IS NULL').run(lease.reservation);
47
+ db.prepare('DELETE FROM device_leases WHERE reservation = ?').run(lease.reservation);
48
+ }
49
+ export function handOver(db, lease, terms) {
50
+ removeLease(db, lease);
51
+ return insertLease(db, { ...lease, reservation: terms.reservation, work: terms.work, holder: terms.holder, consolePort: terms.consolePort }, terms.keeper, terms.now);
52
+ }
53
+ function leaseOf(row) {
54
+ return {
55
+ reservation: text(row, 'reservation'),
56
+ name: text(row, 'name'),
57
+ platform: text(row, 'platform'),
58
+ id: text(row, 'device_id'),
59
+ deviceType: text(row, 'device_type'),
60
+ deviceTypeName: text(row, 'device_type_name'),
61
+ runtime: text(row, 'runtime'),
62
+ runtimeName: text(row, 'runtime_name'),
63
+ createdAt: int(row, 'created_at'),
64
+ work: text(row, 'work'),
65
+ holder: { pid: int(row, 'holder_pid'), start: text(row, 'holder_start') },
66
+ consolePort: optInt(row, 'console_port'),
67
+ };
68
+ }
69
+ export function allLeases(db) {
70
+ return db.prepare('SELECT * FROM device_leases ORDER BY since, reservation').all().map(leaseOf);
71
+ }
72
+ export function leaseReservations(db) {
73
+ return new Map(db
74
+ .prepare('SELECT reservation, work FROM device_leases')
75
+ .all()
76
+ .map(r => [text(r, 'reservation'), text(r, 'work')]));
77
+ }
78
+ export function leasedConsolePorts(db) {
79
+ return db
80
+ .prepare('SELECT console_port FROM device_leases WHERE console_port IS NOT NULL')
81
+ .all()
82
+ .map(r => int(r, 'console_port'));
83
+ }
84
+ export function heldBy(db, lease, holder) {
85
+ return (db
86
+ .prepare('SELECT 1 FROM device_leases WHERE reservation = ? AND holder_pid = ? AND holder_start = ?')
87
+ .get(lease.reservation, holder.pid, holder.start) !== undefined);
88
+ }
89
+ export function endLease(db, lease, outcome, poolCap) {
90
+ if (outcome === 'gone') {
91
+ removeLease(db, lease);
92
+ return 'gone';
93
+ }
94
+ if (db.prepare('SELECT 1 FROM devices WHERE device_id = ? OR name = ?').get(lease.id, lease.name)) {
95
+ removeLease(db, lease);
96
+ return 'recorded-elsewhere';
97
+ }
98
+ const others = db
99
+ .prepare(`SELECT COUNT(*) AS n FROM devices WHERE platform = ? AND name != ?
100
+ AND name NOT IN (SELECT reservation FROM device_leases WHERE work = 'delete')`)
101
+ .get(lease.platform, lease.reservation);
102
+ if (outcome === 'present' && others && int(others, 'n') >= poolCap)
103
+ return 'no-room';
104
+ removeLease(db, lease);
105
+ db.prepare(`INSERT INTO devices (name, platform, device_id, device_type, device_type_name, runtime, runtime_name,
106
+ creator_pid, creator_start, claim_id, created_at)
107
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?)`).run(lease.name, lease.platform, lease.id, lease.deviceType, lease.deviceTypeName, lease.runtime, lease.runtimeName, lease.createdAt);
108
+ return 'restored';
109
+ }
@@ -0,0 +1,55 @@
1
+ import { int, optInt, optText, text } from "./store.js";
2
+ /** How long a lane stays parked, after its owner is found gone, for that owner's session to come back before it ends. */
3
+ export const RETURN_WINDOW_MS = 30 * 60_000;
4
+ /** How long a sighting of a lane's owner, by a check or by a call on the lane, spares the owner a check of its process. */
5
+ export const OWNER_CHECK_MS = 3 * 60_000;
6
+ /** How long an end of a lane may stand unfinished before the sweep asks whether the process ending it still runs. */
7
+ export const REAP_RETRY_MS = 5 * 60_000;
8
+ function goneOf(row) {
9
+ const state = optText(row, 'gone');
10
+ if (state === null)
11
+ return null;
12
+ const pid = optInt(row, 'reaper_pid');
13
+ const start = optText(row, 'reaper_start');
14
+ return {
15
+ state: state,
16
+ foundAt: int(row, 'gone_at'),
17
+ reaper: pid !== null && start !== null ? { pid, start } : null,
18
+ reapingSince: optInt(row, 'reaping_since'),
19
+ attempt: optText(row, 'attempt'),
20
+ };
21
+ }
22
+ /** The checks of the lane's owner keyed `ownerKey`; null when none was recorded, or it was about another owner. */
23
+ export function readCheck(db, laneId, ownerKey) {
24
+ const row = db.prepare('SELECT * FROM owner_checks WHERE claim_id = ?').get(laneId);
25
+ if (!row || text(row, 'owner_key') !== ownerKey)
26
+ return null;
27
+ return { checkedAt: optInt(row, 'checked_at'), gone: goneOf(row) };
28
+ }
29
+ /** Records `at` as when a check last found the owner keyed `ownerKey` alive, or could not tell, unless it is found gone. */
30
+ export function noteChecked(db, laneId, ownerKey, at) {
31
+ db.prepare(`INSERT INTO owner_checks (claim_id, owner_key, checked_at) VALUES (?, ?, ?)
32
+ ON CONFLICT (claim_id) DO UPDATE SET owner_key = excluded.owner_key, checked_at = excluded.checked_at,
33
+ gone = NULL, gone_at = NULL, reaper_pid = NULL, reaper_start = NULL, reaping_since = NULL, attempt = NULL
34
+ WHERE owner_checks.owner_key != excluded.owner_key
35
+ OR (owner_checks.gone IS NULL AND (owner_checks.checked_at IS NULL OR owner_checks.checked_at < excluded.checked_at))`).run(laneId, ownerKey, at);
36
+ }
37
+ /** Records the owner keyed `ownerKey` as found gone at `at`, unless it was found gone before; true when this is the first. */
38
+ export function noteGone(db, laneId, ownerKey, state, at) {
39
+ if (readCheck(db, laneId, ownerKey)?.gone)
40
+ return false;
41
+ db.prepare(`INSERT INTO owner_checks (claim_id, owner_key, gone, gone_at) VALUES (?, ?, ?, ?)
42
+ ON CONFLICT (claim_id) DO UPDATE SET owner_key = excluded.owner_key, gone = excluded.gone, gone_at = excluded.gone_at,
43
+ reaper_pid = NULL, reaper_start = NULL, reaping_since = NULL, attempt = NULL`).run(laneId, ownerKey, state, at);
44
+ return true;
45
+ }
46
+ /** Forgets what the checks found, as when the lane's owner comes back. */
47
+ export function dropCheck(db, laneId) {
48
+ db.prepare('DELETE FROM owner_checks WHERE claim_id = ?').run(laneId);
49
+ }
50
+ export function startReap(db, laneId, reaper, attempt, at) {
51
+ db.prepare('UPDATE owner_checks SET reaper_pid = ?, reaper_start = ?, reaping_since = ?, attempt = ? WHERE claim_id = ?').run(reaper.pid, reaper.start, at, attempt, laneId);
52
+ }
53
+ export function stopReap(db, laneId, attempt) {
54
+ db.prepare('UPDATE owner_checks SET reaper_pid = NULL, reaper_start = NULL, reaping_since = NULL, attempt = NULL WHERE claim_id = ? AND attempt = ?').run(laneId, attempt);
55
+ }
@@ -69,6 +69,24 @@ export function ownerKey(owner) {
69
69
  const label = owner.kind === 'process' ? (agentOf(owner) ?? 'process') : owner.kind;
70
70
  return `${label}:${String(owner.process.pid)}:${owner.process.start}`;
71
71
  }
72
+ /**
73
+ * The host's own id for the session behind an owner, which a later process of that session presents again: Claude
74
+ * Code's session id, or a Codex thread's id. Null for the other agents, whose hosts give none that outlives a process.
75
+ */
76
+ export function hostSession(owner) {
77
+ if (owner.kind === 'claude')
78
+ return owner.sessionId;
79
+ if (owner.kind === 'codex')
80
+ return owner.threadId;
81
+ return null;
82
+ }
83
+ /** The session that can still take its lane back, for people: null when nothing can. */
84
+ export function describeHostSession(owner) {
85
+ const session = hostSession(owner);
86
+ if (session === null)
87
+ return null;
88
+ return owner.kind === 'codex' ? `codex thread ${session}` : `claude session ${session.slice(0, 8)}`;
89
+ }
72
90
  export function describeOwner(owner) {
73
91
  const pid = owner.process ? `pid ${String(owner.process.pid)}` : null;
74
92
  const agent = agentOf(owner);
@@ -0,0 +1,60 @@
1
+ import { DEVICE_NOUN } from "../devices/backend.js";
2
+ import { names } from "./rows.js";
3
+ import { int, optInt, optText, text } from "./store.js";
4
+ export const NOTHING_TO_RESTART = { device: null, services: [], browser: null, app: null };
5
+ function restartsOf(raw) {
6
+ const parsed = JSON.parse(raw);
7
+ return {
8
+ device: parsed.device ?? null,
9
+ services: Array.isArray(parsed.services) ? parsed.services.filter((s) => typeof s === 'string') : [],
10
+ browser: parsed.browser ?? null,
11
+ app: typeof parsed.app === 'string' ? parsed.app : null,
12
+ };
13
+ }
14
+ function parkOf(row) {
15
+ const pid = optInt(row, 'holder_pid');
16
+ const start = optText(row, 'holder_start');
17
+ return {
18
+ state: text(row, 'state'),
19
+ since: int(row, 'since'),
20
+ parkedAt: optInt(row, 'parked_at'),
21
+ holder: pid !== null && start !== null ? { pid, start } : null,
22
+ attempt: optText(row, 'attempt'),
23
+ restarts: restartsOf(text(row, 'restarts')),
24
+ problems: names(row, 'problems'),
25
+ };
26
+ }
27
+ export function readPark(db, laneId) {
28
+ const row = db.prepare('SELECT * FROM parks WHERE claim_id = ?').get(laneId);
29
+ return row ? parkOf(row) : null;
30
+ }
31
+ export function writePark(db, laneId, park) {
32
+ db.prepare(`INSERT INTO parks (claim_id, state, since, parked_at, holder_pid, holder_start, attempt, restarts, problems)
33
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
34
+ ON CONFLICT (claim_id) DO UPDATE SET state = excluded.state, since = excluded.since, parked_at = excluded.parked_at,
35
+ holder_pid = excluded.holder_pid, holder_start = excluded.holder_start, attempt = excluded.attempt,
36
+ restarts = excluded.restarts, problems = excluded.problems`).run(laneId, park.state, park.since, park.parkedAt, park.holder?.pid ?? null, park.holder?.start ?? null, park.attempt, JSON.stringify(park.restarts), JSON.stringify(park.problems));
37
+ }
38
+ export function dropPark(db, laneId) {
39
+ db.prepare('DELETE FROM parks WHERE claim_id = ?').run(laneId);
40
+ }
41
+ /** The restarts of two parks of one lane, for a lane parked again before a wake brought everything back. */
42
+ export function mergeRestarts(earlier, later) {
43
+ return {
44
+ device: later.device ?? earlier.device,
45
+ services: [...new Set([...earlier.services, ...later.services])],
46
+ browser: later.browser ?? earlier.browser,
47
+ app: later.app ?? earlier.app,
48
+ };
49
+ }
50
+ /** What a parked lane's next call brings back, in words. */
51
+ export function describeRestarts(restarts) {
52
+ const { device } = restarts;
53
+ const parts = [
54
+ ...(device ? [`${DEVICE_NOUN[device.platform]} ${device.name} (${device.deviceTypeName}, ${device.runtimeName})`] : []),
55
+ ...(restarts.services.length > 0 ? [`services ${restarts.services.join(', ')}`] : []),
56
+ ...(restarts.app ? [`the app ${restarts.app}`] : []),
57
+ ...(restarts.browser ? [`the ${restarts.browser} browser`] : []),
58
+ ];
59
+ return parts.length > 0 ? parts.join(', ') : 'nothing';
60
+ }
@@ -11,12 +11,36 @@ export function stateDir(env = process.env) {
11
11
  const override = env[STATE_DIR_ENV];
12
12
  if (override)
13
13
  return path.resolve(override);
14
- const xdg = env.XDG_STATE_HOME;
15
- const base = xdg && path.isAbsolute(xdg) ? xdg : path.join(os.homedir(), '.local', 'state');
16
- const own = path.join(base, TOOL);
17
- const former = path.join(base, FORMER.tool);
14
+ const own = path.join(stateBase(env), TOOL);
15
+ const former = formerStateDir(env);
18
16
  return !fs.existsSync(databasePath(own)) && fs.existsSync(databasePath(former)) ? former : own;
19
17
  }
18
+ function homeStateBase(env) {
19
+ return path.join(env.HOME && path.isAbsolute(env.HOME) ? env.HOME : os.homedir(), '.local', 'state');
20
+ }
21
+ function stateBase(env) {
22
+ const xdg = env.XDG_STATE_HOME;
23
+ return xdg && path.isAbsolute(xdg) ? xdg : homeStateBase(env);
24
+ }
25
+ function stateBases(env) {
26
+ return [...new Set([stateBase(env), homeStateBase(env)])];
27
+ }
28
+ function formerStateDir(env = process.env) {
29
+ return path.join(stateBase(env), FORMER.tool);
30
+ }
31
+ export const FORMER_STATE_DIR_ENV = `${FORMER.envPrefix}_STATE_DIR`;
32
+ export function formerRegistryDirs(env = process.env) {
33
+ const override = env[FORMER_STATE_DIR_ENV];
34
+ return [
35
+ ...new Set([...(override ? [path.resolve(override)] : []), ...stateBases(env).map(base => path.join(base, FORMER.tool))]),
36
+ ];
37
+ }
38
+ export function isFormerRegistryDir(env, dir) {
39
+ return path.basename(dir) === FORMER.tool || formerRegistryDirs(env).includes(dir);
40
+ }
41
+ export function registryDirs(env = process.env) {
42
+ return [...new Set([stateDir(env), ...stateBases(env).map(base => path.join(base, TOOL)), ...formerRegistryDirs(env)])];
43
+ }
20
44
  /** The names this version writes in a state folder: in 0.2.x's folder, 0.2.x's names, because 0.2.x reads them there. */
21
45
  export function diskNames(dir) {
22
46
  if (path.basename(dir) === FORMER.tool) {
@@ -8,7 +8,11 @@ function answers(host, port, timeoutMs) {
8
8
  resolve(listening);
9
9
  };
10
10
  socket.setTimeout(timeoutMs, () => {
11
- done(true);
11
+ // libuv runs expired timers before the I/O that arrived while the event loop was busy, so a refusal that came in
12
+ // during a stall is only read after this timeout fires; setImmediate runs after that I/O.
13
+ setImmediate(() => {
14
+ done(true);
15
+ });
12
16
  });
13
17
  socket.once('connect', () => {
14
18
  done(true);