hugging-bay-mcp 0.1.16 → 0.1.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -11
- package/agent-download.mjs +267 -0
- package/hb-lock.mjs +141 -0
- package/index.mjs +52 -6
- package/mcp-prompts.mjs +2 -2
- package/package.json +5 -2
- package/portable-receipt.mjs +3 -1
- package/profile-manifest.mjs +20 -3
- package/public-note-copy.mjs +10 -1
- package/registry-directory-metadata.mjs +9 -9
- package/release-authority.mjs +27 -5
- package/run-plan.mjs +11 -4
- package/run-recipes.mjs +85 -0
- package/server.json +18 -18
- package/tool-descriptions.mjs +180 -127
- package/tool-discovery.mjs +107 -0
- package/tool-input-validation.mjs +2 -2
package/README.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
# hugging-bay-mcp [](https://www.npmjs.com/package/hugging-bay-mcp) [](https://huggingbay.xyz/api/mcp)
|
|
2
2
|
|
|
3
3
|
**Promise:** Find open model files with recorded SHA-256 and license labels. Public reads need no account.<br>
|
|
4
|
-
**Install:** `npx -y hugging-bay-mcp@0.1.
|
|
4
|
+
**Install:** `npx -y hugging-bay-mcp@0.1.16`<br>
|
|
5
5
|
**MCP config (remote):** `claude mcp add --transport http hugging-bay https://huggingbay.xyz/api/mcp`<br>
|
|
6
|
-
**MCP config (stdio):** `{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.
|
|
6
|
+
**MCP config (stdio):** `{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.16"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}`<br>
|
|
7
7
|
**First call:** `search_artifacts({ "q": "Qwen3 0.6B GGUF" })`<br>
|
|
8
8
|
**Ask:** Missing a model, file, tool or feature? Ask with request_feature (hosted MCP) or POST https://huggingbay.xyz/api/v1/requests. No account. You get an id and can check its status. What shipped: https://huggingbay.xyz/changelog<br>
|
|
9
9
|
[Changelog](https://huggingbay.xyz/changelog?ref=npm) · [MCP docs](https://huggingbay.xyz/agents?ref=npm)<br>
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
## Claude Code, Codex CLI and Cursor
|
|
13
13
|
|
|
14
|
-
**
|
|
14
|
+
**Current npm release:** `0.1.16`, published 12 Nov 2026 alongside [Tug 0.2.93](https://huggingbay.xyz/desktop). **Source candidate:** `0.1.17` adds `get_download`, `verify_lock`, file resources and hb.lock v2 (see "Pin and fetch exact files" below). Use `https://huggingbay.xyz/api/mcp?profile=agent` for the agent pack or `https://huggingbay.xyz/api/mcp` for the default hosted core profile. The desktop and native hbay CLI use separate version numbers.
|
|
15
15
|
|
|
16
16
|
Public reads use no bearer token and need no OAuth login. Configure one transport
|
|
17
17
|
per server name. For Claude Code:
|
|
@@ -20,7 +20,7 @@ per server name. For Claude Code:
|
|
|
20
20
|
claude mcp add --transport http hugging-bay https://huggingbay.xyz/api/mcp
|
|
21
21
|
claude mcp list
|
|
22
22
|
# Or use stdio under a separate name:
|
|
23
|
-
claude mcp add hugging-bay-stdio -- npx -y hugging-bay-mcp@0.1.
|
|
23
|
+
claude mcp add hugging-bay-stdio -- npx -y hugging-bay-mcp@0.1.16
|
|
24
24
|
```
|
|
25
25
|
|
|
26
26
|
For Codex CLI:
|
|
@@ -38,7 +38,7 @@ url = "https://huggingbay.xyz/api/mcp"
|
|
|
38
38
|
```
|
|
39
39
|
|
|
40
40
|
For stdio, replace `url` with `command = "npx"` and
|
|
41
|
-
`args = ["-y", "hugging-bay-mcp@0.1.
|
|
41
|
+
`args = ["-y", "hugging-bay-mcp@0.1.16"]`. Codex's MCP list reports configuration;
|
|
42
42
|
it does not prove a tool call succeeded. `auth_status: "unsupported"` describes
|
|
43
43
|
OAuth support, not a requirement to sign in for public reads.
|
|
44
44
|
|
|
@@ -62,7 +62,7 @@ For Claude Desktop, open Settings → Developer → Edit Config and merge this i
|
|
|
62
62
|
`claude_desktop_config.json`. Restart Claude Desktop after saving:
|
|
63
63
|
|
|
64
64
|
```json
|
|
65
|
-
{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.
|
|
65
|
+
{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.16"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}
|
|
66
66
|
```
|
|
67
67
|
|
|
68
68
|
## First live MCP call
|
|
@@ -75,24 +75,39 @@ curl -fsS 'https://huggingbay.xyz/api/mcp' -H 'Content-Type: application/json' -
|
|
|
75
75
|
|
|
76
76
|
A JSON-RPC result without `isError` confirms the search was handled. Results may be empty; inspect any returned model before recommending it. This does not show whether a model runs on your computer.
|
|
77
77
|
|
|
78
|
+
## Pin and fetch exact files
|
|
79
|
+
|
|
80
|
+
`get_download` gives an agent one exact file in one call:
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
curl -fsS 'https://huggingbay.xyz/api/mcp' -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_download","arguments":{"id":"Qwen/Qwen2.5-0.5B-Instruct-GGUF"}}}'
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- Arguments: `id` (artifact id or owner/repo) and optional `path` (default: the recommended file).
|
|
87
|
+
- Returns `url` (a signed link that lasts at most 300 seconds; call again for a fresh one), `expiresAt`, `sha256`, `sizeBytes`, `revision`, `license`, `format`, the stable `downloadUrl`, `hbLock.text` and `run` (start commands for llama.cpp, Ollama, LM Studio, MLX and vLLM, picked from the file format; not a tested run).
|
|
88
|
+
- The link comes from the same live checks as a browser download of `downloadUrl`. Errors name the reason: `file_not_downloadable` (with the file list), `license_acceptance_required`, `busy`, `file_gone`.
|
|
89
|
+
- The result also carries a `resource_link` to `huggingbay://artifact/{id}/file/{path}` with `sha256` and `sizeBytes` in `_meta["xyz.huggingbay/file"]`. `resources/read` on that URI returns the file record, not the bytes.
|
|
90
|
+
|
|
91
|
+
Save `hbLock.text` as `hb.lock` in the repo root. The v2 format (`hugging-bay.hb-lock.v2`) lists `files` with `repo`, `revision`, `path`, `sha256`, `size`, `downloadUrl`, `license`, `artifactId` and `format`. `npx -y hugging-bay-agents fetch` downloads every pinned file, checks SHA-256 and size and resumes after a drop. `verify_lock` (agent profile) checks a lock against the current catalog. v1 locks from `write_receipt` still read.
|
|
92
|
+
|
|
78
93
|
## Profiles: stdio and hosted
|
|
79
94
|
|
|
80
95
|
**MCP 0.1.14:** typed MCP tool results, closed argument validation, and a shared 15-second wait budget across pacing and retries. The npm archive and its integrity were observed on 2026-10-29; its default stdio discovery profile has 29 tools. This is the observed historical package behavior, distinct from current hosted core.
|
|
81
96
|
|
|
82
|
-
Published 0.1.14 defaults to its historical 29-tool discovery profile. The current 0.1.
|
|
97
|
+
Published 0.1.14 defaults to its historical 29-tool discovery profile. The current 0.1.17 source candidate defaults to six hosted read-only core tools, plus local-only `ask_url` in stdio; its explicit discovery profile carries the broader catalog. The package keeps
|
|
83
98
|
the broader catalog available, but a client must opt into it explicitly:
|
|
84
99
|
|
|
85
100
|
| Transport/profile | `tools/list` | What it is |
|
|
86
101
|
| --- | --- | --- |
|
|
87
|
-
| hosted `?profile=core` / stdio `--profile core` (source 0.1.
|
|
88
|
-
| source stdio default (`node packages/mcp/index.mjs`) | **
|
|
102
|
+
| hosted `?profile=core` / stdio `--profile core` (source 0.1.17) | **6 hosted tools; 7 stdio tools** | `find_runnable`, `search_artifacts`, `get_model`, `get_download`, `get_serve_decision`, `hb_run_plan`; all read-only; the source and hosted default. Published npm 0.1.14 core has 8 tools. |
|
|
103
|
+
| source stdio default (`node packages/mcp/index.mjs`) | **7 tools** | six hosted core names plus local-only `ask_url`; `tools/list` is the authority |
|
|
89
104
|
| stdio `--profile full` | **107 tools** in 0.1.14 | the complete current stdio catalog; use `tools/list` as the authority rather than hard-coding the count |
|
|
90
105
|
| stdio `--profile verify` | inspect `tools/list` | discovery plus `get_accepted_run_proof` when `HUGGING_BAY_MCP_ENABLE_UNRELEASED_RUN_PROOF=1` |
|
|
91
|
-
| hosted source `https://huggingbay.xyz/api/mcp` | **
|
|
106
|
+
| hosted source `https://huggingbay.xyz/api/mcp` | **6 tools** | core by default; the running deployment can lag source, so inspect `tools/list`. Other profiles use `?profile=` (see `https://huggingbay.xyz/.well-known/mcp.json`) |
|
|
92
107
|
|
|
93
108
|
The default is also selected when `HUGGING_BAY_MCP_PROFILE` is empty.
|
|
94
109
|
Use
|
|
95
|
-
`--profile core` or `HUGGING_BAY_MCP_PROFILE=core` for the
|
|
110
|
+
`--profile core` or `HUGGING_BAY_MCP_PROFILE=core` for the six hosted tools plus local-only `ask_url` (eight tools in npm 0.1.14).
|
|
96
111
|
Discovery sends concise descriptions and schemas with all constraints intact.
|
|
97
112
|
Use `resources/read` with `huggingbay://tool/TOOL_NAME` for the complete
|
|
98
113
|
parameter notes and examples; the reference is restricted to the selected profile.
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Agent-native download: one call returns a signed short-lived link for one
|
|
2
|
+
// exact file plus its SHA-256, size, revision and license label, and the
|
|
3
|
+
// hb.lock v2 entry that pins it. Shared by the hosted MCP server
|
|
4
|
+
// (apps/web/server.mjs) and the npm stdio server (packages/mcp/index.mjs).
|
|
5
|
+
// The link comes from the normal byte route /api/downloads/{id}/{path}, so the
|
|
6
|
+
// same live checks run; this module never signs anything itself.
|
|
7
|
+
|
|
8
|
+
import { buildLockV2, lockEntryFromPlan, parseLock, LOCK_SITE } from "./hb-lock.mjs";
|
|
9
|
+
import { runRecipesForFile } from "./run-recipes.mjs";
|
|
10
|
+
|
|
11
|
+
export const DOWNLOAD_LINK_SCHEMA = "hugging-bay.download-link.v1";
|
|
12
|
+
export const FILE_RESOURCE_SCHEMA = "hugging-bay.file-resource.v1";
|
|
13
|
+
export const LOCK_CHECK_SCHEMA = "hugging-bay.lock-check.v1";
|
|
14
|
+
export const MAX_LINK_TTL_SECONDS = 300;
|
|
15
|
+
const ARTIFACT_ID = /^[a-z0-9][a-z0-9-]{2,150}$/;
|
|
16
|
+
export const MAX_LOCK_ARTIFACTS = 8;
|
|
17
|
+
const shellSingleQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
|
|
18
|
+
|
|
19
|
+
export const GET_DOWNLOAD_TOOL = Object.freeze({
|
|
20
|
+
name: "get_download",
|
|
21
|
+
title: "Get one exact file",
|
|
22
|
+
description: "One call for one exact model file: a signed download link (lasts at most 300 s) with its SHA-256, size, revision, license label, an hb.lock entry and start commands for llama.cpp, Ollama, LM Studio, MLX and vLLM. Omit path for the recommended file.",
|
|
23
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
24
|
+
inputSchema: { type: "object", required: ["id"], additionalProperties: false, properties: {
|
|
25
|
+
id: { type: "string", minLength: 1, maxLength: 300, description: "Artifact id or owner/repo.", examples: ["Qwen/Qwen3-4B-GGUF"] },
|
|
26
|
+
path: { type: "string", minLength: 1, maxLength: 512, description: "File path from get_model. Default: the recommended file.", examples: ["Qwen3-4B-Q5_K_M.gguf"] },
|
|
27
|
+
} },
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export const VERIFY_LOCK_TOOL = Object.freeze({
|
|
31
|
+
name: "verify_lock",
|
|
32
|
+
title: "Check an hb.lock",
|
|
33
|
+
description: "Check an hb.lock (v1 or v2) against the current catalog: each pinned file still has the same SHA-256 and size and can be downloaded. Does not read local files; npx hugging-bay-agents verify does that.",
|
|
34
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
35
|
+
inputSchema: { type: "object", required: ["lock"], additionalProperties: false, properties: {
|
|
36
|
+
lock: { type: "string", minLength: 2, maxLength: 65536, description: "The hb.lock file contents (JSON text)." },
|
|
37
|
+
} },
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
export const FILE_RESOURCE_TEMPLATE = Object.freeze({
|
|
41
|
+
uriTemplate: "huggingbay://artifact/{id}/file/{path}",
|
|
42
|
+
name: "Model file",
|
|
43
|
+
description: "One exact file: SHA-256, size, revision, license label and its download route. Reading returns this record, not the bytes; call get_download for a signed link.",
|
|
44
|
+
mimeType: "application/json",
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
export function fileResourceUri(artifactId, path) {
|
|
48
|
+
return `huggingbay://artifact/${encodeURIComponent(artifactId)}/file/${encodeURIComponent(path)}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function parseFileResourceUri(uri) {
|
|
52
|
+
if (typeof uri !== "string") return null;
|
|
53
|
+
const match = uri.match(/^huggingbay:\/\/artifact\/([^/]+)\/file\/(.+)$/);
|
|
54
|
+
if (!match) return null;
|
|
55
|
+
try {
|
|
56
|
+
const reference = decodeURIComponent(match[1]);
|
|
57
|
+
const path = match[2].split("/").map(decodeURIComponent).join("/");
|
|
58
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._/@:-]{0,199}$/.test(reference) || reference.split("/").some(part => !part || part === "." || part === "..")) return null;
|
|
59
|
+
if (!path || path.length > 512 || path.startsWith("/") || path.split("/").some(part => !part || part === "." || part === "..")) return null;
|
|
60
|
+
return { reference, path, mimeType: "application/json" };
|
|
61
|
+
} catch { return null; }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function toolError(error, message, extra = {}) {
|
|
65
|
+
return { error, message, ...extra };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function selectPlanFile(plan, path) {
|
|
69
|
+
const rows = Array.isArray(plan?.files) ? plan.files : [];
|
|
70
|
+
if (path) return rows.find(row => row?.path === path) || null;
|
|
71
|
+
const recommended = plan?.recommendedFile?.path;
|
|
72
|
+
if (recommended) return rows.find(row => row?.path === recommended) || plan.recommendedFile;
|
|
73
|
+
const ready = rows.filter(row => lockEntryFromPlan(plan, row));
|
|
74
|
+
return ready.length === 1 ? ready[0] : null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function fileChoices(plan) {
|
|
78
|
+
return (Array.isArray(plan?.files) ? plan.files : []).map(row => lockEntryFromPlan(plan, row)).filter(Boolean)
|
|
79
|
+
.slice(0, 12).map(entry => ({ path: entry.path, sizeBytes: entry.size, format: entry.format }));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function fileResourceRecord(plan, path) {
|
|
83
|
+
const row = selectPlanFile(plan, path);
|
|
84
|
+
const entry = row ? lockEntryFromPlan(plan, row) : null;
|
|
85
|
+
if (!entry) return toolError("file_not_downloadable", `No downloadable file with a recorded SHA-256 at ${path}.`, { artifactId: plan?.artifactId || null, files: fileChoices(plan) });
|
|
86
|
+
return { schema: FILE_RESOURCE_SCHEMA, uri: fileResourceUri(entry.artifactId, entry.path), artifactId: entry.artifactId, repo: entry.repo,
|
|
87
|
+
revision: entry.revision, path: entry.path, sha256: entry.sha256, sizeBytes: entry.size, license: entry.license, format: entry.format,
|
|
88
|
+
downloadUrl: entry.downloadUrl, getDownload: { tool: "get_download", arguments: { id: entry.artifactId, path: entry.path } },
|
|
89
|
+
note: "This record describes the file. The bytes come from get_download or downloadUrl; check the SHA-256 after download." };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// MCP resource entries for every downloadable file in a plan, with the
|
|
93
|
+
// SHA-256 and size in _meta (the resource body is the record, not the bytes).
|
|
94
|
+
export function fileResources(plan, limit = 24) {
|
|
95
|
+
return (Array.isArray(plan?.files) ? plan.files : []).map(row => lockEntryFromPlan(plan, row)).filter(Boolean).slice(0, limit).map(entry => ({
|
|
96
|
+
uri: fileResourceUri(entry.artifactId, entry.path), name: entry.path, title: `${entry.repo}: ${entry.path}`, mimeType: "application/json",
|
|
97
|
+
description: `${formatBytes(entry.size)}, SHA-256 ${entry.sha256.slice(0, 12)}…, license: ${entry.license}.`,
|
|
98
|
+
_meta: { "xyz.huggingbay/file": { sha256: entry.sha256, sizeBytes: entry.size, revision: entry.revision, license: entry.license } },
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function formatBytes(size) {
|
|
103
|
+
if (!Number.isFinite(size)) return "unknown size";
|
|
104
|
+
if (size >= 1e9) return `${(size / 1e9).toFixed(1)} GB`;
|
|
105
|
+
if (size >= 1e6) return `${(size / 1e6).toFixed(1)} MB`;
|
|
106
|
+
if (size >= 1e3) return `${(size / 1e3).toFixed(1)} kB`;
|
|
107
|
+
return `${size} B`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function linkTtlSeconds(value) {
|
|
111
|
+
const ttl = Number.parseInt(String(value ?? ""), 10);
|
|
112
|
+
return Number.isSafeInteger(ttl) && ttl > 0 ? Math.min(ttl, MAX_LINK_TTL_SECONDS) : MAX_LINK_TTL_SECONDS;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// The byte route hands out storage or CDN capability links. A redirect back to
|
|
116
|
+
// a huggingbay.xyz page (an interstitial, a license page) is not a file link.
|
|
117
|
+
function signedLinkAllowed(location) {
|
|
118
|
+
let url;
|
|
119
|
+
try { url = new URL(location); } catch { return false; }
|
|
120
|
+
if (url.protocol !== "https:" || url.username || url.password) return false;
|
|
121
|
+
return !["huggingbay.xyz", "www.huggingbay.xyz"].includes(url.hostname) || url.pathname.startsWith("/api/");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// io.readPlan(artifactIdOrRepo) -> download-plan JSON (throws on failure; a
|
|
125
|
+
// thrown error may carry status and body).
|
|
126
|
+
// io.openDownload(pathAndQuery) -> { status, location, header(name), body }
|
|
127
|
+
// for a GET that does not follow redirects. The caller cancels the body.
|
|
128
|
+
export async function getDownload(args, io, { now = () => Date.now() } = {}) {
|
|
129
|
+
const id = typeof args?.id === "string" ? args.id.trim() : "";
|
|
130
|
+
const path = typeof args?.path === "string" ? args.path.trim() : "";
|
|
131
|
+
if (!id) return toolError("invalid_tool_arguments", "id is required: an artifact id or owner/repo.");
|
|
132
|
+
let plan;
|
|
133
|
+
try { plan = await io.readPlan(id); } catch (error) {
|
|
134
|
+
const status = Number(error?.status) || null;
|
|
135
|
+
return toolError(status === 404 ? "not_found" : "plan_unavailable", status === 404
|
|
136
|
+
? "No public model matched this id or owner/repo. Search for the model or check the reference."
|
|
137
|
+
: "The download plan did not load. Retry in a few seconds.", { status, retryable: status !== 404 });
|
|
138
|
+
}
|
|
139
|
+
if (!ARTIFACT_ID.test(plan?.artifactId || "")) return toolError("plan_unavailable", "The download plan had no artifact id. Retry in a few seconds.", { retryable: true });
|
|
140
|
+
if (plan.error || plan.degraded || plan.stale) return toolError("plan_unavailable", "The download plan is stale or degraded right now, so no file is pinned. Retry in a few seconds.", { artifactId: plan.artifactId, retryable: true });
|
|
141
|
+
const row = selectPlanFile(plan, path);
|
|
142
|
+
const entry = row ? lockEntryFromPlan(plan, row) : null;
|
|
143
|
+
if (!entry) {
|
|
144
|
+
return toolError("file_not_downloadable", path
|
|
145
|
+
? `${path} is not a downloadable file with a recorded SHA-256 and size. Pick one of files.`
|
|
146
|
+
: "This model has no single recommended downloadable file. Pick one of files and pass its path.",
|
|
147
|
+
{ artifactId: plan.artifactId, files: fileChoices(plan), retryable: false });
|
|
148
|
+
}
|
|
149
|
+
const executionBlocked = row.executionPolicy === "blocked" || row.authorityMode === "private-download-only" || plan.authorityMode === "private-download-only";
|
|
150
|
+
const route = new URL(entry.downloadUrl);
|
|
151
|
+
let link;
|
|
152
|
+
try { link = await io.openDownload(`${route.pathname}${route.search}`); } catch {
|
|
153
|
+
link = { status: 0 };
|
|
154
|
+
}
|
|
155
|
+
const issuedAt = now();
|
|
156
|
+
const base = { schema: DOWNLOAD_LINK_SCHEMA, artifactId: entry.artifactId, repo: entry.repo, revision: entry.revision, path: entry.path,
|
|
157
|
+
sha256: entry.sha256, sizeBytes: entry.size, license: entry.license, format: entry.format, downloadUrl: entry.downloadUrl };
|
|
158
|
+
const lock = buildLockV2([entry]);
|
|
159
|
+
const filename = entry.path.split("/").pop();
|
|
160
|
+
const shared = {
|
|
161
|
+
verify: { algorithm: "sha256", sha256: entry.sha256, sizeBytes: entry.size, command: `shasum -a 256 ${filename}` },
|
|
162
|
+
hbLock: { filename: "hb.lock", text: lock.text, fetch: "npx hugging-bay-agents fetch hb.lock" },
|
|
163
|
+
run: { ...runRecipesForFile(entry), ...(executionBlocked ? { executionBlocked: true, note: "Hugging Bay has not tested this file in a run. The commands only show how each runtime loads this file type." } : {}) },
|
|
164
|
+
resource: fileResourceUri(entry.artifactId, entry.path),
|
|
165
|
+
};
|
|
166
|
+
const etag = typeof link.header === "function" ? String(link.header("etag") || "") : "";
|
|
167
|
+
const etagDigest = (etag.match(/sha256-([a-f0-9]{64})/i) || [])[1];
|
|
168
|
+
if (etagDigest && etagDigest.toLowerCase() !== entry.sha256) {
|
|
169
|
+
return { ...base, url: null, ...toolError("file_changed", "The file changed while the link was issued. Call get_download again.", { retryable: true }), ...shared };
|
|
170
|
+
}
|
|
171
|
+
if ([301, 302, 303, 307, 308].includes(link.status) && signedLinkAllowed(link.location)) {
|
|
172
|
+
const ttl = linkTtlSeconds(link.header?.("x-hugging-bay-capability-ttl"));
|
|
173
|
+
return { ...base, url: link.location, expiresInSeconds: ttl, expiresAt: new Date(issuedAt + ttl * 1000).toISOString(),
|
|
174
|
+
curl: `curl -fL -o ${shellSingleQuote(filename)} ${shellSingleQuote(new URL(link.location).href)}`, ...shared,
|
|
175
|
+
note: "The link works for the next few minutes and is single-purpose. For a fresh link, call get_download again or open downloadUrl. Check the SHA-256 after download." };
|
|
176
|
+
}
|
|
177
|
+
if (link.status === 200 || link.status === 206) {
|
|
178
|
+
// Some files stream through the site instead of a signed storage link.
|
|
179
|
+
return { ...base, url: entry.downloadUrl, expiresInSeconds: null, expiresAt: null, streamed: true,
|
|
180
|
+
curl: `curl -fL -o ${shellSingleQuote(filename)} ${shellSingleQuote(entry.downloadUrl)}`, ...shared,
|
|
181
|
+
note: "This file streams through huggingbay.xyz; downloadUrl is the link. Check the SHA-256 after download." };
|
|
182
|
+
}
|
|
183
|
+
const reason = link.status === 403 || link.status === 451 ? "license_acceptance_required"
|
|
184
|
+
: link.status === 404 || link.status === 410 ? "file_gone"
|
|
185
|
+
: link.status === 429 || link.status === 503 ? "busy" : "link_unavailable";
|
|
186
|
+
const message = reason === "license_acceptance_required" ? "This file needs its license accepted before download. Open downloadUrl in a browser to read and accept it."
|
|
187
|
+
: reason === "file_gone" ? "This file is no longer served. Call get_model for current files."
|
|
188
|
+
: reason === "busy" ? "Downloads are busy. Retry after a few seconds."
|
|
189
|
+
: "No download link right now. Retry, or open downloadUrl directly.";
|
|
190
|
+
return { ...base, url: null, linkStatus: link.status || null, ...toolError(reason, message, { retryable: reason === "busy" || reason === "link_unavailable" }), ...shared };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Checks every lock entry against the current download plan of its artifact.
|
|
194
|
+
export async function verifyLockAgainstCatalog(text, io) {
|
|
195
|
+
let parsed;
|
|
196
|
+
try { parsed = parseLock(text); } catch (error) {
|
|
197
|
+
return { schema: LOCK_CHECK_SCHEMA, ok: false, error: "invalid_lock", message: error.message, files: [] };
|
|
198
|
+
}
|
|
199
|
+
const plans = new Map();
|
|
200
|
+
const files = [];
|
|
201
|
+
if (new Set(parsed.files.map(entry => entry.artifactId)).size > MAX_LOCK_ARTIFACTS) {
|
|
202
|
+
return { schema: LOCK_CHECK_SCHEMA, ok: false, error: "too_many_artifacts", message: `verify_lock checks at most ${MAX_LOCK_ARTIFACTS} models per call. Split the lock, or run npx hugging-bay-agents verify.`, files: [] };
|
|
203
|
+
}
|
|
204
|
+
for (const entry of parsed.files) {
|
|
205
|
+
if (!plans.has(entry.artifactId)) {
|
|
206
|
+
try { plans.set(entry.artifactId, await io.readPlan(entry.artifactId)); } catch (error) { plans.set(entry.artifactId, { failed: Number(error?.status) || 0 }); }
|
|
207
|
+
}
|
|
208
|
+
const plan = plans.get(entry.artifactId);
|
|
209
|
+
if (plan.failed !== undefined) {
|
|
210
|
+
files.push({ path: entry.path, artifactId: entry.artifactId, status: plan.failed === 404 ? "artifact_missing" : "unchecked", detail: plan.failed === 404 ? "The artifact is no longer in the catalog." : "The download plan did not load; retry." });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const row = (Array.isArray(plan.files) ? plan.files : []).find(item => item?.path === entry.path);
|
|
214
|
+
const current = row ? lockEntryFromPlan(plan, row) : null;
|
|
215
|
+
if (!row) files.push({ path: entry.path, artifactId: entry.artifactId, status: "file_missing", detail: "The catalog no longer lists this path." });
|
|
216
|
+
else if (String(row.sha256 || "").toLowerCase().replace(/^sha256:/, "") !== entry.sha256) files.push({ path: entry.path, artifactId: entry.artifactId, status: "sha256_changed", detail: "The catalog records different bytes for this path. Re-pin on purpose, or keep your copy." });
|
|
217
|
+
else if (entry.size !== null && current && current.size !== entry.size) files.push({ path: entry.path, artifactId: entry.artifactId, status: "size_changed", detail: "Same SHA-256, different recorded size. Report this." });
|
|
218
|
+
else if (!current) files.push({ path: entry.path, artifactId: entry.artifactId, status: "not_downloadable", detail: "Same bytes are recorded, but the file is not downloadable right now." });
|
|
219
|
+
else files.push({ path: entry.path, artifactId: entry.artifactId, status: "match", sizeBytes: current.size, ...(parsed.version === 1 ? { upgrade: current } : {}) });
|
|
220
|
+
}
|
|
221
|
+
const ok = files.every(file => file.status === "match");
|
|
222
|
+
return { schema: LOCK_CHECK_SCHEMA, ok, lockSchema: parsed.schema, files,
|
|
223
|
+
...(parsed.version === 1 && ok ? { upgradedLock: buildLockV2(files.map(file => file.upgrade)).text } : {}),
|
|
224
|
+
note: ok ? "Every pinned file matches the catalog. Run npx hugging-bay-agents verify to check local copies." : "Some pinned files differ from the catalog. Nothing was changed." };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Public reader for the stdio server and tests: plain fetch against the site.
|
|
228
|
+
export function publicDownloadIo({ fetchImpl = fetch, site = LOCK_SITE, headers = {}, timeoutMs = 15000 } = {}) {
|
|
229
|
+
const common = { Accept: "application/json", DNT: "1", "Sec-GPC": "1", ...headers };
|
|
230
|
+
return {
|
|
231
|
+
async readPlan(reference) {
|
|
232
|
+
let id = reference;
|
|
233
|
+
if (!ARTIFACT_ID.test(id)) {
|
|
234
|
+
// owner/repo or a Hub URL: resolve to the catalog id first.
|
|
235
|
+
const resolved = await fetchImpl(`${site}/api/v1/resolve?repo=${encodeURIComponent(reference)}`, { headers: common, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
|
|
236
|
+
const body = resolved.ok ? await resolved.json().catch(() => null) : null;
|
|
237
|
+
if (!body || body.status !== "found" || !ARTIFACT_ID.test(body.artifactId || "")) throw Object.assign(new Error("not_found"), { status: resolved.ok || resolved.status === 404 ? 404 : resolved.status });
|
|
238
|
+
id = body.artifactId;
|
|
239
|
+
}
|
|
240
|
+
const response = await fetchImpl(`${site}/api/v1/artifacts/${encodeURIComponent(id)}/download-plan`, { headers: common, redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
|
|
241
|
+
const text = await response.text();
|
|
242
|
+
if (!response.ok) throw Object.assign(new Error(`plan_http_${response.status}`), { status: response.status });
|
|
243
|
+
return JSON.parse(text);
|
|
244
|
+
},
|
|
245
|
+
async openDownload(pathAndQuery) {
|
|
246
|
+
const response = await fetchImpl(`${site}${pathAndQuery}`, { headers: { ...common, Accept: "*/*" }, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
|
|
247
|
+
try { await response.body?.cancel(); } catch {}
|
|
248
|
+
return { status: response.status, location: response.headers.get("location"), header: name => response.headers.get(name) };
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// MCP CallToolResult for get_download / verify_lock, shared by hosted and
|
|
254
|
+
// stdio. The file is also offered as a resource_link (2025-06-18+) carrying
|
|
255
|
+
// its SHA-256 and size; servers strip resource_link for 2025-03-26 clients.
|
|
256
|
+
export function agentDownloadResult(name, called) {
|
|
257
|
+
const content = [{ type: "text", text: JSON.stringify(called) }];
|
|
258
|
+
if (name === "get_download" && called?.resource && called.sha256) {
|
|
259
|
+
content.push({ type: "resource_link", uri: called.resource, name: called.path, mimeType: "application/json",
|
|
260
|
+
description: `${formatBytes(called.sizeBytes)}, SHA-256 ${called.sha256}. Reading returns the file record, not the bytes.`,
|
|
261
|
+
_meta: { "xyz.huggingbay/file": { sha256: called.sha256, sizeBytes: called.sizeBytes, revision: called.revision, license: called.license } } });
|
|
262
|
+
}
|
|
263
|
+
const lockText = name === "get_download" ? called?.hbLock?.text : called?.upgradedLock;
|
|
264
|
+
if (lockText) content.push({ type: "resource", resource: { uri: "huggingbay://receipts/hb.lock", mimeType: "application/json", text: lockText } });
|
|
265
|
+
const isError = name === "get_download" ? Boolean(called?.error) : ["invalid_lock", "too_many_artifacts"].includes(called?.error);
|
|
266
|
+
return { content, structuredContent: called, isError };
|
|
267
|
+
}
|
package/hb-lock.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// hb.lock v2: the pin a repo keeps for the exact model files it uses.
|
|
2
|
+
// One source, two copies: packages/mcp/hb-lock.mjs and
|
|
3
|
+
// packages/agent-pack/src/hb-lock.mjs must stay byte-identical (the npm
|
|
4
|
+
// packages ship separately). tests/hb-lock-v2-parity.test.mjs fails on drift.
|
|
5
|
+
// Pure: no filesystem, no network. Readers accept v1 (one caller-supplied
|
|
6
|
+
// file) and v2; writers emit v2.
|
|
7
|
+
|
|
8
|
+
export const LOCK_FILENAME = "hb.lock";
|
|
9
|
+
export const LOCK_SCHEMA_V1 = "hugging-bay.hb-lock.v1";
|
|
10
|
+
export const LOCK_SCHEMA_V2 = "hugging-bay.hb-lock.v2";
|
|
11
|
+
export const LOCK_SITE = "https://huggingbay.xyz";
|
|
12
|
+
export const LOCK_NOTE = "Pins exact bytes by SHA-256 and size. Not a safety check or a license grant; read the license before use.";
|
|
13
|
+
export const NO_LICENSE_LABEL = "No license stated";
|
|
14
|
+
const MAX_FILES = 64;
|
|
15
|
+
const HASH = /^[a-f0-9]{64}$/;
|
|
16
|
+
const REVISION = /^[A-Za-z0-9._-]{1,128}$/;
|
|
17
|
+
const ARTIFACT_ID = /^[a-z0-9][a-z0-9-]{2,150}$/;
|
|
18
|
+
const REPO = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
|
|
19
|
+
const SAFE_PATH = /^(?!\/)(?!.*(?:^|\/)\.{1,2}(?:\/|$))[A-Za-z0-9_.@+=,-]+(?:\/[A-Za-z0-9_.@+=,-]+)*$/;
|
|
20
|
+
const FORMAT = /^[a-z0-9][a-z0-9_.-]{0,31}$/;
|
|
21
|
+
const ENTRY_KEYS = ["repo", "revision", "path", "sha256", "size", "downloadUrl", "license", "artifactId", "format"];
|
|
22
|
+
|
|
23
|
+
function fail(message) {
|
|
24
|
+
return Object.assign(new Error(message), { code: "invalid_lock" });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isSafeLockPath(path) {
|
|
28
|
+
return typeof path === "string" && path.length > 0 && path.length <= 512 && SAFE_PATH.test(path)
|
|
29
|
+
&& !path.split("/").some(part => part.startsWith("-"));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The only download URL a lock may carry: the Hugging Bay byte route for this
|
|
33
|
+
// exact artifact and path. It re-checks the file and redirects to a signed
|
|
34
|
+
// link that lasts at most 300 seconds.
|
|
35
|
+
export function lockDownloadUrl(artifactId, path) {
|
|
36
|
+
return `${LOCK_SITE}/api/downloads/${encodeURIComponent(artifactId)}/${encodeURIComponent(path)}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function downloadUrlMatches(value, artifactId, path) {
|
|
40
|
+
let url;
|
|
41
|
+
try { url = new URL(value); } catch { return false; }
|
|
42
|
+
if (url.origin !== LOCK_SITE || url.username || url.password || url.search || url.hash || value !== url.href) return false;
|
|
43
|
+
const prefix = `/api/downloads/${encodeURIComponent(artifactId)}/`;
|
|
44
|
+
if (!url.pathname.startsWith(prefix)) return false;
|
|
45
|
+
try { return decodeURIComponent(url.pathname.slice(prefix.length)) === path; } catch { return false; }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function licenseLabelFor(value) {
|
|
49
|
+
const text = typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f]/g, "").trim() : "";
|
|
50
|
+
if (!text || ["unknown", "none", "other", "null", "undefined", "noassertion"].includes(text.toLowerCase())) return NO_LICENSE_LABEL;
|
|
51
|
+
return text.slice(0, 120);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// One normalized entry. Throws invalid_lock with a plain reason.
|
|
55
|
+
export function lockEntry(input = {}) {
|
|
56
|
+
const extra = Object.keys(input || {}).filter(key => !ENTRY_KEYS.includes(key));
|
|
57
|
+
if (extra.length) throw fail(`unknown field ${extra[0]}`);
|
|
58
|
+
const { repo, revision = null, path, sha256, size, downloadUrl, license, artifactId, format = null } = input;
|
|
59
|
+
if (typeof repo !== "string" || !REPO.test(repo) || repo.split("/").some(part => part === "." || part === "..")) throw fail("repo must be a name like owner/repo");
|
|
60
|
+
if (revision !== null && (typeof revision !== "string" || !REVISION.test(revision))) throw fail("revision must be a commit id or null");
|
|
61
|
+
if (!isSafeLockPath(path)) throw fail("path must be a safe relative path");
|
|
62
|
+
if (typeof sha256 !== "string" || !HASH.test(sha256.toLowerCase())) throw fail("sha256 must be 64 hex characters");
|
|
63
|
+
if (!Number.isSafeInteger(size) || size < 0) throw fail("size must be a whole number of bytes");
|
|
64
|
+
if (typeof artifactId !== "string" || !ARTIFACT_ID.test(artifactId)) throw fail("artifactId must be a Hugging Bay artifact id");
|
|
65
|
+
if (typeof downloadUrl !== "string" || !downloadUrlMatches(downloadUrl, artifactId, path)) throw fail("downloadUrl must be the Hugging Bay download link for this artifact and path");
|
|
66
|
+
if (format !== null && (typeof format !== "string" || !FORMAT.test(format))) throw fail("format must be a short lowercase name or null");
|
|
67
|
+
return { repo, revision, path, sha256: sha256.toLowerCase(), size, downloadUrl, license: licenseLabelFor(license), artifactId, format };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Builds the canonical v2 document and its text. Files are sorted by path;
|
|
71
|
+
// the same input always gives the same bytes, so the lock diffs cleanly.
|
|
72
|
+
export function buildLockV2(files, { authority = "hugging-bay-catalog" } = {}) {
|
|
73
|
+
if (!Array.isArray(files) || files.length === 0) throw fail("a lock needs at least one file");
|
|
74
|
+
if (files.length > MAX_FILES) throw fail(`a lock holds at most ${MAX_FILES} files`);
|
|
75
|
+
if (!["hugging-bay-catalog", "caller-supplied"].includes(authority)) throw fail("authority must be hugging-bay-catalog or caller-supplied");
|
|
76
|
+
const entries = files.map(lockEntry).sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
77
|
+
for (let i = 1; i < entries.length; i += 1) if (entries[i].path === entries[i - 1].path) throw fail(`path ${entries[i].path} appears twice`);
|
|
78
|
+
const lock = { schema: LOCK_SCHEMA_V2, authority, files: entries, note: LOCK_NOTE };
|
|
79
|
+
return { lock, text: JSON.stringify(lock, null, 2) + "\n" };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Adds or replaces entries (matched by path) in an existing lock text.
|
|
83
|
+
export function mergeLockV2(existingText, files, options = {}) {
|
|
84
|
+
const current = existingText ? parseLock(existingText) : null;
|
|
85
|
+
const byPath = new Map((current?.files || []).map(entry => [entry.path, entry]));
|
|
86
|
+
for (const entry of files) byPath.set(entry.path, entry);
|
|
87
|
+
// A caller-supplied entry downgrades the whole lock; it never upgrades.
|
|
88
|
+
const authority = options.authority === "caller-supplied" || current?.authority === "caller-supplied" ? "caller-supplied" : "hugging-bay-catalog";
|
|
89
|
+
return buildLockV2([...byPath.values()], { authority });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Reads v1 or v2. Returns { schema, version, authority, files } where every
|
|
93
|
+
// v2 file is a full entry; a v1 file has repo, path, sha256, artifactId and a
|
|
94
|
+
// derived downloadUrl, with size, revision and license unknown (null).
|
|
95
|
+
export function parseLock(text) {
|
|
96
|
+
let doc;
|
|
97
|
+
try { doc = typeof text === "string" ? JSON.parse(text) : text; } catch { throw fail("hb.lock is not valid JSON"); }
|
|
98
|
+
if (!doc || typeof doc !== "object") throw fail("hb.lock is not a JSON object");
|
|
99
|
+
if (doc.schema === LOCK_SCHEMA_V2) {
|
|
100
|
+
const { lock } = buildLockV2(doc.files, { authority: doc.authority || "hugging-bay-catalog" });
|
|
101
|
+
return { schema: LOCK_SCHEMA_V2, version: 2, authority: lock.authority, files: lock.files };
|
|
102
|
+
}
|
|
103
|
+
if (doc.schema === LOCK_SCHEMA_V1) {
|
|
104
|
+
const { model, file, sha256, hb_url } = doc;
|
|
105
|
+
if (typeof model !== "string" || !REPO.test(model)) throw fail("model must be a name like owner/repo");
|
|
106
|
+
if (!isSafeLockPath(file)) throw fail("file must be a safe relative path");
|
|
107
|
+
if (typeof sha256 !== "string" || !HASH.test(sha256.toLowerCase())) throw fail("sha256 must be 64 hex characters");
|
|
108
|
+
let url;
|
|
109
|
+
try { url = new URL(hb_url); } catch { throw fail("hb_url must be https://huggingbay.xyz/artifacts/<id>"); }
|
|
110
|
+
const match = url.pathname.match(/^\/artifacts?\/([a-z0-9][a-z0-9-]{2,150})$/);
|
|
111
|
+
if (url.origin !== LOCK_SITE || url.search || url.hash || url.username || url.password || !match) throw fail("hb_url must be https://huggingbay.xyz/artifacts/<id>");
|
|
112
|
+
return { schema: LOCK_SCHEMA_V1, version: 1, authority: "caller-supplied", files: [{
|
|
113
|
+
repo: model, revision: null, path: file, sha256: sha256.toLowerCase(), size: null,
|
|
114
|
+
downloadUrl: lockDownloadUrl(match[1], file), license: null, artifactId: match[1], format: null,
|
|
115
|
+
}] };
|
|
116
|
+
}
|
|
117
|
+
throw fail(`hb.lock schema must be ${LOCK_SCHEMA_V2} or ${LOCK_SCHEMA_V1}`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const digestOf = value => (typeof value === "string" ? value.toLowerCase().replace(/^sha256:/, "") : "");
|
|
121
|
+
|
|
122
|
+
// Turns one download-plan file row (GET /api/v1/artifacts/{id}/download-plan)
|
|
123
|
+
// into a lock entry. Returns null when the row is not a downloadable,
|
|
124
|
+
// hashed, sized Hugging Bay file.
|
|
125
|
+
export function lockEntryFromPlan(plan, row) {
|
|
126
|
+
if (!plan || !row || typeof row !== "object") return null;
|
|
127
|
+
// A degraded, stale or failed plan is not current evidence for a pin.
|
|
128
|
+
if (plan.error || plan.degraded || plan.stale || plan.downloadReady === false) return null;
|
|
129
|
+
const artifactId = plan.artifactId || plan.artifact?.id;
|
|
130
|
+
const sha256 = digestOf(row.sha256);
|
|
131
|
+
const size = Number.isSafeInteger(row.sizeBytes) ? row.sizeBytes : Number.isSafeInteger(row.storageSizeBytes) ? row.storageSizeBytes : null;
|
|
132
|
+
if (!ARTIFACT_ID.test(artifactId || "") || !HASH.test(sha256) || size === null || !isSafeLockPath(row.path)) return null;
|
|
133
|
+
if (row.downloadReady === false || !row.downloadUrl || row.stale || row.degraded || ["blocked", "unknown"].includes(row.readiness)) return null;
|
|
134
|
+
const repo = plan.artifact?.repo;
|
|
135
|
+
if (typeof repo !== "string" || !REPO.test(repo)) return null;
|
|
136
|
+
const revision = typeof plan.artifact?.revision === "string" && REVISION.test(plan.artifact.revision) ? plan.artifact.revision : null;
|
|
137
|
+
const declared = typeof row.format === "string" && FORMAT.test(row.format.toLowerCase()) ? row.format.toLowerCase() : null;
|
|
138
|
+
const format = declared && declared !== "raw" ? declared : /\.gguf$/i.test(row.path) ? "gguf" : /\.safetensors$/i.test(row.path) ? "safetensors" : declared;
|
|
139
|
+
return lockEntry({ repo, revision, path: row.path, sha256, size, downloadUrl: lockDownloadUrl(artifactId, row.path),
|
|
140
|
+
license: plan.artifact?.licenseLabel || row.license || plan.artifact?.license, artifactId, format });
|
|
141
|
+
}
|