@agentguard-run/burn 0.7.2 → 0.7.3

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.3 (2026-12-04)
4
+
5
+ - The status line shows this machine: `N% memory free` always (macOS and Linux), `swap N GB` when swap is heavy (half of physical memory or more, or 4 GB beside a low disk), and `disk N GB free` first when free disk is low. Memory turns yellow at 15% available (or 20% while the macOS kernel reports a warning) and red at 10% or a kernel critical level. These parts are never dropped before the optional fields on a narrow terminal.
6
+ - Available memory is the operating system's own figure (macOS `kern.memorystatus_level`, Linux `MemAvailable`), never `os.freemem()`, read at most once every five seconds across all open sessions through a small private cache file. A figure that cannot be read shows as `memory ?` or not at all, never as fine. Limits: the macOS figure can sit near 20% while the machine swaps hard, which is why swap and disk sit beside it; the Linux figure is the host's and ignores a container's memory ceiling; Windows shows no memory part.
7
+ - The package exports `readStatusMachine(home)`, `swapIsHeavy`, `readMemory` and `memoryLevel`, so the AgentGuard plugin can draw the same parts where the installed Burn has them (`typeof readStatusMachine === 'function'`).
8
+ - Display only: nothing here denies a launch, signals a process or deletes a file.
9
+ - The SessionStart advisory no longer reads "0 idle agent sessions holding 0.0 GB" when only an idle browser or an orphan workspace is past its threshold; it names what was found.
10
+ - `ps` no longer says swap is released only on reboot: swap shrinks when the processes holding memory stop.
11
+
3
12
  ## 0.7.2 (2026-11-13)
4
13
 
5
14
  - Add `models [--days N] [--limit N] [--max-mb N] [json] [--lang en|es|pt]`: the top-level Claude Code and Codex sessions that started in the last N days (default 30, up to 365), each under its dominant model, models ordered by first session so the report reads as before, then after a switch. Per model: sessions, first and last session date, and per-session medians and totals of input tokens, output tokens, cache share, sub-agents launched, sub-agents that ended without finishing, and the API list-price equivalent. Every session's figures are the ones `compare` and `why` print for it, child transcripts included. Unpriced stays unpriced. How sub-agents ended is counted only where a sub-agent transcript records it; elsewhere it is unknown, left out of that row and counted, never 0. Measurement only: it never says which model did better.
package/dist/src/cli.js CHANGED
@@ -94,6 +94,7 @@ const disk_1 = require("./idle/disk");
94
94
  const telemetry_cli_1 = require("./telemetry-cli");
95
95
  const status_fields_1 = require("./insights/status-fields");
96
96
  const status_data_1 = require("./insights/status-data");
97
+ const status_machine_1 = require("./insights/status-machine");
97
98
  const display_mode_1 = require("./display-mode");
98
99
  const i18n_2 = require("./insights/i18n");
99
100
  const simple_data_1 = require("./insights/simple-data");
