diff --git a/.dsh-version.json b/.dsh-version.json index 855c225..d05eb6d 100644 --- a/.dsh-version.json +++ b/.dsh-version.json @@ -177,6 +177,27 @@ "NOTHING is vendored, downloaded or installed: the daemon is the user's own service, and this package ships the HTTP client, one argv for `ollama --version`, and the arithmetic" ] }, + "dsh-huggingface": { + "version": "0.1.0-alpha.1", + "rows": [ + "huggingface" + ], + "rowOverrides": [], + "role": "The Hugging Face Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk - `hf_status` (the CLI and its version, the cache root with the variable that chose it, every repo with BYTE-EXACT sizes, and the split between complete repos and metadata-only stubs), `hf_search` (models / datasets / spaces, ranked), `hf_repo` (one repo's licence, gated flag, architecture, parameter count, weight with the MEASURE named, the files each consumer would fetch, and whether the local copy is complete / stub / stale / absent), `hf_cache` (list without any CLI, plus verify / prune / rm, where an UNCONFIRMED removal is the CLI's own --dry-run, rm needs the repo id repeated back and prune the word \"prune\") and `hf_download` (the only bytes-moving call: the weight first, a byte ceiling it will not cross, the repo id repeated back, and the bytes the cache actually GAINED) - plus two bundled skills (the CLI, the cache layout) whose examples the package check parses. The cache scan walks the directory tree because the CLI's own JSON answers \"17.9G\" and \"3 months ago\", and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a config.json and nothing else. Auth is reported as a PRESENCE only: no token is ever read, echoed or accepted as an argument. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket. See packages/dsh-huggingface/README.md.", + "uses": [ + "@deepseek-ai/dsh-tools (the registry the five tools are registered into)", + "@deepseek-ai/dsh-skill (ctx.skills, resolved lazily; the two skills are also copied into $DSH_HOME/skills by both installers)", + "the user's own `hf` CLI from huggingface_hub (`DSH_HF_CLI` pins a binary PATH does not carry), argv-only with a deadline and a byte cap per stream" + ], + "requires": [ + "`hf` installed for everything except the cache scan, `hf_cache` action list and `hf_repo` in offline mode - `hf_status` names the install line when it is missing", + "a person to accept a gated repo's licence in a browser before any token can fetch it - `hf_repo` names the page", + "`HF_HUB_OFFLINE=1` / `TRANSFORMERS_OFFLINE=1` is HONOURED: search, info and download refuse before a process starts" + ], + "vendors": [ + "NOTHING is vendored, downloaded or installed: `hf` is the user's own program, the cache is the user's own directory, and this package ships the cache scanner, the argv builder and the JSON reader" + ] + }, "dsh-comfyui": { "version": "0.1.0-alpha.1", "rows": [ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6203bbf..f8a22b0 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,6 +69,7 @@ disable/replace a core row **in its own layer** — a later layer wins per row. | `dsh-docker` | `docker` | Docker (or Podman) as a surface: nine `docker_*` tools over the machine's CLI, a `docker_start` that launches Docker Desktop or a podman machine and waits for its **daemon**, and a Docker tab of containers and images. argv-only and validated; no `exec`, no `system prune`, no free-form `run` | | `dsh-sql-server` | `sqlserver` | SQL Server as a surface: seven `sql_*` tools over a container this row owns (2022 image, 1433, named volume) or the `sqlcmd` on PATH, keeping apart a **server** / a **client** / a **listening port** / the machine-wide **ODBC driver** an application connects with; `start` waits until the server ANSWERS a statement, and a dump loads through `-i` (stdin silently dropped rows) with BOM-aware code pages and an optional filter for the dump's own `CREATE DATABASE` header. Host-only, no route, no browser half | | `dsh-ollama` | `ollama` | Ollama as a **measured** surface: five `ollama_*` tools over the machine's own daemon — status (models on disk, what is loaded, and `ollama serve` when nothing answers), one bounded inference with the daemon's token counts and nanosecond durations, a benchmark that **refuses fewer than 3 runs** and reports a median with spread (cold vs warm stated at the first token), models with pull/delete confirmed by repeating the tag, embeddings with cosine similarity — three skills whose examples a check parses, and a **loopback fence** that refuses a daemon on another machine before any request. Host-only, no route, no browser half | +| `dsh-huggingface` | `huggingface` | the Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_status` resolves the cache root through the library's own precedence (`HF_HUB_CACHE` > `HUGGINGFACE_HUB_CACHE` > `HF_HOME/hub` > default, with `TRANSFORMERS_CACHE` flagged deprecated) and counts every repo with BYTE-EXACT sizes, separating complete repos from the metadata-only stubs that look identical in a listing; `hf_repo` answers one repo's licence, gated flag, architecture, parameter count, weight (the Hub's `used_storage`, labelled as the measure it is, because this CLI line reports no per-file sizes), which files each consumer would fetch, and whether the local copy is complete / a stub / stale by revision / absent; `hf_cache` lists, verifies, prunes and removes — an UNCONFIRMED removal is the CLI's own `--dry-run`, `rm` needs the repo id repeated back and `prune` the word "prune"; `hf_download` reports the weight, refuses over a byte ceiling, needs the id repeated back, and answers with the bytes the cache actually GAINED. The cache scan is of the directory tree because the CLI's JSON answers `"size": "17.9G"` and `"last_accessed": "3 months ago"`, and it is what makes the finding reportable: MEASURED on this machine, 42 of 49 cached repos are a `config.json` and nothing else. Two skills (`huggingface-hub`, `huggingface-cache`) whose examples the package check parses. Host-only: one row, no route, no browser half, zero npm dependencies, no bundled engine, no socket, and no token ever read | | `dsh-proto-lab` | `proto-lab` | the **prototyping lab**: five `lab_*` tools write a run into the lab root (`~/Desktop/vncode-lab/runs///` on a machine with a Desktop, `/lab` otherwise, `DSH_PROTO_LAB_ROOT` to move it; gitignored — the bundle ships the generator, not the runs), a runtime registry (`p5js`, `openframeworks`, and a template for the third) whose every module the checks drive, a committed example library beside each skill, an offline-vendored p5.js, and verification as an explicit ladder — `t0-structure` → `t4-measure` — that always names the tier it reached | | `dsh-browser` | `browser` | web surface: the host fetches and renders a page in a disposable sandboxed browser (**currently disabled by the master**) | | `dsh-themes` | `themes` | extra palettes (Nord, Monokai, Hacker, Cyber), header controls, branding, account-menu trimming | diff --git a/README.md b/README.md index 027bb71..9e445a5 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ way and what it touches. The exact versions are in | [`dsh-editor`](packages/dsh-editor/README.md) | Text and code tabs over a vendored CodeMirror 6, with save/create and a Markdown preview. Every extension is mapped through a guard, so an older engine opens the document unhighlighted instead of killing the tab. It also backs the `.scd`, diagram-source and research-document editors. | | [`dsh-frontend-craft`](packages/dsh-frontend-craft/README.md) | Front-end design craft: Impeccable's Apache-2.0 corpus vendored at a pinned commit, plus its 61-rule detector built to WebAssembly inside the package. Five `fe_*` tools include `fe_render`, which renders a page in headless Chrome or Edge and measures contrast, tap targets and overflow. There is no `npx impeccable`, no engine download and no network. A Frontend tab shows findings, artifacts and the direction round. | | [`dsh-gittree`](packages/dsh-gittree/README.md) | A read-only History tab: the workspace commits as a graph rail with lanes, merges and PR chips. Each commit lists the files it touched. It never runs a write. | +| [`dsh-huggingface`](packages/dsh-huggingface/README.md) | The Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools over the machine's own `hf` CLI and the cache on disk. `hf_repo` gives one repo's licence, gated flag, weight (the Hub's `used_storage`, labelled as such) and whether this disk already has it — complete, metadata-only, stale or absent; `hf_status` counts the stubs that look cached and cannot load; `hf_cache` verifies and reclaims, with an unconfirmed removal being the CLI's own dry run; `hf_download` reports the weight, refuses over a ceiling, and needs the repo id repeated back. Two skills teach the CLI and the cache layout. Host-only, zero npm dependencies, no bundled engine. | | [`dsh-image`](packages/dsh-image/README.md) | An image viewer that fits, zooms and pans, and reads the source pixel under the pointer. It opens from the Files tab and the Media panel. | | [`dsh-image-upscale`](packages/dsh-image-upscale/README.md) | Four `upscale_*` tools over Real-ESRGAN, through the Python and torch this machine already has. It writes a NEW file and never the original, a manifest batch is a dry run by default, and the weight fetch refuses without `confirm`. Host-only, with no engine bundled. | | [`dsh-media`](packages/dsh-media/README.md) | The pack ffmpeg owner: `media_probe`, `media_run` and `media_frames` over a pinned, SHA-256-verified ffmpeg copy. It also serves the Range routes the video tab streams through. No other package ships ffmpeg. | diff --git a/assets/banner.html b/assets/banner.html new file mode 100644 index 0000000..f8ba3d9 --- /dev/null +++ b/assets/banner.html @@ -0,0 +1,57 @@ + + + + + vncode banner + + + +
+
+
+

VNCODE · ADE

+

35 plugins, 59 skills.

+

Node application.

+

PDF, OCR, diagrams, media, lab, editor
docker, wsl, research, huggingface, skills, themes

+
+ + diff --git a/assets/vncode-banner6.png b/assets/vncode-banner6.png index 6bd660c..851ff63 100644 Binary files a/assets/vncode-banner6.png and b/assets/vncode-banner6.png differ diff --git a/packages/dsh-huggingface/README.md b/packages/dsh-huggingface/README.md new file mode 100644 index 0000000..61ea7a3 --- /dev/null +++ b/packages/dsh-huggingface/README.md @@ -0,0 +1,107 @@ +# dsh-huggingface (alpha.1) + +**The Hub as a surface the agent can interrogate before it downloads.** Five +`hf_*` tools over the machine's own `hf` CLI and the cache on this disk: +`hf_status`, `hf_search`, `hf_repo`, `hf_cache`, `hf_download`. Plus the two +skills that teach the CLI and the cache layout. + +Why it earns a row: a Hub repo is a directory like any other, so a listing says +`models--lukey03--Qwen3.5-9B-abliterated` and stops. It does not say that the +entry is 16.7 GB, that **42 of the 49 entries on this machine are a `config.json` +and nothing else**, that a repo's licence is gated, or that the cached copy sits +three commits behind the Hub. Those are exactly the facts a person needs before +18 GB of bandwidth — and nothing in the pack read them. The CLI's own +`cache ls --json` answers in human strings (`"size": "17.9G"`, +`"last_accessed": "3 months ago"`), which is why the scan here walks the +directory tree. + +Measured on the machine that wrote this: `hf` is **1.26.1**, the cache holds +**49 repos / 19.8 GB**, and **7 are complete** while **42 are metadata only**. + +## What it adds + +- **`hf_status`** — the CLI and its version, the cache root and **which variable + chose it** (`HF_HUB_CACHE` > `HUGGINGFACE_HUB_CACHE` > `HF_HOME/hub` > + default, with the deprecated `TRANSFORMERS_CACHE` flagged), every repo with + byte-exact size, and the split between complete repos and the metadata-only + stubs that look identical in a listing. Auth is a **presence** only — the token + is never read, echoed or logged. One process (`hf --version`), no network. +- **`hf_search`** — models / datasets / spaces by query, author, tag and sort, + parsed from `--json`. Refused with a code on a machine in offline mode, before + any process starts. +- **`hf_repo`** — the decision, one repo at a time: licence, gated flag and the + page that accepts it, architecture and parameter count, the repo weight **with + the measure named**, which files each consumer would fetch (transformers, + sentence-transformers, diffusers, GGUF quants, ONNX), and the local verdict — + `complete`, `stub`, `stale` (cached revision vs the Hub's current `sha`) or + `absent`. +- **`hf_cache`** — `list` (no CLI, no network), `verify`, `prune`, `rm`. An + **unconfirmed removal is the CLI's own `--dry-run`**, so the answer is a real + preview with the bytes it would cost; `rm` needs the repo id repeated back and + `prune` needs the word `prune`. +- **`hf_download`** — the only bytes-moving call: the Hub's weight first, a + ceiling it will not cross (8 GiB default), then `confirm: ""`, then + the fetch — answered with **the bytes the cache actually gained**, measured by + rescanning the repo directory rather than trusting a transfer log. + +## The three findings it is engineered around + +**A blob is named by its hash.** In a canonical cache, `blobs/9f3c…` has no +extension, so a weight test by extension reports every repo weightless. The +names that say what a file IS live in `snapshots//` — and that is where a +copy is real. + +**Both sides of the layout hold the same bytes.** Summing `blobs` *and* +`snapshots` doubles a cache. Exactly one side is summed — and the side that +counts is `snapshots` on a machine where Xet or Windows wrote copies and `blobs/` +is empty, which is the layout measured here (a 418 MB repo with a 0-byte blobs +directory). + +**This CLI line gives no per-file sizes.** `--expand siblings` carries +`rfilename` only, and there is no `--blobs` flag, so the repo weight comes from +`used_storage` and is labelled as such. A narrowed selection cannot be measured +at all: the plan says so instead of inventing a number, and the ceiling is +applied only to a measured size. + +## How it plugs in + +| Piece | Value | +|---|---| +| row / tools | `huggingface` / `hf_status`, `hf_search`, `hf_repo`, `hf_cache`, `hf_download` | +| host | one row, no route, no browser half (`package.json` declares no `dsh.client`) | +| engine | the user's own `hf` (huggingface_hub); `DSH_HF_CLI` pins a binary PATH does not carry | +| transport | argv-only child processes, a deadline per call, a byte cap per stream; **no socket in this package** | +| state | none on disk; only the resolved CLI is cached per boot | +| skills | `huggingface-hub`, `huggingface-cache` - registered at boot, copied into `$DSH_HOME/skills` by both installers | +| credentials | none read: `HF_TOKEN` / the stored token file are reported as *present*, never read back | + +## Limits + +| | | +|---|---| +| `hf` | must be installed for everything except `hf_status`'s cache scan, `hf_cache` action "list" and `hf_repo` in offline mode | +| sizes | per-file sizes are not available on this CLI line; the repo total is `used_storage` | +| downloads | `hf_download` never accepts a token and never runs `hf update`; a gated repo must be accepted in a browser first | +| network | only a call the caller asked for reaches it; `HF_HUB_OFFLINE=1` is honoured and refuses before a process starts | +| UI | none - a tool surface plus skills, not a second conversation | + +## Verify + +```sh +node checks/check-huggingface-node.mjs # 217 checks, no network, no real cache touched +``` + +The cache is a fixture tree in a temp directory built to the real layout, +including the two cases that make a naive size rule wrong. The CLI is a fake +runner that **records the exact argv**, which is how the `-y` / `--dry-run` +decisions and the "no download over the ceiling" rule are asserted rather than +hoped for; a download in the check writes real bytes, so `addedBytes` is measured. + +The pack-wide checks still own the row: `check-node-routes.mjs` (the row, the +manifest, the skill registration), `check-no-secrets.mjs`, and the root +README/ARCHITECTURE rows. + +## Install + +Both installers pick it up from `packages/`; as a new bundle the profile learns +it once, then a restart of `npx @deepseek-ai/dsh web` and a hard refresh. diff --git a/packages/dsh-huggingface/checks/check-huggingface-node.mjs b/packages/dsh-huggingface/checks/check-huggingface-node.mjs new file mode 100644 index 0000000..e2147f8 --- /dev/null +++ b/packages/dsh-huggingface/checks/check-huggingface-node.mjs @@ -0,0 +1,579 @@ +// check-huggingface-node.mjs - dsh-huggingface's own contract, driven end to end. +// +// Nothing here needs the network and nothing here can delete a real cache: +// +// - the CACHE is a fixture tree in a temp directory, built to the layout the +// library actually uses (blobs + snapshots + refs), including the two cases +// that make a naive size rule wrong - a blobs cache whose bytes must NOT be +// added to the snapshot copies, and a cache with NO blobs at all (the Xet / +// Windows-copy case measured on the machine that wrote this); +// - the CLI is a FAKE runner: it records the exact argv and answers canned +// JSON, which is the only way to assert the `-y` / `--dry-run` decision +// without touching somebody's 17 GB download; +// - the CONFIRMATION rules are asserted where they matter: a download over its +// ceiling runs NO download, and an unconfirmed removal is a dry run. +// +// Run: node checks/check-huggingface-node.mjs +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { HfError, classifyFailure } from '../lib/errors.js' +import { offlineOf, resolveCacheRoot, tokenPresence } from '../lib/paths.js' +import { describeRepoDir, repoDirName, scanCache, splitRepoDir } from '../lib/cache.js' +import { CAPS, validateCache, validateDownload, validateRepo, validateSearch } from '../lib/validate.js' +import { + buildCacheArgv, + buildDownloadArgv, + buildInfoArgv, + buildSearchArgv, + consumersOf, + globToRegExp, + normalizeInfo, + parseDownloadAnswer, + projectDownload, + selected, +} from '../lib/hf.js' +import { CLI_CANDIDATES, parseVersion, resolveCli } from '../lib/cli.js' +import { buildTools, formatBytes, formatParamCount } from '../lib/tools.js' +import { SKILL_FILES, apply, createDeps, parseSkillFile, PLUGIN_VERSION, __internals } from '../lib/index.js' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const packageRoot = path.join(here, '..') +const manifest = JSON.parse(readFileSync(path.join(packageRoot, 'package.json'), 'utf8')) +const SHA_A = 'a'.repeat(40) +const SHA_B = 'b'.repeat(40) + +let checks = 0 +let failures = 0 +let skipped = 0 +const check = (label, actual, expected) => { + checks += 1 + const ok = expected === undefined ? Boolean(actual) : actual === expected + if (!ok) failures += 1 + console.log((ok ? 'ok ' : 'FAIL ') + label.padEnd(62) + (expected === undefined ? '' : ' ' + JSON.stringify(actual))) + return ok +} +const skip = (label, reason) => { + skipped += 1 + console.log('skip ' + label.padEnd(62) + ' (' + reason + ')') +} + +// --------------------------------------------------------------------------- +// The fixture cache +// --------------------------------------------------------------------------- +/** Write a file, creating its directory. */ +function put(file, contents) { + mkdirSync(path.dirname(file), { recursive: true }) + writeFileSync(file, contents) +} + +/** + * Build a cache that has all three layouts this row must survive: + * - acme/alpha: blobs AND a snapshot copy of the same bytes (must not double) + * - acme/stub: one config.json, no weight file (the 40-of-50 case) + * - acme/data: a DATASET whose bytes are a parquet, not a weight + * - acme/beta: a complete model at an OLD revision (staleness) + */ +function makeCache() { + const root = mkdtempSync(path.join(os.tmpdir(), 'dsh-hf-cache-')) + // acme/alpha - canonical blobs layout, plus a snapshot copy that must not be added + const alpha = path.join(root, 'models--acme--alpha') + put(path.join(alpha, 'refs', 'main'), SHA_A + '\n') + put(path.join(alpha, 'blobs', 'f'.repeat(64)), Buffer.alloc(3000, 1)) + put(path.join(alpha, 'blobs', 'e'.repeat(64)), Buffer.alloc(100, 2)) + put(path.join(alpha, 'snapshots', SHA_A, 'model.safetensors'), Buffer.alloc(3000, 1)) + put(path.join(alpha, 'snapshots', SHA_A, 'config.json'), Buffer.alloc(100, 2)) + // acme/stub - metadata only + const stub = path.join(root, 'models--acme--stub') + put(path.join(stub, 'refs', 'main'), SHA_B + '\n') + put(path.join(stub, 'snapshots', SHA_B, 'config.json'), '{"model_type":"qwen3"}') + // acme/data - dataset, no weights by definition + const data = path.join(root, 'datasets--acme--data') + put(path.join(data, 'snapshots', 'c'.repeat(40), 'train.parquet'), Buffer.alloc(2_000_000, 3)) + // acme/beta - complete model, old revision + const beta = path.join(root, 'models--acme--beta') + put(path.join(beta, 'refs', 'main'), 'd'.repeat(40) + '\n') + put(path.join(beta, 'snapshots', 'd'.repeat(40), 'model.safetensors'), Buffer.alloc(5000, 4)) + return root +} + +// --------------------------------------------------------------------------- +// The manifest +// --------------------------------------------------------------------------- +check('the package is a dsh bundle with a patch layer', manifest.dsh && manifest.dsh.bundle && manifest.dsh.bundle.patch, './cordis.patch.yml') +check('the row owns no browser half', manifest.dsh.client === undefined, true) +check('the row has no npm dependency', manifest.dependencies === undefined && manifest.peerDependencies === undefined, true) +check('the version is the alpha this check knows', manifest.version, PLUGIN_VERSION) +check('the skills and checks ship in the package', ['lib', 'skills', 'checks', 'cordis.patch.yml'].every((entry) => manifest.files.includes(entry)), true) + +// --------------------------------------------------------------------------- +// Environment resolution +// --------------------------------------------------------------------------- +const home = path.join(os.tmpdir(), 'fake-home') +check('no variable means the default cache', resolveCacheRoot({}, home).root, path.join(home, '.cache', 'huggingface', 'hub')) +check('...and says so', resolveCacheRoot({}, home).from, 'default') +check('HF_HOME puts the cache under it', resolveCacheRoot({ HF_HOME: '/big/hf' }, home).root, path.join(path.resolve('/big/hf'), 'hub')) +check('HF_HUB_CACHE wins over HF_HOME', resolveCacheRoot({ HF_HUB_CACHE: '/c1', HF_HOME: '/big/hf' }, home).root, path.resolve('/c1')) +check('HUGGINGFACE_HUB_CACHE is the older name', resolveCacheRoot({ HUGGINGFACE_HUB_CACHE: '/c2', HF_HOME: '/big' }, home).from, 'HUGGINGFACE_HUB_CACHE') +check('an empty variable is not a path', resolveCacheRoot({ HF_HUB_CACHE: ' ' }, home).from, 'default') +check('TRANSFORMERS_CACHE is read last and marked deprecated', resolveCacheRoot({ TRANSFORMERS_CACHE: '/old' }, home).deprecated, true) +check('offline is read from HF_HUB_OFFLINE', offlineOf({ HF_HUB_OFFLINE: '1' }), true) +check('...and from TRANSFORMERS_OFFLINE', offlineOf({ TRANSFORMERS_OFFLINE: 'true' }), true) +check('...and "0" is not offline', offlineOf({ HF_HUB_OFFLINE: '0' }), false) +check('a token is reported by PRESENCE only', tokenPresence({ HF_TOKEN: 'hf_secretvalue' }, false).source, 'HF_TOKEN') +check('...and never carries the value', JSON.stringify(tokenPresence({ HF_TOKEN: 'hf_secretvalue' }, false)).includes('secretvalue'), false) +check('a stored token file counts as present', tokenPresence({}, true).present, true) +check('no token at all', tokenPresence({}, false).present, false) + +// --------------------------------------------------------------------------- +// The cache scan +// --------------------------------------------------------------------------- +const root = makeCache() +const scan = scanCache(root) +check('the scan finds every repo', scan.counts.repos, 4) +check('...and marks the directory as present', scan.exists, true) +check('the count splits complete from metadata-only', scan.counts.stubs, 1) +check('...with the rest complete', scan.counts.complete, 3) +check('types are counted separately', scan.counts.byType.dataset, 1) +check('splitRepoDir reads a model directory', splitRepoDir('models--acme--alpha').id, 'acme/alpha') +check('splitRepoDir reads a dataset directory', splitRepoDir('datasets--acme--data').type, 'dataset') +check('a directory that is not a repo is refused', splitRepoDir('random-folder'), null) +check('repoDirName is the inverse', repoDirName('model', 'acme/alpha'), 'models--acme--alpha') + +const alpha = describeRepoDir(root, 'models--acme--alpha') +check('a blobs cache is measured on the blobs side', alpha.layout, 'blobs') +check('...and the snapshot copies are NOT added to it', alpha.bytes, 3100) +check('...so the double-counted number is not what is reported', alpha.bytes !== 6200, true) +check('a hash-named blob still counts as a weight (via the snapshot name)', alpha.weights, true) +check('a complete repo is not a stub', alpha.stub, false) +check('the revision comes from refs/main', alpha.revision, SHA_A) + +const noBlobs = describeRepoDir(root, 'models--acme--beta') +check('a cache with no blobs is measured on the snapshots side', noBlobs.layout, 'snapshots') +check('...and its bytes are the copies\'', noBlobs.bytes, 5000) + +const stub = describeRepoDir(root, 'models--acme--stub') +check('a metadata-only model is a stub', stub.stub, true) +check('...and says it has no weight file', stub.weights, false) + +const dataset = describeRepoDir(root, 'datasets--acme--data') +check('a dataset is not called weightless at 2 MB', dataset.stub, false) +check('...although it has no weight file', dataset.weights, false) +check('a dataset is still a stub when it is only metadata', describeRepoDir(root, 'datasets--acme--data').stub === false, true) + +const filtered = scanCache(root, { type: 'model' }) +check('a type filter drops the others', filtered.counts.repos, 3) +const byName = scanCache(root, { filter: 'alph' }) +check('a text filter selects by id', byName.repos.length === 1 && byName.repos[0].id, 'acme/alpha') +const limited = scanCache(root, { limit: 2 }) +check('a limit shortens the list', limited.repos.length, 2) +check('...and is reported as limited', limited.limited, true) +check('a missing cache root is an answer, not an error', scanCache(path.join(root, 'nope')).exists, false) + +// --------------------------------------------------------------------------- +// The CLI: the version trap, and how the binary is found +// --------------------------------------------------------------------------- +const stderrHint = 'Hint: A new version of huggingface_hub (2.5.0) is available! You are using version 1.26.1.\nTo update, run: hf update' +check('the version is read from STDOUT, not the upgrade hint', parseVersion('1.26.1\n', stderrHint), '1.26.1') +check('...so the "available" version is never reported as installed', parseVersion('1.26.1\n', stderrHint) !== '2.5.0', true) +check('a stream with no stdout falls back to stderr', parseVersion('', 'huggingface_hub version: 0.20.3'), '0.20.3') +check('the upgrade hint alone yields NO version', parseVersion('', stderrHint), '') +check('the candidates are the modern name first', CLI_CANDIDATES[0], 'hf') +check('classifyFailure: gated before a bare 403', classifyFailure('403 Forbidden: access to model is restricted', 403), 'GATED') +check('classifyFailure: dataset 404', classifyFailure('404 Client Error: Repository Not Found', 404), 'NOT_FOUND') +check('classifyFailure: auth', classifyFailure('Invalid credentials in Authorization header', 401), 'AUTH') +check('classifyFailure: rate limit', classifyFailure('429 Too Many Requests', 429), 'RATE_LIMIT') +check('classifyFailure: no space', classifyFailure('OSError: [Errno 28] No space left on device', 1), 'DISK_FULL') +check('classifyFailure: network', classifyFailure('getaddrinfo failed for huggingface.co', 1), 'NETWORK') +check('classifyFailure: anything else', classifyFailure('some new message', 1), 'OUTPUT') + +const missing = await resolveCli({ env: {}, cache: {}, runner: async () => ({ status: null, stdout: '', stderr: '', error: 'ENOENT' }) }) +check('no CLI is a result, not an exception', missing.bin, null) +check('...and every candidate was tried', missing.tried.length, 2) +const pinnedMiss = await resolveCli({ env: { DSH_HF_CLI: '/opt/hf' }, cache: {}, runner: async (argv) => ({ status: argv[0] === '/opt/hf' ? 0 : null, stdout: '9.9.9', stderr: '' }) }) +check('DSH_HF_CLI pins a binary PATH does not carry', pinnedMiss.bin + ' ' + pinnedMiss.version, '/opt/hf 9.9.9') +check('...and is named as the source', pinnedMiss.source, 'DSH_HF_CLI') + +// --------------------------------------------------------------------------- +// argv: the flags that keep a removal from hanging or acting unasked +// --------------------------------------------------------------------------- +const bin = 'hf' +check('search argv asks for JSON last', buildSearchArgv(bin, { group: 'models', query: 'qwen3', limit: 5, author: '', filters: [], sort: 'downloads' }).slice(-2).join(' '), '--format json') +check('search argv carries the query', buildSearchArgv(bin, { group: 'models', query: 'qwen3', limit: 5, author: '', filters: [], sort: '' }).includes('qwen3'), true) +check('info argv expands the fields this row reads', buildInfoArgv(bin, { group: 'models', repo: 'acme/alpha' }).join(',').includes('siblings'), true) +check('an UNCONFIRMED rm is the CLI\'s own dry run', buildCacheArgv(bin, { action: 'rm', type: 'model', repo: 'acme/alpha', confirm: '', revision: '' }).includes('--dry-run'), true) +check('...and does NOT pass -y', buildCacheArgv(bin, { action: 'rm', type: 'model', repo: 'acme/alpha', confirm: '', revision: '' }).includes('--yes'), false) +check('a confirmed rm passes -y (stdin is closed, so a prompt would hang)', buildCacheArgv(bin, { action: 'rm', type: 'model', repo: 'acme/alpha', confirm: 'acme/alpha', revision: '' }).includes('--yes'), true) +check('a rm target is /', buildCacheArgv(bin, { action: 'rm', type: 'model', repo: 'acme/alpha', confirm: 'acme/alpha', revision: '' })[3], 'model/acme/alpha') +check('prune is confirmed by the word "prune"', buildCacheArgv(bin, { action: 'prune', confirm: 'prune' }).includes('--yes'), true) +check('...and is a dry run otherwise', buildCacheArgv(bin, { action: 'prune', confirm: '' }).includes('--dry-run'), true) +check('verify passes the repo type', buildCacheArgv(bin, { action: 'verify', type: 'dataset', repo: 'acme/data', revision: '', confirm: '' }).join(' '), 'hf cache verify acme/data --type dataset --format json') +check('download argv never carries a token', buildDownloadArgv(bin, { repo: 'acme/alpha', type: 'model', files: ['config.json'], include: ['*.safetensors'], exclude: [], revision: '', maxBytes: 1, confirm: 'acme/alpha' }).some((entry) => entry === '--token'), false) + +// --------------------------------------------------------------------------- +// Patterns and projection +// --------------------------------------------------------------------------- +check('* stays inside one segment', globToRegExp('*.safetensors').test('sub/x.safetensors'), false) +check('...and matches the bare name', globToRegExp('*.safetensors').test('x.safetensors'), true) +check('** crosses segments', globToRegExp('**/*.safetensors').test('sub/x.safetensors'), true) +check('an exclude always wins', selected('model.safetensors', ['*.safetensors'], ['model.*']), false) +check('an empty include means everything', selected('whatever.bin', [], []), true) + +const infoFixture = { + id: 'acme/alpha', + sha: SHA_A, + gated: 'manual', + private: false, + downloads: 12345, + likes: 678, + pipeline_tag: 'text-generation', + library_name: 'transformers', + lastModified: '2026-11-01T10:00:00.000Z', + cardData: { license: 'apache-2.0' }, + tags: ['license:apache-2.0', 'text-generation'], + safetensors: { total: 8_800_000_000 }, + config: { architectures: ['Qwen3ForCausalLM'], model_type: 'qwen3', max_position_embeddings: 32768 }, + siblings: [ + { rfilename: 'config.json', size: 800 }, + { rfilename: 'tokenizer.json', size: 11_000 }, + { rfilename: 'model.safetensors', size: 17_000_000 }, + { rfilename: 'README.md' }, + ], +} +const info = normalizeInfo(infoFixture, { repo: 'acme/alpha', type: 'model', group: 'models' }) +check('normalizeInfo reads the licence', info.licence, 'apache-2.0') +check('...the gated status', info.gated, 'manual') +check('...the parameter count', info.params, 8_800_000_000) +check('...the architecture', info.architectures[0], 'Qwen3ForCausalLM') +check('...the context length', info.contextLength, 32768) +check('...and the sum of the sizes it was given', info.totalBytes, 17_011_800) +check('a file with no size makes the total a LOWER BOUND', info.sizesComplete, false) +check('...and is counted as unknown', info.unknownSizes, 1) +check('a licence tag is used when the card has none', normalizeInfo({ tags: ['license:mit'] }, { repo: 'a/b', type: 'model' }).licence, 'mit') + +// The MEASURED shape of this CLI line: no per-file sizes, only used_storage. +const hubSized = normalizeInfo( + { ...infoFixture, siblings: infoFixture.siblings.map((entry) => ({ rfilename: entry.rfilename })), used_storage: 4_105_073_268 }, + { repo: 'acme/alpha', type: 'model' }, +) +check('used_storage is the repo total when no file size is given', hubSized.totalBytes, 4_105_073_268) +check('...and the measure is named', hubSized.totalSource, 'hub storage') +check('...with per-file sizes reported as absent', hubSized.sizesComplete, false) +const hubPlan = projectDownload(hubSized, { files: [], include: [], exclude: [], maxBytes: 1 }) +check('a whole-repo selection is measured by used_storage', hubPlan.bytes, 4_105_073_268) +check('...labelled as the repo measure', hubPlan.measured, 'repo') +check('...and counts as measured', hubPlan.complete, true) +const partialPlan = projectDownload(hubSized, { files: [], include: ['*.safetensors'], exclude: [], maxBytes: 1 }) +check('a partial selection with no file sizes is NOT measured', partialPlan.bytes, null) +check('...and says so rather than inventing a number', partialPlan.measured, 'unknown') + +const plan = projectDownload(info, { files: [], include: ['*.safetensors'], exclude: [], maxBytes: 1 }) +check('the projection filters to the include patterns', plan.files.join(','), 'model.safetensors') +check('...and sums exactly those bytes', plan.bytes, 17_000_000) +check('...reporting a known total as complete', plan.complete, true) +const everything = projectDownload(info, { files: [], include: [], exclude: [], maxBytes: 1 }) +check('no pattern means the whole repo', everything.files.length, 4) +check('...which is a lower bound here', everything.complete, false) + +const consumers = consumersOf(info.files) +check('a transformers consumer is detected', consumers.some((entry) => entry.consumer === 'transformers'), true) +check('...and it names the config first', consumers[0].files.includes('config.json'), true) +check('gguf quants are their own consumer', consumersOf([{ name: 'a-Q4_K_M.gguf' }, { name: 'a-Q8_0.gguf' }]).some((entry) => entry.consumer === 'llama.cpp / Ollama'), true) +check('a repo with no consumer match says nothing', consumersOf([{ name: 'train.parquet' }]).length, 0) + +check('a download answer as an array', parseDownloadAnswer(['a.json']).shape, 'array') +check('...as an object', parseDownloadAnswer({ downloaded: ['b.json'] }).paths[0], 'b.json') +check('...as loose lines', parseDownloadAnswer({ lines: ['c.json'] }).paths[0], 'c.json') + +// --------------------------------------------------------------------------- +// Validation: refusals, never clamps +// --------------------------------------------------------------------------- +const rejects = (label, fn, code) => { + try { + fn() + check(label, 'no error', code) + } catch (error) { + check(label, error instanceof HfError ? error.code : 'wrong type: ' + error, code) + } +} +rejects('a local path is not a repo id', () => validateRepo({ repo: './local/model' }), 'BAD_INPUT') +rejects('a single name is not a repo id', () => validateRepo({ repo: 'gpt2' }), 'BAD_INPUT') +rejects('an unknown type is refused', () => validateRepo({ repo: 'a/b', type: 'widget' }), 'BAD_INPUT') +rejects('a limit of 500 is refused, not clamped', () => validateSearch({ limit: 500 }), 'BAD_INPUT') +rejects('an unknown sort is refused', () => validateSearch({ sort: 'popularity' }), 'BAD_INPUT') +rejects('a files entry with .. is refused', () => validateDownload({ repo: 'a/b', files: ['../../etc/passwd'] }), 'BAD_INPUT') +rejects('an absolute files entry is refused', () => validateDownload({ repo: 'a/b', files: ['/etc/passwd'] }), 'BAD_INPUT') +rejects('a maxBytes under 1 MiB is refused', () => validateDownload({ repo: 'a/b', maxBytes: 5 }), 'BAD_INPUT') +rejects('an unknown cache action is refused', () => validateCache({ action: 'burn' }), 'BAD_INPUT') +check('a valid repo normalises', validateRepo({ repo: ' acme/alpha ' }).repo, 'acme/alpha') +check('the default ceiling is 8 GiB', CAPS.maxDownloadBytes, 8 * 1024 ** 3) + +// --------------------------------------------------------------------------- +// The tools, end to end, against a fake CLI +// --------------------------------------------------------------------------- +/** + * A deps object whose runner records every argv. + * + * @param env - the environment the row sees. + * @param handlers - `(argv) => response | undefined`. + */ +function harness(env, handlers) { + const calls = [] + const runner = async (argv) => { + calls.push(argv.slice()) + const answer = handlers(argv) + if (answer === undefined) return { status: 0, stdout: '{}', stderr: '', timedOut: false } + return { status: 0, stdout: '', stderr: '', timedOut: false, ...answer } + } + const deps = createDeps({ logger: { info() {}, warn() {} } }, { env, runner, now: () => 0 }) + return { deps, calls, tools: buildTools(deps) } +} +const tool = (tools, name) => tools.find((entry) => entry.name === name) +const versionOk = { status: 0, stdout: '1.26.1\n', stderr: 'Hint: a new version (2.5.0) is available.' } + +// status: one process, no network +{ + const { calls, tools } = harness({ HF_HUB_CACHE: root }, () => versionOk) + const answer = await tool(tools, 'hf_status').execute({}) + check('hf_status reports the CLI', answer.view.cli.bin + ' ' + answer.view.cli.version, 'hf 1.26.1') + check('hf_status counts the fixture repos', answer.view.cache.counts.repos, 4) + check('hf_status separates the stub', answer.view.cache.counts.stubs, 1) + check('hf_status names the stub', answer.view.stubs[0].id, 'acme/stub') + check('hf_status made exactly ONE process call', calls.length, 1) + check('...and it was the version probe', calls[0].join(' '), 'hf --version') + check('hf_status is read-only over the cache', existsSync(path.join(root, 'models--acme--stub')), true) + check('...and reports auth as a presence, never a value', answer.view.auth.present, false) + check('...naming the login command when there is none', answer.text.includes('hf auth login'), true) +} + +// status with no CLI at all +{ + const { tools } = harness({ HF_HUB_CACHE: root }, () => ({ status: null, error: 'ENOENT' })) + const answer = await tool(tools, 'hf_status').execute({}) + check('with no CLI the cache scan still answers', answer.view.cache.counts.repos, 4) + check('...and the install line is named', answer.text.includes('pip install -U huggingface_hub'), true) +} + +// search +{ + const results = [ + { id: 'acme/alpha', downloads: 1234, likes: 56, lastModified: '2026-10-02T00:00:00Z', library_name: 'transformers', pipeline_tag: 'text-generation' }, + { id: 'acme/beta', downloads: 99, likes: 1, lastModified: '2026-09-01T00:00:00Z' }, + ] + const { calls, tools } = harness({}, () => ({ ...versionOk, status: 0, stdout: JSON.stringify(results) })) + const answer = await tool(tools, 'hf_search').execute({ query: 'alpha', limit: 2, sort: 'downloads' }) + check('hf_search returns the ids', answer.view.count, 2) + check('hf_search ranks a table by the columns asked for', answer.text.includes('acme/alpha'), true) + check('hf_search passes --search and --limit', calls[1].join(' ').includes('--search alpha') && calls[1].includes('--limit'), true) + + const offline = harness({ HF_HUB_OFFLINE: '1' }, () => versionOk) + const refused = await tool(offline.tools, 'hf_search').execute({ query: 'x' }) + check('offline search is refused with a code', refused.view.code, 'OFFLINE') + check('...and makes NO process call', offline.calls.length, 0) +} + +// repo: complete / absent / gated / offline +{ + const infoJson = JSON.stringify({ ...infoFixture, gated: false, sha: SHA_A }) + const { tools } = harness({ HF_HUB_CACHE: root }, (argv) => (argv[1] === 'models' && argv[2] === 'info' ? { ...versionOk, stdout: infoJson } : versionOk)) + const cached = await tool(tools, 'hf_repo').execute({ repo: 'acme/alpha' }) + check('hf_repo sees the local copy', cached.view.local.state, 'complete') + check('...with its bytes', cached.view.local.entry.bytes, 3100) + check('...and the Hub total', cached.view.repo.bytes, 17_011_800) + check('...and the consumer grouping', cached.view.consumers[0].consumer, 'transformers') + check('...and the lower-bound caveat in prose', cached.text.includes('LOWER BOUND'), true) + + const absent = await tool(tools, 'hf_repo').execute({ repo: 'acme/not-here' }) + check('hf_repo calls an uncached repo absent', absent.view.local.state, 'absent') + check('...and the prose says not cached', absent.text.includes('not cached'), true) + check('...and says nothing was downloaded', absent.text.includes('Nothing was downloaded') || absent.text.includes('hf_download'), true) + + const stale = await tool(tools, 'hf_repo').execute({ repo: 'acme/beta' }) + check('hf_repo detects a revision that moved', stale.view.local.state, 'stale') + check('...and names the Hub revision it differs from', stale.text.includes(SHA_A.slice(0, 12)), true) + + const gatedInfo = JSON.stringify({ ...infoFixture, gated: 'manual' }) + const gated = harness({ HF_HUB_CACHE: root }, (argv) => (argv[2] === 'info' ? { ...versionOk, stdout: gatedInfo } : versionOk)) + const gatedAnswer = await tool(gated.tools, 'hf_repo').execute({ repo: 'acme/alpha' }) + check('hf_repo names a gated repo before a download', gatedAnswer.text.includes('GATED'), true) + + const offline = harness({ HF_HUB_CACHE: root, HF_HUB_OFFLINE: '1' }, () => versionOk) + const offlineAnswer = await tool(offline.tools, 'hf_repo').execute({ repo: 'acme/alpha' }) + check('offline hf_repo reports the disk and says the Hub was not asked', offlineAnswer.view.offline, true) + check('...and makes no call at all', offline.calls.length, 0) +} + +// cache: list, verify, the two removals +{ + const { calls, tools } = harness({ HF_HUB_CACHE: root }, (argv) => (argv[1] === '--version' ? versionOk : { status: 0, stdout: '{}', stderr: '' })) + const list = await tool(tools, 'hf_cache').execute({}) + check('hf_cache list needs no CLI', calls.length, 0) + check('hf_cache list shows the stub as NO weights', list.text.includes('NO'), true) + check('...and names the metadata-only count', list.view.counts.stubs, 1) + + const dry = await tool(tools, 'hf_cache').execute({ action: 'rm', repo: 'acme/alpha' }) + check('an unconfirmed rm is a DRY RUN', dry.text.startsWith('DRY RUN'), true) + check('...and says nothing was removed', dry.text.includes('nothing was removed'), true) + check('...and the repo still exists', existsSync(path.join(root, 'models--acme--alpha')), true) + const rmCall = calls[calls.length - 1] + check('...and the CLI was asked for a dry run', rmCall.includes('--dry-run') && !rmCall.includes('--yes'), true) + check('...and reports the bytes a delete would cost', dry.view.before.bytes, 3100) + + await tool(tools, 'hf_cache').execute({ action: 'rm', repo: 'acme/alpha', confirm: 'acme/alpha' }) + check('a CONFIRMED rm passes -y', calls[calls.length - 1].includes('--yes'), true) + + await tool(tools, 'hf_cache').execute({ action: 'prune' }) + check('prune unconfirmed is a dry run', calls[calls.length - 1].includes('--dry-run'), true) + await tool(tools, 'hf_cache').execute({ action: 'prune', confirm: 'prune' }) + check('prune confirmed passes -y', calls[calls.length - 1].includes('--yes'), true) + + await tool(tools, 'hf_cache').execute({ action: 'verify', repo: 'acme/alpha' }) + check('verify is the CLI\'s checksum pass', calls[calls.length - 1].slice(0, 3).join(' '), 'hf cache verify') +} + +// download: ceiling, confirmation, then the real thing +{ + const dryInfo = JSON.stringify({ + ...infoFixture, + gated: false, + sha: 'f'.repeat(40), + siblings: [ + { rfilename: 'config.json', size: 100 }, + { rfilename: 'model.safetensors', size: 10_000_000 }, + { rfilename: 'README.md', size: 2000 }, + ], + }) + const downloads = [] + const handlers = (argv) => { + if (argv[1] === '--version') return versionOk + if (argv[1] !== 'download') return { ...versionOk, stdout: dryInfo } + downloads.push(argv.slice()) + // Write real bytes, so "added" is measured rather than assumed. + const dir = path.join(root, 'models--acme--gamma', 'snapshots', 'f'.repeat(40)) + put(path.join(dir, 'model.safetensors'), Buffer.alloc(7000, 7)) + return { ...versionOk, stdout: JSON.stringify([path.join(dir, 'model.safetensors')]) } + } + const { tools, calls } = harness({ HF_HUB_CACHE: root }, handlers) + + const over = await tool(tools, 'hf_download').execute({ repo: 'acme/gamma', maxBytes: 5_000_000 }) + check('a download over the ceiling is refused', over.view.code, 'TOO_BIG') + check('...and NO download ran', downloads.length, 0) + check('...and the size is in the sentence', over.text.includes(formatBytes(10_002_100)), true) + + const unconfirmed = await tool(tools, 'hf_download').execute({ repo: 'acme/gamma', maxBytes: 20_000_000 }) + check('an unconfirmed download is a PLAN', unconfirmed.view.code, 'NOT_CONFIRMED') + check('...and NO download ran', downloads.length, 0) + check('...and the plan names the size', unconfirmed.text.includes(formatBytes(10_002_100)), true) + check('...and asks for the repo id back', unconfirmed.text.includes('confirm: "acme/gamma"'), true) + + const done = await tool(tools, 'hf_download').execute({ repo: 'acme/gamma', maxBytes: 20_000_000, confirm: 'acme/gamma' }) + check('a confirmed download runs ONE download', downloads.length, 1) + check('...and reports the bytes the cache GAINED', done.view.addedBytes, 7000) + check('...and the file that appeared', done.text.includes('model.safetensors'), true) + check('...and the cache now holds it', existsSync(path.join(root, 'models--acme--gamma')), true) + check('...with no token flag anywhere', calls.flat().includes('--token'), false) + + const gatedRepo = harness({ HF_HUB_CACHE: root }, () => ({ ...versionOk, stdout: JSON.stringify({ ...infoFixture, gated: 'manual' }) })) + const refused = await tool(gatedRepo.tools, 'hf_download').execute({ repo: 'acme/gated', confirm: 'acme/gated' }) + check('a gated repo is refused before a byte moves', refused.view.code, 'GATED') + check('...and the licence page is named', refused.text.includes('huggingface.co/'), true) + + const offline = harness({ HF_HUB_CACHE: root, HF_HUB_OFFLINE: '1' }, () => versionOk) + const offlineRefused = await tool(offline.tools, 'hf_download').execute({ repo: 'acme/gamma', confirm: 'acme/gamma' }) + check('offline download is refused', offlineRefused.view.code, 'OFFLINE') + check('...before any process starts', offline.calls.length, 0) +} + +// --------------------------------------------------------------------------- +// The skills: registered, parsed, and their examples checked +// --------------------------------------------------------------------------- +const KNOWN_VERBS = new Set(['auth', 'buckets', 'cache', 'collections', 'cp', 'datasets', 'discussions', 'download', 'endpoints', 'env', 'extensions', 'jobs', 'models', 'papers', 'repos', 'sandbox', 'skills', 'spaces', 'sync', 'update', 'upload', 'version', 'webhooks']) +const skillTexts = [] +for (const entry of SKILL_FILES) { + const file = fileURLToPath(new URL(entry.file, import.meta.url)) + const raw = readFileSync(file, 'utf8') + const { meta, content } = parseSkillFile(raw) + skillTexts.push(content) + check('skill ' + entry.name + ' is registered under its own name', meta.name, entry.name) + check('skill ' + entry.name + ' has a description', typeof meta.description === 'string' && meta.description.length > 80, true) + check('skill ' + entry.name + ' has a body', content.length > 500, true) + check('skill ' + entry.name + ' has no token-shaped string', /hf_[A-Za-z0-9]{20,}/.test(raw), false) + + const blocks = [...raw.matchAll(/```([a-z]*)\n([\s\S]*?)```/g)] + let jsonBlocks = 0 + let commandLines = 0 + for (const block of blocks) { + const lang = block[1] + const body = block[2] + if (lang === 'json') { + jsonBlocks += 1 + try { + JSON.parse(body) + check('skill ' + entry.name + ': a JSON example parses', true) + } catch (error) { + check('skill ' + entry.name + ': a JSON example parses', false) + } + continue + } + if (lang !== 'bash' && lang !== 'sh') continue + for (const line of body.split('\n')) { + const trimmed = line.trim() + if (!trimmed.startsWith('hf ') && !trimmed.startsWith('huggingface-cli ')) continue + commandLines += 1 + const tokens = trimmed.split(/\s+/) + const verb = tokens[1] ?? '' + if (verb.startsWith('-')) continue + check('skill ' + entry.name + ': "' + verb + '" is a real verb', KNOWN_VERBS.has(verb)) + } + } + check('skill ' + entry.name + ' shows at least one command', commandLines > 0) +} +const allSkills = skillTexts.join('\n') +for (const name of ['hf_status', 'hf_search', 'hf_repo', 'hf_cache', 'hf_download']) { + check('the skill set documents ' + name, allSkills.includes(name) || allSkills.includes(name.replace('hf_', 'hf ')), true) +} + +// --------------------------------------------------------------------------- +// Activation: the row registers without a skill registry +// --------------------------------------------------------------------------- +{ + const registered = [] + const skills = [] + const ctx = { + logger: { info() {}, warn() {} }, + tools: { register: (entry) => registered.push(entry.name) }, + get: (name) => (name === 'skills' ? { register: (entry) => skills.push(entry.name) } : undefined), + effect: (fn) => fn(), + } + apply(ctx) + check('activation registers five tools', registered.length, 5) + check('...all of them hf_*', registered.every((name) => name.startsWith('hf_')), true) + check('...and two skills', skills.length, 2) + check('the activation line names the cache root', __internals.activationLine({ env: { HF_HUB_CACHE: '/x' } }).includes(resolveCacheRoot({ HF_HUB_CACHE: '/x' }).root), true) + + const bare = { logger: { info() {}, warn() {} }, tools: { register() {} }, get: () => undefined, effect: (fn) => fn() } + let threw = null + try { + apply(bare) + } catch (error) { + threw = error + } + check('the row activates with no skill registry', threw, null) +} + +// --------------------------------------------------------------------------- +// Formatting +// --------------------------------------------------------------------------- +check('bytes read as bytes', formatBytes(3100), '3.0 KB') +check('...and gigabytes', formatBytes(17_900_000_000), '16.7 GB') +check('...and a negative is not a number it invents', formatBytes(-1), 'n/a') +check('parameters read as parameters', formatParamCount(8_800_000_000), '8.8B') +check('...and millions', formatParamCount(418_000_000), '418M') + +// --------------------------------------------------------------------------- +rmSync(root, { recursive: true, force: true }) +console.log('') +console.log(checks + ' checks, ' + failures + ' failed' + (skipped > 0 ? ', ' + skipped + ' skipped' : '')) +if (failures > 0) process.exit(1) diff --git a/packages/dsh-huggingface/cordis.patch.yml b/packages/dsh-huggingface/cordis.patch.yml new file mode 100644 index 0000000..7bd95d1 --- /dev/null +++ b/packages/dsh-huggingface/cordis.patch.yml @@ -0,0 +1,30 @@ +# dsh-huggingface bundle layer (alpha). +# +# One row ('huggingface') owns the whole plugin: its Node half registers FIVE +# tools over the machine's own `hf` CLI and the cache on this disk - `hf_status` +# (the CLI, the cache root, the repos on disk with BYTE-EXACT sizes, and an auth +# PRESENCE that never reads the token), `hf_search` (models / datasets / spaces +# by query, author, tag or sort), `hf_repo` (one repo's card, licence, gated +# flag, siblings with sizes, the consumers that would fetch them, and whether +# this disk already holds it at the current revision), `hf_cache` (scan, verify, +# prune, rm - the writes confirmed by repeating the target) and `hf_download` +# (the only bytes-moving call: a projected size first, a byte ceiling, and the +# repo id repeated back). +# +# Host-only: the answer is a table and a verdict, so there is no route to serve +# and no browser half to load - the package declares no dsh.client, and the boot +# graph gains one row. The same shape as dsh-ollama and dsh-image-upscale. +# +# Nothing shipped is patched and no core row is disabled: core DSH can call a +# URL and can read a directory listing, but nothing in it reconciles the Hub's +# file tree against a cache layout (`blobs` / `snapshots` / `refs`), and nothing +# tells a reader that "cached" on this machine means metadata only for forty of +# the fifty repos that look present. +# +# Nothing for scripts/sync-vendored.ps1 either: no engine is vendored, forked or +# bundled. `hf` is the user's own program (huggingface_hub's CLI) and the cache +# is the user's own directory; this package ships the cache scanner, the argv +# builder and the JSON reader. +- insert: + - id: huggingface + name: 'dsh-huggingface' diff --git a/packages/dsh-huggingface/lib/cache.js b/packages/dsh-huggingface/lib/cache.js new file mode 100644 index 0000000..f7d241a --- /dev/null +++ b/packages/dsh-huggingface/lib/cache.js @@ -0,0 +1,247 @@ +/** + * dsh-huggingface — the cache on THIS disk, walked without the CLI. + * + * The CLI's own `hf cache ls --json` cannot answer the question this row exists + * for, and the reason is measured rather than assumed: its JSON carries + * `"size": "17.9G"` and `"last_accessed": "3 months ago"` - a human string and a + * relative time. Byte-exact arithmetic, a revision comparison and "is the weight + * file actually here" all need the directory tree. + * + * THE LAYOUT, and why sizes are computed the way they are: + * + * /models----/ + * blobs/ content-addressed bytes (a POSIX cache keeps them here) + * snapshots// links into blobs - or, where links are + * unavailable or Xet wrote the files, REAL copies + * refs/ branch/tag -> revision + * + * Summing both sides double-counts whenever snapshots are links, so exactly one + * side is summed: `blobs` when it holds a non-empty file, `snapshots` otherwise. + * MEASURED on the machine that wrote this: that cache has NO blobs at all and + * real files under `snapshots/`, so the blobs-first rule alone would report 0 + * bytes for a 418 MB repo. + * + * AND THE FINDING THE ROW IS WORTH HAVING: a repository that is "cached" is very + * often metadata only. On the same machine 40 of 50 entries were a config.json + * and nothing else - a repo that looks present, cannot be loaded, and is + * indistinguishable from a complete one in a directory listing. Every entry here + * carries `weights` and `stub`, so "cached" and "complete" are different words. + */ + +import { lstatSync, readdirSync, readFileSync, statSync } from 'node:fs' +import path from 'node:path' + +/** The directory prefix per repo type. */ +export const REPO_PREFIXES = [ + { prefix: 'models--', type: 'model' }, + { prefix: 'datasets--', type: 'dataset' }, + { prefix: 'spaces--', type: 'space' }, +] + +/** A file that means "the weights are actually here". */ +export const WEIGHT_PATTERN = /\.(safetensors|bin|gguf|pt|pth|onnx|h5|msgpack|ckpt|npz)$/i + +/** A repo below this many bytes cannot hold weights, whatever it contains. */ +export const STUB_BYTES = 1_048_576 + +/** The most files one repo is walked before the scan stops counting. */ +export const MAX_FILES_PER_REPO = 20_000 + +/** + * Split `models--org--name` into its type and id. + * + * @param directory - the directory name. + * @returns `{ type, id }` or null when it is not a repo directory. + */ +export function splitRepoDir(directory) { + for (const entry of REPO_PREFIXES) { + if (directory.startsWith(entry.prefix) && directory.length > entry.prefix.length) { + return { type: entry.type, id: directory.slice(entry.prefix.length).split('--').join('/') } + } + } + return null +} + +/** The directory name a repo id and type map to. */ +export function repoDirName(type, id) { + const entry = REPO_PREFIXES.find((candidate) => candidate.type === type) + if (entry === undefined) return null + return entry.prefix + id.split('/').join('--') +} + +/** + * Every file under `dir`, bounded, with its size and modification time. + * + * @returns `{ files: [{ path, bytes, mtimeMs }], truncated }`. + */ +export function walkFiles(dir, limit = MAX_FILES_PER_REPO) { + const files = [] + let truncated = false + const queue = [dir] + while (queue.length > 0) { + const current = queue.pop() + let entries + try { + entries = readdirSync(current, { withFileTypes: true }) + } catch (error) { + continue + } + for (const entry of entries) { + const full = path.join(current, entry.name) + if (entry.isDirectory()) { + queue.push(full) + continue + } + if (files.length >= limit) { + truncated = true + return { files, truncated } + } + try { + // stat() follows a link to the blob it names, which is the byte count + // that matters; lstat() is used only to know that it IS a link. + const stat = statSync(full) + const link = lstatSync(full) + files.push({ path: full, bytes: stat.size, mtimeMs: stat.mtimeMs, link: link.isSymbolicLink() }) + } catch (error) { + /* a file removed mid-walk is not a repo we can describe */ + } + } + } + return { files, truncated } +} + +/** The sum of a list of entries' bytes. */ +function sumBytes(entries) { + return entries.reduce((total, entry) => total + (Number.isFinite(entry.bytes) ? entry.bytes : 0), 0) +} + +/** + * Describe one repo directory. + * + * @param root - the cache root. + * @param directory - the repo's directory name. + * @returns the repo's facts, or null when the directory cannot be read. + */ +export function describeRepoDir(root, directory) { + const split = splitRepoDir(directory) + if (split === null) return null + const repoRoot = path.join(root, directory) + let entries + try { + entries = readdirSync(repoRoot, { withFileTypes: true }) + } catch (error) { + return null + } + const has = (name) => entries.some((entry) => entry.isDirectory() && entry.name === name) + + // refs: branch/tag -> revision. Read as text, bounded: these are 40-hex ids. + const refs = {} + if (has('refs')) { + for (const entry of readdirSync(path.join(repoRoot, 'refs'), { withFileTypes: true })) { + if (!entry.isFile()) continue + try { + refs[entry.name] = readFileSync(path.join(repoRoot, 'refs', entry.name), 'utf8').trim() + } catch (error) { + /* unreadable ref: reported as absent rather than guessed */ + } + } + } + + // snapshots: one directory per revision. + const revisions = [] + if (has('snapshots')) { + for (const entry of readdirSync(path.join(repoRoot, 'snapshots'), { withFileTypes: true })) { + if (entry.isDirectory()) revisions.push(entry.name) + } + } + + const blobs = has('blobs') ? walkFiles(path.join(repoRoot, 'blobs')) : { files: [], truncated: false } + const snapshots = has('snapshots') ? walkFiles(path.join(repoRoot, 'snapshots')) : { files: [], truncated: false } + const blobBytes = sumBytes(blobs.files.filter((file) => file.bytes > 0)) + const layout = blobBytes > 0 ? 'blobs' : 'snapshots' + + // Only ONE side is summed: both sides hold the same bytes whenever snapshots + // are links, and adding them would report a cache twice its size. + // + // The weight test is the opposite way round on purpose: a blob is named by its + // HASH, so `blobs/9f3c...` carries no extension and an extension test against + // it would call every canonical POSIX repo weightless. The NAMES that say what + // a file is are the snapshot entries - which is also where a copy is real. + const counted = layout === 'blobs' ? blobs.files : snapshots.files + const truncated = layout === 'blobs' ? blobs.truncated : snapshots.truncated + const weights = snapshots.files.filter((file) => WEIGHT_PATTERN.test(file.path) && file.bytes > 0) + const bytes = sumBytes(counted) + const newest = counted.reduce((latest, file) => (file.mtimeMs > latest ? file.mtimeMs : latest), 0) + const revision = refs.main ?? revisions[0] ?? '' + // A model is metadata-only when it has no weight file, whatever its size: a + // small repo WITH weights is a small model, not a stub. A dataset or a space + // has no weights by definition, so there the size is what separates a real + // download from a few KB of cards and config. + const stub = split.type === 'model' ? weights.length === 0 : bytes < STUB_BYTES + + return { + type: split.type, + id: split.id, + directory, + path: repoRoot, + bytes, + files: counted.length, + layout, + revisions, + refs, + revision, + weights: weights.length > 0, + weightFiles: weights.map((file) => path.basename(file.path)).slice(0, 8), + stub, + modifiedMs: newest, + truncated, + } +} + +/** + * Scan a cache root. + * + * @param root - the directory holding `models--*` / `datasets--*` / `spaces--*`. + * @param options - `{ type, filter, limit }`. + * @returns `{ root, exists, repos, counts }`. + */ +export function scanCache(root, options = {}) { + let entries + try { + entries = readdirSync(root, { withFileTypes: true }) + } catch (error) { + return { root, exists: false, repos: [], counts: { repos: 0, bytes: 0, stubs: 0, complete: 0, byType: {} } } + } + const repos = [] + for (const entry of entries) { + if (!entry.isDirectory()) continue + const described = describeRepoDir(root, entry.name) + if (described === null) continue + if (options.type !== undefined && described.type !== options.type) continue + if (typeof options.filter === 'string' && options.filter !== '' && !described.id.toLowerCase().includes(options.filter.toLowerCase())) continue + repos.push(described) + } + repos.sort((left, right) => right.bytes - left.bytes || left.id.localeCompare(right.id)) + const limited = Number.isFinite(options.limit) && options.limit > 0 ? repos.slice(0, options.limit) : repos + const counts = { repos: repos.length, bytes: 0, stubs: 0, complete: 0, byType: {} } + for (const repo of repos) { + counts.bytes += repo.bytes + if (repo.stub) counts.stubs += 1 + else counts.complete += 1 + counts.byType[repo.type] = (counts.byType[repo.type] ?? 0) + 1 + } + return { root, exists: true, repos: limited, all: repos, counts, limited: limited.length !== repos.length } +} + +/** + * Find one repo in a scan, by id and type. + * + * @returns the entry, or null. + */ +export function findRepo(scan, type, id) { + const wanted = String(id).toLowerCase() + for (const repo of scan.all ?? scan.repos ?? []) { + if (repo.type === type && repo.id.toLowerCase() === wanted) return repo + } + return null +} diff --git a/packages/dsh-huggingface/lib/cli.js b/packages/dsh-huggingface/lib/cli.js new file mode 100644 index 0000000..f497330 --- /dev/null +++ b/packages/dsh-huggingface/lib/cli.js @@ -0,0 +1,136 @@ +/** + * dsh-huggingface — one bounded child process, and the CLI it runs. + * + * `spawn` with an argv ARRAY and no shell: a repo id is data, never a command. + * Every call has a deadline and a byte cap, and a CLI that is not installed is a + * normal result (`bin: null`) rather than an exception - the cache scan needs no + * CLI at all, and saying "no hf on this PATH" is more useful than a stack trace. + * + * TWO MEASURED TRAPS, both handled here because they are silent: + * + * 1. `hf --version` writes the version to STDOUT and a "a new version is + * available (2.5.0), you are using 1.26.1" hint to STDERR. Parsing stderr + * first reports the version that is NOT installed. Standard output wins. + * 2. `hf --help` exits NON-ZERO (measured: -1 on this install). An exit + * code is therefore not a verdict; a call is judged by whether its stdout + * parses, and `--help` is never run by this row. + */ + +import { spawn } from 'node:child_process' + +/** The programs tried, in order, when `DSH_HF_CLI` is not set. */ +export const CLI_CANDIDATES = ['hf', 'huggingface-cli'] + +/** The variable that pins a binary PATH does not cover. */ +export const CLI_ENV = 'DSH_HF_CLI' + +/** + * Run one argv array and collect its output. + * + * @param argv - the program and its arguments, one element each. + * @param options - `{ timeoutMs, maxBytes, env, cwd }`. + * @returns `{ status, stdout, stderr, timedOut, error }`; `status` is null when + * the program could not start at all (ENOENT, EACCES). + */ +export function runProcess(argv, options = {}) { + const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 15_000 + const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : 1_000_000 + return new Promise((resolve) => { + let settled = false + let timedOut = false + let stdout = '' + let stderr = '' + const finish = (result) => { + if (settled) return + settled = true + resolve(result) + } + let child + try { + child = spawn(argv[0], argv.slice(1), { + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + env: options.env ?? process.env, + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + }) + } catch (error) { + finish({ status: null, stdout: '', stderr: '', timedOut: false, error: error && error.message ? String(error.message) : String(error) }) + return + } + const timer = setTimeout(() => { + timedOut = true + try { + child.kill('SIGKILL') + } catch (error) { + /* already gone */ + } + }, timeoutMs) + child.stdout?.setEncoding('utf8') + child.stderr?.setEncoding('utf8') + child.stdout?.on('data', (chunk) => { + if (stdout.length < maxBytes) stdout += chunk + }) + child.stderr?.on('data', (chunk) => { + if (stderr.length < maxBytes) stderr += chunk + }) + child.on('error', (error) => { + clearTimeout(timer) + finish({ status: null, stdout, stderr, timedOut, error: error && error.message ? String(error.message) : String(error) }) + }) + child.on('close', (code) => { + clearTimeout(timer) + finish({ status: code, stdout, stderr, timedOut }) + }) + }) +} + +/** + * Read a version out of the two streams, in the order that is correct. + * + * @param stdout - what the program wrote to stdout. + * @param stderr - what it wrote to stderr. + * @returns the version string, or ''. + */ +export function parseVersion(stdout, stderr) { + const first = /(\d+\.\d+(?:\.\d+)?(?:[-.][0-9A-Za-z.]+)?)/.exec(String(stdout ?? '')) + if (first !== null) return first[1] + // Only the lines that are not the "new version available" advertisement. + for (const line of String(stderr ?? '').split(/\r?\n/)) { + if (/available|To update|pip install|conda/i.test(line)) continue + const match = /(\d+\.\d+(?:\.\d+)?(?:[-.][0-9A-Za-z.]+)?)/.exec(line) + if (match !== null) return match[1] + } + return '' +} + +/** + * Find the CLI, once per boot. + * + * The answer is cached on `deps.cache.cli` because it cannot change while the + * process runs, and a status call should cost one process, not three. + * + * @param deps - `{ env, runner, cache }`. + * @returns `{ bin, version, source, tried }`; `bin` is null when none started. + */ +export async function resolveCli(deps) { + if (deps.cache?.cli !== undefined) return deps.cache.cli + const pinned = typeof deps.env?.[CLI_ENV] === 'string' ? deps.env[CLI_ENV].trim() : '' + const candidates = pinned === '' ? CLI_CANDIDATES : [pinned] + const tried = [] + let answer = { bin: null, version: '', source: '', tried } + for (const candidate of candidates) { + const result = await deps.runner([candidate, '--version'], { timeoutMs: 8000, maxBytes: 64_000, env: deps.env }) + const started = result !== null && result !== undefined && result.status !== null + tried.push({ bin: candidate, started }) + if (!started) continue + answer = { + bin: candidate, + version: parseVersion(result.stdout, result.stderr), + source: pinned === '' ? 'PATH' : CLI_ENV, + tried, + } + break + } + if (deps.cache) deps.cache.cli = answer + return answer +} diff --git a/packages/dsh-huggingface/lib/errors.js b/packages/dsh-huggingface/lib/errors.js new file mode 100644 index 0000000..3ae5a3f --- /dev/null +++ b/packages/dsh-huggingface/lib/errors.js @@ -0,0 +1,74 @@ +/** + * dsh-huggingface — the one error type, so every refusal carries a code. + * + * A refusal is an answer. Each code below is a thing the caller can branch on + * and a thing the prose must name the fix for: a missing CLI says where the CLI + * comes from, a gated repo names the licence page, a repo over the byte ceiling + * says its size and the ceiling it was measured against. + */ + +export class HfError extends Error { + /** + * @param code - one of the codes in `HfError.CODES`. + * @param message - the sentence a reader acts on. + * @param details - extra facts for the view (sizes, names, versions). + */ + constructor(code, message, details = undefined) { + super(message) + this.name = 'HfError' + this.code = code + this.details = details ?? {} + } +} + +/** Every code this row can answer with. */ +HfError.CODES = { + NO_CLI: 'no `hf` CLI on this PATH - `pip install -U huggingface_hub` provides it (huggingface-cli is the old name)', + BAD_INPUT: 'bad input', + OFFLINE: 'this machine is in offline mode (HF_HUB_OFFLINE=1 / TRANSFORMERS_OFFLINE=1)', + NOT_FOUND: 'the Hub does not have that repo (or that revision)', + GATED: 'the repo is gated: its licence must be accepted by a person in a browser first', + AUTH: 'the Hub refused the credentials (401) - `hf auth login`', + FORBIDDEN: 'the Hub refused access (403) - a token is required, or it lacks the scope', + RATE_LIMIT: 'the Hub is rate-limiting (429) - wait, or use a token', + NETWORK: 'no answer from huggingface.co', + DISK_FULL: 'no space left on the disk that holds the cache', + TIMEOUT: 'the command exceeded its deadline', + OUTPUT: 'the CLI answered something this row could not read as JSON', + NOT_CONFIRMED: 'the write was not confirmed', + TOO_BIG: 'the download is larger than the byte ceiling', + UNSUPPORTED: 'not supported here', +} + +/** The message of any thrown value. */ +export function messageOf(error) { + if (error && typeof error.message === 'string' && error.message !== '') return error.message + return String(error) +} + +/** + * Map the CLI's stderr onto a code. + * + * `hf` writes one short reason per line and exits non-zero; the exit code alone + * cannot tell a gated repo from a missing one, so the text is what is read. The + * order matters: "access to model ... is restricted" must win over a generic + * 403, and "Repository Not Found" must win over a generic 404. + * + * @param text - stderr (and stdout, which sometimes carries the message). + * @param status - the exit code, for the cases the text does not name. + */ +export function classifyFailure(text, status) { + const body = String(text ?? '') + if (/gated|access to model .*restricted|awaiting a review|you need to agree|accept the terms/i.test(body)) return 'GATED' + if (/Repository Not Found|404 Client Error|Entry not found/i.test(body)) return 'NOT_FOUND' + if (/Invalid credentials|authentication|token is invalid|401 Client Error|must be authenticated/i.test(body)) return 'AUTH' + if (/403 Client Error|Forbidden|cannot access/i.test(body)) return 'FORBIDDEN' + if (/429|rate limit/i.test(body)) return 'RATE_LIMIT' + if (/No space left|ENOSPC|not enough space/i.test(body)) return 'DISK_FULL' + if (/Connection|getaddrinfo|Name or service not known|timed out|Max retries|Network is unreachable/i.test(body)) return 'NETWORK' + if (status === 401) return 'AUTH' + if (status === 403) return 'FORBIDDEN' + if (status === 404) return 'NOT_FOUND' + if (status === 429) return 'RATE_LIMIT' + return 'OUTPUT' +} diff --git a/packages/dsh-huggingface/lib/hf.js b/packages/dsh-huggingface/lib/hf.js new file mode 100644 index 0000000..6188464 --- /dev/null +++ b/packages/dsh-huggingface/lib/hf.js @@ -0,0 +1,372 @@ +/** + * dsh-huggingface — argv builders and the JSON reader. + * + * The CLI is the user's own program and its `--format json` is the contract this + * row reads; nothing here talks HTTP. That keeps the "no network egress a plugin + * starts on its own" rule intact: a call is made because a tool was asked for, + * the CLI carries the credentials, and this package ships no client. + * + * THE SHAPES THIS ROW HAD TO MEASURE, because each one is silent when wrong: + * + * - `hf cache ls --json` is REAL JSON but its `size` is a human string + * ("17.9G") and its `last_accessed` is relative ("3 months ago"). Byte-exact + * numbers therefore come from `cache.js`, never from this JSON. + * - `hf cache rm` prompts unless `-y` is given, and stdin is closed here, so a + * missing `-y` is a hang. The confirmation is this row's own (`confirm`), and + * `-y` is passed only after it. + * - an UNCONFIRMED removal is the CLI's own `--dry-run`, so the answer is a + * real preview rather than prose about one. + * - a removal target is `/` (the `id` field of `cache ls`), not a + * bare repo id. + */ + +import { HfError, classifyFailure } from './errors.js' +import { CAPS } from './validate.js' +import { resolveCli } from './cli.js' + +/** The properties `hf info --expand` is asked for. */ +export const EXPAND_PROPERTIES = [ + 'author', + 'cardData', + 'config', + 'createdAt', + 'downloads', + 'downloadsAllTime', + 'gated', + 'gguf', + 'lastModified', + 'library_name', + 'likes', + 'pipeline_tag', + 'private', + 'safetensors', + 'sha', + 'siblings', + 'tags', + 'trendingScore', + 'usedStorage', +].join(',') + +/** The flags that turn any subcommand's output into JSON. */ +export const JSON_FLAGS = ['--format', 'json'] + +// --------------------------------------------------------------------------- +// argv +// --------------------------------------------------------------------------- +/** `hf list` for a search. */ +export function buildSearchArgv(bin, spec) { + const argv = [bin, spec.group, 'list', '--limit', String(spec.limit)] + if (spec.query !== '') argv.push('--search', spec.query) + if (spec.author !== '') argv.push('--author', spec.author) + for (const filter of spec.filters) argv.push('--filter', filter) + if (spec.sort !== '') argv.push('--sort', spec.sort) + argv.push(...JSON_FLAGS) + return argv +} + +/** `hf info --expand ...`. */ +export function buildInfoArgv(bin, spec) { + return [bin, spec.group, 'info', spec.repo, '--expand', EXPAND_PROPERTIES, ...JSON_FLAGS] +} + +/** `hf cache ...` for one action; a removal without confirmation is a dry run. */ +export function buildCacheArgv(bin, spec) { + if (spec.action === 'list') return [bin, 'cache', 'ls', ...JSON_FLAGS] + if (spec.action === 'verify') { + const argv = [bin, 'cache', 'verify', spec.repo, '--type', spec.type] + if (spec.revision !== '') argv.push('--revision', spec.revision) + argv.push(...JSON_FLAGS) + return argv + } + const confirmed = spec.confirm === (spec.action === 'prune' ? 'prune' : spec.repo) + if (spec.action === 'prune') { + return [bin, 'cache', 'prune', ...(confirmed ? ['--yes'] : ['--dry-run']), ...JSON_FLAGS] + } + return [bin, 'cache', 'rm', spec.type + '/' + spec.repo, ...(confirmed ? ['--yes'] : ['--dry-run']), ...JSON_FLAGS] +} + +/** `hf download [files] --include ...`. */ +export function buildDownloadArgv(bin, spec) { + const argv = [bin, 'download', spec.repo] + for (const file of spec.files) argv.push(file) + argv.push('--type', spec.type) + if (spec.revision !== '') argv.push('--revision', spec.revision) + for (const pattern of spec.include) argv.push('--include', pattern) + for (const pattern of spec.exclude) argv.push('--exclude', pattern) + argv.push('--max-workers', '8', ...JSON_FLAGS) + return argv +} + +// --------------------------------------------------------------------------- +// the one call +// --------------------------------------------------------------------------- +/** + * Run one `hf` argv and read its stdout as JSON. + * + * @param deps - `{ env, runner, cache, log }`. + * @param argv - the complete argv, `bin` included. + * @param options - `{ timeoutMs, maxBytes, allowLoose }`. + * @returns `{ data, argv, status, elapsedMs, stdout, stderr, cli }`; `data` is + * the parsed JSON, or - with `allowLoose` - `{ lines }` of non-empty stdout. + */ +export async function callCli(deps, argv, options = {}) { + const cli = await resolveCli(deps) + if (cli.bin === null) { + throw new HfError('NO_CLI', 'No `hf` on this PATH, and none named by DSH_HF_CLI. ' + HfError.CODES.NO_CLI + '. The cache scan still works without it: `hf_status` / `hf_cache` action "list" read the directory tree.') + } + const started = typeof deps.now === 'function' ? deps.now() : Date.now() + const result = await deps.runner(argv, { + timeoutMs: options.timeoutMs ?? CAPS.readTimeoutMs, + maxBytes: options.maxBytes ?? CAPS.maxOutputBytes, + env: deps.env, + }) + const elapsedMs = (typeof deps.now === 'function' ? deps.now() : Date.now()) - started + const base = { argv, elapsedMs, stdout: '', stderr: '', status: null, cli } + if (result === null || result === undefined || result.status === null) { + throw new HfError('NO_CLI', '`' + argv[0] + '` could not be started: ' + (result && result.error ? result.error : 'unknown error') + '.') + } + const stdout = String(result.stdout ?? '') + const stderr = String(result.stderr ?? '') + if (result.timedOut === true) { + throw new HfError('TIMEOUT', '`hf ' + argv.slice(1, 3).join(' ') + '` exceeded ' + Math.round((options.timeoutMs ?? CAPS.readTimeoutMs) / 1000) + ' s and was killed.') + } + let data + try { + data = JSON.parse(stdout.trim()) + } catch (error) { + if (result.status !== 0) { + const code = classifyFailure(stderr + '\n' + stdout, result.status) + throw new HfError(code, (HfError.CODES[code] ?? 'the command failed') + '\n\n' + tail(stderr || stdout)) + } + if (options.allowLoose === true) { + return { ...base, data: { lines: stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== '') }, status: result.status, stdout, stderr } + } + throw new HfError('OUTPUT', '`hf ' + argv.slice(1, 3).join(' ') + '` exited 0 but did not answer JSON, so this row cannot read it. That is a version mismatch: run `hf --version` and compare it with the version this row was checked against.\n\n' + tail(stdout || stderr)) + } + return { ...base, data, status: result.status, stdout, stderr } +} + +/** The last few lines of a stream, for an error message. */ +function tail(text, lines = 6) { + const all = String(text ?? '').trim().split(/\r?\n/) + return all.slice(Math.max(0, all.length - lines)).join('\n') +} + +/** Run one argv through `callCli` after resolving the binary. */ +export async function runHf(deps, build, spec, options = {}) { + const cli = await resolveCli(deps) + if (cli.bin === null) { + throw new HfError('NO_CLI', 'No `hf` on this PATH, and none named by DSH_HF_CLI. ' + HfError.CODES.NO_CLI) + } + return callCli(deps, build(cli.bin, spec), options) +} + +// --------------------------------------------------------------------------- +// reading a repo's info +// --------------------------------------------------------------------------- +/** A finite number or null. */ +function finite(value) { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +/** A trimmed string or ''. */ +function str(value) { + return typeof value === 'string' ? value.trim() : '' +} + +/** + * Normalise `hf info` into the facts this row reports. + * + * @param data - the parsed JSON. + * @param spec - `{ repo, type, group }`. + * @returns the normalised record. + */ +export function normalizeInfo(data, spec) { + const body = data !== null && typeof data === 'object' ? data : {} + const card = body.cardData !== null && typeof body.cardData === 'object' ? body.cardData : {} + const siblings = Array.isArray(body.siblings) ? body.siblings : [] + const files = siblings + .map((entry) => { + const name = str(entry?.rfilename) || str(entry?.path) + const size = finite(entry?.size) ?? finite(entry?.lfs?.size) + return name === '' ? null : { name, bytes: size, lfs: entry?.lfs !== undefined && entry?.lfs !== null } + }) + .filter((entry) => entry !== null) + const sized = files.filter((entry) => entry.bytes !== null) + const siblingTotal = sized.reduce((sum, entry) => sum + entry.bytes, 0) + // MEASURED: `hf models info` on this line has NO --blobs flag, so `siblings` + // never carries per-file sizes - only `used_storage` (bytes) is available for + // the repo. A size is therefore reported with its SOURCE, never as if the file + // list had been summed when it was not. + const usedStorage = finite(body.used_storage) ?? finite(body.usedStorage) + const totalBytes = usedStorage !== null ? usedStorage : siblingTotal + const totalSource = usedStorage !== null ? 'hub storage' : sized.length > 0 ? 'file sizes' : 'none' + const perFileSizes = files.length > 0 && sized.length === files.length + const rawLicence = card.license + const licence = Array.isArray(rawLicence) ? rawLicence.map((value) => str(value)).filter(Boolean).join(', ') : str(rawLicence) + const licenceFromTag = (Array.isArray(body.tags) ? body.tags : []).map(str).find((tag) => tag.startsWith('license:')) + const gated = body.gated === true || body.gated === 'auto' || body.gated === 'manual' ? String(body.gated) : '' + const config = body.config !== null && typeof body.config === 'object' ? body.config : {} + const safetensors = body.safetensors !== null && typeof body.safetensors === 'object' ? body.safetensors : {} + const gguf = body.gguf !== null && typeof body.gguf === 'object' ? body.gguf : {} + const params = finite(safetensors.total) ?? finite(gguf.total) + return { + repo: str(body.id) || spec.repo, + type: spec.type, + sha: str(body.sha), + private: body.private === true, + gated, + licence: licence !== '' ? licence : licenceFromTag !== undefined ? licenceFromTag.slice('license:'.length) : '', + pipelineTag: str(body.pipeline_tag), + library: str(body.library_name), + downloads: finite(body.downloads), + likes: finite(body.likes), + createdAt: str(body.createdAt), + lastModified: str(body.lastModified), + tags: (Array.isArray(body.tags) ? body.tags : []).map(str).filter(Boolean), + files, + totalBytes, + totalSource, + perFileSizes, + sizesComplete: perFileSizes, + unknownSizes: files.length - sized.length, + params, + architectures: (Array.isArray(config.architectures) ? config.architectures : []).map(str).filter(Boolean), + modelType: str(config.model_type), + contextLength: finite(config.max_position_embeddings) ?? finite(config.n_positions) ?? finite(config.text_config?.max_position_embeddings), + quant: str(gguf.architecture) !== '' ? str(gguf.architecture) : '', + } +} + +/** + * Which consumer would fetch which files - the question a 17 GB repo hides. + * + * @param files - `[{ name, bytes }]`. + * @returns `[{ consumer, files, note }]`, only for consumers that match. + */ +export function consumersOf(files) { + const names = files.map((file) => file.name) + const pick = (predicate) => files.filter((file) => predicate(file.name)).map((file) => file.name) + const out = [] + const transformers = pick((name) => /(^|\/)(config\.json|tokenizer(\.json|_config\.json)?|special_tokens_map\.json|vocab\.json|vocab\.txt|merges\.txt|generation_config\.json|model\.safetensors|pytorch_model.*\.bin)$/.test(name)) + if (transformers.length > 0) { + out.push({ consumer: 'transformers', files: transformers, note: 'config + tokenizer + one weight format: fetch these, not the whole repo' }) + } + const sentence = pick((name) => /(^|\/)(modules\.json|config_sentence_transformers\.json|sentence_bert_config\.json)$/.test(name)) + if (sentence.length > 0) out.push({ consumer: 'sentence-transformers', files: sentence, note: 'embeddings through sentence-transformers' }) + const diffusers = pick((name) => /(^|\/)model_index\.json$/.test(name)) + if (diffusers.length > 0) out.push({ consumer: 'diffusers', files: diffusers, note: 'a diffusion pipeline: dsh-comfyui owns running one' }) + const gguf = names.filter((name) => /\.gguf$/i.test(name)) + if (gguf.length > 0) out.push({ consumer: 'llama.cpp / Ollama', files: gguf, note: 'pick ONE quant, not every quant in the repo' }) + const onnx = names.filter((name) => /\.onnx$/i.test(name)) + if (onnx.length > 0) out.push({ consumer: 'onnxruntime', files: onnx, note: 'an ONNX export is not a transformers checkpoint' }) + return out +} + +// --------------------------------------------------------------------------- +// patterns and projection +// --------------------------------------------------------------------------- +/** + * Compile a Hub glob (`*`, `**`, `?`) into a regular expression. + * + * `*` stays inside one path segment; `**` crosses them. That difference is the + * one that decides whether `--include *.safetensors` reaches a sharded subfolder. + */ +export function globToRegExp(pattern) { + let out = '^' + for (let index = 0; index < pattern.length; index += 1) { + const char = pattern[index] + if (char === '*') { + if (pattern[index + 1] === '*') { + out += '.*' + index += 1 + } else { + out += '[^/]*' + } + continue + } + if (char === '?') { + out += '[^/]' + continue + } + out += char.replace(/[.+^${}()|[\]\\]/g, '\\$&') + } + return new RegExp(out + '$') +} + +/** + * Whether a file passes the include/exclude patterns. + * + * An empty include list means "everything"; an exclude always wins. + */ +export function selected(name, include, exclude) { + const included = include.length === 0 || include.some((pattern) => globToRegExp(pattern).test(name)) + if (!included) return false + return !exclude.some((pattern) => globToRegExp(pattern).test(name)) +} + +/** + * What a download would fetch, from the repo's own file list. + * + * The answer names WHICH measure it used, because this CLI line gives no + * per-file sizes: a selection that covers the whole repo is measured by the + * Hub's `used_storage`, and a narrower one can only be measured when the file + * list carried sizes. Reporting a made-up number for a partial selection would + * be worse than reporting none. + * + * @returns `{ files, bytes, known, unknown, complete, measured, coversAll }` + * where `bytes` is null when nothing measured it and `measured` is + * 'repo' | 'files' | 'unknown'. + */ +export function projectDownload(info, spec) { + const coversAll = spec.files.length === 0 && spec.include.length === 0 && spec.exclude.length === 0 + const wanted = info.files.filter((file) => { + if (spec.files.length > 0 && !spec.files.includes(file.name)) return false + return selected(file.name, spec.include, spec.exclude) + }) + const known = wanted.filter((file) => file.bytes !== null) + const sum = known.reduce((total, file) => total + file.bytes, 0) + let bytes = null + let measured = 'unknown' + if (wanted.length > 0 && known.length === wanted.length) { + bytes = sum + measured = 'files' + } else if (coversAll && info.totalSource === 'hub storage' && info.totalBytes > 0) { + // The whole repo, which is exactly what `used_storage` describes - and the + // selection IS everything, so the figure applies to it. + bytes = info.totalBytes + measured = 'repo' + } else if (coversAll && known.length > 0) { + // Every file was selected but some sizes are missing: this is a floor, not + // a total, and it is labelled as one. + bytes = sum + measured = 'lower-bound' + } + return { + files: wanted.map((file) => file.name), + bytes, + known: known.length, + unknown: wanted.length - known.length, + complete: measured === 'files' || measured === 'repo', + measured, + coversAll, + } +} + +/** + * Read a `hf download` answer into file paths. + * + * The CLI's own answer has been a JSON array of paths in the versions seen so + * far, but a `{"downloaded": [...]}` object and a plain line-per-path are both + * plausible, so all three are accepted rather than assumed. + */ +export function parseDownloadAnswer(data) { + if (Array.isArray(data)) return { paths: data.filter((entry) => typeof entry === 'string'), shape: 'array' } + if (data !== null && typeof data === 'object') { + for (const key of ['downloaded', 'paths', 'files']) { + if (Array.isArray(data[key])) return { paths: data[key].filter((entry) => typeof entry === 'string'), shape: 'object.' + key } + } + if (Array.isArray(data.lines)) return { paths: data.lines.filter((line) => line !== '' && !line.startsWith('{')), shape: 'lines' } + } + return { paths: [], shape: 'unknown' } +} diff --git a/packages/dsh-huggingface/lib/index.js b/packages/dsh-huggingface/lib/index.js new file mode 100644 index 0000000..f22226a --- /dev/null +++ b/packages/dsh-huggingface/lib/index.js @@ -0,0 +1,197 @@ +/** + * dsh-huggingface — Node half. + * + * One row, five tools, no browser surface and no route. "What does this repo + * weigh and do I already have it" is a host question whose answer is a table and + * a verdict, so there is nothing for the right bar to draw and nothing to serve - + * the same shape as `dsh-ollama` and `dsh-image-upscale`. + * + * WHY IT EXISTS: a Hub repo directory is a directory like any other on disk, so a + * listing says `models--lukey03--Qwen3.5-9B-abliterated` and stops there. It does + * not say that the entry is 17.9 GB, that forty of the fifty entries on this + * machine are a config.json and nothing else, that the repo's licence is gated, + * or that the cached revision is three commits behind the Hub's. Those are the + * facts a person needs BEFORE 18 GB of bandwidth, and nothing in the pack read + * them. The CLI's own `cache ls --json` answers in human strings ("17.9G", + * "3 months ago"), which is why the scan here is of the directory tree. + * + * WHAT IT IS NOT: not a downloader that acts on its own (the only bytes-moving + * call needs `confirm` and a ceiling), not a client for the Hub API (the user's + * own `hf` does the talking, and its `--format json` is the contract), not a + * model runner (that is `dsh-transformers` / `dsh-ollama`), and not a cache + * cleaner that acts silently (an unconfirmed removal is the CLI's own dry run). + * + * Zero npm dependencies, no engine bundled, no socket, and no network egress of + * its own: every call is one the caller asked for. + */ + +import { readFileSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +import { runProcess } from './cli.js' +import { resolveCacheRoot } from './paths.js' +import { buildTools } from './tools.js' +import { CAPS } from './validate.js' + +export const name = 'dsh-huggingface' +export const inject = ['tools'] + +/** Kept in step with package.json by the tracked check. */ +export const PLUGIN_VERSION = '0.1.0-alpha.1' + +/** The two skills, as files beside this module. */ +export const SKILL_FILES = [ + { name: 'huggingface-hub', file: '../skills/huggingface-hub/SKILL.md' }, + { name: 'huggingface-cache', file: '../skills/huggingface-cache/SKILL.md' }, +] + +/** What this row offers, for the README and the package check. */ +export const CAPABILITIES = { + tools: ['hf_status', 'hf_search', 'hf_repo', 'hf_cache', 'hf_download'], + env: ['DSH_HF_CLI', 'HF_HUB_CACHE', 'HUGGINGFACE_HUB_CACHE', 'HF_HOME', 'TRANSFORMERS_CACHE', 'HF_TOKEN', 'HF_HUB_OFFLINE', 'TRANSFORMERS_OFFLINE'], + skills: SKILL_FILES.map((entry) => entry.name), + caps: { ...CAPS }, + notBuilt: ['uploading', 'creating or deleting repos on the Hub', 'a chat or inference surface', 'reading, echoing or accepting a token', 'running the CLI\'s own updater'], +} + +/** + * The row's shared dependencies, one per boot. + * + * `runner` is injectable so the package check can drive every branch with a fake + * CLI and assert the exact argv, which is the only way to prove the `-y` and + * `--dry-run` decisions without deleting somebody's cache. + * + * @param ctx - the plugin context (inject: tools). + * @param options - `{ env, runner, now, platform }`. + */ +export function createDeps(ctx, options = {}) { + return { + ctx, + env: options.env ?? process.env, + runner: options.runner ?? runProcess, + now: options.now ?? (() => Date.now()), + platform: options.platform ?? process.platform, + cache: {}, + log: { + warn: (text) => ctx.logger?.warn?.('[dsh-huggingface] ' + text), + info: (text) => ctx.logger?.info?.('[dsh-huggingface] ' + text), + }, + } +} + +/** + * The one activation line. + * + * It does NOT resolve the CLI (that is one child process nobody asked for at + * boot) and does not read the cache: it names where the cache would be, and + * `hf_status` is the tool that answers what is in it. + * + * @param deps - the row's dependencies. + */ +export function activationLine(deps) { + const root = resolveCacheRoot(deps.env) + return ( + 'active: five hf_* tools over the machine\'s own `hf` CLI; cache ' + + root.root + + ' (' + root.from + ')' + + '; nothing is downloaded without `confirm`, and no token is ever read' + ) +} + +// --------------------------------------------------------------------------- +// Skills +// --------------------------------------------------------------------------- +/** + * Split one skill document into its frontmatter and its body. + * + * @param text - the file's contents. + * @returns `{ meta, content }`. + */ +export function parseSkillFile(text) { + const normalized = String(text).replace(/\r\n?/g, '\n') + const match = /^---\n([\s\S]*?)\n---\n?/.exec(normalized) + if (!match) return { meta: {}, content: normalized.trim() } + const meta = {} + for (const line of match[1].split('\n')) { + const entry = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line) + if (!entry) continue + let value = entry[2].trim() + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1) + meta[entry[1]] = value + } + return { meta: meta, content: normalized.slice(match[0].length).trim() } +} + +/** + * Register the bundled skills. + * + * @returns the number of skills registered. + */ +export function registerSkills(ctx, log) { + const skills = typeof ctx.get === 'function' ? ctx.get('skills') : undefined + if (skills === null || skills === undefined || typeof skills.register !== 'function') { + log.warn('skill registry unavailable - the two bundled huggingface skills were not registered') + return 0 + } + let count = 0 + for (const entry of SKILL_FILES) { + try { + const file = fileURLToPath(new URL(entry.file, import.meta.url)) + const { meta, content } = parseSkillFile(readFileSync(file, 'utf8')) + if (content.length === 0) { + log.warn('skill file is empty: ' + entry.file) + continue + } + const skillName = typeof meta.name === 'string' && meta.name.length > 0 ? meta.name : entry.name + ctx.effect( + () => + skills.register({ + name: skillName, + description: typeof meta.description === 'string' ? meta.description : '', + whenToUse: typeof meta.whenToUse === 'string' ? meta.whenToUse : undefined, + content: content, + provider: 'dsh-huggingface', + source: 'bundled', + path: file, + resourceBase: { kind: 'directory', path: path.dirname(file) }, + }), + 'dsh-huggingface: skill ' + skillName, + ) + count += 1 + } catch (err) { + log.warn('could not register skill ' + entry.name + ': ' + (err && err.message ? err.message : String(err))) + } + } + return count +} + +// --------------------------------------------------------------------------- +// Activation +// --------------------------------------------------------------------------- +/** + * Activate the row. + * + * @param ctx - cordis context (inject: tools). + */ +export function apply(ctx) { + const deps = createDeps(ctx) + deps.log.info(activationLine(deps)) + const skillCount = registerSkills(ctx, deps.log) + deps.log.info('registered ' + skillCount + ' bundled skill(s)') + for (const tool of buildTools(deps)) { + ctx.effect(() => ctx.tools.register(tool), 'dsh-huggingface: tool ' + tool.name) + } +} + +/** Exported for the tracked checks: the parts of this row worth driving directly. */ +export const __internals = { + buildTools, + createDeps, + registerSkills, + parseSkillFile, + activationLine, + CAPABILITIES, + PLUGIN_VERSION, + SKILL_FILES, +} diff --git a/packages/dsh-huggingface/lib/paths.js b/packages/dsh-huggingface/lib/paths.js new file mode 100644 index 0000000..7fa62ef --- /dev/null +++ b/packages/dsh-huggingface/lib/paths.js @@ -0,0 +1,82 @@ +/** + * dsh-huggingface — where the cache is, in the order huggingface_hub resolves it. + * + * The precedence is the library's own (`huggingface_hub.constants`), because a + * reader who moved their cache with one variable must not be told about a + * different directory by this row: + * + * HF_HUB_CACHE > HUGGINGFACE_HUB_CACHE > HF_HOME/hub > ~/.cache/huggingface/hub + * + * The deprecated `TRANSFORMERS_CACHE` is read LAST and reported as deprecated + * rather than as a supported location: it still moves the cache for some + * library versions, so silently ignoring it would make this row describe the + * wrong directory on a machine that set it. + * + * Nothing here writes, probes or creates a directory. + */ + +import os from 'node:os' +import path from 'node:path' + +/** The variable names, in resolution order, each with what it means. */ +export const CACHE_ENV_ORDER = [ + { key: 'HF_HUB_CACHE', kind: 'root' }, + { key: 'HUGGINGFACE_HUB_CACHE', kind: 'root' }, + { key: 'HF_HOME', kind: 'home' }, + { key: 'TRANSFORMERS_CACHE', kind: 'root', deprecated: true }, +] + +/** True when a variable holds a usable path. */ +function usable(value) { + return typeof value === 'string' && value.trim() !== '' +} + +/** + * Resolve the cache root and say which variable chose it. + * + * @param env - the environment (`process.env` by default). + * @param homedir - the home directory (`os.homedir()` by default). + * @returns `{ root, from, deprecated, candidates }` where `candidates` is every + * directory that COULD hold a cache, so a caller can report the ones that + * exist without claiming the others are empty. + */ +export function resolveCacheRoot(env = process.env, homedir = os.homedir()) { + if (usable(env.HF_HUB_CACHE)) return { root: path.resolve(env.HF_HUB_CACHE.trim()), from: 'HF_HUB_CACHE', deprecated: false } + if (usable(env.HUGGINGFACE_HUB_CACHE)) return { root: path.resolve(env.HUGGINGFACE_HUB_CACHE.trim()), from: 'HUGGINGFACE_HUB_CACHE', deprecated: false } + if (usable(env.HF_HOME)) return { root: path.join(path.resolve(env.HF_HOME.trim()), 'hub'), from: 'HF_HOME', deprecated: false } + for (const entry of CACHE_ENV_ORDER) { + if (entry.deprecated === true && usable(env[entry.key])) { + return { root: path.resolve(env[entry.key].trim()), from: entry.key, deprecated: true } + } + } + return { root: path.join(homedir, '.cache', 'huggingface', 'hub'), from: 'default', deprecated: false } +} + +/** + * Whether the libraries are told to stay off the network. + * + * Both variables are read: `HF_HUB_OFFLINE` governs the Hub client and + * `TRANSFORMERS_OFFLINE` is what transformers users set, and a machine with + * either set must not be sent to the network by this row. + */ +export function offlineOf(env = process.env) { + const value = String(env.HF_HUB_OFFLINE ?? env.TRANSFORMERS_OFFLINE ?? '').trim().toLowerCase() + return value === '1' || value === 'true' || value === 'yes' +} + +/** + * Whether a token is configured - the PRESENCE only, never the value. + * + * `HF_TOKEN` wins over the stored file, because that is the order the library + * reads them in. The caller reports "a token is set (HF_TOKEN)" and never the + * secret; nothing in this row reads the file's contents. + * + * @param env - the environment. + * @param tokenFileExists - whether `~/.cache/huggingface/token` exists. + */ +export function tokenPresence(env = process.env, tokenFileExists = false) { + if (usable(env.HF_TOKEN)) return { present: true, source: 'HF_TOKEN' } + if (usable(env.HUGGING_FACE_HUB_TOKEN)) return { present: true, source: 'HUGGING_FACE_HUB_TOKEN' } + if (tokenFileExists) return { present: true, source: 'stored token file' } + return { present: false, source: '' } +} diff --git a/packages/dsh-huggingface/lib/tools.js b/packages/dsh-huggingface/lib/tools.js new file mode 100644 index 0000000..2648a3d --- /dev/null +++ b/packages/dsh-huggingface/lib/tools.js @@ -0,0 +1,600 @@ +/** + * dsh-huggingface — the five tools, and the verdict each one ends with. + * + * The row exists for ONE question a person asks before committing disk and + * bandwidth: *what am I about to download, and do I already have it?* Every + * answer therefore ends in a verdict rather than a wall of metadata: + * + * - `hf_status` counts what is on this disk and separates COMPLETE repos from + * the metadata-only stubs that look identical in a directory listing; + * - `hf_search` is a ranked list, with the licence and gated flag a download + * would need first; + * - `hf_repo` is the decision: weight, licence, gated status, which files a + * consumer would actually fetch, and whether the local copy is complete and + * at the CURRENT revision; + * - `hf_cache` lists, verifies, and removes - an unconfirmed removal is the + * CLI's own --dry-run, and a confirmed one needs the target repeated back; + * - `hf_download` is the only call that moves bytes: a projected size first, a + * ceiling it will not cross, then the repo id repeated back, and afterwards + * the bytes the cache actually GAINED. + */ + +import { existsSync } from 'node:fs' +import path from 'node:path' + +import { HfError, messageOf } from './errors.js' +import { CAPS, validateCache, validateDownload, validateRepo, validateSearch } from './validate.js' +import { describeRepoDir, repoDirName, scanCache } from './cache.js' +import { offlineOf, resolveCacheRoot, tokenPresence } from './paths.js' +import { resolveCli } from './cli.js' +import { + buildCacheArgv, + buildDownloadArgv, + buildInfoArgv, + buildSearchArgv, + callCli, + consumersOf, + normalizeInfo, + parseDownloadAnswer, + projectDownload, + runHf, +} from './hf.js' + +/** The output shape every tool returns: prose for the model, a view for the card. */ +const OUTPUT = { + schema: { + type: 'object', + properties: { text: { type: 'string' }, view: { type: 'object' } }, + required: ['text', 'view'], + }, + render: (_args, value) => [{ type: 'text', text: value.text }], + presentationMeta: (_args, value) => value.view, +} + +/** A card for the transcript. */ +function present(title) { + return { + presentCall: () => ({ card: 'generic', title: title, kind: 'other' }), + presentResult: (_args, result) => ({ card: 'generic', title: title, content: result && result.text ? result.text : '' }), + } +} + +/** A refusal: a sentence, and a view a caller can branch on. */ +function refusal(code, message, extra) { + return { text: message, view: { ok: false, code: code, ...(extra ?? {}) } } +} + +/** The same refusal for any thrown failure. */ +function failureOf(error) { + if (error instanceof HfError) return refusal(error.code, error.message, error.details) + return refusal('FAILED', error && error.message ? String(error.message) : String(error)) +} + +// --------------------------------------------------------------------------- +// formatting +// --------------------------------------------------------------------------- +/** Bytes as a reader reads them. */ +export function formatBytes(bytes) { + if (!Number.isFinite(bytes) || bytes < 0) return 'n/a' + if (bytes < 1024) return bytes + ' B' + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let index = 0 + while (value >= 1024 && index < units.length - 1) { + value /= 1024 + index += 1 + } + return (value >= 100 ? value.toFixed(0) : value.toFixed(1)) + ' ' + units[index] +} + +/** A count with thousands separators. */ +export function formatCount(value) { + return Number.isFinite(value) ? String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'n/a' +} + +/** Pad a column, clipping it to its width. */ +function cell(value, width) { + const text = String(value === undefined || value === null ? '' : value) + const cut = text.length > width ? text.slice(0, Math.max(0, width - 1)) + '\u2026' : text + return cut.padEnd(width) +} + +/** A fixed-width table. */ +function table(headers, rows) { + if (rows.length === 0) return headers.join(' ') + const widths = headers.map((header, index) => Math.min(46, Math.max(header.length, ...rows.map((row) => String(row[index] ?? '').length)))) + const line = (cells) => cells.map((value, index) => cell(value, widths[index])).join(' ').trimEnd() + return [line(headers), ...rows.map(line)].join('\n') +} + +/** A date, or the raw ISO slice. */ +function dayOf(iso) { + const text = String(iso ?? '') + return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : '' +} + +/** One repo's local state, without scanning every repo in the cache. */ +function localState(root, type, id) { + const directory = repoDirName(type, id) + if (directory === null) return null + const entry = describeRepoDir(root, directory) + if (entry === null) return null + return { bytes: entry.bytes, files: entry.files, revision: entry.revision, weights: entry.weights, stub: entry.stub, layout: entry.layout, modifiedMs: entry.modifiedMs } +} + +/** The local verdict for one repo against the Hub's current revision. */ +function localVerdict(local, hubSha) { + if (local === null) return { state: 'absent', label: 'not cached on this machine' } + if (local.stub) { + return { state: 'stub', label: 'cached, but METADATA ONLY (' + formatBytes(local.bytes) + ', no weight file) - it cannot be loaded' } + } + const stale = hubSha !== '' && local.revision !== '' && hubSha !== local.revision + if (stale) { + return { state: 'stale', label: 'cached at ' + local.revision.slice(0, 12) + ', but the Hub\'s current revision is ' + hubSha.slice(0, 12) + ' - a load would fetch the difference' } + } + return { state: 'complete', label: 'cached and complete (' + formatBytes(local.bytes) + ')' } +} + +// --------------------------------------------------------------------------- +// the tools +// --------------------------------------------------------------------------- +/** A repo's weight, with the measure that produced it. */ +export function weightLine(info) { + if (info.sizesComplete) return formatBytes(info.totalBytes) + ' in ' + info.files.length + ' file(s)' + if (info.totalSource === 'hub storage') { + return formatBytes(info.totalBytes) + ' on the Hub (used_storage: the whole repo, every file and revision - this CLI reports no per-file sizes)' + } + if (info.totalSource === 'file sizes') return formatBytes(info.totalBytes) + ' in ' + info.files.length + ' file(s) (LOWER BOUND: ' + info.unknownSizes + ' had no reported size)' + return 'size not reported' +} + +/** Build the tools. @param deps - `{ env, runner, now, cache, log }`. */ +export function buildTools(deps) { + /** `hf_status`: what is here, without touching the network. */ + const status = { + name: 'hf_status', + description: [ + 'Report the Hugging Face surface on THIS machine: whether the `hf` CLI is on PATH and which version it is, where the cache lives (and which variable chose it), every repo already downloaded with its BYTE-EXACT size, and - the part a directory listing cannot tell you - which of those repos are COMPLETE and which are metadata-only stubs that cannot be loaded.', + 'Call this FIRST. It starts no download and makes no network request: it reads the cache directory, the environment and one `hf --version`.', + 'Auth is reported as a PRESENCE only ("a token is set (stored token file)"), because the token is a credential: this tool never reads, echoes or logs it, and `hf auth whoami` is the command that names the account.', + ].join('\n'), + parameters: { type: 'object', additionalProperties: false, properties: {} }, + output: OUTPUT, + ...present('Hugging Face status'), + async execute() { + try { + const cacheRoot = resolveCacheRoot(deps.env) + const scan = scanCache(cacheRoot.root) + const cli = await resolveCli(deps) + const offline = offlineOf(deps.env) + const token = tokenPresence(deps.env, existsSync(path.join(cacheRoot.root, '..', 'token'))) + const largest = scan.repos.slice(0, 5) + const stubs = scan.repos.filter((repo) => repo.stub) + + const lines = [] + lines.push('Hugging Face CLI: ' + (cli.bin === null ? 'none on this PATH (install `pip install -U huggingface_hub`; the cache scan still works)' : cli.bin + ' ' + (cli.version === '' ? '(version not reported)' : cli.version) + ' (' + cli.source + ')')) + lines.push('Cache: ' + cacheRoot.root + ' (from ' + cacheRoot.from + (cacheRoot.deprecated ? ', DEPRECATED variable' : '') + ')') + if (!scan.exists) { + lines.push(' the directory does not exist: nothing has been downloaded here yet.') + } else { + lines.push(' ' + scan.counts.repos + ' repo(s), ' + formatBytes(scan.counts.bytes) + ' on disk') + lines.push(' ' + scan.counts.complete + ' complete \u00b7 ' + scan.counts.stubs + ' metadata only (no weight file)') + const byType = Object.entries(scan.counts.byType).map(([type, count]) => count + ' ' + type + (count === 1 ? '' : 's')).join(' \u00b7 ') + if (byType !== '') lines.push(' ' + byType) + if (largest.length > 0) { + lines.push('') + lines.push(table(['LARGEST', 'TYPE', 'SIZE', 'FILES', 'UPDATE FILE'], largest.map((repo) => [repo.id, repo.type, formatBytes(repo.bytes), String(repo.files), repo.stub ? 'none' : 'yes']))) + } + if (stubs.length > 0) { + lines.push('') + lines.push('Metadata only - these look present and cannot be loaded (' + stubs.length + '):') + for (const repo of stubs.slice(0, 10)) lines.push(' ' + repo.id + ' (' + repo.type + ', ' + formatBytes(repo.bytes) + ')') + if (stubs.length > 10) lines.push(' ... and ' + (stubs.length - 10) + ' more; `hf_cache` action "list" shows all') + lines.push('A load of one of these would go to the network. `hf_repo` says what it would weigh.') + } + } + lines.push('') + lines.push('Auth: ' + (token.present ? 'a token is set (' + token.source + ') - never read or echoed here; `hf auth whoami` names the account' : 'no token set - public repos work, gated and private ones need `hf auth login`')) + lines.push('Offline: ' + (offline ? 'yes (HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE is set) - search, info and download will refuse' : 'no')) + lines.push('') + lines.push('Next: `hf_repo` for one repo\'s weight, licence and local state; `hf_search` to find one; `hf_cache` to verify or reclaim space; `hf_download` to fetch (it reports the size first).') + return { + text: lines.join('\n'), + view: { + ok: true, + cli: { bin: cli.bin, version: cli.version, source: cli.source }, + cache: { root: cacheRoot.root, from: cacheRoot.from, deprecated: cacheRoot.deprecated, exists: scan.exists, counts: scan.counts }, + largest: largest.map((repo) => ({ id: repo.id, type: repo.type, bytes: repo.bytes, stub: repo.stub })), + stubs: stubs.map((repo) => ({ id: repo.id, type: repo.type, bytes: repo.bytes })), + auth: token, + offline, + }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `hf_search`: ranked ids, with the flags a download needs. */ + const search = { + name: 'hf_search', + description: [ + 'Search the Hub for models, datasets or spaces: a free-text `query`, an `author` (org or user), tag `filters`, a `sort` key (downloads, likes, last_modified, created_at, trending_score) and a `limit` up to 50.', + 'It returns ids with downloads, likes, last update, pipeline tag and library - the ranking columns, so the choice is made on evidence. It does NOT download anything.', + 'A machine in offline mode (HF_HUB_OFFLINE=1) is refused with the variable that turns it off, because a search with no network can only fail.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + query: { type: 'string', description: 'Free text, e.g. "qwen3 8b" or "whisper large". Omit to list by sort order.' }, + type: { type: 'string', enum: ['model', 'dataset', 'space'], description: 'Which repo kind to search. Default model.' }, + limit: { type: 'integer', description: 'How many results: 1-50. Default 10.' }, + author: { type: 'string', description: 'An org or user name, e.g. "Qwen" or "sentence-transformers".' }, + filters: { type: 'array', items: { type: 'string' }, description: 'Tag filters, e.g. ["text-generation"] or ["license:apache-2.0"]. At most 5.' }, + sort: { type: 'string', enum: ['created_at', 'downloads', 'last_modified', 'likes', 'trending_score'], description: 'Ranking key.' }, + }, + }, + output: OUTPUT, + ...present('Hugging Face search'), + async execute(args) { + try { + if (offlineOf(deps.env)) { + return refusal('OFFLINE', 'This machine is in offline mode (' + (deps.env.HF_HUB_OFFLINE === '1' ? 'HF_HUB_OFFLINE=1' : 'TRANSFORMERS_OFFLINE=1') + '), so a Hub search cannot answer. Unset it for the search, or use `hf_cache` and `hf_repo` on what is already on disk.') + } + const spec = validateSearch(args) + const answer = await runHf(deps, buildSearchArgv, spec, { timeoutMs: CAPS.readTimeoutMs }) + const results = Array.isArray(answer.data) ? answer.data : Array.isArray(answer.data?.models) ? answer.data.models : [] + const rows = results.slice(0, spec.limit).map((entry) => { + const body = entry !== null && typeof entry === 'object' ? entry : {} + return { + id: typeof body.id === 'string' ? body.id : typeof body.modelId === 'string' ? body.modelId : '', + downloads: typeof body.downloads === 'number' ? body.downloads : null, + likes: typeof body.likes === 'number' ? body.likes : null, + // MEASURED: `hf models list` answers `created_at`, not `lastModified`. + created: dayOf(body.createdAt ?? body.created_at ?? body.lastModified), + task: typeof body.pipeline_tag === 'string' ? body.pipeline_tag : '', + library: typeof body.library_name === 'string' ? body.library_name : '', + gated: body.gated === true || body.gated === 'auto' || body.gated === 'manual' ? String(body.gated) : '', + } + }).filter((entry) => entry.id !== '') + const lines = [] + const what = spec.query === '' ? 'the Hub' : '"' + spec.query + '"' + lines.push(rows.length + ' ' + spec.type + '(s) for ' + what + (spec.sort === '' ? '' : ', sorted by ' + spec.sort) + (spec.author === '' ? '' : ', author ' + spec.author)) + if (rows.length === 0) { + lines.push('') + lines.push('Nothing matched. A Hub search is exact about the query: try fewer words, or drop the `filters`.') + } else { + lines.push(table(['ID', 'DOWNLOADS', 'LIKES', 'CREATED', 'TASK', 'LIB'], rows.map((entry) => [entry.id, formatCount(entry.downloads), formatCount(entry.likes), entry.created, entry.task, entry.library]))) + } + lines.push('') + lines.push('Next: `hf_repo` on an id gives the licence, the gated flag, the file sizes and whether this disk already has it. Nothing was downloaded.') + return { text: lines.join('\n'), view: { ok: true, type: spec.type, query: spec.query, count: rows.length, results: rows } } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `hf_repo`: the download decision, one repo at a time. */ + const repo = { + name: 'hf_repo', + description: [ + 'Describe ONE Hub repo before anything is fetched: licence, gated status (and the page that accepts it), downloads and likes, the architecture and parameter count when the card reports them, the file list, the repo weight AS THE HUB REPORTS IT, which files each CONSUMER would actually fetch (transformers, sentence-transformers, diffusers, llama.cpp/Ollama quants, ONNX), and whether THIS machine already holds it - complete, metadata-only, at an older revision, or absent.', + 'This is the tool that answers "how big is it and do I already have it" without downloading a byte. MEASURED: this CLI line gives no per-file sizes (its `--expand siblings` carries only names), so the weight is the Hub\'s `used_storage` - labelled as such rather than summed from files that were never sized.', + 'With no network (or in offline mode) it reports what is on disk and says the Hub side was not asked.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['repo'], + properties: { + repo: { type: 'string', description: 'A Hub id as `org/name`, e.g. "sentence-transformers/all-mpnet-base-v2".' }, + type: { type: 'string', enum: ['model', 'dataset', 'space'], description: 'Repo kind. Default model.' }, + revision: { type: 'string', description: 'A branch, tag or commit to describe instead of the default branch.' }, + }, + }, + output: OUTPUT, + ...present('Hugging Face repo'), + async execute(args) { + try { + const spec = validateRepo(args) + const cacheRoot = resolveCacheRoot(deps.env) + const local = localState(cacheRoot.root, spec.type, spec.repo) + const offline = offlineOf(deps.env) + if (offline) { + const verdict = localVerdict(local, '') + const lines = [spec.repo + ' (' + spec.type + ') - offline, so the Hub side was not asked', '', 'Local: ' + verdict.label] + if (local !== null) { + lines.push(' ' + formatBytes(local.bytes) + ' in ' + local.files + ' file(s), revision ' + (local.revision === '' ? 'unknown' : local.revision.slice(0, 12)) + ', layout ' + local.layout) + if (local.weights === false) lines.push(' No weight file is present: this copy cannot be loaded, and a load would need the network this machine has turned off.') + } + lines.push('') + lines.push('Unset HF_HUB_OFFLINE / TRANSFORMERS_OFFLINE to ask the Hub about the licence, sizes and current revision.') + return { text: lines.join('\n'), view: { ok: true, offline: true, repo: { id: spec.repo, type: spec.type }, local: { ...verdict, entry: local } } } + } + const answer = await runHf(deps, buildInfoArgv, spec, { timeoutMs: CAPS.readTimeoutMs }) + const info = normalizeInfo(answer.data, spec) + const verdict = localVerdict(local, info.sha) + const consumers = consumersOf(info.files) + const gatedUrl = 'https://huggingface.co/' + (spec.type === 'dataset' ? 'datasets/' : spec.type === 'space' ? 'spaces/' : '') + spec.repo + + const lines = [] + lines.push(info.repo + ' (' + spec.type + ')' + (info.architectures.length > 0 ? ' \u00b7 ' + info.architectures[0] : info.modelType !== '' ? ' \u00b7 ' + info.modelType : '') + (info.licence === '' ? ' \u00b7 licence not stated' : ' \u00b7 ' + info.licence)) + const facts = [] + if (info.params !== null) facts.push(formatParamCount(info.params) + ' params') + if (info.contextLength !== null) facts.push('context ' + formatCount(info.contextLength)) + if (info.pipelineTag !== '') facts.push(info.pipelineTag) + if (info.library !== '') facts.push(info.library) + if (facts.length > 0) lines.push(' ' + facts.join(' \u00b7 ')) + lines.push(' ' + weightLine(info)) + const popularity = [] + if (info.downloads !== null) popularity.push(formatCount(info.downloads) + ' downloads') + if (info.likes !== null) popularity.push(formatCount(info.likes) + ' likes') + const modified = dayOf(info.lastModified) + if (modified !== '') popularity.push('modified ' + modified) + if (popularity.length > 0) lines.push(' ' + popularity.join(' \u00b7 ')) + if (info.gated !== '') lines.push(' GATED (' + info.gated + '): a person must accept the licence first - ' + gatedUrl) + if (info.private) lines.push(' PRIVATE: needs a token with access.') + lines.push('') + lines.push('Local: ' + verdict.label) + if (verdict.state === 'complete' && local !== null) lines.push(' revision ' + local.revision.slice(0, 12) + ' \u00b7 layout ' + local.layout + ' \u00b7 ' + local.files + ' file(s)') + if (consumers.length > 0) { + lines.push('') + lines.push('What a consumer would fetch:') + for (const consumer of consumers) { + const shown = consumer.files.slice(0, 6).join(', ') + const more = consumer.files.length > 6 ? ', +' + (consumer.files.length - 6) + ' more' : '' + lines.push(' ' + consumer.consumer + ': ' + shown + more) + lines.push(' ' + consumer.note) + } + } + const biggest = info.files.filter((file) => file.bytes !== null).sort((left, right) => right.bytes - left.bytes).slice(0, CAPS.maxFilesListed) + if (biggest.length > 0) { + lines.push('') + lines.push(table(['FILE', 'SIZE'], biggest.map((file) => [file.name, formatBytes(file.bytes)]))) + if (info.files.length > biggest.length) lines.push('... ' + (info.files.length - biggest.length) + ' smaller file(s)') + } else if (info.files.length > 0) { + lines.push('') + lines.push(info.files.length + ' file(s): ' + info.files.slice(0, 8).map((file) => file.name).join(', ') + (info.files.length > 8 ? ', ...' : '')) + lines.push('This CLI reports no per-file sizes, so narrow a download by `files` or `include` rather than by measurement.') + } + lines.push('') + lines.push(verdict.state === 'absent' ? 'Next: `hf_download` to fetch it - it reports this size and needs the repo id repeated back' : 'Next: `hf_cache` action "verify" to check the local bytes, or `hf_download` to fetch what is missing') + return { + text: lines.join('\n'), + view: { + ok: true, + offline: false, + repo: { + id: info.repo, + type: info.type, + sha: info.sha, + licence: info.licence, + gated: info.gated, + private: info.private, + downloads: info.downloads, + likes: info.likes, + pipelineTag: info.pipelineTag, + library: info.library, + architectures: info.architectures, + modelType: info.modelType, + contextLength: info.contextLength, + params: info.params, + bytes: info.totalBytes, + sizesComplete: info.sizesComplete, + files: info.files, + }, + local: { ...verdict, entry: local }, + consumers, + }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `hf_cache`: list, verify, and reclaim - never silently. */ + const cache = { + name: 'hf_cache', + description: [ + 'Work the cache on THIS disk: `action: "list"` (the default) scans it without any CLI or network and reports every repo with its exact bytes, file count, whether it holds a weight file, and its revision; `verify` asks the CLI to checksum one repo revision; `prune` removes detached revisions and incomplete downloads; `rm` removes one repo.', + 'NEITHER REMOVAL HAPPENS WITHOUT `confirm`: `rm` wants the repo id repeated back, `prune` wants the word "prune". Without it the call runs the CLI\'s own `--dry-run` and reports what WOULD be freed - a real preview, not prose about one.', + 'This is the only place a gigabyte is reclaimed, and it is also the place that names the metadata-only stubs: entries that look cached, weigh a few KB, and cannot be loaded.', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + properties: { + action: { type: 'string', enum: ['list', 'verify', 'prune', 'rm'], description: 'Default list.' }, + repo: { type: 'string', description: 'For verify and rm: the repo id as `org/name`.' }, + type: { type: 'string', enum: ['model', 'dataset', 'space'], description: 'Repo kind for repo/verify/rm, and a filter for list. Default model.' }, + revision: { type: 'string', description: 'For verify: the revision to check. Default main.' }, + confirm: { type: 'string', description: 'The repo id (for rm) or the word "prune", repeated back. Without it the call is a dry run.' }, + filter: { type: 'string', description: 'For list: only ids containing this text.' }, + limit: { type: 'integer', description: 'For list: how many rows, 1-500. Default 100.' }, + }, + }, + output: OUTPUT, + ...present('Hugging Face cache'), + async execute(args) { + try { + const spec = validateCache(args) + const cacheRoot = resolveCacheRoot(deps.env) + if (spec.action === 'list') { + const scan = scanCache(cacheRoot.root, { type: spec.type === '' ? undefined : spec.type, filter: spec.filter, limit: spec.limit }) + const lines = [] + lines.push('Cache ' + cacheRoot.root + ' (from ' + cacheRoot.from + ')') + if (!scan.exists) { + lines.push(' the directory does not exist: nothing has been downloaded here yet.') + lines.push('') + lines.push('`hf_download` writes here; nothing is there to verify or remove.') + return { text: lines.join('\n'), view: { ok: true, root: cacheRoot.root, exists: false, counts: scan.counts, repos: [] } } + } + const shown = scan.repos + lines.push(' ' + scan.counts.repos + ' repo(s), ' + formatBytes(scan.counts.bytes) + ' \u00b7 ' + scan.counts.complete + ' complete \u00b7 ' + scan.counts.stubs + ' metadata only') + if (scan.limited) lines.push(' showing ' + shown.length + ' (limit ' + spec.limit + ')') + if (shown.length === 0) lines.push(' no repo matched.') + else { + lines.push('') + lines.push(table(['ID', 'TYPE', 'SIZE', 'FILES', 'WEIGHTS', 'REVISION'], shown.map((entry) => [entry.id, entry.type, formatBytes(entry.bytes), String(entry.files), entry.weights ? 'yes' : 'NO', entry.revision === '' ? 'n/a' : entry.revision.slice(0, 8)]))) + } + lines.push('') + if (scan.counts.stubs > 0) lines.push(scan.counts.stubs + ' entries hold no weight file - they cannot be loaded. `hf_cache` action "rm" with the id repeated back removes one; `hf_repo` says what a real download would weigh.') + lines.push('Reclaim space with `hf_cache` action "prune" (confirm "prune") or "rm" (confirm the repo id); both are dry runs without it.') + return { text: lines.join('\n'), view: { ok: true, root: cacheRoot.root, from: cacheRoot.from, exists: true, counts: scan.counts, repos: shown } } + } + + if (spec.action === 'verify') { + const answer = await runHf(deps, buildCacheArgv, spec, { timeoutMs: CAPS.downloadTimeoutMs }) + const body = answer.data !== null && typeof answer.data === 'object' ? answer.data : {} + const lines = [] + lines.push('Verified ' + spec.repo + (spec.revision === '' ? '' : ' at ' + spec.revision) + ' in ' + Math.round(answer.elapsedMs / 100) / 10 + ' s') + for (const [key, value] of Object.entries(body)) { + if (key === 'repo_id' || key === 'id') continue + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') lines.push(' ' + key + ': ' + value) + if (Array.isArray(value)) lines.push(' ' + key + ': ' + (value.length === 0 ? 'none' : value.length + ' entry/entries')) + } + lines.push('') + lines.push('A checksum verdict is the CLI\'s own: "OK" means the bytes match the Hub\'s, and any mismatch is listed above.') + return { text: lines.join('\n'), view: { ok: true, repo: spec.repo, revision: spec.revision, report: body } } + } + + // prune / rm + const target = spec.action === 'prune' ? 'detached revisions and incomplete downloads' : spec.repo + const before = spec.action === 'rm' ? localState(cacheRoot.root, spec.type, spec.repo) : null + const confirmed = spec.confirm === (spec.action === 'prune' ? 'prune' : spec.repo) + const answer = await runHf(deps, buildCacheArgv, spec, { timeoutMs: CAPS.downloadTimeoutMs }) + const after = spec.action === 'rm' ? localState(cacheRoot.root, spec.type, spec.repo) : null + const freed = before !== null && before.bytes > 0 ? before.bytes - (after === null ? 0 : after.bytes) : 0 + const lines = [] + if (!confirmed) { + lines.push('DRY RUN - nothing was removed.') + lines.push('') + lines.push('Would ' + (spec.action === 'prune' ? 'prune ' + target : 'remove ' + target + (before === null ? ' (not in the cache)' : ' (' + formatBytes(before.bytes) + ')')) + '.') + if (before !== null) lines.push('That repository holds ' + formatBytes(before.bytes) + ' in ' + before.files + ' file(s); a re-download costs exactly that.') + lines.push('') + lines.push('To do it, call again with `confirm: "' + (spec.action === 'prune' ? 'prune' : spec.repo) + '"`.') + } else { + lines.push('Removed ' + target + (freed > 0 ? ' - ' + formatBytes(freed) + ' reclaimed' : '') + '.') + if (freed === 0 && spec.action === 'rm') lines.push('The directory is gone; the byte total could not be measured from this cache layout.') + lines.push('') + lines.push('The Hub copy is untouched: `hf_download` can restore it, and `hf_repo` will report its size again.') + } + return { + text: lines.join('\n'), + view: { ok: true, action: spec.action, repo: spec.repo === '' ? null : spec.repo, confirmed, freedBytes: freed, cli: answer.data, before, after }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + /** `hf_download`: the one call that moves bytes. */ + const download = { + name: 'hf_download', + description: [ + 'Download one Hub repo into the local cache - the only call in this row that moves bytes, and the only one that needs the repo id repeated back as `confirm`.', + 'It reports the weight the Hub gives for the repo FIRST and refuses a download larger than `maxBytes` (8 GiB by default) rather than starting one; then it refuses without `confirm`; then it fetches, and answers with the bytes the cache actually GAINED, the files, and the elapsed time.', + 'Narrow it with `files` (repo-relative paths) or `include` / `exclude` globs - `*` stays inside a segment, `**` crosses them - because a repo often ships four quantizations and a tokenizer you already have. A narrowed selection cannot be measured on this CLI line (no per-file sizes), and the plan says so instead of guessing. It never accepts or echoes a token: authentication is the CLI\'s own (`hf auth login`).', + ].join('\n'), + parameters: { + type: 'object', + additionalProperties: false, + required: ['repo'], + properties: { + repo: { type: 'string', description: 'A Hub id as `org/name`.' }, + type: { type: 'string', enum: ['model', 'dataset', 'space'], description: 'Repo kind. Default model.' }, + files: { type: 'array', items: { type: 'string' }, description: 'Repo-relative paths to fetch. At most 200; use include for more.' }, + include: { type: 'array', items: { type: 'string' }, description: 'Glob patterns to include, e.g. ["*.safetensors", "*.json"].' }, + exclude: { type: 'array', items: { type: 'string' }, description: 'Glob patterns to skip, e.g. ["*.gguf", "*.onnx"].' }, + revision: { type: 'string', description: 'A branch, tag or commit. Default the repo\'s default branch.' }, + maxBytes: { type: 'number', description: 'The ceiling this call will not cross, in bytes. 1 MiB - 1 TiB. Default 8 GiB.' }, + confirm: { type: 'string', description: 'The repo id, repeated back. Without it the call reports the plan and downloads nothing.' }, + }, + }, + output: OUTPUT, + ...present('Hugging Face download'), + async execute(args) { + try { + if (offlineOf(deps.env)) { + return refusal('OFFLINE', 'This machine is in offline mode (' + (deps.env.HF_HUB_OFFLINE === '1' ? 'HF_HUB_OFFLINE=1' : 'TRANSFORMERS_OFFLINE=1') + '), so nothing can be downloaded. Unset it for this call.') + } + const spec = validateDownload(args) + const cacheRoot = resolveCacheRoot(deps.env) + const infoAnswer = await runHf(deps, buildInfoArgv, spec, { timeoutMs: CAPS.readTimeoutMs }) + const info = normalizeInfo(infoAnswer.data, spec) + if (info.gated !== '' && info.gated !== 'false') { + return refusal('GATED', info.repo + ' is gated (' + info.gated + '): a person has to accept its licence in a browser before any token can fetch it - https://huggingface.co/' + (spec.type === 'dataset' ? 'datasets/' : spec.type === 'space' ? 'spaces/' : '') + info.repo + '\n\nNothing was downloaded.', { repo: info.repo, gated: info.gated }) + } + const plan = projectDownload(info, spec) + if (plan.files.length === 0) { + return refusal('BAD_INPUT', 'No file in ' + info.repo + ' matches that selection (' + [...spec.files, ...spec.include].join(', ') + '). `hf_repo` lists what the repo actually contains.', { repo: info.repo, files: info.files.map((file) => file.name).slice(0, 40) }) + } + if (plan.bytes !== null && plan.bytes > spec.maxBytes) { + return refusal('TOO_BIG', 'That selection weighs ' + formatBytes(plan.bytes) + ', over the ' + formatBytes(spec.maxBytes) + ' ceiling for this call. Nothing was downloaded.\n\nEither narrow it with `files` / `include` / `exclude`, or raise the ceiling with `maxBytes` - deliberately, with the size in hand.', { repo: info.repo, bytes: plan.bytes, ceiling: spec.maxBytes, measured: plan.measured }) + } + if (spec.confirm !== spec.repo) { + const lines = [] + lines.push('PLAN - nothing was downloaded.') + lines.push('') + lines.push(' repo: ' + info.repo + ' (' + info.type + ')') + lines.push(' files: ' + plan.files.length + ' of ' + info.files.length) + if (plan.bytes === null) { + lines.push(' size: not measured for this selection: this CLI reports no per-file sizes') + lines.push(' the whole repo is ' + (info.totalBytes > 0 ? formatBytes(info.totalBytes) + ' (used_storage)' : 'also unreported')) + lines.push(' ceiling: ' + formatBytes(spec.maxBytes) + ' - applies only to a measured size, so narrow the selection or pass `maxBytes` knowingly') + } else { + lines.push(' size: ' + formatBytes(plan.bytes) + (plan.measured === 'repo' ? ' (the whole repo, per the Hub)' : plan.measured === 'lower-bound' ? ' (at least - some sizes were not reported)' : ' (' + plan.files.length + ' measured file(s))')) + lines.push(' ceiling: ' + formatBytes(spec.maxBytes) + ' - within it') + } + lines.push(' cache: ' + cacheRoot.root) + const local = localState(cacheRoot.root, spec.type, spec.repo) + if (local !== null) lines.push(' already: ' + formatBytes(local.bytes) + (local.stub ? ' (metadata only)' : '') + ' - the difference is what downloads') + lines.push('') + lines.push('To fetch it, call again with `confirm: "' + spec.repo + '"`.') + return refusal('NOT_CONFIRMED', lines.join('\n'), { repo: info.repo, plan, ceiling: spec.maxBytes }) + } + const before = localState(cacheRoot.root, spec.type, spec.repo) + const answer = await runHf(deps, buildDownloadArgv, spec, { timeoutMs: CAPS.downloadTimeoutMs, allowLoose: true }) + const parsed = parseDownloadAnswer(answer.data) + const after = localState(cacheRoot.root, spec.type, spec.repo) + const added = (after === null ? 0 : after.bytes) - (before === null ? 0 : before.bytes) + const lines = [] + lines.push('Downloaded ' + info.repo + ': ' + parsed.paths.length + ' file(s) reported, ' + formatBytes(Math.max(0, added)) + ' added to the cache in ' + Math.round(answer.elapsedMs / 100) / 10 + ' s') + lines.push(' cache now: ' + (after === null ? 'no directory was created' : formatBytes(after.bytes) + ' in ' + after.files + ' file(s)' + (after.weights ? ', with a weight file' : ', STILL no weight file'))) + if (parsed.paths.length > 0) { + lines.push('') + for (const entry of parsed.paths.slice(0, 8)) lines.push(' ' + entry) + if (parsed.paths.length > 8) lines.push(' ... and ' + (parsed.paths.length - 8) + ' more') + } + lines.push('') + lines.push('Next: `hf_repo` confirms the local revision and weight files; `hf_cache` action "verify" checksums the bytes.') + return { + text: lines.join('\n'), + view: { ok: true, repo: info.repo, type: info.type, plan, addedBytes: Math.max(0, added), elapsedMs: answer.elapsedMs, paths: parsed.paths, answerShape: parsed.shape, before, after }, + } + } catch (error) { + return failureOf(error) + } + }, + } + + return [status, search, repo, cache, download] +} + +/** Parameter counts as a reader sizes them: 8.8B, 418M. */ +export function formatParamCount(value) { + if (!Number.isFinite(value) || value <= 0) return 'n/a' + if (value >= 1e12) return (value / 1e12).toFixed(1) + 'T' + if (value >= 1e9) return (value / 1e9).toFixed(1) + 'B' + if (value >= 1e6) return (value / 1e6).toFixed(0) + 'M' + if (value >= 1e3) return (value / 1e3).toFixed(0) + 'K' + return String(value) +} + +/** Exported for the package check. */ +export const __tools = { formatBytes, formatCount, formatParamCount, table, localVerdict, localState } diff --git a/packages/dsh-huggingface/lib/validate.js b/packages/dsh-huggingface/lib/validate.js new file mode 100644 index 0000000..a7cd3be --- /dev/null +++ b/packages/dsh-huggingface/lib/validate.js @@ -0,0 +1,174 @@ +/** + * dsh-huggingface — the caps, and the one place an argument becomes a plan. + * + * Every limit here is a refusal, never a clamp: a search limit of 500 is + * refused with the cap named instead of being quietly turned into 50, and a + * download over the ceiling is refused with its measured size beside the + * ceiling. A clamped input is a claim about a setting nobody applied. + */ + +import { HfError } from './errors.js' + +/** Every bound this row enforces. */ +export const CAPS = { + statusTimeoutMs: 15_000, + readTimeoutMs: 30_000, + downloadTimeoutMs: 3_600_000, + /** A download larger than this needs an explicit `maxBytes` that admits it. */ + maxDownloadBytes: 8 * 1024 ** 3, + maxAllowedBytes: 1024 ** 4, + defaultSearchLimit: 10, + maxSearchLimit: 50, + maxFilesListed: 25, + maxDownloadFiles: 200, + maxPatterns: 20, + maxOutputBytes: 4_000_000, +} + +/** The repo types the Hub has, and the CLI's subcommand for each. */ +export const REPO_TYPES = { + model: { group: 'models', label: 'model' }, + dataset: { group: 'datasets', label: 'dataset' }, + space: { group: 'spaces', label: 'space' }, +} + +/** `org/name`, the only shape a Hub id has. */ +export const REPO_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}\/[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/ + +/** A revision is a branch, a tag or a commit: no spaces, no traversal. */ +const REVISION = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/ + +/** The sort keys `hf models list --sort` accepts. */ +export const SORT_KEYS = ['created_at', 'downloads', 'last_modified', 'likes', 'trending_score'] + +/** True for a non-empty string after trimming. */ +function text(value) { + return typeof value === 'string' && value.trim() !== '' +} + +/** + * Validate a repo id and type. + * + * @returns `{ repo, type, group }`. + */ +export function validateRepo(args) { + const repo = text(args.repo) ? args.repo.trim() : '' + if (repo === '') throw new HfError('BAD_INPUT', 'A repo id is required, as `org/name` (e.g. `sentence-transformers/all-mpnet-base-v2`).') + if (!REPO_ID.test(repo)) { + throw new HfError('BAD_INPUT', 'That is not a Hub repo id: expected `org/name`, got "' + repo + '". A local path is a file, not a repo - use a filesystem tool for it.') + } + const type = text(args.type) ? args.type.trim().toLowerCase() : 'model' + const entry = REPO_TYPES[type] + if (entry === undefined) throw new HfError('BAD_INPUT', 'A repo type is one of ' + Object.keys(REPO_TYPES).join(', ') + ' (got "' + type + '").') + return { repo, type, group: entry.group } +} + +/** + * Validate a search. + * + * @returns `{ query, type, group, limit, sort, author, filters }`. + */ +export function validateSearch(args) { + const type = text(args.type) ? args.type.trim().toLowerCase() : 'model' + const entry = REPO_TYPES[type] + if (entry === undefined) throw new HfError('BAD_INPUT', 'A repo type is one of ' + Object.keys(REPO_TYPES).join(', ') + ' (got "' + type + '").') + let limit = CAPS.defaultSearchLimit + if (args.limit !== undefined && args.limit !== null) { + if (typeof args.limit !== 'number' || !Number.isInteger(args.limit) || args.limit < 1 || args.limit > CAPS.maxSearchLimit) { + throw new HfError('BAD_INPUT', '`limit` is a whole number from 1 to ' + CAPS.maxSearchLimit + ' (got ' + JSON.stringify(args.limit) + ').') + } + limit = args.limit + } + let sort = '' + if (text(args.sort)) { + sort = args.sort.trim() + if (!SORT_KEYS.includes(sort)) throw new HfError('BAD_INPUT', '`sort` is one of ' + SORT_KEYS.join(', ') + ' (got "' + sort + '").') + } + const filters = Array.isArray(args.filters) ? args.filters.filter((value) => text(value)).map((value) => value.trim()) : [] + if (filters.length > 5) throw new HfError('BAD_INPUT', 'At most 5 `filters` (got ' + filters.length + ').') + if (text(args.author) && !/^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/.test(args.author.trim())) { + throw new HfError('BAD_INPUT', '`author` is an org or user name, not a path (got "' + args.author + '").') + } + return { + query: text(args.query) ? args.query.trim() : '', + type, + group: entry.group, + limit, + sort, + author: text(args.author) ? args.author.trim() : '', + filters, + } +} + +/** + * Validate a cache action. + * + * @returns `{ action, repo, type, group, revision, confirm, filter, limit }`. + */ +export function validateCache(args) { + const action = text(args.action) ? args.action.trim().toLowerCase() : 'list' + if (!['list', 'verify', 'prune', 'rm'].includes(action)) { + throw new HfError('BAD_INPUT', '`action` is one of list, verify, prune, rm (got "' + action + '").') + } + const base = { action, confirm: text(args.confirm) ? args.confirm.trim() : '' } + if (action === 'list') { + const type = text(args.type) ? args.type.trim().toLowerCase() : '' + if (type !== '' && REPO_TYPES[type] === undefined) throw new HfError('BAD_INPUT', '`type` is one of ' + Object.keys(REPO_TYPES).join(', ') + ' (got "' + type + '").') + const limit = Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 500) : 100 + return { ...base, type, filter: text(args.filter) ? args.filter.trim() : '', limit } + } + if (action === 'prune') { + // A prune is cache-wide: there is no repo to name, and demanding one would + // make the action unreachable. + return { ...base, type: '', repo: '', group: '', revision: '' } + } + const repo = validateRepo(args) + for (const key of ['revision']) { + if (text(args[key]) && !REVISION.test(args[key].trim())) throw new HfError('BAD_INPUT', '`' + key + '` is a branch, tag or commit (got "' + args[key] + '").') + } + return { ...base, ...repo, revision: text(args.revision) ? args.revision.trim() : '' } +} + +/** + * Validate a download, before anything is fetched. + * + * @returns the plan: repo, type, group, files, include, exclude, revision, + * maxBytes, confirm. + */ +export function validateDownload(args) { + const repo = validateRepo(args) + const files = Array.isArray(args.files) ? args.files : [] + if (files.length > CAPS.maxDownloadFiles) throw new HfError('BAD_INPUT', 'At most ' + CAPS.maxDownloadFiles + ' `files` per call (got ' + files.length + '); use `include` patterns for more.') + const cleanFiles = files.map((value) => { + if (!text(value)) throw new HfError('BAD_INPUT', 'A `files` entry is a repo-relative path, not an empty value.') + const name = value.trim() + if (name.startsWith('/') || /^[A-Za-z]:[\\/]/.test(name) || name.split(/[\\/]/).includes('..')) { + throw new HfError('BAD_INPUT', 'A `files` entry is a path INSIDE the repo, never an absolute path or one with ".." (got "' + name + '").') + } + return name + }) + const patterns = (value, key) => { + const list = Array.isArray(value) ? value.filter((entry) => text(entry)).map((entry) => entry.trim()) : [] + if (list.length > CAPS.maxPatterns) throw new HfError('BAD_INPUT', 'At most ' + CAPS.maxPatterns + ' `' + key + '` patterns (got ' + list.length + ').') + return list + } + let maxBytes = CAPS.maxDownloadBytes + if (args.maxBytes !== undefined && args.maxBytes !== null) { + if (typeof args.maxBytes !== 'number' || !Number.isFinite(args.maxBytes) || args.maxBytes < 1_048_576 || args.maxBytes > CAPS.maxAllowedBytes) { + throw new HfError('BAD_INPUT', '`maxBytes` is a byte count from 1 MiB to 1 TiB (got ' + JSON.stringify(args.maxBytes) + ').') + } + maxBytes = Math.floor(args.maxBytes) + } + if (text(args.revision) && !REVISION.test(args.revision.trim())) { + throw new HfError('BAD_INPUT', '`revision` is a branch, tag or commit (got "' + args.revision + '").') + } + return { + ...repo, + files: cleanFiles, + include: patterns(args.include, 'include'), + exclude: patterns(args.exclude, 'exclude'), + revision: text(args.revision) ? args.revision.trim() : '', + maxBytes, + confirm: text(args.confirm) ? args.confirm.trim() : '', + } +} diff --git a/packages/dsh-huggingface/package.json b/packages/dsh-huggingface/package.json new file mode 100644 index 0000000..4d6ef68 --- /dev/null +++ b/packages/dsh-huggingface/package.json @@ -0,0 +1,29 @@ +{ + "name": "dsh-huggingface", + "version": "0.1.0-alpha.1", + "description": "The Hugging Face Hub as a surface the agent can interrogate before it downloads: five `hf_*` tools that reconcile the Hub's own file tree against the cache on THIS disk - what a repo weighs, which files a consumer would fetch, whether it is gated, whether it is already cached and at which revision - with byte-exact local sizes the CLI's JSON does not give, a cache that distinguishes 'cached' from 'complete', and a download that names its size and needs the repo id repeated back. Host-only: zero npm dependencies, no bundled engine, nothing fetched without `confirm`.", + "type": "module", + "main": "lib/index.js", + "exports": { + ".": "./lib/index.js", + "./package.json": "./package.json" + }, + "files": [ + "lib", + "checks", + "skills", + "cordis.patch.yml" + ], + "scripts": { + "check": "node checks/check-huggingface-node.mjs" + }, + "engines": { + "node": ">=22" + }, + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "license": "AGPL-3.0-only" +} diff --git a/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md b/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md new file mode 100644 index 0000000..c903e61 --- /dev/null +++ b/packages/dsh-huggingface/skills/huggingface-cache/SKILL.md @@ -0,0 +1,160 @@ +--- +name: huggingface-cache +description: The Hugging Face cache as bytes on a disk - the models--org--name layout with blobs, snapshots and refs; why one repo's size must be summed on ONE side of that layout; the difference between a repo that is cached and one that is COMPLETE; how revisions multiply a repo's footprint; verify, prune and rm without losing what you meant to keep; moving the cache with HF_HOME and what breaks when you do; and the Windows link-versus-copy trap. +whenToUse: Use when a download "already exists" but loads nothing, when disk space is disappearing, before deleting anything from the cache, when moving it to another drive, when a model re-downloads after a revision bump, or when reporting how much a repo actually weighs. +--- + +# The Hub cache on disk + +The cache is not one file per repo. It is a content-addressed store with a +directory layout per repo, and almost every surprise about it comes from reading +that layout as if it were a plain folder. + +## The layout + +``` +$HF_HUB_CACHE/ # ~/.cache/huggingface/hub by default +├── models--Qwen--Qwen2.5-3B-Instruct/ +│ ├── blobs/ +│ │ ├── 5a1b... # the bytes, named by their hash +│ │ └── 9f3c... +│ ├── snapshots/ +│ │ └── / +│ │ ├── config.json -> ../../blobs/5a1b... +│ │ └── model.safetensors -> ../../blobs/9f3c... +│ ├── refs/ +│ │ ├── main # the text "4b1e..." - branch -> commit +│ │ └── v1.0 +│ └── .no_exist/ # markers for files confirmed absent upstream +├── datasets--org--name/ +└── spaces--org--name/ +``` + +Three facts follow from this and each one breaks a naive script: + +1. **A repo is `models--org--name`**: the `/` in the id becomes `--`, and the + type lives in the prefix. `org/name` is ambiguous until the prefix says which + kind of repo it is. +2. **The same bytes live on both sides** whenever `snapshots/` holds links: + summing blobs **and** snapshots reports a cache twice its real size. Sum + `blobs` when it has bytes, `snapshots` otherwise. +3. **On Windows, or with Xet, snapshots can be real copies** rather than links. + Measured on a machine that does this: `blobs/` was empty and a 418 MB repo was + entirely under `snapshots//`. A blobs-only size rule reports **0 bytes** + there. + +## "Cached" is not "complete" + +This is the finding worth carrying: a repo directory can exist, hold a +`config.json`, and contain **no weight file at all**. It looks identical in a +listing - and it cannot be loaded, because a load needs the weights and would go +to the network to get them. + +The test is not "does the directory exist": + +- does any file match `*.safetensors`, `*.bin`, `*.gguf`, `*.pt`, `*.onnx`, + `*.msgpack`, `*.h5`; and +- is the repo's total more than a few KB of metadata. + +Measured on one developer machine: **40 of 50 entries** were metadata-only +(3.5 KB, 7.3 KB, 0 bytes), while five held real weights (17.9 GB, 1.2 GB, 418 MB). +An agent that treats "present" as "usable" plans a pipeline that fails at load +time, after the import cost. + +## Revisions multiply the footprint + +`refs/main` is a pointer to a commit, and `snapshots//` is the content +of one commit. Two commits of the same repo can share many blobs (deduplicated +by hash) and differ in a few - but a model pushed with a new hash for every +shard costs its full size a second time. + +So "why is this repo 17 GB when the model is 9 GB?" has a real answer: two +revisions, or two quantizations in one repo. Check both before deleting +anything: + +```bash +hf cache ls --revisions --format json +hf cache verify org/name --revision +``` + +## Space, and how to reclaim it safely + +The order that does not lose work: + +```bash +hf cache ls --sort size --limit 20 +hf cache prune --dry-run +hf cache rm model/org-name --dry-run +``` + +- `prune` removes **detached revisions and incomplete downloads** - interrupted + pulls, revisions nothing points at. It is the safe one. +- `rm` removes a whole repo or a single revision, and its target is + `/` (`model/org/name`), not a bare id. +- Both accept `--dry-run`, and both **prompt for confirmation without `-y`**. + In a non-interactive process (stdin closed) a missing `-y` is not a "no", it + is a hang or an abort - so the confirmation must belong to the caller, and + `-y` is passed only after a person or an explicit tool argument has said yes. + +Deleting the cache does not delete the Hub copy; a re-download costs the same +bandwidth it cost the first time. A `rm` of a 17 GB repo is a 17 GB decision. + +## Moving the cache + +```bash +HF_HOME=/mnt/big/hf-cache hf download org/name +export HF_HOME=/mnt/big/hf-cache +``` + +`HF_HOME` puts the cache at `$HF_HOME/hub`. Precedence, highest first: + +``` +HF_HUB_CACHE > HUGGINGFACE_HUB_CACHE > HF_HOME/hub > ~/.cache/huggingface/hub +``` + +Two traps when moving: + +- A stale `TRANSFORMERS_CACHE` (deprecated, still honoured by some library + versions) silently points at the old place, so `hf` finds one cache and + transformers finds another. +- Moving the directory without the variables moves nothing for the libraries: + they will recreate the old path and re-download. Move the bytes **and** set the + variable in the shell that runs the job. + +## Offline mode + +```bash +HF_HUB_OFFLINE=1 hf cache ls +``` + +With `HF_HUB_OFFLINE=1` (or `TRANSFORMERS_OFFLINE=1`) the libraries refuse all +Hub traffic and read only the cache. That is the correct mode for a reproducible +job - and it is also why "it worked yesterday" and "it fails today" can both be +true: yesterday the cache had the revision, today the ref moved. +`from_pretrained(..., local_files_only=True)` is the per-call form. + +## Windows: links vs copies + +The POSIX cache uses symlinks, which costs nothing. Windows only creates them +with Developer Mode or an elevated process; without that, the library may copy +the file into `snapshots/` instead, doubling the footprint for the same repo and +making a blobs-only size rule report zero. `HF_HUB_DISABLE_SYMLINKS=1` forces +copies deliberately (for example on a network share) and the +`HF_HUB_DISABLE_SYMLINKS_WARNING=1` variable only silences the notice. + +## What a correct size report says + +A number is only honest with its method attached: + +- **bytes**, not "17.9G" parsed from a screen; +- **which side of the layout** was summed (blobs or snapshots); +- **complete vs metadata-only**, because a 7 KB repo is not a small model; +- **which revision**, because two revisions of one repo are two downloads; +- and the **file count**, because a directory with a `.no_exist` marker and a + single `config.json` is not a download that succeeded. + +The `dsh-huggingface` row reports exactly those: `hf_status` and `hf_cache` +action "list" give per-repo `bytes`, `layout`, `weights`, `revision` and `stub`, +`hf_repo` compares a cached revision against the Hub's own `sha`, and +`hf_download` answers with the bytes the cache GAINED rather than the bytes the +CLI says it transferred. diff --git a/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md b/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md new file mode 100644 index 0000000..f04f191 --- /dev/null +++ b/packages/dsh-huggingface/skills/huggingface-hub/SKILL.md @@ -0,0 +1,208 @@ +--- +name: huggingface-hub +description: The Hugging Face Hub as this machine's own `hf` CLI presents it - the v1 command set and what the deprecated `huggingface-cli` name still does, repo ids and the three repo types, revisions vs branches vs commits, `hf://` paths, the `--format json` contract and where it speaks in human strings, gated and private repos, authentication that never passes a token through a transcript, the environment variables that move the cache and turn the network off, and the raw Hub API endpoints for anything the CLI does not cover. +whenToUse: Use before downloading, inspecting or citing a Hub repo; when choosing between `hf` verbs; when a repo is gated, private or 404; when the JSON from the CLI is not the shape you expected; or when a script needs the Hub API directly rather than a shell call. +--- + +# The Hugging Face Hub from the command line + +The Hub is a git-backed file store with a JSON API in front of it. This install +has `hf` **1.26.1** (huggingface_hub), where `hf` is the command and +`huggingface-cli` is a deprecated alias for the same entry point. + +## The CLI, in the order worth knowing + +```bash +hf --version +hf env +``` + +`hf env` prints the resolved cache paths, tokens' *presence*, and the library +versions - the fastest way to answer "which cache is this machine actually +using". `--version` writes the version to **stdout** and an upgrade hint to +**stderr**; a parser that reads stderr first reports the version that is *not* +installed. + +| Verb | What it is for | +|---|---| +| `hf download [files]` | fetch into the cache (or `--local-dir`) | +| `hf models list / info / card` | search, metadata, README | +| `hf datasets list / info / parquet / sql` | the same for datasets, plus DuckDB over parquet | +| `hf spaces list / info / logs / restart` | Spaces, including their runtime logs | +| `hf cache ls / verify / prune / rm` | the local cache as a first-class object | +| `hf auth whoami / login / logout` | who the token belongs to | +| `hf repos create / delete` | repo lifecycle | +| `hf upload` | push files | +| `hf jobs`, `hf sandbox`, `hf endpoints` | remote compute; not a local concern | + +`hf --help` exits **non-zero** on this build (measured: -1). An exit code +is not a success signal for a help call, and no automation should infer anything +from it. + +## Repo ids and the three types + +An id is exactly `org/name` - one slash, no nesting, no local path: + +```bash +hf models info sentence-transformers/all-mpnet-base-v2 --format json +hf datasets info HuggingFaceFW/fineweb --format json +hf spaces info gradio/hello-world --format json +``` + +The type is **not** in the id. `org/name` is a model, a dataset and a space all +at once depending on the verb you call, which is why every command that takes a +non-model repo also takes `--type` (or `--repo-type`): + +```bash +hf download HuggingFaceFW/fineweb --type dataset --include "sample/*" +hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset +``` + +A bare `org/name` with no `--type` means **model**. That default is the most +common wrong answer: a dataset downloaded as a model lands in +`models--HuggingFaceFW--fineweb` and no loader finds it. + +## The JSON contract - and its two lies + +Every verb takes `--format json` (or `--json`). Three things about it are +measured on this install and are easy to get wrong: + +1. **Sizes are human strings, not bytes.** `hf cache ls --json` answers + `"size": "17.9G"`, not a number. Anything that has to do arithmetic - a + budget, a delta, a comparison - reads the directory tree instead. +2. **Times are relative.** `"last_accessed": "3 months ago"`. Fine to print, + useless to sort on. +3. **`--expand` decides the fields.** `hf models info` returns a small default + object; ask for what you need or parse a shape you do not have: + +```bash +hf models info Qwen/Qwen2.5-3B-Instruct --expand gated,cardData,siblings,safetensors,sha,downloads --format json +``` + +`siblings` is the file list, and each entry carries at least `rfilename`. On this +CLI line (1.26.1) that is **all** it carries - there is no `--blobs` flag and no +per-file size, which is why `hf models info --expand usedStorage` exists: it +answers a single `used_storage` in bytes for the whole repo. The raw API is the +place that reports per-file sizes (`?blobs=true`, below). + +```json +{ + "id": "sentence-transformers/all-mpnet-base-v2", + "sha": "e8c3b32edf5434bc2275fc9bab85f82640a19130", + "gated": false, + "cardData": { "license": "apache-2.0" }, + "siblings": [ + { "rfilename": "config.json", "size": 571 }, + { "rfilename": "model.safetensors", "size": 437971872 } + ] +} +``` + +## Revisions, branches and commits + +A repo has branches (`main`), tags (`v1.0`), and pull-request refs +(`refs/pr/1`). `sha` in the info answer is the commit the *default branch* points +at right now - the number to compare a local copy against. + +```bash +hf download org/name --revision v1.0 +hf cache verify org/name --revision refs/pr/1 +``` + +A revision that moved is why "it is already downloaded" and "it still +downloads" are both true: the cache is keyed by commit, so a new commit is a new +set of files even when the filenames are identical. + +## Gated and private + +`gated` is `false`, `"auto"` or `"manual"`. It is **not** a token problem - a +person accepts the licence on the repo page first, and only then does a token +carry access. A 403 on a gated repo before that acceptance is expected, and +retrying with a different token does not help. + +Private repos need a token with the right scope. Report the account, never the +secret: + +```bash +hf auth whoami +``` + +**A token is a credential.** It belongs in `HF_TOKEN` or the CLI's own store +(`hf auth login`), never in a command line that a transcript records, never in a +workspace file, never in a URL. A gated URL with `?token=` in it is a leak. +`hf download` also accepts `--token`; treat that flag as unavailable in an agent +session. + +## `hf://` paths + +The CLI speaks a URI form for cross-repo copies, which is also how +`hf cp` addresses a file inside a repo: + +```bash +hf cp hf://datasets/org/name/data/train.parquet . +``` + +Shape: `hf://///` where the plural is +`datasets` for a dataset and omitted for a model. This is the form `hf cache rm` +also accepts for a repo. + +## Environment variables that change behaviour + +| Variable | Effect | +|---|---| +| `HF_HUB_CACHE` | the cache root, highest precedence | +| `HUGGINGFACE_HUB_CACHE` | the same, older name | +| `HF_HOME` | the parent (`$HF_HOME/hub` is the cache) | +| `TRANSFORMERS_CACHE` | deprecated, still read by some library versions | +| `HF_TOKEN` | the credential | +| `HF_HUB_OFFLINE=1` | refuse all Hub traffic | +| `TRANSFORMERS_OFFLINE=1` | the transformers-side equivalent | +| `HF_HUB_DISABLE_TELEMETRY=1` | no usage ping | +| `HF_HUB_ENABLE_HF_TRANSFER=1` / Xet | a different transfer backend | + +The precedence order matters when a person says "I moved my cache": the +highest-numbered variable that is set wins, and a stale `TRANSFORMERS_CACHE` +silently points the cache somewhere else. + +## The raw API, when the CLI is not enough + +The Hub is also plain HTTP, and for anything the CLI does not expose this is the +contract (no token needed for public repos): + +```bash +curl -s "https://huggingface.co/api/models?search=qwen3&limit=5&sort=downloads" +curl -s "https://huggingface.co/api/models/Qwen/Qwen2.5-3B-Instruct?blobs=true" +curl -s "https://huggingface.co/Qwen/Qwen2.5-3B-Instruct/resolve/main/config.json" +``` + +- `/api/models/?blobs=true` adds per-file `size` and `lfs` blocks. +- `/api/models//tree/main?recursive=true` is the directory listing. +- `/api/datasets/` and `/api/spaces/` mirror it for the other types. +- `//resolve//` is the content URL; `?download=true` adds + `Content-Disposition`. + +Rate limits are per IP: 429 means wait, and a token raises the ceiling. + +## The tools that answer these questions + +This pack's `dsh-huggingface` row is a typed layer over exactly this CLI, and it +is worth using instead of shelling out when the question is one of these: + +| Tool | Answers | +|---|---| +| `hf_status` | is `hf` here, which version, where the cache is, what is in it (complete vs metadata-only) | +| `hf_search` | what exists, ranked, with licence and gated flags | +| `hf_repo` | what ONE repo weighs, what a consumer would fetch, whether this disk already has it, at which revision | +| `hf_cache` | list / verify / prune / rm, with an unconfirmed removal being a dry run | +| `hf_download` | fetch, after reporting the size and taking the repo id back as `confirm` | + +## Failures, and what each one means + +| Symptom | Cause | Fix | +|---|---|---| +| 401 / "Invalid credentials" | no token, or a bad one | `hf auth login` | +| 403 on a repo whose page opens | gated licence not accepted | accept it in a browser, then retry | +| 404 on a repo that exists in a browser | wrong `--type` (dataset read as model) | pass `--type dataset` | +| 404 on a *file* | the revision moved and the path changed | `hf models info --expand siblings` | +| 429 | IP rate limit | wait, or use a token | +| download "succeeds" but the file is 1 KB | the repo is metadata-only, or the include pattern matched nothing | check `siblings` before trusting a size |