@isentinel/machine-budget 0.1.0 → 0.2.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.
@@ -0,0 +1,663 @@
1
+ import { createRequire } from "node:module";
2
+ import process from "node:process";
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout } from "node:timers/promises";
8
+ import { type } from "arktype";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { Buffer } from "node:buffer";
11
+ // src/learned-cost.ts
12
+ const MINIMUM_SAMPLES = 3;
13
+ const PERCENTILE = .9;
14
+ /**
15
+ * Names a learned cost: the clone's git common directory, the project and the
16
+ * pass. All worktrees of one clone share the common directory, so they share
17
+ * costs.
18
+ *
19
+ * @param gitCommonDirectory - The git common directory of the clone.
20
+ * @param scope - The project and the pass.
21
+ * @returns The key of the cost in the ledger.
22
+ */
23
+ function costKey(gitCommonDirectory, scope) {
24
+ return JSON.stringify([
25
+ gitCommonDirectory,
26
+ scope.project,
27
+ scope.pass
28
+ ]);
29
+ }
30
+ /**
31
+ * Estimates the memory of one worker from the peaks of earlier runs.
32
+ *
33
+ * @param samples - Peak memory of one worker in earlier runs, in bytes.
34
+ * @returns About the 90th percentile, or undefined with too few samples.
35
+ */
36
+ function learnedCost(samples) {
37
+ if (samples.length < MINIMUM_SAMPLES) return;
38
+ const sorted = samples.toSorted((left, right) => left - right);
39
+ return sorted[Math.ceil(sorted.length * PERCENTILE) - 1];
40
+ }
41
+ // src/ledger.ts
42
+ const LEDGER_FORMAT = 2;
43
+ const BUSY_TIMEOUT_MS = 3e4;
44
+ const LAST_SEEN = "last_seen_at";
45
+ const SQLITE_BUSY = 5;
46
+ const SQLITE_PRIMARY_CODE = 255;
47
+ const SCHEMA = `
48
+ CREATE TABLE IF NOT EXISTS sessions (
49
+ id TEXT PRIMARY KEY,
50
+ pid INTEGER NOT NULL,
51
+ started_at INTEGER NOT NULL,
52
+ heartbeat_at INTEGER NOT NULL,
53
+ worktree TEXT NOT NULL
54
+ );
55
+ CREATE TABLE IF NOT EXISTS leases (
56
+ id TEXT PRIMARY KEY,
57
+ session TEXT NOT NULL,
58
+ lane TEXT NOT NULL,
59
+ memory INTEGER NOT NULL,
60
+ threads INTEGER NOT NULL
61
+ );
62
+ CREATE TABLE IF NOT EXISTS waiters (
63
+ id TEXT PRIMARY KEY,
64
+ session TEXT NOT NULL,
65
+ is_big INTEGER NOT NULL,
66
+ since INTEGER NOT NULL,
67
+ memory INTEGER NOT NULL,
68
+ threads INTEGER NOT NULL
69
+ );
70
+ CREATE TABLE IF NOT EXISTS costs (
71
+ key TEXT NOT NULL,
72
+ at INTEGER NOT NULL,
73
+ bytes INTEGER NOT NULL
74
+ );
75
+ CREATE INDEX IF NOT EXISTS costs_by_key ON costs (key, at);
76
+ CREATE TABLE IF NOT EXISTS meta (
77
+ key TEXT PRIMARY KEY,
78
+ value INTEGER NOT NULL
79
+ );
80
+ `;
81
+ const sessionRows = type({
82
+ id: "string",
83
+ heartbeatAt: "number",
84
+ pid: "number",
85
+ startedAt: "number",
86
+ worktree: "string"
87
+ }).array();
88
+ const leaseRows = type({
89
+ id: "string",
90
+ lane: "'main' | 'small'",
91
+ memory: "number",
92
+ session: "string",
93
+ threads: "number"
94
+ }).array();
95
+ const waiterRows = type({
96
+ id: "string",
97
+ isBig: type("0 | 1").pipe((bit) => bit === 1),
98
+ memory: "number",
99
+ session: "string",
100
+ since: "number",
101
+ threads: "number"
102
+ }).array();
103
+ const valueRows = type({ value: "number" }).array();
104
+ /**
105
+ * Tells whether an error says that another process holds the ledger lock.
106
+ *
107
+ * @param error - What a ledger call threw.
108
+ * @returns Whether SQLite reported the database busy.
109
+ */
110
+ function isLedgerLocked(error) {
111
+ return error instanceof Error && "errcode" in error && typeof error.errcode === "number" && (error.errcode & SQLITE_PRIMARY_CODE) === SQLITE_BUSY;
112
+ }
113
+ /**
114
+ * Names the ledger file in a directory. A new format takes a new file, so an
115
+ * older client never reads a format it does not know.
116
+ *
117
+ * @param directory - Where the machine keeps its ledger.
118
+ * @returns The path of the ledger file.
119
+ */
120
+ function ledgerPath(directory) {
121
+ return path.join(directory, `ledger-v${LEDGER_FORMAT}.sqlite`);
122
+ }
123
+ /**
124
+ * Opens the ledger, and makes its tables when they do not exist. The
125
+ * directory of the file must exist.
126
+ *
127
+ * @param file - A path from `ledgerPath`, or `:memory:` for a private one.
128
+ * @param busyTimeout - How long to wait for the lock of another process, in
129
+ * milliseconds.
130
+ * @returns A handle that runs transactions on the file.
131
+ */
132
+ function openLedger(file, busyTimeout = BUSY_TIMEOUT_MS) {
133
+ const database = openDatabase(file, busyTimeout);
134
+ function query(sql) {
135
+ return database.prepare(sql);
136
+ }
137
+ const transaction = {
138
+ ...metaTable(query),
139
+ ...sessionTable(query),
140
+ ...leaseTable(query),
141
+ ...waiterTable(query),
142
+ ...costTable(query)
143
+ };
144
+ return {
145
+ close: () => {
146
+ database.close();
147
+ },
148
+ read: (work) => runIn(database, {
149
+ begin: "BEGIN",
150
+ work: () => work(transaction)
151
+ }),
152
+ transact: (work) => {
153
+ return runIn(database, {
154
+ begin: "BEGIN IMMEDIATE",
155
+ work: () => work(transaction)
156
+ });
157
+ }
158
+ };
159
+ }
160
+ /**
161
+ * Reads the sessions, leases and waiters of a ledger file through a read-only
162
+ * handle, so the read neither prunes nor writes.
163
+ *
164
+ * @param file - A path from `ledgerPath` that exists.
165
+ * @returns The rows of the ledger.
166
+ */
167
+ function readLedger(file) {
168
+ const database = new DatabaseSync(file, {
169
+ readOnly: true,
170
+ timeout: BUSY_TIMEOUT_MS
171
+ });
172
+ function query(sql) {
173
+ return database.prepare(sql);
174
+ }
175
+ try {
176
+ return {
177
+ leases: leaseTable(query).leases(),
178
+ sessions: sessionTable(query).sessions(),
179
+ waiters: waiterTable(query).waiters()
180
+ };
181
+ } finally {
182
+ database.close();
183
+ }
184
+ }
185
+ function runIn(database, { begin, work }) {
186
+ database.exec(begin);
187
+ try {
188
+ const result = work();
189
+ database.exec("COMMIT");
190
+ return result;
191
+ } catch (err) {
192
+ database.exec("ROLLBACK");
193
+ throw err;
194
+ }
195
+ }
196
+ function openDatabase(file, timeout) {
197
+ const database = new DatabaseSync(file, { timeout });
198
+ database.exec("PRAGMA journal_mode = WAL");
199
+ database.exec(SCHEMA);
200
+ return database;
201
+ }
202
+ function parseRows(schema, rows) {
203
+ const parsed = schema(rows.map((row) => ({ ...row })));
204
+ if (parsed instanceof type.errors) throw new Error(`machine budget ledger holds an invalid row: ${parsed.summary}`);
205
+ return parsed;
206
+ }
207
+ function metaTable(query) {
208
+ return {
209
+ lastSeenAt: () => {
210
+ const rows = query("SELECT value FROM meta WHERE key = ?").all(LAST_SEEN);
211
+ return parseRows(valueRows, rows)[0]?.value;
212
+ },
213
+ markSeen: (at) => {
214
+ query("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(LAST_SEEN, at);
215
+ }
216
+ };
217
+ }
218
+ function sessionTable(query) {
219
+ return {
220
+ refreshHeartbeats: (at) => {
221
+ query("UPDATE sessions SET heartbeat_at = ?").run(at);
222
+ },
223
+ removeSessions: (ids) => {
224
+ for (const id of ids) {
225
+ query("DELETE FROM leases WHERE session = ?").run(id);
226
+ query("DELETE FROM waiters WHERE session = ?").run(id);
227
+ query("DELETE FROM sessions WHERE id = ?").run(id);
228
+ }
229
+ },
230
+ sessions: () => {
231
+ const rows = query("SELECT id, heartbeat_at AS heartbeatAt, pid, started_at AS startedAt, worktree FROM sessions").all();
232
+ return parseRows(sessionRows, rows);
233
+ },
234
+ upsertSession: ({ id, heartbeatAt, pid, startedAt, worktree }) => {
235
+ query("INSERT INTO sessions (id, pid, started_at, heartbeat_at, worktree) VALUES (?, ?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET heartbeat_at = excluded.heartbeat_at").run(id, pid, startedAt, heartbeatAt, worktree);
236
+ }
237
+ };
238
+ }
239
+ function leaseTable(query) {
240
+ return {
241
+ addLease: ({ id, lane, memory, session, threads }) => {
242
+ query("INSERT OR IGNORE INTO leases (id, session, lane, memory, threads) VALUES (?, ?, ?, ?, ?)").run(id, session, lane, memory, threads);
243
+ },
244
+ leases: () => {
245
+ const rows = query("SELECT id, lane, memory, session, threads FROM leases").all();
246
+ return parseRows(leaseRows, rows);
247
+ },
248
+ removeLease: (id) => {
249
+ query("DELETE FROM leases WHERE id = ?").run(id);
250
+ }
251
+ };
252
+ }
253
+ function waiterTable(query) {
254
+ return {
255
+ removeWaiter: (id) => {
256
+ query("DELETE FROM waiters WHERE id = ?").run(id);
257
+ },
258
+ upsertWaiter: ({ id, isBig, memory, session, since, threads }) => {
259
+ query("INSERT OR IGNORE INTO waiters (id, session, is_big, since, memory, threads) VALUES (?, ?, ?, ?, ?, ?)").run(id, session, isBig ? 1 : 0, since, memory, threads);
260
+ },
261
+ waiters: () => {
262
+ const rows = query("SELECT id, is_big AS isBig, memory, session, since, threads FROM waiters").all();
263
+ return parseRows(waiterRows, rows);
264
+ }
265
+ };
266
+ }
267
+ function costTable(query) {
268
+ return {
269
+ addSample: ({ key, at, bytes }) => {
270
+ query("INSERT INTO costs (key, at, bytes) VALUES (?, ?, ?)").run(key, at, bytes);
271
+ query("DELETE FROM costs WHERE key = ? AND rowid NOT IN (SELECT rowid FROM costs WHERE key = ? ORDER BY at DESC, rowid DESC LIMIT ?)").run(key, key, 20);
272
+ },
273
+ costSamples: (key) => {
274
+ const rows = query("SELECT bytes AS value FROM costs WHERE key = ? ORDER BY at DESC, rowid DESC").all(key);
275
+ return parseRows(valueRows, rows).map((row) => row.value);
276
+ }
277
+ };
278
+ }
279
+ // src/memory-probe.ts
280
+ const PAGE_SIZE = /page size of (\d+) bytes/;
281
+ const AVAILABLE_PAGES = /* @__PURE__ */ new Set([
282
+ "Pages free",
283
+ "Pages inactive",
284
+ "Pages purgeable"
285
+ ]);
286
+ const PRESSURE_LEVELS = /* @__PURE__ */ new Map([
287
+ ["1", "normal"],
288
+ ["2", "warn"],
289
+ ["4", "critical"]
290
+ ]);
291
+ /**
292
+ * Reads the memory that can be given now. MacOS counts free, inactive and
293
+ * purgeable pages, and reports its pressure level; Windows and Linux report
294
+ * free memory, which on Linux is already the kernel's available estimate.
295
+ *
296
+ * @param sources - The operating system and how to read it.
297
+ * @returns The available memory and the pressure level.
298
+ */
299
+ function readMemory(sources) {
300
+ if (sources.platform !== "darwin") return {
301
+ availableMemory: sources.freeMemory(),
302
+ pressure: "normal"
303
+ };
304
+ const vmStat = sources.run("vm_stat", []);
305
+ const level = sources.run("sysctl", ["-n", "kern.memorystatus_vm_pressure_level"]);
306
+ return {
307
+ availableMemory: (vmStat === void 0 ? void 0 : parseVmStat(vmStat)) ?? sources.freeMemory(),
308
+ pressure: parsePressure(level)
309
+ };
310
+ }
311
+ function parsePressure(level) {
312
+ if (level === void 0) return "normal";
313
+ return PRESSURE_LEVELS.get(level.trim()) ?? "normal";
314
+ }
315
+ function parseVmStat(output) {
316
+ const pageSize = PAGE_SIZE.exec(output)?.[1];
317
+ if (pageSize === void 0) return;
318
+ let pages = 0;
319
+ for (const line of output.split("\n")) {
320
+ const separator = line.indexOf(":");
321
+ if (AVAILABLE_PAGES.has(line.slice(0, separator))) pages += Number.parseInt(line.slice(separator + 1), 10);
322
+ }
323
+ return pages * Number(pageSize);
324
+ }
325
+ // src/tree-linux.ts
326
+ const BYTES_PER_KB = 1024;
327
+ const PARENT_FIELD = 1;
328
+ const PEAK_RESIDENT = /^VmHWM:\s+(\d+) kB$/m;
329
+ const RESIDENT = /^VmRSS:\s+(\d+) kB$/m;
330
+ /**
331
+ * Reads a process tree from `/proc`. Linux keeps no peak commit, so the peak
332
+ * of a descendant is its peak resident set, and the peak of the tree is the
333
+ * highest sum of resident sets over the samples.
334
+ *
335
+ * @param root - The pid at the top of the tree.
336
+ * @param source - How to read `/proc`.
337
+ * @returns The probe, which keeps the peaks of descendants that have exited.
338
+ */
339
+ function linuxTreeProbe(root, source) {
340
+ const peaks = /* @__PURE__ */ new Map();
341
+ let treePeak;
342
+ return {
343
+ descendants: () => peaks,
344
+ sample: () => {
345
+ let resident = 0;
346
+ let isSeen = false;
347
+ for (const pid of [root, ...descendantsOf(source, root)]) {
348
+ const status = source.read(`/proc/${pid}/status`);
349
+ if (status === void 0) continue;
350
+ isSeen = true;
351
+ resident += bytes(status, RESIDENT);
352
+ if (pid !== root) peaks.set(pid, Math.max(peaks.get(pid) ?? 0, bytes(status, PEAK_RESIDENT)));
353
+ }
354
+ if (isSeen) treePeak = Math.max(treePeak ?? 0, resident);
355
+ },
356
+ tree: () => treePeak
357
+ };
358
+ }
359
+ function parentOf(source, pid) {
360
+ const stat = source.read(`/proc/${pid}/stat`);
361
+ if (stat === void 0) return;
362
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ", 2)[PARENT_FIELD]);
363
+ }
364
+ function descendantsOf(source, root) {
365
+ const children = /* @__PURE__ */ new Map();
366
+ for (const pid of source.pids()) {
367
+ const parent = parentOf(source, pid);
368
+ if (parent !== void 0) children.set(parent, [...children.get(parent) ?? [], pid]);
369
+ }
370
+ const found = [];
371
+ const pending = [root];
372
+ for (let pid = pending.pop(); pid !== void 0; pid = pending.pop()) {
373
+ const next = children.get(pid) ?? [];
374
+ found.push(...next);
375
+ pending.push(...next);
376
+ }
377
+ return found;
378
+ }
379
+ function bytes(status, field) {
380
+ return Number(field.exec(status)?.[1] ?? 0) * BYTES_PER_KB;
381
+ }
382
+ // src/tree-windows.ts
383
+ const QUERY_LIMITED_ACCESS = 4096;
384
+ const BASIC_PROCESS_ID_LIST = 3;
385
+ const EXTENDED_LIMIT_INFORMATION = 9;
386
+ const EXTENDED_LIMIT_SIZE = 144;
387
+ const PEAK_JOB_MEMORY_OFFSET = 136;
388
+ const LISTED_COUNT_OFFSET = 4;
389
+ const PROCESS_ID_LIST_HEADER = 8;
390
+ const PROCESS_ID_SIZE = 8;
391
+ const MEMORY_COUNTERS_SIZE = 72;
392
+ const PEAK_PAGEFILE_OFFSET = 64;
393
+ /**
394
+ * Puts the root in a new Job Object. The tree peak is the job's peak commit.
395
+ * A descendant's peak is its peak pagefile usage, read through a handle that
396
+ * opens when a sample first lists it, so the figure outlives the process.
397
+ *
398
+ * @param root - The pid at the top of the tree.
399
+ * @returns The probe, or undefined when koffi does not load or the root cannot
400
+ * join a job.
401
+ */
402
+ function windowsTreeProbe(root) {
403
+ let kernel32;
404
+ try {
405
+ kernel32 = loadKernel32();
406
+ } catch {
407
+ return;
408
+ }
409
+ const job = attach(kernel32, root);
410
+ if (job === null) return;
411
+ const state = {
412
+ handles: /* @__PURE__ */ new Map(),
413
+ job,
414
+ kernel32,
415
+ root
416
+ };
417
+ return {
418
+ close: () => {
419
+ closeJob(state);
420
+ },
421
+ descendants: () => descendantPeaks(state),
422
+ sample: () => {
423
+ openNewDescendants(state);
424
+ },
425
+ tree: () => jobPeak(state)
426
+ };
427
+ }
428
+ function loadKernel32() {
429
+ const library = createRequire(import.meta.url)("koffi").load("kernel32.dll");
430
+ return {
431
+ assign: library.func("bool AssignProcessToJobObject(void *job, void *process)"),
432
+ close: library.func("bool CloseHandle(void *handle)"),
433
+ createJob: library.func("void *CreateJobObjectW(void *attributes, void *name)"),
434
+ open: library.func("void *OpenProcess(uint32_t access, bool inherit, uint32_t pid)"),
435
+ queryJob: library.func("bool QueryInformationJobObject(void *job, int infoClass, _Out_ uint8_t *info, uint32_t size, void *returned)"),
436
+ readCounters: library.func("bool K32GetProcessMemoryInfo(void *process, _Out_ uint8_t *counters, uint32_t size)")
437
+ };
438
+ }
439
+ function attach(kernel32, root) {
440
+ const process = kernel32.open(257, false, root);
441
+ if (process === null) return null;
442
+ const job = kernel32.createJob(null, null);
443
+ const isAssigned = job !== null && kernel32.assign(job, process) === true;
444
+ kernel32.close(process);
445
+ if (!isAssigned && job !== null) kernel32.close(job);
446
+ return isAssigned ? job : null;
447
+ }
448
+ function listedProcesses({ job, kernel32 }) {
449
+ const list = Buffer.alloc(8200);
450
+ if (kernel32.queryJob(job, BASIC_PROCESS_ID_LIST, list, list.length, null) !== true) return [];
451
+ return Array.from({ length: list.readUInt32LE(LISTED_COUNT_OFFSET) }, (_, index) => {
452
+ return Number(list.readBigUInt64LE(PROCESS_ID_LIST_HEADER + index * PROCESS_ID_SIZE));
453
+ });
454
+ }
455
+ function openNewDescendants(state) {
456
+ for (const pid of listedProcesses(state)) {
457
+ if (pid === state.root || state.handles.has(pid)) continue;
458
+ const handle = state.kernel32.open(QUERY_LIMITED_ACCESS, false, pid);
459
+ if (handle !== null) state.handles.set(pid, handle);
460
+ }
461
+ }
462
+ function descendantPeaks({ handles, kernel32 }) {
463
+ const counters = Buffer.alloc(MEMORY_COUNTERS_SIZE);
464
+ const peaks = /* @__PURE__ */ new Map();
465
+ for (const [pid, handle] of handles) if (kernel32.readCounters(handle, counters, counters.length) === true) peaks.set(pid, Number(counters.readBigUInt64LE(PEAK_PAGEFILE_OFFSET)));
466
+ return peaks;
467
+ }
468
+ function jobPeak({ job, kernel32 }) {
469
+ const limits = Buffer.alloc(EXTENDED_LIMIT_SIZE);
470
+ if (kernel32.queryJob(job, EXTENDED_LIMIT_INFORMATION, limits, limits.length, null) !== true) return;
471
+ return Number(limits.readBigUInt64LE(PEAK_JOB_MEMORY_OFFSET));
472
+ }
473
+ function closeJob({ handles, job, kernel32 }) {
474
+ for (const handle of handles.values()) kernel32.close(handle);
475
+ handles.clear();
476
+ kernel32.close(job);
477
+ }
478
+ // src/adapters.ts
479
+ const COMMAND_TIMEOUT_MS = 5e3;
480
+ const LINUX_CLOCK_TICKS_PER_SECOND = 100;
481
+ const LINUX_START_TIME_FIELD = 19;
482
+ const BOOT_TIME = /^btime (\d+)$/m;
483
+ const PID_NAME = /^\d+$/;
484
+ /**
485
+ * Opens the ledger of this machine in the directory that `ledgerDirectory`
486
+ * names for this process, and makes the directory when it does not exist.
487
+ *
488
+ * @param busyTimeout - How long to wait for the lock of another process, in
489
+ * milliseconds.
490
+ * @returns The ledger that every run of this user on the machine opens.
491
+ */
492
+ function openSharedLedger(busyTimeout) {
493
+ const directory = ledgerDirectory(process.env);
494
+ mkdirSync(directory, { recursive: true });
495
+ return openLedger(ledgerPath(directory), busyTimeout);
496
+ }
497
+ /**
498
+ * Reads the ledger of this machine without writing to it, and without making
499
+ * its directory.
500
+ *
501
+ * @returns The path of the ledger file, and its rows when the file exists.
502
+ */
503
+ function readSharedLedger() {
504
+ const file = ledgerPath(ledgerDirectory(process.env));
505
+ return {
506
+ file,
507
+ snapshot: existsSync(file) ? readLedger(file) : void 0
508
+ };
509
+ }
510
+ function ledgerDirectory(environment) {
511
+ const configured = environment["MACHINE_BUDGET_DIR"];
512
+ if (configured !== void 0 && configured !== "") return configured;
513
+ return path.join(os.tmpdir(), `machine-budget-${os.userInfo().username}`);
514
+ }
515
+ function constrainedMemory() {
516
+ return process.constrainedMemory?.() ?? 0;
517
+ }
518
+ function freeMemory() {
519
+ return Math.min(os.freemem(), process.availableMemory());
520
+ }
521
+ function run(command, args) {
522
+ try {
523
+ return execFileSync(command, args, {
524
+ encoding: "utf8",
525
+ stdio: [
526
+ "ignore",
527
+ "pipe",
528
+ "ignore"
529
+ ],
530
+ timeout: COMMAND_TIMEOUT_MS,
531
+ windowsHide: true
532
+ });
533
+ } catch {
534
+ return;
535
+ }
536
+ }
537
+ function isAlive(pid) {
538
+ try {
539
+ process.kill(pid, 0);
540
+ return true;
541
+ } catch (err) {
542
+ return !(err instanceof Error) || !("code" in err) || err.code !== "ESRCH";
543
+ }
544
+ }
545
+ function linuxStartTime(pid) {
546
+ try {
547
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
548
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
549
+ const bootTime = BOOT_TIME.exec(readFileSync("/proc/stat", "utf8"))?.[1];
550
+ const ticks = fields[LINUX_START_TIME_FIELD];
551
+ if (bootTime === void 0 || ticks === void 0) return;
552
+ return (Number(bootTime) + Number(ticks) / LINUX_CLOCK_TICKS_PER_SECOND) * 1e3;
553
+ } catch {
554
+ return;
555
+ }
556
+ }
557
+ function parseTime(text) {
558
+ const time = text === void 0 ? NaN : Date.parse(text.trim());
559
+ return Number.isNaN(time) ? void 0 : time;
560
+ }
561
+ function windowsStartTime(pid) {
562
+ return parseTime(run("powershell.exe", [
563
+ "-NoProfile",
564
+ "-NonInteractive",
565
+ "-Command",
566
+ `(Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('o')`
567
+ ]));
568
+ }
569
+ const START_TIME_READERS = {
570
+ darwin: (pid) => parseTime(run("ps", [
571
+ "-o",
572
+ "lstart=",
573
+ "-p",
574
+ String(pid)
575
+ ])),
576
+ linux: linuxStartTime,
577
+ win32: windowsStartTime
578
+ };
579
+ function startTime(pid) {
580
+ return START_TIME_READERS[process.platform]?.(pid);
581
+ }
582
+ /** The real machine and process. */
583
+ const nodePlatform = {
584
+ every: (milliseconds, work) => {
585
+ const timer = setInterval(work, milliseconds);
586
+ timer.unref();
587
+ return () => {
588
+ clearInterval(timer);
589
+ };
590
+ },
591
+ gitCommonDirectory: (workspaceRoot) => {
592
+ const output = run("git", [
593
+ "-C",
594
+ workspaceRoot,
595
+ "rev-parse",
596
+ "--path-format=absolute",
597
+ "--git-common-dir"
598
+ ]);
599
+ return output === void 0 ? workspaceRoot : output.trim();
600
+ },
601
+ now: Date.now,
602
+ pid: process.pid,
603
+ probe: {
604
+ isAlive,
605
+ startTime
606
+ },
607
+ readMemory: () => readMemory({
608
+ freeMemory,
609
+ platform: process.platform,
610
+ run
611
+ }),
612
+ sleepAsync: async (milliseconds) => {
613
+ await setTimeout(milliseconds);
614
+ },
615
+ startedAt: Date.now() - process.uptime() * 1e3,
616
+ threads: os.availableParallelism(),
617
+ totalMemory: Math.min(os.totalmem(), constrainedMemory() || Infinity)
618
+ };
619
+ /**
620
+ * Chooses how this platform reads a process tree: a Job Object on Windows,
621
+ * `/proc` on Linux, and nothing elsewhere.
622
+ *
623
+ * @param pid - The pid at the top of the tree.
624
+ * @returns The probe of this platform, or undefined where it cannot read one.
625
+ */
626
+ function treeProbe(pid) {
627
+ if (process.platform === "win32") return windowsTreeProbe(pid);
628
+ return process.platform === "linux" ? linuxTreeProbe(pid, {
629
+ pids: procPids,
630
+ read: readProc
631
+ }) : void 0;
632
+ }
633
+ function readProc(file) {
634
+ try {
635
+ return readFileSync(file, "utf8");
636
+ } catch {
637
+ return;
638
+ }
639
+ }
640
+ function procPids() {
641
+ return readdirSync("/proc").filter((name) => PID_NAME.test(name)).map(Number);
642
+ }
643
+ // src/run-text.ts
644
+ const BYTES_PER_GB = 2 ** 30;
645
+ /**
646
+ * Formats a memory size in gigabytes with one decimal.
647
+ *
648
+ * @param bytes - A memory size.
649
+ * @returns The text, such as `2.4 GB`.
650
+ */
651
+ function formatGb(bytes) {
652
+ return `${(bytes / BYTES_PER_GB).toFixed(1)} GB`;
653
+ }
654
+ /**
655
+ * Names a run by its pid and worktree.
656
+ *
657
+ * @param session - The session of the run, or undefined when it left.
658
+ * @returns The text, such as `pid 7 in /wt`.
659
+ */
660
+ function describeRun(session) {
661
+ return session === void 0 ? "a run that left" : `pid ${session.pid} in ${session.worktree}`;
662
+ }
663
+ export { readSharedLedger as a, costKey as c, openSharedLedger as i, learnedCost as l, formatGb as n, treeProbe as o, nodePlatform as r, isLedgerLocked as s, describeRun as t };
@@ -0,0 +1,53 @@
1
+ import { n as Waiter, t as HeldLease } from "./admission-DcnnK4uq.mjs";
2
+ /** A run that holds a session in the ledger. */
3
+ interface SessionRecord {
4
+ /** The id of the session. */
5
+ id: string;
6
+ /** When the session last stamped its heartbeat, in epoch milliseconds. */
7
+ heartbeatAt: number;
8
+ /** The pid of the process that owns the session. */
9
+ pid: number;
10
+ /** When that process started, in epoch milliseconds. */
11
+ startedAt: number;
12
+ }
13
+ /** A lease as the ledger stores it. */
14
+ interface StoredLease extends HeldLease {
15
+ /** The id of the lease. */
16
+ id: string;
17
+ }
18
+ /** A session as the ledger stores it. */
19
+ interface StoredSession extends SessionRecord {
20
+ /** The workspace root that the run opened the budget with. */
21
+ worktree: string;
22
+ }
23
+ /** A waiting request as the ledger stores it. */
24
+ interface StoredWaiter extends Waiter {
25
+ /** The memory of the fewest workers that the request needs, in bytes. */
26
+ memory: number;
27
+ /** The fewest workers that the request needs. */
28
+ threads: number;
29
+ }
30
+ /** Every session, lease and waiter of the ledger at one moment. */
31
+ interface LedgerSnapshot {
32
+ /** Every lease. */
33
+ leases: Array<StoredLease>;
34
+ /** Every session. */
35
+ sessions: Array<StoredSession>;
36
+ /** Every waiter. */
37
+ waiters: Array<StoredWaiter>;
38
+ }
39
+ /** What the status report reads. */
40
+ interface StatusInput {
41
+ /** The path of the ledger file. */
42
+ file: string;
43
+ /** The time of the report, in epoch milliseconds. */
44
+ now: number;
45
+ /** The rows of the ledger, or undefined when the file does not exist. */
46
+ snapshot: LedgerSnapshot | undefined;
47
+ }
48
+ /**
49
+ * Prints the machine budget ledger of this machine and writes nothing.
50
+ *
51
+ * @param read - Reads the ledger path and its rows.
52
+ */
53
+ export declare function main(read?: () => Pick<StatusInput, "file" | "snapshot">): void;