@@ -664,7 +665,7 @@ async function main(argv) {
664
665
  const burn = (0, status_data_1.readStatusBurn)(HOME, session);
665
666
  if (!(0, node_fs_1.existsSync)((0, node_path_1.join)(HOME, 'sessions')) && metrics.totalTokens !== undefined)
666
667
  burn.tokens.used = metrics.totalTokens;
667
- const formatted = (0, status_fields_1.formatStatusFields)({ ...metrics, burn, fields, windows: observation.snapshot?.windows,
668
+ const formatted = (0, status_fields_1.formatStatusFields)({ ...metrics, burn, fields, windows: observation.snapshot?.windows, machine: await (0, status_machine_1.readStatusMachine)(HOME),
668
669
  width,
669
670
  lang: (0, i18n_1.detectWhyLang)({ flag: lang, env: process.env, intlLocale: intlLocale() }) });
670
671
  const line = process.env.NO_COLOR !== undefined || noColor || formatted.clipped ? formatted.text : formatted.parts.map(part => {
@@ -25,6 +25,13 @@ function warningForAudit(report, policy, now = Date.now()) {
25
25
  if (!warnings.length)
26
26
  return null;
27
27
  const sessions = warnings.filter(row => row.kind === 'session');
28
+ // An idle browser or an orphan workspace alone still points to ps, in its own words:
29
+ // "0 idle agent sessions holding 0.0 GB" reads as a broken count.
30
+ if (!sessions.length) {
31
+ const browsers = warnings.filter(row => row.kind === 'browser').length, workspaces = warnings.filter(row => row.kind === 'workspace').length;
32
+ const parts = [browsers ? `${browsers} idle agent browser${browsers === 1 ? '' : 's'}` : '', workspaces ? `${workspaces} orphan workspace${workspaces === 1 ? '' : 's'}` : ''].filter(Boolean);
33
+ return parts.length ? `${parts.join(' and ')}, run agentguard-burn ps` : null;
34
+ }
28
35
  const gb = sessions.reduce((sum, row) => sum + row.rssBytes, 0) / 1_000_000_000;
29
36
  return `${sessions.length} idle agent sessions holding ${gb.toFixed(1)} GB, run agentguard-burn ps`;
30
37
  }
@@ -0,0 +1,38 @@
1
+ import type { PressureLevel } from './disk';
2
+ import { type CommandRunner } from './platform';
3
+ /** At or under this share available, memory is short whatever the kernel says. */
4
+ export declare const MEMORY_WARN_PERCENT = 15;
5
+ /** The kernel's own warning counts once available memory is also at or under this. */
6
+ export declare const MEMORY_WARN_PRESSURE_PERCENT = 20;
7
+ export declare const MEMORY_CRIT_PERCENT = 10;
8
+ export type MemorySource = 'darwin-sysctl' | 'linux-meminfo' | 'none';
9
+ export interface MemoryReading {
10
+ /** Whole percent of memory the system reports as available, 0 to 100. Null when unknown. */
11
+ availablePercent: number | null;
12
+ /** The macOS kernel's pressure level (1, 2 or 4). Null elsewhere or when unread. */
13
+ kernelPressure: 1 | 2 | 4 | null;
14
+ level: PressureLevel;
15
+ /** Swap in use and allocated, when the same read reported them. Null when unknown. */
16
+ swapUsedBytes: number | null;
17
+ swapTotalBytes: number | null;
18
+ source: MemorySource;
19
+ }
20
+ export declare const UNKNOWN_MEMORY: MemoryReading;
21
+ export declare function memoryLevel(availablePercent: number | null, kernelPressure?: 1 | 2 | 4 | null): PressureLevel;
22
+ /** Reads `sysctl kern.memorystatus_level kern.memorystatus_vm_pressure_level vm.swapusage` output, one "name: value" per line. */
23
+ export declare function parseDarwinMemory(text: string): MemoryReading;
24
+ /** Reads /proc/meminfo. A kernel without MemAvailable is unknown: MemFree alone would under-report. */
25
+ export declare function parseLinuxMemory(text: string): MemoryReading;
26
+ export type MemoryProbe = () => Promise<MemoryReading>;
27
+ export declare const MEMORY_PROBE_TIMEOUT_MS = 200;
28
+ /** One bounded read. Any failure is unknown. */
29
+ export declare function systemMemoryProbe(platform?: string, runner?: CommandRunner, meminfo?: string): MemoryProbe;
30
+ export declare const MEMORY_CHECK_TTL_MS = 5000;
31
+ export declare const memoryCheckPath: (home: string) => string;
32
+ /**
33
+ * The reading every status line shares: one system read at most every five
34
+ * seconds across all open sessions, kept in a small file in the Burn home.
35
+ * A cache that cannot be written (a full disk) still returns the fresh
36
+ * reading. Never throws.
37
+ */
38
+ export declare function readMemory(home: string, now: number, probe?: MemoryProbe): Promise<MemoryReading>;
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.memoryCheckPath = exports.MEMORY_CHECK_TTL_MS = exports.MEMORY_PROBE_TIMEOUT_MS = exports.UNKNOWN_MEMORY = exports.MEMORY_CRIT_PERCENT = exports.MEMORY_WARN_PRESSURE_PERCENT = exports.MEMORY_WARN_PERCENT = void 0;
4
+ exports.memoryLevel = memoryLevel;
5
+ exports.parseDarwinMemory = parseDarwinMemory;
6
+ exports.parseLinuxMemory = parseLinuxMemory;
7
+ exports.systemMemoryProbe = systemMemoryProbe;
8
+ exports.readMemory = readMemory;
9
+ /**
10
+ * Available memory on this machine.
11
+ *
12
+ * Many agent sessions and sub-agents on one laptop use memory until the
13
+ * system swaps, and swap then fills the disk. This reads what the operating
14
+ * system itself calls available, never Node's os.freemem(): on macOS that
15
+ * counts only free pages and reads near zero on a healthy machine.
16
+ *
17
+ * macOS: kern.memorystatus_level (percent available, the figure
18
+ * `memory_pressure` prints) and kern.memorystatus_vm_pressure_level
19
+ * (1 normal, 2 warn, 4 critical).
20
+ * Linux: MemAvailable over MemTotal from /proc/meminfo.
21
+ *
22
+ * Limits, stated: the macOS figure is an undocumented kernel value and can
23
+ * sit near 20% while the machine swaps hard; the Linux figure is the host's
24
+ * and ignores a container's own memory ceiling. A source that cannot be read
25
+ * is reported as unknown, never as zero and never as fine.
26
+ *
27
+ * Reported only. Nothing here denies, signals or deletes.
28
+ */
29
+ const node_crypto_1 = require("node:crypto");
30
+ const node_fs_1 = require("node:fs");
31
+ const node_fs_2 = require("node:fs");
32
+ const node_path_1 = require("node:path");
33
+ const platform_1 = require("./platform");
34
+ /** At or under this share available, memory is short whatever the kernel says. */
35
+ exports.MEMORY_WARN_PERCENT = 15;
36
+ /** The kernel's own warning counts once available memory is also at or under this. */
37
+ exports.MEMORY_WARN_PRESSURE_PERCENT = 20;
38
+ exports.MEMORY_CRIT_PERCENT = 10;
39
+ exports.UNKNOWN_MEMORY = { availablePercent: null, kernelPressure: null, level: 'unknown', swapUsedBytes: null, swapTotalBytes: null, source: 'none' };
40
+ function memoryLevel(availablePercent, kernelPressure = null) {
41
+ if (availablePercent === null)
42
+ return 'unknown';
43
+ if (kernelPressure === 4 || availablePercent <= exports.MEMORY_CRIT_PERCENT)
44
+ return 'crit';
45
+ if (availablePercent <= exports.MEMORY_WARN_PERCENT)
46
+ return 'warn';
47
+ return kernelPressure === 2 && availablePercent <= exports.MEMORY_WARN_PRESSURE_PERCENT ? 'warn' : 'ok';
48
+ }
49
+ /** A garbled swap figure is unknown swap. It never costs the memory percent read beside it. */
50
+ function finiteSwap(swap) {
51
+ return swap && Number.isFinite(swap.usedBytes) && Number.isFinite(swap.totalBytes) && swap.usedBytes >= 0 && swap.totalBytes >= 0 ? swap : null;
52
+ }
53
+ const percent = (value) => Number.isFinite(value) && value >= 0 && value <= 100 ? Math.round(value) : null;
54
+ /** Reads `sysctl kern.memorystatus_level kern.memorystatus_vm_pressure_level vm.swapusage` output, one "name: value" per line. */
55
+ function parseDarwinMemory(text) {
56
+ const level = /^kern\.memorystatus_level:\s*(\d{1,3})\s*$/m.exec(text);
57
+ const available = level ? percent(Number(level[1])) : null;
58
+ if (available === null)
59
+ return exports.UNKNOWN_MEMORY;
60
+ const pressure = /^kern\.memorystatus_vm_pressure_level:\s*(\d)\s*$/m.exec(text);
61
+ const kernelPressure = pressure && ['1', '2', '4'].includes(pressure[1]) ? Number(pressure[1]) : null;
62
+ const swap = finiteSwap((0, platform_1.parseSwapUsage)(text, 'darwin'));
63
+ return { availablePercent: available, kernelPressure, level: memoryLevel(available, kernelPressure),
64
+ swapUsedBytes: swap?.usedBytes ?? null, swapTotalBytes: swap?.totalBytes ?? null, source: 'darwin-sysctl' };
65
+ }
66
+ /** Reads /proc/meminfo. A kernel without MemAvailable is unknown: MemFree alone would under-report. */
67
+ function parseLinuxMemory(text) {
68
+ const total = /^MemTotal:\s+(\d+)\s+kB$/m.exec(text), free = /^MemAvailable:\s+(\d+)\s+kB$/m.exec(text);
69
+ if (!total || !free || Number(total[1]) <= 0)
70
+ return exports.UNKNOWN_MEMORY;
71
+ const available = percent(100 * Number(free[1]) / Number(total[1]));
72
+ if (available === null)
73
+ return exports.UNKNOWN_MEMORY;
74
+ const swap = finiteSwap((0, platform_1.parseSwapUsage)(text, 'linux'));
75
+ return { availablePercent: available, kernelPressure: null, level: memoryLevel(available),
76
+ swapUsedBytes: swap?.usedBytes ?? null, swapTotalBytes: swap?.totalBytes ?? null, source: 'linux-meminfo' };
77
+ }
78
+ exports.MEMORY_PROBE_TIMEOUT_MS = 200;
79
+ /** One bounded read. Any failure is unknown. */
80
+ function systemMemoryProbe(platform = process.platform, runner = platform_1.runLocal, meminfo = '/proc/meminfo') {
81
+ return async () => {
82
+ try {
83
+ if (platform === 'darwin') {
84
+ const result = await runner('/usr/sbin/sysctl', ['kern.memorystatus_level', 'kern.memorystatus_vm_pressure_level', 'vm.swapusage'], { timeoutMs: exports.MEMORY_PROBE_TIMEOUT_MS });
85
+ // A missing key makes sysctl exit non-zero but still print the others.
86
+ return parseDarwinMemory(result.stdout || '');
87
+ }
88
+ if (platform === 'linux')
89
+ return parseLinuxMemory(await node_fs_2.promises.readFile(meminfo, 'utf8'));
90
+ return exports.UNKNOWN_MEMORY;
91
+ }
92
+ catch {
93
+ return exports.UNKNOWN_MEMORY;
94
+ }
95
+ };
96
+ }
97
+ exports.MEMORY_CHECK_TTL_MS = 5_000;
98
+ const MEMORY_CHECK_MAX_BYTES = 4 * 1024;
99
+ const memoryCheckPath = (home) => (0, node_path_1.join)(home, 'memory-check.json');
100
+ exports.memoryCheckPath = memoryCheckPath;
101
+ /**
102
+ * The one way a reading enters from outside (a probe's answer, the cache file):
103
+ * each field is read once, checked, and copied into a fresh object holding
104
+ * exactly these six fields. The level is never taken from the source: it is
105
+ * judged from the numbers, so neither a tampered file nor a careless probe can
106
+ * claim "ok". Anything that does not fit is unknown.
107
+ */
108
+ function sound(value) {
109
+ try {
110
+ if (!value || typeof value !== 'object' || Array.isArray(value))
111
+ return exports.UNKNOWN_MEMORY;
112
+ const raw = value;
113
+ const available = raw.availablePercent, pressure = raw.kernelPressure, used = raw.swapUsedBytes, total = raw.swapTotalBytes, source = raw.source;
114
+ if (typeof available !== 'number' || percent(available) !== available)
115
+ return exports.UNKNOWN_MEMORY;
116
+ if (source !== 'darwin-sysctl' && source !== 'linux-meminfo')
117
+ return exports.UNKNOWN_MEMORY;
118
+ if (pressure !== null && pressure !== 1 && pressure !== 2 && pressure !== 4)
119
+ return exports.UNKNOWN_MEMORY;
120
+ const bytes = (n) => n === null || (typeof n === 'number' && Number.isFinite(n) && n >= 0);
121
+ if (!bytes(used) || !bytes(total))
122
+ return exports.UNKNOWN_MEMORY;
123
+ return { availablePercent: available, kernelPressure: pressure, level: memoryLevel(available, pressure), swapUsedBytes: used, swapTotalBytes: total, source };
124
+ }
125
+ catch {
126
+ return exports.UNKNOWN_MEMORY;
127
+ }
128
+ }
129
+ /**
130
+ * One open, never following a link and never waiting (a pipe at this path
131
+ * must not hang the status line), then every check on that same open file:
132
+ * a file swapped in between a check and a read cannot be the one that is read.
133
+ * Where the system has no no-follow open (Windows), a link is refused by a
134
+ * check before the open instead.
135
+ */
136
+ function readMemoryCheck(home) {
137
+ let fd = null;
138
+ try {
139
+ const file = (0, exports.memoryCheckPath)(home), noFollow = node_fs_1.constants.O_NOFOLLOW, noWait = node_fs_1.constants.O_NONBLOCK;
140
+ if (typeof noFollow !== 'number' || typeof noWait !== 'number') {
141
+ const before = (0, node_fs_1.lstatSync)(file);
142
+ if (!before.isFile() || before.isSymbolicLink())
143
+ return null;
144
+ }
145
+ fd = (0, node_fs_1.openSync)(file, node_fs_1.constants.O_RDONLY | (typeof noFollow === 'number' ? noFollow : 0) | (typeof noWait === 'number' ? noWait : 0));
146
+ const stat = (0, node_fs_1.fstatSync)(fd);
147
+ if (!stat.isFile() || stat.size > MEMORY_CHECK_MAX_BYTES)
148
+ return null;
149
+ const buffer = Buffer.alloc(MEMORY_CHECK_MAX_BYTES + 1), length = (0, node_fs_1.readSync)(fd, buffer, 0, buffer.length, 0);
150
+ if (length > MEMORY_CHECK_MAX_BYTES)
151
+ return null;
152
+ const value = JSON.parse(buffer.toString('utf8', 0, length));
153
+ if (!value || value.version !== 1 || typeof value.checkedAt !== 'number' || !Number.isFinite(value.checkedAt))
154
+ return null;
155
+ const reading = sound(value.reading);
156
+ // An honest "could not read" is stored with source none and is kept for its
157
+ // five seconds. Anything else that does not fit is a corrupt file: read afresh.
158
+ if (reading.availablePercent === null && value.reading?.source !== 'none')
159
+ return null;
160
+ return { version: 1, checkedAt: value.checkedAt, reading };
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ finally {
166
+ if (fd !== null)
167
+ try {
168
+ (0, node_fs_1.closeSync)(fd);
169
+ }
170
+ catch { }
171
+ }
172
+ }
173
+ function writeMemoryCheck(home, check) {
174
+ (0, node_fs_1.mkdirSync)(home, { recursive: true, mode: 0o700 });
175
+ const file = (0, exports.memoryCheckPath)(home), temporary = `${file}.${process.pid}.${(0, node_crypto_1.randomUUID)()}`;
176
+ try {
177
+ (0, node_fs_1.writeFileSync)(temporary, JSON.stringify(check) + '\n', { mode: 0o600, flag: 'wx' });
178
+ (0, node_fs_1.renameSync)(temporary, file);
179
+ }
180
+ finally {
181
+ try {
182
+ (0, node_fs_1.unlinkSync)(temporary);
183
+ }
184
+ catch { }
185
+ }
186
+ }
187
+ /**
188
+ * The reading every status line shares: one system read at most every five
189
+ * seconds across all open sessions, kept in a small file in the Burn home.
190
+ * A cache that cannot be written (a full disk) still returns the fresh
191
+ * reading. Never throws.
192
+ */
193
+ async function readMemory(home, now, probe = systemMemoryProbe()) {
194
+ try {
195
+ const cached = readMemoryCheck(home);
196
+ if (cached && now >= cached.checkedAt && now - cached.checkedAt < exports.MEMORY_CHECK_TTL_MS)
197
+ return cached.reading;
198
+ let reading;
199
+ try {
200
+ reading = sound(await probe());
201
+ }
202
+ catch {
203
+ reading = exports.UNKNOWN_MEMORY;
204
+ }
205
+ let written = false;
206
+ try {
207
+ writeMemoryCheck(home, { version: 1, checkedAt: now, reading });
208
+ written = true;
209
+ }
210
+ catch { /* best effort */ }
211
+ // A cache dated ahead of now that could not be replaced (a full disk) must not
212
+ // wait there to be believed once the clock reaches it. Removing needs no space.
213
+ // Limit, stated: in a home folder that cannot be changed at all, it stays.
214
+ if (!written && cached && cached.checkedAt > now) {
215
+ try {
216
+ (0, node_fs_1.unlinkSync)((0, exports.memoryCheckPath)(home));
217
+ }
218
+ catch { }
219
+ }
220
+ return reading;
221
+ }
222
+ catch {
223
+ return exports.UNKNOWN_MEMORY;
224
+ }
225
+ }
@@ -119,7 +119,7 @@ function renderAudit(report, options = {}) {
119
119
  line(`Idle agent held memory: ${memory(report.totals.idleAgentMemoryBytes)}`);
120
120
  line(`Orphan workspace disk: ${memory(report.totals.orphanWorkspaceBytes)}`);
121
121
  line(`Swap in use: ${memory(report.swapUsedBytes)}`);
122
- wrap('Swap is only released by the operating system on reboot. Burn does not touch it.');
122
+ wrap('Swap shrinks when the processes holding memory stop. Burn does not touch it.');
123
123
  wrap('RSS is resident memory, not a bill. Shared pages can be counted in more than one process.');
124
124
  wrap('Idle methods: terminal device access time; transcript file writes; profile file writes; unknown.');
125
125
  for (const skipped of report.skipped)
@@ -32,6 +32,8 @@ export { readLaunchTree, readLaunchTreeWithReceipts, buildLaunchTree, renderLaun
32
32
  export { sessionTally, tallyEntries, readLedgerTallies, readLedgerDailyTallies, renderSessionTally, pluginLedgerDirectories, sessionLaunchReceipts, type SessionTally, type TallyCounts } from './insights/tally';
33
33
  export { formatStatusFields, parseStatusFields, statusPace, statusColor, type StatusInput, type StatusMetrics } from './insights/status-fields';
34
34
  export { readStatusBurn, readStatusMetrics } from './insights/status-data';
35
+ export { readStatusMachine, swapIsHeavy, type MachineSources } from './insights/status-machine';
36
+ export { readMemory, memoryLevel, type MemoryReading } from './idle/memory';
35
37
  export { collectWeek, saveWeek, weekFigures, weekStartOf, lastCompletedWeekStart, isMonday, WEEK_SCHEMA, SMALLER_MODEL, type WeekFigures, type WeekReport, type WeekAmount, type WeekCause, type WeekTopCause, type BurnWeekFile, type CollectWeekOptions, type SaveWeekResult } from './insights/week';
36
38
  export { renderWeek } from './insights/week-render';
37
39
  export { modelsReport, renderModels, modelGroups, subagentsUnfinished, sessionBytes, MODELS_DEFAULT_DAYS, MODELS_MAX_DAYS, MODELS_DEFAULT_LIMIT, MODELS_MAX_LIMIT, MODELS_DEFAULT_MAX_SESSION_BYTES, MODELS_MAX_SESSION_MEGABYTES, type ModelsReport, type ModelsGroup, type ModelsSession, type ModelsSessionInput, type ModelsSkipped, type ModelsSkippedSession, type ModelsOptions } from './insights/models';
package/dist/src/index.js CHANGED
@@ -16,7 +16,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.agentOverrideAttempt = exports.asksPerson = exports.settingsSnippet = exports.loadPolicy = exports.refreshSession = exports.handlePreToolUse = exports.calibrate = exports.OVERRIDE_COMMAND = exports.stopSummary = exports.sessionSoFar = exports.primarySummary = exports.overriddenLine = exports.continueLines = exports.askReason = exports.renderStop = exports.renderReplay = exports.discoverTranscripts = exports.replayEvents = exports.replaySession = exports.replayAll = exports.RESERVATION_TTL_MS = exports.Transaction = exports.ReservationStore = exports.cacheReadRatio = exports.medianCompletedMinute = exports.windowSum = exports.newSessionState = exports.applyCorrection = exports.applyEvent = exports.checkPolicyFile = exports.sessionTip = exports.MIN_FINISHED_SUBAGENTS = exports.decisionCostLine = exports.subagentCostLine = exports.finishedSubagents = exports.cloneReaderCursor = exports.restoreReaderCursor = exports.saveReaderCursor = exports.readSessionIncremental = exports.normaliseLine = exports.newCursor = exports.readAll = exports.readIncremental = exports.evaluateLocalCompute = exports.fmt = exports.evaluate = exports.CALL_RESERVATION_TTL_MS = exports.DEFAULT_LOCAL_COMPUTE = exports.DEFAULT_THRESHOLDS = exports.DEFAULT_POLICY = void 0;
18
18
  exports.parseStatusFields = exports.formatStatusFields = exports.sessionLaunchReceipts = exports.pluginLedgerDirectories = exports.renderSessionTally = exports.readLedgerDailyTallies = exports.readLedgerTallies = exports.tallyEntries = exports.sessionTally = exports.renderLaunchTree = exports.buildLaunchTree = exports.readLaunchTreeWithReceipts = exports.readLaunchTree = exports.inflateHookSession = exports.findingSignature = exports.renderHostHealth = exports.readHookSessions = exports.configPath = exports.health = exports.install = exports.OVERRIDE_WINDOW_MS = exports.clearOverride = exports.consumeOverride = exports.readOverride = exports.writeOverride = exports.runConformance = exports.renderMachineStatus = exports.UsageObserver = exports.profileFor = exports.startProxy = exports.LAUNCH_TOOLS = exports.isLaunchTool = exports.CODEX_FORBIDDEN_FIELDS = exports.readCodexTranscriptUsage = exports.parseCodexTranscript = exports.codexHooksSnippet = exports.handleCodexHook = exports.cursorHooksSnippet = exports.handleCursorHook = exports.BurnStopError = exports.createRawApiGuard = exports.sha256 = exports.canonical = exports.readSpawnAdmission = exports.receiptDigest = exports.verifyReceipt = exports.ReceiptSigner = exports.mergeCapabilities = exports.Gateway = exports.AGENT_OVERRIDE_REASON = void 0;
19
- exports.MODELS_MAX_SESSION_MEGABYTES = exports.MODELS_DEFAULT_MAX_SESSION_BYTES = exports.MODELS_MAX_LIMIT = exports.MODELS_DEFAULT_LIMIT = exports.MODELS_MAX_DAYS = exports.MODELS_DEFAULT_DAYS = exports.sessionBytes = exports.subagentsUnfinished = exports.modelGroups = exports.renderModels = exports.modelsReport = exports.renderWeek = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = exports.isMonday = exports.lastCompletedWeekStart = exports.weekStartOf = exports.weekFigures = exports.saveWeek = exports.collectWeek = exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
19
+ exports.MODELS_MAX_SESSION_MEGABYTES = exports.MODELS_DEFAULT_MAX_SESSION_BYTES = exports.MODELS_MAX_LIMIT = exports.MODELS_DEFAULT_LIMIT = exports.MODELS_MAX_DAYS = exports.MODELS_DEFAULT_DAYS = exports.sessionBytes = exports.subagentsUnfinished = exports.modelGroups = exports.renderModels = exports.modelsReport = exports.renderWeek = exports.SMALLER_MODEL = exports.WEEK_SCHEMA = exports.isMonday = exports.lastCompletedWeekStart = exports.weekStartOf = exports.weekFigures = exports.saveWeek = exports.collectWeek = exports.memoryLevel = exports.readMemory = exports.swapIsHeavy = exports.readStatusMachine = exports.readStatusMetrics = exports.readStatusBurn = exports.statusColor = exports.statusPace = void 0;
20
20
  __exportStar(require("./types"), exports);
21
21
  var defaults_1 = require("./defaults");
22
22
  Object.defineProperty(exports, "DEFAULT_POLICY", { enumerable: true, get: function () { return defaults_1.DEFAULT_POLICY; } });
@@ -159,6 +159,12 @@ Object.defineProperty(exports, "statusColor", { enumerable: true, get: function
159
159
  var status_data_1 = require("./insights/status-data");
160
160
  Object.defineProperty(exports, "readStatusBurn", { enumerable: true, get: function () { return status_data_1.readStatusBurn; } });
161
161
  Object.defineProperty(exports, "readStatusMetrics", { enumerable: true, get: function () { return status_data_1.readStatusMetrics; } });
162
+ var status_machine_1 = require("./insights/status-machine");
163
+ Object.defineProperty(exports, "readStatusMachine", { enumerable: true, get: function () { return status_machine_1.readStatusMachine; } });
164
+ Object.defineProperty(exports, "swapIsHeavy", { enumerable: true, get: function () { return status_machine_1.swapIsHeavy; } });
165
+ var memory_1 = require("./idle/memory");
166
+ Object.defineProperty(exports, "readMemory", { enumerable: true, get: function () { return memory_1.readMemory; } });
167
+ Object.defineProperty(exports, "memoryLevel", { enumerable: true, get: function () { return memory_1.memoryLevel; } });
162
168
  var week_1 = require("./insights/week");
163
169
  Object.defineProperty(exports, "collectWeek", { enumerable: true, get: function () { return week_1.collectWeek; } });
164
170
  Object.defineProperty(exports, "saveWeek", { enumerable: true, get: function () { return week_1.saveWeek; } });
@@ -44,7 +44,26 @@ export interface StatusMetrics {
44
44
  resetsAt: number;
45
45
  } | null;
46
46
  }
47
+ /**
48
+ * This machine's memory and disk, already judged by the reader. Display only:
49
+ * memory null hides the part (a system we cannot read), availablePercent null
50
+ * shows it as unknown, disk and swap are present only when they need a look.
51
+ */
52
+ export interface StatusMachine {
53
+ memory?: {
54
+ availablePercent: number | null;
55
+ level: 'ok' | 'warn' | 'crit' | 'unknown';
56
+ } | null;
57
+ disk?: {
58
+ freeBytes: number;
59
+ level: 'warn' | 'crit';
60
+ } | null;
61
+ swap?: {
62
+ usedBytes: number;
63
+ } | null;
64
+ }
47
65
  export interface StatusInput extends StatusMetrics {
66
+ machine?: StatusMachine | null;
48
67
  burn?: StatusBurn | null;
49
68
  share?: number | null;
50
69
  windows?: UsageWindow[];
@@ -32,6 +32,12 @@ function statusCount(n) {
32
32
  function money(value, range) {
33
33
  return Math.abs(value.max - value.min) < .000001 ? `$${value.min.toFixed(2)}` : `$${value.min.toFixed(2)} ${range} $${value.max.toFixed(2)}`;
34
34
  }
35
+ function gigabytes(bytes, short = false) {
36
+ // Under 10 GB one decimal place, from 10 GB whole numbers. The switch is made on
37
+ // the rounded tenths so 9.96 reads "10" (not "10.0"), and each side rounds once.
38
+ const tenths = Math.round(bytes / 1e8), text = tenths >= 100 ? String(Math.round(bytes / 1e9)) : (tenths / 10).toFixed(1);
39
+ return short ? `${text}G` : `${text} GB`;
40
+ }
35
41
  function duration(minutes) {
36
42
  const n = Math.max(0, Math.round(minutes / 10) * 10);
37
43
  return '~' + (n >= 60 ? `${Math.floor(n / 60)}h` : '') + (n % 60 || n < 60 ? `${n % 60}m` : '');
@@ -70,6 +76,31 @@ function formatStatusFields(input) {
70
76
  const ctx = input.context && Number.isFinite(input.context.tokens) && input.context.tokens >= 0 &&
71
77
  Number.isFinite(input.context.threshold) && input.context.threshold > 0 ? input.context : null;
72
78
  const left = ctx ? Math.max(0, Math.round(100 - (100 * ctx.tokens) / ctx.threshold)) : null;
79
+ const whole = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
80
+ // The machine parts come from outside this file. Each value is read once and
81
+ // copied into a fresh object in one of the few shapes drawn below: a share
82
+ // from 0 to 100 with a known level, or an unread share marked unknown; a low
83
+ // disk; swap in use. Anything else is malformed and draws nothing, never a quiet "fine".
84
+ const object = (v) => v && typeof v === 'object' && !Array.isArray(v) ? v : null;
85
+ let memory = null;
86
+ let disk = null, swap = null;
87
+ try {
88
+ const machine = object(input.machine), m = object(machine?.memory), d = object(machine?.disk), s = object(machine?.swap);
89
+ const share = m?.availablePercent, shareLevel = m?.level, free = d?.freeBytes, freeLevel = d?.level, used = s?.usedBytes;
90
+ if (m && share === null && shareLevel === 'unknown')
91
+ memory = { availablePercent: null, level: 'unknown' };
92
+ else if (m && whole(share) && share <= 100 && (shareLevel === 'ok' || shareLevel === 'warn' || shareLevel === 'crit'))
93
+ memory = { availablePercent: Math.round(share), level: shareLevel };
94
+ if (d && whole(free) && (freeLevel === 'warn' || freeLevel === 'crit'))
95
+ disk = { freeBytes: free, level: freeLevel };
96
+ if (s && whole(used) && used > 0)
97
+ swap = { usedBytes: used };
98
+ }
99
+ catch {
100
+ memory = null;
101
+ disk = null;
102
+ swap = null;
103
+ }
73
104
  const optional = new Map();
74
105
  if (pace !== null)
75
106
  optional.set('pace', { text: `${words.limit} ${duration(pace)}`, color: pace < 30 ? 'yellow' : null });
@@ -108,6 +139,18 @@ function formatStatusFields(input) {
108
139
  const color = left <= 10 ? 'red' : left <= 30 ? 'yellow' : null;
109
140
  add(short > 1 ? `ac ${left}%` : `${left}% ${short ? words.compactShort : words.compact}`, color ? { color } : {});
110
141
  }
142
+ // The machine's own state sits with the session's limits and is never one of
143
+ // the optional fields dropped for width: a red disk is the part to keep.
144
+ // Low disk comes first of the three: on a clipped line it is the one to keep.
145
+ if (disk)
146
+ add(short ? `${words.disk} ${gigabytes(disk.freeBytes, true)}` : `${words.disk} ${gigabytes(disk.freeBytes)} ${words.diskFree}`, { color: disk.level === 'crit' ? 'red' : 'yellow' });
147
+ if (memory) {
148
+ const color = memory.level === 'crit' ? 'red' : memory.level === 'warn' ? 'yellow' : null;
149
+ add(memory.availablePercent === null ? (short ? `${words.memoryShort} ?` : words.memoryUnknown)
150
+ : short ? `${short > 1 ? 'm' : words.memoryShort} ${memory.availablePercent}%` : `${memory.availablePercent}% ${words.memory}`, color ? { color } : {});
151
+ }
152
+ if (swap)
153
+ add(`${words.swap} ${gigabytes(swap.usedBytes, short > 0)}`, { color: 'yellow' });
111
154
  if (typeof input.share === 'number' && Number.isFinite(input.share))
112
155
  add(`${Math.round(input.share)}% ${short ? words.sub : words.share}`);
113
156
  if (plan)
@@ -141,6 +184,9 @@ function formatStatusFields(input) {
141
184
  ...(ctx && left !== null ? [words.contextLine.replace('{used}', Math.round(ctx.tokens).toLocaleString('en-US'))
142
185
  .replace('{threshold}', Math.round(ctx.threshold).toLocaleString('en-US')).replace('{left}', String(left))] : []),
143
186
  ...plans.map(window => `${words.plan} ${Math.round(window.usedPercent)}% (${planName(window)}). ${words.reset} ${Number.isFinite(window.resetsAt) ? new Date(window.resetsAt).toISOString() : words.none}.${age(window) ? ` ${words.lastRead} ${age(window)}.` : ''}`),
187
+ ...(memory ? [memory.availablePercent === null ? words.memoryLineUnknown : words.memoryLine.replace('{percent}', String(memory.availablePercent))] : []),
188
+ ...(swap ? [words.swapLine.replace('{used}', gigabytes(swap.usedBytes))] : []),
189
+ ...(disk ? [words.diskLine.replace('{free}', gigabytes(disk.freeBytes))] : []),
144
190
  pace !== null ? `${words.limit} ${duration(pace)}.` : words.paceEmpty,
145
191
  input.cost ? `${words.costLead} ≈ ${money(input.cost, words.range)} ${words.costFull}.` : words.costEmpty,
146
192
  input.cache && input.cache.tokens > 0 ? `${words.cacheLead} ${input.cache.tokens.toLocaleString('en-US')} ${words.tokens}${input.cache.usd ? ` (≈ ${money(input.cache.usd, words.range)} ${words.costFull})` : ''}.` : words.cacheEmpty,
@@ -0,0 +1,21 @@
1
+ import { type VolumeProbe } from '../idle/disk';
2
+ import { type MemoryProbe } from '../idle/memory';
3
+ import type { StatusMachine } from './status-fields';
4
+ /** Swap this large against physical memory means the machine is living on disk. */
5
+ export declare const SWAP_HEAVY_FRACTION = 0.5;
6
+ /** With the disk already low, this much swap is worth showing: swap is what fills it. */
7
+ export declare const SWAP_WITH_LOW_DISK_BYTES: number;
8
+ export interface MachineSources {
9
+ platform?: string;
10
+ memory?: MemoryProbe;
11
+ volume?: VolumeProbe;
12
+ volumePath?: string;
13
+ physicalBytes?: number;
14
+ }
15
+ /**
16
+ * macOS grows swap files on demand, so "used over total" is near full whenever
17
+ * any swap exists and says nothing. Size against physical memory, or against a
18
+ * disk that is already low, is what tells a person something.
19
+ */
20
+ export declare function swapIsHeavy(usedBytes: number | null, physicalBytes: number, diskLow: boolean): boolean;
21
+ export declare function readStatusMachine(home: string, now?: number, sources?: MachineSources): Promise<StatusMachine>;
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SWAP_WITH_LOW_DISK_BYTES = exports.SWAP_HEAVY_FRACTION = void 0;
4
+ exports.swapIsHeavy = swapIsHeavy;
5
+ exports.readStatusMachine = readStatusMachine;
6
+ /**
7
+ * What the status line says about this machine: available memory always (on
8
+ * systems we can read), swap only when it is heavy, free disk only when it is
9
+ * low. Local metadata reads, shared across sessions through small cache files.
10
+ * Reported only: nothing here denies, signals or deletes.
11
+ */
12
+ const node_os_1 = require("node:os");
13
+ const disk_1 = require("../idle/disk");
14
+ const memory_1 = require("../idle/memory");
15
+ /** Swap this large against physical memory means the machine is living on disk. */
16
+ exports.SWAP_HEAVY_FRACTION = 0.5;
17
+ /** With the disk already low, this much swap is worth showing: swap is what fills it. */
18
+ exports.SWAP_WITH_LOW_DISK_BYTES = 4 * 1024 ** 3;
19
+ /**
20
+ * macOS grows swap files on demand, so "used over total" is near full whenever
21
+ * any swap exists and says nothing. Size against physical memory, or against a
22
+ * disk that is already low, is what tells a person something.
23
+ */
24
+ function swapIsHeavy(usedBytes, physicalBytes, diskLow) {
25
+ if (usedBytes === null || !Number.isFinite(usedBytes) || usedBytes <= 0)
26
+ return false;
27
+ if (Number.isFinite(physicalBytes) && physicalBytes > 0 && usedBytes >= physicalBytes * exports.SWAP_HEAVY_FRACTION)
28
+ return true;
29
+ return diskLow && usedBytes >= exports.SWAP_WITH_LOW_DISK_BYTES;
30
+ }
31
+ async function readStatusMachine(home, now = Date.now(), sources = {}) {
32
+ const out = {};
33
+ try {
34
+ const platform = sources.platform ?? process.platform;
35
+ let level = 'unknown';
36
+ try {
37
+ const space = (sources.volume ?? disk_1.statfsProbe)(sources.volumePath ?? (0, node_os_1.homedir)());
38
+ level = (0, disk_1.diskLevel)(space);
39
+ if (space && (level === 'warn' || level === 'crit'))
40
+ out.disk = { freeBytes: space.freeBytes, level };
41
+ }
42
+ catch { /* unknown disk shows nothing */ }
43
+ // A system with no memory source shows no memory part at all, rather than a permanent question mark.
44
+ if (platform !== 'darwin' && platform !== 'linux')
45
+ return out;
46
+ const reading = await (0, memory_1.readMemory)(home, now, sources.memory ?? (0, memory_1.systemMemoryProbe)(platform));
47
+ out.memory = { availablePercent: reading.availablePercent, level: reading.level };
48
+ if (swapIsHeavy(reading.swapUsedBytes, sources.physicalBytes ?? (0, node_os_1.totalmem)(), level === 'warn' || level === 'crit'))
49
+ out.swap = { usedBytes: reading.swapUsedBytes };
50
+ }
51
+ catch { /* the line is drawn without the machine parts */ }
52
+ return out;
53
+ }
@@ -10,6 +10,16 @@ export declare const STATUS_TEXT: {
10
10
  share: string;
11
11
  sub: string;
12
12
  weekly: string;
13
+ memory: string;
14
+ memoryShort: string;
15
+ memoryUnknown: string;
16
+ disk: string;
17
+ diskFree: string;
18
+ swap: string;
19
+ memoryLine: string;
20
+ memoryLineUnknown: string;
21
+ diskLine: string;
22
+ swapLine: string;
13
23
  pastLimit: string;
14
24
  pastShort: string;
15
25
  waits: string;
@@ -51,6 +61,16 @@ export declare const STATUS_TEXT: {
51
61
  share: string;
52
62
  sub: string;
53
63
  weekly: string;
64
+ memory: string;
65
+ memoryShort: string;
66
+ memoryUnknown: string;
67
+ disk: string;
68
+ diskFree: string;
69
+ swap: string;
70
+ memoryLine: string;
71
+ memoryLineUnknown: string;
72
+ diskLine: string;
73
+ swapLine: string;
54
74
  pastLimit: string;
55
75
  pastShort: string;
56
76
  waits: string;
@@ -92,6 +112,16 @@ export declare const STATUS_TEXT: {
92
112
  share: string;
93
113
  sub: string;
94
114
  weekly: string;
115
+ memory: string;
116
+ memoryShort: string;
117
+ memoryUnknown: string;
118
+ disk: string;
119
+ diskFree: string;
120
+ swap: string;
121
+ memoryLine: string;
122
+ memoryLineUnknown: string;
123
+ diskLine: string;
124
+ swapLine: string;
95
125
  pastLimit: string;
96
126
  pastShort: string;
97
127
  waits: string;
@@ -4,6 +4,9 @@ exports.STATUS_TEXT = void 0;
4
4
  // Display-only words shared with the Claude mod. No environment or I/O here.
5
5
  exports.STATUS_TEXT = {
6
6
  en: { ago: '{minutes}m ago', lastRead: 'Last read', range: 'to', fiveHour: '5-hour', agents: 'sub-agents', tokens: 'tokens', of: 'of', share: 'to sub-agents', sub: 'sub', weekly: 'weekly',
7
+ memory: 'memory free', memoryShort: 'mem', memoryUnknown: 'memory ?', disk: 'disk', diskFree: 'free', swap: 'swap',
8
+ memoryLine: 'Memory: {percent}% of this machine\'s memory is available.', memoryLineUnknown: 'Memory: the available share could not be read.',
9
+ diskLine: 'Disk: {free} free on the volume holding your home folder.', swapLine: 'Swap: {used} in use. Heavy swap means memory is short and the disk is filling.',
7
10
  pastLimit: 'past the {limit} limit', pastShort: 'past {limit}', waits: 'sub-agents wait for your yes', compact: 'to auto-compact', compactShort: 'to compact',
8
11
  contextLine: 'Context: {used} of {threshold} tokens, {left}% left before Claude Code compacts the conversation.',
9
12
  limit: 'limit in', cache: 'cache waste', spend: 'spend', today: 'today', list: 'list', watching: 'watching only',
@@ -16,6 +19,9 @@ exports.STATUS_TEXT = {
16
19
  enabled: 'Optional status fields on:', none: 'none', change: 'Change status_fields in the AgentGuard plugin settings, or pass the fields flag to Burn statusline.',
17
20
  unknown: 'Ignored unknown status fields:', reset: 'Resets at', plan: 'Plan usage:', hidden: 'Fields hidden to fit this width:' },
18
21
  es: { ago: 'hace {minutes}min', lastRead: 'Última lectura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'a subagentes', sub: 'sub', weekly: 'semanal',
22
+ memory: 'de memoria libre', memoryShort: 'mem', memoryUnknown: 'memoria ?', disk: 'disco', diskFree: 'libres', swap: 'swap',
23
+ memoryLine: 'Memoria: {percent}% de la memoria de este equipo está disponible.', memoryLineUnknown: 'Memoria: no se pudo leer la parte disponible.',
24
+ diskLine: 'Disco: {free} libres en el volumen de tu carpeta personal.', swapLine: 'Swap: {used} en uso. Mucho swap significa que falta memoria y el disco se llena.',
19
25
  pastLimit: 'pasó el límite de {limit}', pastShort: 'pasó {limit}', waits: 'los subagentes esperan tu sí', compact: 'para autocompactar', compactShort: 'hasta compactar',
20
26
  contextLine: 'Contexto: {used} de {threshold} tokens, queda {left}% antes de que Claude Code compacte la conversación.',
21
27
  limit: 'límite en', cache: 'caché reescrita', spend: 'gasto', today: 'hoy', list: 'lista', watching: 'solo observando',
@@ -28,6 +34,9 @@ exports.STATUS_TEXT = {
28
34
  enabled: 'Campos opcionales activos:', none: 'ninguno', change: 'Cambia status_fields en los ajustes del plugin AgentGuard o pasa la opción fields a Burn statusline.',
29
35
  unknown: 'Campos de estado desconocidos ignorados:', reset: 'Se reinicia a las', plan: 'Uso del plan:', hidden: 'Campos ocultos para caber en este ancho:' },
30
36
  pt: { ago: 'há {minutes}min', lastRead: 'Última leitura', range: 'a', fiveHour: '5 horas', agents: 'subagentes', tokens: 'tokens', of: 'de', share: 'para subagentes', sub: 'sub', weekly: 'semanal',
37
+ memory: 'de memória livre', memoryShort: 'mem', memoryUnknown: 'memória ?', disk: 'disco', diskFree: 'livres', swap: 'swap',
38
+ memoryLine: 'Memória: {percent}% da memória desta máquina está disponível.', memoryLineUnknown: 'Memória: não foi possível ler a parte disponível.',
39
+ diskLine: 'Disco: {free} livres no volume da sua pasta pessoal.', swapLine: 'Swap: {used} em uso. Muito swap significa pouca memória e disco enchendo.',
31
40
  pastLimit: 'passou do limite de {limit}', pastShort: 'passou {limit}', waits: 'subagentes esperam seu sim', compact: 'até autocompactar', compactShort: 'até compactar',
32
41
  contextLine: 'Contexto: {used} de {threshold} tokens, resta {left}% antes de o Claude Code compactar a conversa.',
33
42
  limit: 'limite em', cache: 'cache regravado', spend: 'gasto', today: 'hoje', list: 'lista', watching: 'só observando',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentguard-run/burn",
3
- "version": "0.7.2",
3
+ "version": "0.7.3",
4
4
  "description": "Local session usage and runaway-agent circuit breaker. Explain tokens, cache rewrites and API list cost, track pace, warn on heavy turns, and gate agent fan-out with signed receipts. Developer command ranking requires explicit --rank.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://agentguard.run/burn",