@agentguard-run/burn 0.7.2 → 0.7.4
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 +19 -0
- package/dist/src/cli.js +2 -1
- package/dist/src/idle/classify.js +13 -1
- package/dist/src/idle/growth-runner.d.ts +85 -0
- package/dist/src/idle/growth-runner.js +228 -0
- package/dist/src/idle/growth-sample.d.ts +48 -0
- package/dist/src/idle/growth-sample.js +101 -0
- package/dist/src/idle/growth.d.ts +157 -0
- package/dist/src/idle/growth.js +337 -0
- package/dist/src/idle/hook.js +7 -0
- package/dist/src/idle/memory.d.ts +38 -0
- package/dist/src/idle/memory.js +225 -0
- package/dist/src/idle/platform.d.ts +2 -1
- package/dist/src/idle/platform.js +1 -1
- package/dist/src/idle/render.js +1 -1
- package/dist/src/index.d.ts +5 -0
- package/dist/src/index.js +23 -1
- package/dist/src/insights/status-fields.d.ts +19 -0
- package/dist/src/insights/status-fields.js +46 -0
- package/dist/src/insights/status-machine.d.ts +21 -0
- package/dist/src/insights/status-machine.js +53 -0
- package/dist/src/insights/status-text.d.ts +30 -0
- package/dist/src/insights/status-text.js +9 -0
- package/package.json +1 -1
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import type { PressureLevel } from './disk';
|
|
2
|
+
export declare const GIB: number;
|
|
3
|
+
export declare const MIB: number;
|
|
4
|
+
export interface GrowthConfig {
|
|
5
|
+
/** The sustained-growth window. */
|
|
6
|
+
windowMs: number;
|
|
7
|
+
/** Tolerance on the window edge, one sample interval: samples run late on a machine that is swapping. */
|
|
8
|
+
slackMs: number;
|
|
9
|
+
/** Readings in the window must span at least this long. */
|
|
10
|
+
minSpanMs: number;
|
|
11
|
+
/** Judged by time, not by count: missed samples, slow samples and missing footprints are all tolerated down to this many readings. */
|
|
12
|
+
minReadings: number;
|
|
13
|
+
minGrowthBytes: number;
|
|
14
|
+
/** Each third of the window must carry at least this share of the growth: one load followed by drift, or a climb shorter than the window, is not a leak. */
|
|
15
|
+
minThirdShare: number;
|
|
16
|
+
/** Readings at or above this size are whole gigabytes on macOS. They are judged over the longer window below, by the same rule. */
|
|
17
|
+
coarseFromBytes: number;
|
|
18
|
+
coarseWindowMs: number;
|
|
19
|
+
coarseMinSpanMs: number;
|
|
20
|
+
/** Memory handed back inside the window may be at most this share of the growth: a collector's sawtooth is not a leak. */
|
|
21
|
+
maxGiveBackShare: number;
|
|
22
|
+
/** A process this large under a session is listed, without a notice, while the machine is short of memory. */
|
|
23
|
+
largeMinBytes: number;
|
|
24
|
+
largeShare: number;
|
|
25
|
+
/** Size floor while the machine is short of memory. */
|
|
26
|
+
pressuredFloorBytes: number;
|
|
27
|
+
/** Size floor as a share of RAM while memory is fine or unknown. */
|
|
28
|
+
calmFloorShare: number;
|
|
29
|
+
calmFloorMinBytes: number;
|
|
30
|
+
/** A named process with no growth for this long reads "holding". */
|
|
31
|
+
holdingAfterMs: number;
|
|
32
|
+
maxTracks: number;
|
|
33
|
+
}
|
|
34
|
+
export declare const DEFAULT_GROWTH: GrowthConfig;
|
|
35
|
+
export interface GrowthProcess {
|
|
36
|
+
pid: number;
|
|
37
|
+
ppid: number;
|
|
38
|
+
/** Stable OS start identity. A process without one is never tracked. */
|
|
39
|
+
startedAt: string | null;
|
|
40
|
+
command: string;
|
|
41
|
+
/** Null when this sample has no footprint for the process. */
|
|
42
|
+
footprintBytes: number | null;
|
|
43
|
+
}
|
|
44
|
+
export interface GrowthSample {
|
|
45
|
+
at: number;
|
|
46
|
+
/** False when the process table or the footprint read was cut short. Ignored whole. */
|
|
47
|
+
complete: boolean;
|
|
48
|
+
totalRamBytes: number | null;
|
|
49
|
+
level: PressureLevel;
|
|
50
|
+
processes: GrowthProcess[];
|
|
51
|
+
}
|
|
52
|
+
interface Track {
|
|
53
|
+
pid: number;
|
|
54
|
+
startedAt: string;
|
|
55
|
+
/** The latest command line. Not part of the identity: a program may rename itself in place. */
|
|
56
|
+
command: string;
|
|
57
|
+
/** Seen under an agent session at least once. Kept after a reparent. */
|
|
58
|
+
underSession: boolean;
|
|
59
|
+
readings: Array<[at: number, bytes: number]>;
|
|
60
|
+
}
|
|
61
|
+
export interface GrowthFinding {
|
|
62
|
+
key: string;
|
|
63
|
+
pid: number;
|
|
64
|
+
startedAt: string;
|
|
65
|
+
command: string;
|
|
66
|
+
namedAt: number;
|
|
67
|
+
/** 'grew': sustained growth was seen. 'large': listed for its size alone while memory is short; never announced. */
|
|
68
|
+
origin: 'grew' | 'large';
|
|
69
|
+
/** Size when it was first listed. Falling under half of it drops the finding. */
|
|
70
|
+
namedBytes: number;
|
|
71
|
+
sizeBytes: number;
|
|
72
|
+
peakBytes: number;
|
|
73
|
+
/** Growth over the window the last time sustained growth was seen. Zero for a process listed for size alone. */
|
|
74
|
+
grewBytes: number;
|
|
75
|
+
/** The span that growth was measured over: about two minutes, about four where sizes are whole gigabytes. */
|
|
76
|
+
grewOverMs: number;
|
|
77
|
+
lastGrewAt: number | null;
|
|
78
|
+
status: 'growing' | 'holding' | 'stop_sent';
|
|
79
|
+
stopSentAt: number | null;
|
|
80
|
+
}
|
|
81
|
+
export interface GrowthState {
|
|
82
|
+
version: 1;
|
|
83
|
+
lastAt: number | null;
|
|
84
|
+
/** When machine memory was last warn or crit. A process listed for size alone leaves the list two minutes after. */
|
|
85
|
+
pressuredAt: number | null;
|
|
86
|
+
tracks: Record<string, Track>;
|
|
87
|
+
findings: Record<string, GrowthFinding>;
|
|
88
|
+
}
|
|
89
|
+
export declare const emptyGrowthState: () => GrowthState;
|
|
90
|
+
export declare const growthKey: (pid: number, startedAt: string) => string;
|
|
91
|
+
/** Pids with an agent session process somewhere above them in this sample. */
|
|
92
|
+
export declare function underAgentSession(processes: GrowthProcess[]): Set<number>;
|
|
93
|
+
export declare function sizeFloor(level: PressureLevel, totalRamBytes: number | null, config?: GrowthConfig): number;
|
|
94
|
+
/** How much, and over how long: the words shown to the person must name the real span. */
|
|
95
|
+
export interface MeasuredGrowth {
|
|
96
|
+
grewBytes: number;
|
|
97
|
+
overMs: number;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Growth over the window, or null when the readings do not show sustained
|
|
101
|
+
* growth. Judged on time and totals, never on sample-to-sample steps. Where
|
|
102
|
+
* the reader only prints whole gigabytes (macOS, from 10 GB up) a two-minute
|
|
103
|
+
* window holds too few steps to tell a leak from one load, so those readings
|
|
104
|
+
* are judged by the same rule over four minutes.
|
|
105
|
+
*/
|
|
106
|
+
export declare function sustainedGrowth(readings: Array<[number, number]>, now: number, config?: GrowthConfig): number | null;
|
|
107
|
+
export declare function measureGrowth(readings: Array<[number, number]>, now: number, config?: GrowthConfig): MeasuredGrowth | null;
|
|
108
|
+
/** Size at which a process under a session is listed for its size alone. Only while the machine is short of memory. */
|
|
109
|
+
export declare function largeFloor(level: PressureLevel, totalRamBytes: number | null, config?: GrowthConfig): number;
|
|
110
|
+
export interface GrowthStep {
|
|
111
|
+
state: GrowthState;
|
|
112
|
+
/** Everything named right now, largest first. */
|
|
113
|
+
findings: GrowthFinding[];
|
|
114
|
+
/** Sustained growth seen for the first time in this step: the only moment a notice is due. Never a process listed for size alone. */
|
|
115
|
+
fresh: GrowthFinding[];
|
|
116
|
+
}
|
|
117
|
+
export declare function stepGrowth(previous: GrowthState, sample: GrowthSample, config?: GrowthConfig): GrowthStep;
|
|
118
|
+
export interface StopDependencies {
|
|
119
|
+
/** One fresh single-process read, made by the same process that signals. Null when the pid is gone. */
|
|
120
|
+
readOne(pid: number): Promise<GrowthProcess | null>;
|
|
121
|
+
/** Pid 1, this process and its ancestors. Null when the ancestry could not be verified. */
|
|
122
|
+
protectedPids(): Promise<Set<number> | null>;
|
|
123
|
+
signal(pid: number, signal: 'SIGTERM'): Promise<void>;
|
|
124
|
+
now(): number;
|
|
125
|
+
}
|
|
126
|
+
export type StopOutcome = 'sent' | 'refused' | 'signal_failed';
|
|
127
|
+
export interface StopResult {
|
|
128
|
+
state: GrowthState;
|
|
129
|
+
outcome: StopOutcome;
|
|
130
|
+
reason: string;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The person chose "Stop it" for one named process. Sends SIGTERM at most once
|
|
134
|
+
* per listing, only to the same program that was named, never anything
|
|
135
|
+
* stronger. Any doubt is a refusal. `shown` answers whether a command line is
|
|
136
|
+
* what the person saw when they chose.
|
|
137
|
+
*/
|
|
138
|
+
export declare function stopNamed(state: GrowthState, key: string, dependencies: StopDependencies, shown?: (command: string) => boolean): Promise<StopResult>;
|
|
139
|
+
/**
|
|
140
|
+
* The one authoritative state for a worker: samples and stop requests go
|
|
141
|
+
* through here, so two taps on the same finding send one signal and a sample
|
|
142
|
+
* that lands while a stop is in flight does not lose its record.
|
|
143
|
+
*/
|
|
144
|
+
export declare class GrowthWatch {
|
|
145
|
+
private readonly dependencies;
|
|
146
|
+
private readonly config;
|
|
147
|
+
private current;
|
|
148
|
+
private readonly stopping;
|
|
149
|
+
constructor(dependencies: StopDependencies, config?: GrowthConfig, state?: GrowthState);
|
|
150
|
+
get state(): GrowthState;
|
|
151
|
+
step(sample: GrowthSample): GrowthStep;
|
|
152
|
+
stop(key: string, shown?: (command: string) => boolean): Promise<{
|
|
153
|
+
outcome: StopOutcome;
|
|
154
|
+
reason: string;
|
|
155
|
+
}>;
|
|
156
|
+
}
|
|
157
|
+
export {};
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GrowthWatch = exports.growthKey = exports.emptyGrowthState = exports.DEFAULT_GROWTH = exports.MIB = exports.GIB = void 0;
|
|
4
|
+
exports.underAgentSession = underAgentSession;
|
|
5
|
+
exports.sizeFloor = sizeFloor;
|
|
6
|
+
exports.sustainedGrowth = sustainedGrowth;
|
|
7
|
+
exports.measureGrowth = measureGrowth;
|
|
8
|
+
exports.largeFloor = largeFloor;
|
|
9
|
+
exports.stepGrowth = stepGrowth;
|
|
10
|
+
exports.stopNamed = stopNamed;
|
|
11
|
+
/**
|
|
12
|
+
* Growth watch: names a process under an agent session whose memory keeps
|
|
13
|
+
* climbing, and stops it only when the person chooses to. Pure state machine:
|
|
14
|
+
* the worker feeds it one sample every 15 seconds and no clock, file or OS
|
|
15
|
+
* call lives here. Nothing in this file acts on its own.
|
|
16
|
+
*
|
|
17
|
+
* Size is the process footprint (resident plus compressed and swapped). On a
|
|
18
|
+
* pressured Mac the resident size alone can read 11 MB for a 5 GB process.
|
|
19
|
+
*/
|
|
20
|
+
const classify_1 = require("./classify");
|
|
21
|
+
exports.GIB = 1024 ** 3;
|
|
22
|
+
exports.MIB = 1024 ** 2;
|
|
23
|
+
exports.DEFAULT_GROWTH = {
|
|
24
|
+
windowMs: 120_000, slackMs: 15_000, minSpanMs: 105_000, minReadings: 5,
|
|
25
|
+
minGrowthBytes: 512 * exports.MIB, minThirdShare: 0.2, coarseFromBytes: 10 * exports.GIB, coarseWindowMs: 240_000, coarseMinSpanMs: 225_000, maxGiveBackShare: 0.25,
|
|
26
|
+
largeMinBytes: 2 * exports.GIB, largeShare: 0.1, pressuredFloorBytes: exports.GIB, calmFloorShare: 0.25, calmFloorMinBytes: 2 * exports.GIB,
|
|
27
|
+
holdingAfterMs: 120_000, maxTracks: 600,
|
|
28
|
+
};
|
|
29
|
+
const emptyGrowthState = () => ({ version: 1, lastAt: null, pressuredAt: null, tracks: {}, findings: {} });
|
|
30
|
+
exports.emptyGrowthState = emptyGrowthState;
|
|
31
|
+
const growthKey = (pid, startedAt) => `${pid}|${startedAt}`;
|
|
32
|
+
exports.growthKey = growthKey;
|
|
33
|
+
const whole = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
34
|
+
/** One closed-shape read of an untrusted process row. */
|
|
35
|
+
function cleanProcess(input) {
|
|
36
|
+
if (!input || typeof input !== 'object')
|
|
37
|
+
return null;
|
|
38
|
+
const { pid, ppid, startedAt, command, footprintBytes } = input;
|
|
39
|
+
if (!whole(pid) || pid < 1 || !whole(ppid) || typeof command !== 'string' || command.length === 0)
|
|
40
|
+
return null;
|
|
41
|
+
return {
|
|
42
|
+
pid, ppid, command, startedAt: typeof startedAt === 'string' && startedAt.length > 0 ? startedAt : null,
|
|
43
|
+
footprintBytes: typeof footprintBytes === 'number' && Number.isFinite(footprintBytes) && footprintBytes >= 0 ? footprintBytes : null,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** Pids with an agent session process somewhere above them in this sample. */
|
|
47
|
+
function underAgentSession(processes) {
|
|
48
|
+
const parent = new Map(), hosts = new Set(), result = new Set();
|
|
49
|
+
for (const item of processes) {
|
|
50
|
+
parent.set(item.pid, item.ppid);
|
|
51
|
+
if ((0, classify_1.agentHost)(item.command))
|
|
52
|
+
hosts.add(item.pid);
|
|
53
|
+
}
|
|
54
|
+
for (const item of processes) {
|
|
55
|
+
const seen = new Set([item.pid]);
|
|
56
|
+
let current = item.ppid;
|
|
57
|
+
while (current > 0 && !seen.has(current)) {
|
|
58
|
+
if (hosts.has(current)) {
|
|
59
|
+
result.add(item.pid);
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
seen.add(current);
|
|
63
|
+
const next = parent.get(current);
|
|
64
|
+
if (next === undefined)
|
|
65
|
+
break;
|
|
66
|
+
current = next;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
function sizeFloor(level, totalRamBytes, config = exports.DEFAULT_GROWTH) {
|
|
72
|
+
if (level === 'warn' || level === 'crit')
|
|
73
|
+
return config.pressuredFloorBytes;
|
|
74
|
+
// With memory fine or unreadable, only a process holding a large share of the machine is worth a word.
|
|
75
|
+
if (totalRamBytes === null || !Number.isFinite(totalRamBytes) || totalRamBytes <= 0)
|
|
76
|
+
return Number.POSITIVE_INFINITY;
|
|
77
|
+
return Math.max(config.calmFloorMinBytes, totalRamBytes * config.calmFloorShare);
|
|
78
|
+
}
|
|
79
|
+
/** The size at one instant, on the straight line between the readings either side of it. */
|
|
80
|
+
function sizeAt(readings, at) {
|
|
81
|
+
for (let index = 1; index < readings.length; index++) {
|
|
82
|
+
const [t0, v0] = readings[index - 1], [t1, v1] = readings[index];
|
|
83
|
+
if (at <= t1)
|
|
84
|
+
return t1 === t0 ? v1 : v0 + (v1 - v0) * (at - t0) / (t1 - t0);
|
|
85
|
+
}
|
|
86
|
+
return readings[readings.length - 1][1];
|
|
87
|
+
}
|
|
88
|
+
function grewThroughout(inside, now, minSpanMs, minReadings, config) {
|
|
89
|
+
if (inside.length < minReadings)
|
|
90
|
+
return null;
|
|
91
|
+
const first = inside[0], last = inside[inside.length - 1];
|
|
92
|
+
if (last[0] !== now || last[0] - first[0] < minSpanMs)
|
|
93
|
+
return null;
|
|
94
|
+
const grew = last[1] - first[1];
|
|
95
|
+
if (grew < config.minGrowthBytes)
|
|
96
|
+
return null;
|
|
97
|
+
let givenBack = 0;
|
|
98
|
+
for (let index = 1; index < inside.length; index++) {
|
|
99
|
+
const change = inside[index][1] - inside[index - 1][1];
|
|
100
|
+
if (change < 0)
|
|
101
|
+
givenBack -= change;
|
|
102
|
+
}
|
|
103
|
+
if (givenBack > grew * config.maxGiveBackShare)
|
|
104
|
+
return null;
|
|
105
|
+
// Growth in every third of the span, measured at the exact third marks so a late or missing sample does not move them.
|
|
106
|
+
const span = last[0] - first[0];
|
|
107
|
+
const edges = [first[1], sizeAt(inside, first[0] + span / 3), sizeAt(inside, first[0] + span * 2 / 3), last[1]];
|
|
108
|
+
for (let part = 0; part < 3; part++)
|
|
109
|
+
if (edges[part + 1] - edges[part] < grew * config.minThirdShare)
|
|
110
|
+
return null;
|
|
111
|
+
return { grewBytes: grew, overMs: span };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Growth over the window, or null when the readings do not show sustained
|
|
115
|
+
* growth. Judged on time and totals, never on sample-to-sample steps. Where
|
|
116
|
+
* the reader only prints whole gigabytes (macOS, from 10 GB up) a two-minute
|
|
117
|
+
* window holds too few steps to tell a leak from one load, so those readings
|
|
118
|
+
* are judged by the same rule over four minutes.
|
|
119
|
+
*/
|
|
120
|
+
function sustainedGrowth(readings, now, config = exports.DEFAULT_GROWTH) {
|
|
121
|
+
return measureGrowth(readings, now, config)?.grewBytes ?? null;
|
|
122
|
+
}
|
|
123
|
+
function measureGrowth(readings, now, config = exports.DEFAULT_GROWTH) {
|
|
124
|
+
const within = (windowMs) => readings.filter(([at]) => at > now - windowMs - config.slackMs && at <= now);
|
|
125
|
+
const inside = within(config.windowMs);
|
|
126
|
+
if (inside.length === 0)
|
|
127
|
+
return null;
|
|
128
|
+
const coarse = inside.every(([, bytes]) => bytes >= config.coarseFromBytes && bytes % exports.GIB === 0);
|
|
129
|
+
return coarse
|
|
130
|
+
? grewThroughout(within(config.coarseWindowMs), now, config.coarseMinSpanMs, config.minReadings * 2, config)
|
|
131
|
+
: grewThroughout(inside, now, config.minSpanMs, config.minReadings, config);
|
|
132
|
+
}
|
|
133
|
+
/** At or over the size for the whole two-minute window, not for one sample. */
|
|
134
|
+
function largeThroughout(readings, now, large, config) {
|
|
135
|
+
const inside = readings.filter(([at]) => at > now - config.windowMs - config.slackMs && at <= now);
|
|
136
|
+
return inside.length >= config.minReadings && inside[inside.length - 1][0] === now && now - inside[0][0] >= config.minSpanMs && inside.every(([, bytes]) => bytes >= large);
|
|
137
|
+
}
|
|
138
|
+
/** Size at which a process under a session is listed for its size alone. Only while the machine is short of memory. */
|
|
139
|
+
function largeFloor(level, totalRamBytes, config = exports.DEFAULT_GROWTH) {
|
|
140
|
+
if (level !== 'warn' && level !== 'crit')
|
|
141
|
+
return Number.POSITIVE_INFINITY;
|
|
142
|
+
const share = totalRamBytes !== null && Number.isFinite(totalRamBytes) && totalRamBytes > 0 ? totalRamBytes * config.largeShare : 0;
|
|
143
|
+
return Math.max(config.largeMinBytes, share);
|
|
144
|
+
}
|
|
145
|
+
const listed = (state) => Object.values(state.findings).sort((a, b) => b.sizeBytes - a.sizeBytes || a.pid - b.pid);
|
|
146
|
+
function stepGrowth(previous, sample, config = exports.DEFAULT_GROWTH) {
|
|
147
|
+
const at = sample?.at;
|
|
148
|
+
// A cut-short sample or a clock that did not move forward proves nothing: absence in it is not an exit.
|
|
149
|
+
if (!sample || sample.complete !== true || typeof at !== 'number' || !Number.isFinite(at) || !Array.isArray(sample.processes)
|
|
150
|
+
|| (previous.lastAt !== null && at <= previous.lastAt)) {
|
|
151
|
+
return { state: previous, findings: listed(previous), fresh: [] };
|
|
152
|
+
}
|
|
153
|
+
const level = sample.level === 'warn' || sample.level === 'crit' || sample.level === 'ok' ? sample.level : 'unknown';
|
|
154
|
+
const ram = typeof sample.totalRamBytes === 'number' ? sample.totalRamBytes : null;
|
|
155
|
+
const rows = [], seenPids = new Set();
|
|
156
|
+
for (const raw of sample.processes) {
|
|
157
|
+
const item = cleanProcess(raw);
|
|
158
|
+
// A pid listed twice makes the table ambiguous for that pid: neither row is used.
|
|
159
|
+
if (!item)
|
|
160
|
+
continue;
|
|
161
|
+
if (seenPids.has(item.pid)) {
|
|
162
|
+
const index = rows.findIndex(row => row.pid === item.pid);
|
|
163
|
+
if (index >= 0)
|
|
164
|
+
rows.splice(index, 1);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
seenPids.add(item.pid);
|
|
168
|
+
rows.push(item);
|
|
169
|
+
}
|
|
170
|
+
const sessionPids = underAgentSession(rows);
|
|
171
|
+
const tracks = {}, findings = {}, fresh = [];
|
|
172
|
+
const floor = sizeFloor(level, ram, config), large = largeFloor(level, ram, config);
|
|
173
|
+
const edge = at - Math.max(config.windowMs, config.coarseWindowMs) - config.slackMs;
|
|
174
|
+
const pressuredAt = level === 'warn' || level === 'crit' ? at : previous.pressuredAt ?? null;
|
|
175
|
+
const calmTooLong = pressuredAt === null || at - pressuredAt >= config.holdingAfterMs;
|
|
176
|
+
for (const item of rows) {
|
|
177
|
+
if (item.startedAt === null || (0, classify_1.agentHost)(item.command))
|
|
178
|
+
continue;
|
|
179
|
+
// Identity is the process number and its OS start time. The command line is not: a program may rename itself in place.
|
|
180
|
+
const key = (0, exports.growthKey)(item.pid, item.startedAt);
|
|
181
|
+
const before = Object.prototype.hasOwnProperty.call(previous.tracks, key) ? previous.tracks[key] : undefined;
|
|
182
|
+
const underSession = sessionPids.has(item.pid) || before?.underSession === true;
|
|
183
|
+
if (!underSession)
|
|
184
|
+
continue;
|
|
185
|
+
const readings = before ? before.readings.filter(([time]) => time > edge) : [];
|
|
186
|
+
if (item.footprintBytes !== null)
|
|
187
|
+
readings.push([at, item.footprintBytes]);
|
|
188
|
+
tracks[key] = { pid: item.pid, startedAt: item.startedAt, command: item.command, underSession, readings };
|
|
189
|
+
const measured = item.footprintBytes === null ? null : measureGrowth(readings, at, config);
|
|
190
|
+
const named = before && Object.prototype.hasOwnProperty.call(previous.findings, key) ? previous.findings[key] : undefined;
|
|
191
|
+
if (named) {
|
|
192
|
+
const size = item.footprintBytes ?? named.sizeBytes;
|
|
193
|
+
// It gave the memory back, or an exec replaced the program: no longer a finding. A stop already sent stays on record.
|
|
194
|
+
if (size < named.namedBytes / 2 && named.status !== 'stop_sent')
|
|
195
|
+
continue;
|
|
196
|
+
// Listed for size alone, and the machine has had memory to spare for two minutes: off the list.
|
|
197
|
+
if (named.origin === 'large' && calmTooLong && named.status !== 'stop_sent')
|
|
198
|
+
continue;
|
|
199
|
+
// A process listed for size alone counts as growing on the same terms as any other: only at or over the size floor.
|
|
200
|
+
const grew = measured !== null && (named.origin === 'grew' || size >= floor) ? measured : null;
|
|
201
|
+
const lastGrewAt = grew !== null ? at : named.lastGrewAt;
|
|
202
|
+
const announce = grew !== null && named.origin === 'large';
|
|
203
|
+
const next = {
|
|
204
|
+
...named, command: item.command, sizeBytes: size, peakBytes: Math.max(named.peakBytes, size), lastGrewAt,
|
|
205
|
+
origin: announce ? 'grew' : named.origin, grewBytes: grew?.grewBytes ?? named.grewBytes, grewOverMs: grew?.overMs ?? named.grewOverMs,
|
|
206
|
+
status: named.status === 'stop_sent' ? 'stop_sent' : lastGrewAt !== null && at - lastGrewAt < config.holdingAfterMs ? 'growing' : 'holding',
|
|
207
|
+
};
|
|
208
|
+
findings[key] = next;
|
|
209
|
+
if (announce && named.status !== 'stop_sent')
|
|
210
|
+
fresh.push(next);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (item.footprintBytes === null)
|
|
214
|
+
continue;
|
|
215
|
+
if (measured !== null && item.footprintBytes >= floor) {
|
|
216
|
+
const finding = {
|
|
217
|
+
key, pid: item.pid, startedAt: item.startedAt, command: item.command, namedAt: at, origin: 'grew', namedBytes: item.footprintBytes,
|
|
218
|
+
sizeBytes: item.footprintBytes, peakBytes: item.footprintBytes, grewBytes: measured.grewBytes, grewOverMs: measured.overMs, lastGrewAt: at, status: 'growing', stopSentAt: null,
|
|
219
|
+
};
|
|
220
|
+
findings[key] = finding;
|
|
221
|
+
fresh.push(finding);
|
|
222
|
+
}
|
|
223
|
+
else if (largeThroughout(readings, at, large, config)) {
|
|
224
|
+
// Watched for two minutes, large, and the machine is short of memory: listed quietly so the person can see what holds it.
|
|
225
|
+
findings[key] = {
|
|
226
|
+
key, pid: item.pid, startedAt: item.startedAt, command: item.command, namedAt: at, origin: 'large', namedBytes: item.footprintBytes,
|
|
227
|
+
sizeBytes: item.footprintBytes, peakBytes: item.footprintBytes, grewBytes: 0, grewOverMs: 0, lastGrewAt: null, status: 'holding', stopSentAt: null,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// Bound the state: keep the tracks with the most to say.
|
|
232
|
+
const keys = Object.keys(tracks);
|
|
233
|
+
if (keys.length > config.maxTracks) {
|
|
234
|
+
const size = (key) => { const list = tracks[key].readings; return list.length ? list[list.length - 1][1] : 0; };
|
|
235
|
+
for (const key of keys.sort((a, b) => Number(Boolean(findings[b])) - Number(Boolean(findings[a])) || size(b) - size(a)).slice(config.maxTracks)) {
|
|
236
|
+
if (!findings[key])
|
|
237
|
+
delete tracks[key];
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const state = { version: 1, lastAt: at, pressuredAt, tracks, findings };
|
|
241
|
+
return { state, findings: listed(state), fresh };
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* The person chose "Stop it" for one named process. Sends SIGTERM at most once
|
|
245
|
+
* per listing, only to the same program that was named, never anything
|
|
246
|
+
* stronger. Any doubt is a refusal. `shown` answers whether a command line is
|
|
247
|
+
* what the person saw when they chose.
|
|
248
|
+
*/
|
|
249
|
+
async function stopNamed(state, key, dependencies, shown) {
|
|
250
|
+
const refuse = (reason) => ({ state, outcome: 'refused', reason });
|
|
251
|
+
const finding = Object.prototype.hasOwnProperty.call(state.findings, key) ? state.findings[key] : undefined;
|
|
252
|
+
if (!finding)
|
|
253
|
+
return refuse('That process is no longer listed.');
|
|
254
|
+
if (finding.status === 'stop_sent')
|
|
255
|
+
return refuse('It was already asked to stop. Nothing stronger is sent.');
|
|
256
|
+
// What the person was shown when they chose. If the process has become something else since, they have not chosen that.
|
|
257
|
+
if (shown && !shown(finding.command))
|
|
258
|
+
return refuse('That process changed since the list was shown. Look at the list again.');
|
|
259
|
+
let guarded;
|
|
260
|
+
try {
|
|
261
|
+
guarded = await dependencies.protectedPids();
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
guarded = null;
|
|
265
|
+
}
|
|
266
|
+
if (!guarded)
|
|
267
|
+
return refuse('This process ancestry could not be verified.');
|
|
268
|
+
if (finding.pid <= 1 || guarded.has(finding.pid))
|
|
269
|
+
return refuse('That process is part of what runs this session.');
|
|
270
|
+
let current;
|
|
271
|
+
try {
|
|
272
|
+
const read = await dependencies.readOne(finding.pid);
|
|
273
|
+
current = read ? cleanProcess(read) : null;
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
return refuse('The process could not be read again.');
|
|
277
|
+
}
|
|
278
|
+
if (!current)
|
|
279
|
+
return refuse('The process already exited.');
|
|
280
|
+
if (current.pid !== finding.pid || current.startedAt === null || current.startedAt !== finding.startedAt || current.command !== finding.command) {
|
|
281
|
+
return refuse('A different program now has that process number. Nothing was sent.');
|
|
282
|
+
}
|
|
283
|
+
if ((0, classify_1.agentHost)(current.command))
|
|
284
|
+
return refuse('That process is an agent session.');
|
|
285
|
+
// The only signal site. No await sits between the identity check and this call.
|
|
286
|
+
try {
|
|
287
|
+
await dependencies.signal(finding.pid, 'SIGTERM');
|
|
288
|
+
}
|
|
289
|
+
catch {
|
|
290
|
+
return { state, outcome: 'signal_failed', reason: 'The stop request could not be sent. Nothing stronger was tried.' };
|
|
291
|
+
}
|
|
292
|
+
const sent = { ...finding, status: 'stop_sent', stopSentAt: dependencies.now() };
|
|
293
|
+
return { state: { ...state, findings: { ...state.findings, [key]: sent } }, outcome: 'sent', reason: 'Asked it to stop.' };
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* The one authoritative state for a worker: samples and stop requests go
|
|
297
|
+
* through here, so two taps on the same finding send one signal and a sample
|
|
298
|
+
* that lands while a stop is in flight does not lose its record.
|
|
299
|
+
*/
|
|
300
|
+
class GrowthWatch {
|
|
301
|
+
dependencies;
|
|
302
|
+
config;
|
|
303
|
+
current;
|
|
304
|
+
stopping = new Set();
|
|
305
|
+
constructor(dependencies, config = exports.DEFAULT_GROWTH, state = (0, exports.emptyGrowthState)()) {
|
|
306
|
+
this.dependencies = dependencies;
|
|
307
|
+
this.config = config;
|
|
308
|
+
this.current = state;
|
|
309
|
+
}
|
|
310
|
+
get state() { return this.current; }
|
|
311
|
+
step(sample) {
|
|
312
|
+
const result = stepGrowth(this.current, sample, this.config);
|
|
313
|
+
this.current = result.state;
|
|
314
|
+
return result;
|
|
315
|
+
}
|
|
316
|
+
async stop(key, shown) {
|
|
317
|
+
// Claimed before the first await: a second request for the same finding never reaches the signal.
|
|
318
|
+
if (this.stopping.has(key))
|
|
319
|
+
return { outcome: 'refused', reason: 'It is already being asked to stop.' };
|
|
320
|
+
this.stopping.add(key);
|
|
321
|
+
try {
|
|
322
|
+
const result = await stopNamed(this.current, key, this.dependencies, shown);
|
|
323
|
+
if (result.outcome === 'sent') {
|
|
324
|
+
const sent = result.state.findings[key];
|
|
325
|
+
// Samples may have advanced the state meanwhile. A process that already left the list is not put back on it.
|
|
326
|
+
if (Object.prototype.hasOwnProperty.call(this.current.findings, key)) {
|
|
327
|
+
this.current = { ...this.current, findings: { ...this.current.findings, [key]: { ...this.current.findings[key], status: 'stop_sent', stopSentAt: sent.stopSentAt } } };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return { outcome: result.outcome, reason: result.reason };
|
|
331
|
+
}
|
|
332
|
+
finally {
|
|
333
|
+
this.stopping.delete(key);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
exports.GrowthWatch = GrowthWatch;
|
package/dist/src/idle/hook.js
CHANGED
|
@@ -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>;
|