hugging-bay-mcp 0.1.16 → 0.1.18

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 CHANGED
@@ -1,17 +1,17 @@
1
- # hugging-bay-mcp [![npm version](https://img.shields.io/npm/v/hugging-bay-mcp.svg)](https://www.npmjs.com/package/hugging-bay-mcp) [![MCP discovery tools](https://img.shields.io/badge/discovery%20tools-29-blue)](https://huggingbay.xyz/api/mcp)
1
+ # hugging-bay-mcp [![npm version](https://img.shields.io/npm/v/hugging-bay-mcp.svg)](https://www.npmjs.com/package/hugging-bay-mcp) [![MCP discovery tools](https://img.shields.io/badge/discovery%20tools-30-blue)](https://huggingbay.xyz/.well-known/mcp.json)
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.15`<br>
4
+ **Install:** `npx -y hugging-bay-mcp@0.1.17`<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.15"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}`<br>
6
+ **MCP config (stdio):** `{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.17"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}`<br>
7
7
  **First call:** `search_artifacts({ "q": "Qwen3 0.6B GGUF" })`<br>
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>
8
+ **Ask:** Missing a model, file, tool or feature? Select `?profile=discovery` to call `request_feature`, 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>
10
10
  **Keywords:** `gguf`, `local-llm`, `huggingface-alternative`, `mcp`
11
11
 
12
12
  ## Claude Code, Codex CLI and Cursor
13
13
 
14
- **Source candidate:** `0.1.16`, prepared for founder publication alongside [Tug 0.2.93](https://huggingbay.xyz/desktop). The install commands below use the current npm release `0.1.15`; after publication, replace that pin with `0.1.16`. 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.
14
+ **Current npm release:** `0.1.17`, published on 13 Nov 2026. It includes `get_download`, `verify_lock`, file resources and hb.lock v2. Hosted MCP exposes six core tools, 10 agent tools and 30 discovery tools. npm 0.1.17 stdio lists seven default tools: the six core tools plus local-only `ask_url`. Call `tools/list` for the selected transport and profile. Use `https://huggingbay.xyz/api/mcp?profile=agent` for `deployment_plan`, `report_run`, `write_receipt` and `verify_lock`. Tug and native hbay 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.15
23
+ claude mcp add hugging-bay-stdio -- npx -y hugging-bay-mcp@0.1.17
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.15"]`. Codex's MCP list reports configuration;
41
+ `args = ["-y", "hugging-bay-mcp@0.1.17"]`. 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
 
@@ -48,6 +48,25 @@ For Cursor, merge this into `.cursor/mcp.json` (project) or `~/.cursor/mcp.json`
48
48
  {"mcpServers":{"hugging-bay":{"url":"https://huggingbay.xyz/api/mcp"}}}
49
49
  ```
50
50
 
51
+ ### Optional API key
52
+
53
+ For hosted MCP, configure your client to supply an `Authorization: Bearer`
54
+ header from its secret store. For the Codex CLI example above, add
55
+ `bearer_token_env_var = "HUGGING_BAY_TOKEN"` to the server entry and set that
56
+ environment variable outside the configuration file. For stdio, pass
57
+ `HUGGING_BAY_TOKEN` to the child process. Public tools work with either
58
+ transport without a key. Authenticated calls use the scopes on the key.
59
+ Keep keys out of URLs, tool arguments, and checked-in files.
60
+
61
+ ### Optional hardware estimate
62
+
63
+ Under **Set my machine**, copy the hardware code to your other browser or
64
+ send it as `params._meta["huggingbay.xyz/hardwareProfile"]` with a hosted
65
+ `get_model`, `search_artifacts`, or `find_runnable` call. Read the estimate
66
+ from `result._meta["huggingbay.xyz/personalizedFit"]` when it fits the response
67
+ budget. The code contains the memory choice and its confirmation date, and
68
+ expires after 90 days. Omit it or pass `"off"` to skip the estimate.
69
+
51
70
  Use `tools/list` before calling a tool. The explicit discovery profile includes
52
71
  `deployment_plan({"artifact":"<returned id>"})` for current file links and
53
72
  hashes. `plan_local_deployment` belongs to the full profile. A successful search
@@ -62,7 +81,7 @@ For Claude Desktop, open Settings → Developer → Edit Config and merge this i
62
81
  `claude_desktop_config.json`. Restart Claude Desktop after saving:
63
82
 
64
83
  ```json
65
- {"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.15"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}
84
+ {"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.17"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}
66
85
  ```
67
86
 
68
87
  ## First live MCP call
@@ -75,24 +94,39 @@ curl -fsS 'https://huggingbay.xyz/api/mcp' -H 'Content-Type: application/json' -
75
94
 
76
95
  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
96
 
78
- ## Profiles: stdio and hosted
97
+ ## Pin and fetch exact files
98
+
99
+ `get_download` gives an agent one exact file in one call:
100
+
101
+ ```sh
102
+ 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":"hf-model-qwen-qwen3-0-6b-gguf"}}}'
103
+ ```
79
104
 
80
- **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.
105
+ - Arguments: `id` (artifact id or owner/repo) and optional `path` (default: the recommended file).
106
+ - 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).
107
+ - 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`.
108
+ - 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.
81
109
 
82
- Published 0.1.14 defaults to its historical 29-tool discovery profile. The current 0.1.16 source candidate defaults to five hosted read-only core tools, plus local-only `ask_url` in stdio; its explicit discovery profile carries the broader catalog. The package keeps
83
- the broader catalog available, but a client must opt into it explicitly:
110
+ 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`. Agent-pack source 0.1.3 has `pin`, `fetch` and `verify`; as observed on 2026-11-13, npm's latest `hugging-bay-agents` is 0.1.2 and predates those commands. From this repository checkout, run `node packages/agent-pack/cli.mjs fetch [hb.lock] [--dir <folder>]` to download every pinned file, check SHA-256 and size, and resume after a drop. MCP `verify_lock` on the agent profile checks a lock against the current catalog. v1 locks from `write_receipt` still read.
111
+
112
+ In agent-pack source 0.1.3, `answer --pin` writes an exact file to `hb.lock` only after a signed answer verifies against a trusted key: `node packages/agent-pack/cli.mjs answer coding --ram 32 --pin`. npm 0.1.2 does not include this source flow. As observed on 2026-11-13, the production answer endpoint returned `state: timeout` and the key endpoint listed no signing keys, so there was no live answer to pin.
113
+
114
+ ## Profiles: stdio and hosted
115
+
116
+ The hosted core profile observed on 2026-11-13 has six read-only tools. npm 0.1.17 stdio lists those six core tools plus local-only `ask_url`, for seven tools total. Its bounded discovery profile and the hosted 30-tool discovery profile can differ; call `tools/list` on the selected transport for its exact contract.
84
117
 
85
118
  | Transport/profile | `tools/list` | What it is |
86
119
  | --- | --- | --- |
87
- | hosted `?profile=core` / stdio `--profile core` (source 0.1.16) | **5 hosted tools; 6 stdio tools** | `hb_run_plan`, `search_artifacts`, `find_runnable`, `get_model`, `get_serve_decision`; all read-only; the source and hosted default. Published npm 0.1.14 core has 8 tools. |
88
- | source stdio default (`node packages/mcp/index.mjs`) | **6 tools** | five hosted core names plus local-only `ask_url`; `tools/list` is the authority |
89
- | 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
- | 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` | **5 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`) |
120
+ | hosted `?profile=core` | **6 tools** | `find_runnable`, `search_artifacts`, `get_model`, `get_download`, `get_serve_decision`, `hb_run_plan`; all read-only |
121
+ | hosted `?profile=agent` | **10 tools** | the six core tools plus `deployment_plan`, `report_run`, `write_receipt`, `verify_lock` |
122
+ | hosted `?profile=discovery` | **30 tools** | broader public catalog, request and board tools, including `request_feature` and `request_missing` |
123
+ | hosted `?profile=directory` | **3 tools** | connector subset: `search`, `fetch`, `find_runnable` |
124
+ | npm 0.1.17 and current source stdio default / `--profile core` | **7 tools** | six read-only core tools plus local-only `ask_url` |
125
+ | hosted `?profile=verify` | inspect `tools/list` | hosted public verification list; it does not include `get_accepted_run_proof` |
126
+ | npm 0.1.17 and source stdio `--profile verify` | inspect `tools/list` | `get_accepted_run_proof` is listed only when `HUGGING_BAY_MCP_ENABLE_UNRELEASED_RUN_PROOF=1` |
92
127
 
93
128
  The default is also selected when `HUGGING_BAY_MCP_PROFILE` is empty.
94
- Use
95
- `--profile core` or `HUGGING_BAY_MCP_PROFILE=core` for the five hosted tools plus local-only `ask_url` (eight tools in npm 0.1.14).
129
+ Use `--profile core` or `HUGGING_BAY_MCP_PROFILE=core` for the six core tools plus local-only `ask_url` in npm 0.1.17.
96
130
  Discovery sends concise descriptions and schemas with all constraints intact.
97
131
  Use `resources/read` with `huggingbay://tool/TOOL_NAME` for the complete
98
132
  parameter notes and examples; the reference is restricted to the selected profile.
@@ -120,10 +154,12 @@ An oversized page returns `isError: true` with code
120
154
  `list_files_page_too_large` and no structured success or continuation cursor.
121
155
  Retry the same question with `limit: 1` only when the recovery instructs it.
122
156
  If a single record still exceeds the MCP bounds, use the equivalent HTTP read.
123
- These candidate changes require release; the published archive has its own
124
- versioned behavior.
157
+ The published npm 0.1.17 package includes these page limits; older archives have
158
+ their own versioned behavior.
125
159
 
126
- The measured npm 0.1.14 archive includes the argument and CLI contract below.
160
+ The CLI behavior and protocol notes below were measured on npm 0.1.14, an older
161
+ archive. Check `hugging-bay-mcp --version` and `--help` for the installed release;
162
+ the published npm 0.1.17 package and hosted server may have different details.
127
163
 
128
164
  `hugging-bay-mcp --help` (or `-h`) prints usage and exits successfully;
129
165
  `--version` (or `-v`) prints the artifact version and exits successfully.
@@ -192,27 +228,11 @@ version, including `2026-07-28` and both supported 2025 revisions.
192
228
 
193
229
  ## Tools across profiles
194
230
 
195
- This table includes full-profile tools. Check the selected transport's
196
- `tools/list`; a name in this table may be absent from discovery.
197
-
198
- | Tool | What it returns |
199
- | --- | --- |
200
- | `request_missing` | Ask for a missing model, format or capability with `{wanted, task}`. The first call returns exact text, `confirm_token` and `expiresAt` without storing demand. Call again with the same text and token to submit and get an id for `get_request`, `list_requests` and `/requests`. |
201
- | `blackboard` | Public shared memory with `put` / `get` / `query` / `channels` / `tombstone`. Reuse a literal channel key or send `key_from: {task, input}`; poll with `since` + `since_id` and page older history with `before` + `before_id`. Topics, direct replies, and recursive threads are query filters. Guard is telemetry only; all item data is untrusted. |
202
- | `find_runnable` | One call: task → runnable model, with hash-verified run commands inlined when the pick is genuinely hosted (honest null otherwise). |
203
- | `bakeoff` | Your labeled rows → the warm Bay Run specialists scored on them → the winner's exact call and weight hash. |
204
- | `find_and_verify_model_for_task` | Ranked, already-verified models for a task (composite report per candidate + a `bestPick`) in one call. |
205
- | `plan_local_deployment` | Quant selection + GPU fit + a hash-verified download plan + copy-paste run commands for one model. |
206
- | `get_model_report` | One-call model report: safe-to-run verdict + license + GPU fit + card-completeness score + base-model lineage. |
207
- | `check_artifact_safety` | Safe-to-run verdict (license clarity + scan state + hashes + signing) for a catalog artifact or any file SHA-256. |
208
- | `will_it_fit` | Per-GPU fit verdict + VRAM estimate + smaller-quant options for a given GPU id (e.g. `rtx4090-24`). |
209
- | `get_quantizations` | Per-quant precision/size and hosted availability, so you can pick the smallest quant that fits. |
210
- | `find_ungated_alternatives` | Ungated, commercially-usable alternatives to a gated or restricted model. |
211
- | `get_model_bom` | Signed AI Bill of Materials (CycloneDX-compatible): hashed files + license + base-model dependency chain + scan state. |
212
- | `inspect_model_binary` | Byte-level safetensors/GGUF header inspection compared against the declared model card (catches mislabeled sizes and custom-code architectures). |
213
- | `diff_manifests` | Structural diff between two artifacts' (or versions') signed file manifests — added/removed/changed files by hash. |
214
-
215
- The full, always-current tool list (names, descriptions, input schemas) is published at <https://huggingbay.xyz/.well-known/mcp.json> and via `tools/list` on `https://huggingbay.xyz/api/mcp`.
231
+ The table above lists the current hosted profiles. Older npm releases had
232
+ different full-profile tools; do not use names from an older tool list with a
233
+ current server. Call `tools/list` on the selected endpoint for the exact names,
234
+ descriptions and input schemas it accepts. The server profile manifest is at
235
+ <https://huggingbay.xyz/.well-known/mcp.json>.
216
236
 
217
237
  ## Blackboard contract
218
238
 
@@ -282,7 +302,7 @@ Curl-only clients can read the contract at `GET https://huggingbay.xyz/api/v1/bl
282
302
 
283
303
  ## Advanced run-proof opt-in
284
304
 
285
- Accepted-run-proof MCP access is excluded from the default discovery profile
305
+ Accepted-run-proof MCP access is excluded from the hosted discovery profile
286
306
  and explicit `full` profile. The stdio launcher exposes only exact
287
307
  `get_accepted_run_proof` and `huggingbay://run-proof/{proofId}` reads, and only
288
308
  when started with both `HUGGING_BAY_MCP_PROFILE=verify` and
@@ -334,18 +354,15 @@ Downloadable doesn't mean tested: this record says whether the exact file can be
334
354
 
335
355
  ## Release dependency
336
356
 
337
- The request-and-status sentence above is approved copy held on the c29 AEO-72/AEO-73 deployment gate. Verify the deployed `request_feature`, `get_request`, and public changelog/status path before package publication or directory copy uses it.
338
-
339
-
340
357
  ### Run a model on your computer (optional, default off)
341
358
 
342
- Install hbay 0.2.0 or later and the local MCP package, then set `HUGGING_BAY_MCP_ENABLE_RUN_LOCAL=1` to expose `run_local` to your assistant. This feature runs on your computer; the hosted MCP does not start a model.
359
+ The optional `run_local` path requires native hbay 0.2.4 and the local MCP package, then `HUGGING_BAY_MCP_ENABLE_RUN_LOCAL=1`. The qualified release manifest now selects published hbay 0.2.5. This feature runs on your computer; the hosted MCP does not start a model.
343
360
 
344
361
  #### 1. Set up the local tools
345
362
 
346
363
  Use a terminal on your own computer. You need both the native hbay program and the local MCP package before calling your assistant.
347
364
 
348
- Install the hbay 0.2.0 or later binary, then start the local npm stdio package with `HUGGING_BAY_MCP_ENABLE_RUN_LOCAL=1`. The flag defaults off. `HBAY_BINARY` may name a trusted local executable; `HBAY_DATA_DIR` may select an isolated data directory.
365
+ Install the published hbay release, then start the local npm stdio package with `HUGGING_BAY_MCP_ENABLE_RUN_LOCAL=1`. The flag defaults off. `HBAY_BINARY` may name a trusted local executable; `HBAY_DATA_DIR` may select an isolated data directory.
349
366
 
350
367
  #### 2. Start one model
351
368
 
@@ -359,7 +376,7 @@ Prompts stay on your machine.
359
376
 
360
377
  ## Complete tool reference for agent builders
361
378
 
362
- The expanded [MCP reference](https://huggingbay.xyz/docs/mcp) is staged behind
379
+ The expanded [MCP reference](https://huggingbay.xyz/developers/mcp) is staged behind
363
380
  `HUGGING_BAY_AGENT_BUILDER_DOCS=1` (default off). With
364
381
  `HUGGING_BAY_AGENT_GUARDRAILS=1`, the `verify-before-finish` MCP prompt is also
365
382
  listed. It lists each hosted tool and
@@ -398,7 +415,11 @@ stays unchanged. See [the quickstart](../../docs/swarm-quickstart.md).
398
415
 
399
416
  ## Portable receipts and local Ask links
400
417
 
401
- The current package includes `write_receipt`, digest receipt links and the stdio-only `ask_url` draft builder (29 hosted discovery tools; 30 stdio discovery tools). See [RECEIPTS.md](RECEIPTS.md) for hb.lock and authority limits. The 0.1.16 candidate refreshes release metadata, package contents and the Tug 0.2.93 handoff. Directory submission field packets remain draft-only under `listings/drafts/`; publication remains founder-owned.
418
+ Published npm 0.1.17 includes `write_receipt`, digest receipt links and the stdio-only `ask_url` draft builder. Its default stdio list has seven tools: the six core tools plus `ask_url`. See [RECEIPTS.md](RECEIPTS.md) for hb.lock and authority limits. Native hbay 0.2.5 is published as recorded in the release manifest and its checksum receipt. The hosted installer defaults to that release. Check `hbay --version` and `hbay help pin` before using these commands:
402
419
 
420
+ ```sh
421
+ hbay pin hf-model-qwen-qwen3-0-6b-gguf
422
+ hbay fetch hb.lock --dir models --connections 8
423
+ ```
403
424
 
404
- The hosted MCP default is the five read-only core tools. Use `?profile=discovery` for the public board, request and plan tools; operator-only tools retain their authorization requirements. The hosted release and this source candidate have separate version numbers. The npm install pins follow the measured 0.1.15 publication, not the 0.1.16 source candidate. Call `tools/list` on your selected transport.
425
+ `hbay pin` writes a v2 `hb.lock` entry for the exact selected file. `hbay fetch` downloads the pinned file and checks its SHA-256 and size. Windows `install.ps1` refuses by default while signature verification is pending. These native commands are separate from the Node package CLI.
package/RECEIPTS.md CHANGED
@@ -1,14 +1,16 @@
1
- # Portable MCP receipts (source candidate)
1
+ # Portable MCP receipts (npm 0.1.17)
2
2
 
3
- The candidate starts in one command after its separately approved npm release:
3
+ The published package starts in one command:
4
4
 
5
5
  ```sh
6
- npx -y hugging-bay-mcp@0.1.15
6
+ npx -y hugging-bay-mcp@0.1.17
7
7
  ```
8
8
 
9
- Use `node packages/mcp/index.mjs` to run reviewed source now. This source has
10
- 30 default discovery tools; the recorded npm 0.1.14 and hosted observations still
11
- have 29. No package publication or deployment is implied by this document.
9
+ As observed on 2026-11-13, npm's latest published `hugging-bay-mcp` is 0.1.17.
10
+ The hosted default core profile has six read-only tools; hosted discovery has 30
11
+ tools. npm 0.1.17 stdio lists those six core tools plus local-only `ask_url`, for
12
+ seven default tools. Hosted and stdio profile names or counts can differ. Call
13
+ `tools/list` for the exact selected transport and profile.
12
14
 
13
15
  Every `tools/call` result, including a tool-level error, carries a receipt URL in
14
16
  `_meta["xyz.huggingbay/receipt"].url` and a `resource_link` content block. JSON-RPC
@@ -61,12 +61,21 @@ export function conciseDeploymentPlan(payload, sourceUrl = '') {
61
61
  return out;
62
62
  }
63
63
 
64
+ export function hostedInventoryPendingText(payload) {
65
+ if (payload?.loading !== true || payload.warning !== 'hosted_inventory_pending') return '';
66
+ const seconds = payload.retryAfterSeconds;
67
+ const delay = Number.isSafeInteger(seconds) && seconds > 0 ? ` in ${seconds} second${seconds === 1 ? '' : 's'}` : ' shortly';
68
+ return `Hosted inventory is still loading. Retry the same search${delay}.`;
69
+ }
70
+
64
71
  export function conciseToolText(payload) {
65
72
  if (!payload || typeof payload !== 'object') return String(payload ?? '');
66
73
  if (payload.error) return payload.message || String(payload.error);
67
74
  const id = payload.repo || payload.artifact?.repo || payload.id || payload.artifactId || payload.artifact?.id;
68
75
  const rows = payload.rows || payload.files;
69
- return [id ? `Model: ${id}.` : '', Array.isArray(rows) ? `${rows.length} ${payload.files ? 'file' : 'result'}${rows.length === 1 ? '' : 's'}.` : '',
76
+ const resultCount = Array.isArray(rows) ? `${rows.length} ${payload.files ? 'file' : 'result'}${rows.length === 1 ? '' : 's'}.` : '';
77
+ const resultText = hostedInventoryPendingText(payload) || resultCount;
78
+ return [id ? `Model: ${id}.` : '', resultText,
70
79
  payload.available === false ? 'No confirmed download plan is available.' : '',
71
80
  payload.stale || payload.degraded ? 'This answer is dated or incomplete. Check its freshness before downloading.' : '',
72
81
  // Text-only clients retain the public note exactly once.
@@ -0,0 +1,323 @@
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 pinned upstream or short-lived signed download link 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
+ const stalePlanError = () => 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
+ if (plan.error) return stalePlanError();
142
+ // prod-e2e-health 27 Nov: a stale/degraded plan (its authority read could not
143
+ // finish) may still name the file, but it grants nothing. The live byte route
144
+ // re-checks admission on every open; accept only its success, and only when
145
+ // its SHA-256 header equals the plan's recorded SHA-256. Anything else is the
146
+ // unchanged plan_unavailable answer.
147
+ const provisional = plan.degraded === true || plan.stale === true;
148
+ // Only the plan-level stale/degraded marks are lifted, and only to name the
149
+ // candidate file. Denials (downloadReady false, row stale/blocked/unknown)
150
+ // still refuse; the pin below is issued only after the live SHA-256 match.
151
+ const selectable = provisional ? { ...plan, degraded: false, stale: false } : plan;
152
+ const row = selectPlanFile(selectable, path);
153
+ const entry = row ? lockEntryFromPlan(selectable, row) : null;
154
+ if (!entry && provisional) return stalePlanError();
155
+ if (!entry) {
156
+ return toolError("file_not_downloadable", path
157
+ ? `${path} is not a downloadable file with a recorded SHA-256 and size. Pick one of files.`
158
+ : "This model has no single recommended downloadable file. Pick one of files and pass its path.",
159
+ { artifactId: plan.artifactId, files: fileChoices(plan), retryable: false });
160
+ }
161
+ const executionBlocked = provisional || row.executionPolicy === "blocked" || row.authorityMode === "private-download-only" || plan.authorityMode === "private-download-only";
162
+ const route = new URL(entry.downloadUrl);
163
+ let link;
164
+ try { link = await io.openDownload(`${route.pathname}${route.search}`); } catch {
165
+ link = { status: 0 };
166
+ }
167
+ if (provisional && !liveLinkConfirmsFile(link, entry.sha256)) return stalePlanError();
168
+ const freshnessNote = provisional ? " The download plan was stale, so this link and its SHA-256 were confirmed by a live re-check. The license label and hb.lock are omitted until a fresh plan; no tested run is claimed." : "";
169
+ const issuedAt = now();
170
+ const base = { schema: DOWNLOAD_LINK_SCHEMA, artifactId: entry.artifactId, repo: entry.repo, revision: entry.revision, path: entry.path,
171
+ sha256: entry.sha256, sizeBytes: entry.size, license: entry.license, format: entry.format, downloadUrl: entry.downloadUrl,
172
+ // The live SHA-256 match covers the bytes, not plan labels: a stale plan's
173
+ // license may come from a failed evidence read, so it is not repeated, and
174
+ // no hb.lock pin (which embeds it) is issued.
175
+ ...(provisional ? { license: null, licenseVerified: false, planFreshness: "stale", authority: "live-download-route" } : {}) };
176
+ const lock = provisional ? null : buildLockV2([entry]);
177
+ const filename = entry.path.split("/").pop();
178
+ const shared = {
179
+ verify: { algorithm: "sha256", sha256: entry.sha256, sizeBytes: entry.size, command: `shasum -a 256 ${filename}` },
180
+ ...(lock ? { hbLock: { filename: "hb.lock", text: lock.text, fetch: "npx hugging-bay-agents fetch hb.lock" } } : {}),
181
+ 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." } : {}) },
182
+ resource: fileResourceUri(entry.artifactId, entry.path),
183
+ };
184
+ const etag = typeof link.header === "function" ? String(link.header("etag") || "") : "";
185
+ const etagDigest = (etag.match(/sha256-([a-f0-9]{64})/i) || [])[1];
186
+ if (etagDigest && etagDigest.toLowerCase() !== entry.sha256) {
187
+ return { ...base, url: null, ...toolError("file_changed", "The file changed while the link was issued. Call get_download again.", { retryable: true }), ...shared };
188
+ }
189
+ const verifiedCurl = url => `(tmp=$(mktemp ./.hb-download.XXXXXX) && trap 'rm -f -- "$tmp"' EXIT && curl -fL --proto '=https' --proto-redir '=https' -o "$tmp" ${shellSingleQuote(url)} && printf '%s %s\\n' ${shellSingleQuote(entry.sha256)} "$tmp" | shasum -a 256 -c - && mv -f -- "$tmp" ${shellSingleQuote(`./${filename}`)})`;
190
+ const verifyNote = `The command verifies SHA-256 before moving the file into place.${freshnessNote}`;
191
+ if ([301, 302, 303, 307, 308].includes(link.status) && signedLinkAllowed(link.location)) {
192
+ const mode = link.header?.("x-hugging-bay-download-mode");
193
+ const target = new URL(link.location);
194
+ const ttl = linkTtlSeconds(link.header?.("x-hugging-bay-capability-ttl"));
195
+ if (mode === "huggingface-pinned" || mode === "huggingface-cdn") {
196
+ const commit = target.pathname.split("/resolve/")[1]?.split("/")[0];
197
+ const pinned = target.origin === "https://huggingface.co" && /^[a-f0-9]{40}$/.test(commit || "") && commit === entry.revision;
198
+ const cdn = !target.port && !target.hash && /^(?:cas-bridge\.xethub\.hf\.co|(?:[a-z0-9-]+\.)?aws\.cdn\.hf\.co|cdn-lfs(?:-[a-z0-9-]+)?\.(?:hf\.co|huggingface\.co))$/.test(target.hostname);
199
+ if (!(mode === "huggingface-pinned" ? pinned : cdn) || !liveLinkConfirmsFile(link, entry.sha256)) {
200
+ return { ...base, url: null, ...toolError("file_changed", "The upstream link did not match the recorded file. Call get_download again.", { retryable: true }) };
201
+ }
202
+ const expiry = mode === "huggingface-cdn" ? ttl : null;
203
+ return { ...base, url: target.href, source: mode, expiresInSeconds: expiry,
204
+ expiresAt: expiry ? new Date(issuedAt + expiry * 1000).toISOString() : null,
205
+ curl: verifiedCurl(target.href), ...shared, note: verifyNote };
206
+ }
207
+ return { ...base, url: target.href, expiresInSeconds: ttl, expiresAt: new Date(issuedAt + ttl * 1000).toISOString(),
208
+ curl: verifiedCurl(target.href), ...shared, note: verifyNote };
209
+ }
210
+ if (link.status === 200 || link.status === 206) {
211
+ return { ...base, url: entry.downloadUrl, expiresInSeconds: null, expiresAt: null, streamed: true,
212
+ curl: verifiedCurl(entry.downloadUrl), ...shared, note: verifyNote };
213
+ }
214
+ const sourceError = link.header?.("x-hugging-bay-download-error");
215
+ if (["upstream_download_access_unavailable", "upstream_download_restricted", "upstream_download_license_unresolved"].includes(sourceError)) {
216
+ return { ...base, url: null, linkStatus: link.status, ...toolError("source_withheld",
217
+ "The verified source is unavailable under its current access or license settings.", { retryable: false }), ...shared };
218
+ }
219
+ if (["upstream_download_integrity_mismatch", "upstream_download_binding_unverified"].includes(sourceError)) {
220
+ return { ...base, url: null, linkStatus: link.status, ...toolError("file_changed",
221
+ "The verified source did not match the file pin. Call get_download again before downloading.", { retryable: true }), ...shared };
222
+ }
223
+ const reason = link.status === 403 || link.status === 451 ? "license_acceptance_required"
224
+ : link.status === 404 || link.status === 410 ? "file_gone"
225
+ : link.status === 429 || link.status === 503 ? "busy" : "link_unavailable";
226
+ const message = reason === "license_acceptance_required" ? "This file needs its license accepted before download. Open downloadUrl in a browser to read and accept it."
227
+ : reason === "file_gone" ? "This file is no longer served. Call get_model for current files."
228
+ : reason === "busy" ? "Downloads are busy. Retry after a few seconds."
229
+ : "No download link right now. Retry, or open downloadUrl directly.";
230
+ const retryAfter = Number(link.header?.("retry-after"));
231
+ return { ...base, url: null, linkStatus: link.status || null, ...toolError(reason, message, { retryable: reason === "busy" || reason === "link_unavailable",
232
+ ...(reason === "busy" && Number.isSafeInteger(retryAfter) && retryAfter > 0 ? { retryAfterSeconds: retryAfter } : {}) }), ...shared };
233
+ }
234
+
235
+ // The live byte route's own identity for the bytes it just admitted: an ETag
236
+ // "sha256-<hex>" and/or X-Hugging-Bay-Sha256. Every present value must match
237
+ // and at least one must be present; only a success status counts.
238
+ export function liveLinkConfirmsFile(link, sha256) {
239
+ const want = String(sha256 || "").toLowerCase();
240
+ if (!/^[a-f0-9]{64}$/.test(want) || typeof link?.header !== "function") return false;
241
+ const ok = ([301, 302, 303, 307, 308].includes(link.status) && signedLinkAllowed(link.location)) || link.status === 200 || link.status === 206;
242
+ if (!ok) return false;
243
+ const etag = (String(link.header("etag") || "").match(/sha256-([a-f0-9]{64})/i) || [])[1];
244
+ const direct = String(link.header("x-hugging-bay-sha256") || "").trim();
245
+ const seen = [etag, direct].filter(Boolean).map(value => value.toLowerCase());
246
+ return seen.length > 0 && seen.every(value => value === want);
247
+ }
248
+
249
+ // Checks every lock entry against the current download plan of its artifact.
250
+ export async function verifyLockAgainstCatalog(text, io) {
251
+ let parsed;
252
+ try { parsed = parseLock(text); } catch (error) {
253
+ return { schema: LOCK_CHECK_SCHEMA, ok: false, error: "invalid_lock", message: error.message, files: [] };
254
+ }
255
+ const plans = new Map();
256
+ const files = [];
257
+ if (new Set(parsed.files.map(entry => entry.artifactId)).size > MAX_LOCK_ARTIFACTS) {
258
+ 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: [] };
259
+ }
260
+ for (const entry of parsed.files) {
261
+ if (!plans.has(entry.artifactId)) {
262
+ try { plans.set(entry.artifactId, await io.readPlan(entry.artifactId)); } catch (error) { plans.set(entry.artifactId, { failed: Number(error?.status) || 0 }); }
263
+ }
264
+ const plan = plans.get(entry.artifactId);
265
+ if (plan.failed !== undefined) {
266
+ 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." });
267
+ continue;
268
+ }
269
+ const row = (Array.isArray(plan.files) ? plan.files : []).find(item => item?.path === entry.path);
270
+ const current = row ? lockEntryFromPlan(plan, row) : null;
271
+ if (!row) files.push({ path: entry.path, artifactId: entry.artifactId, status: "file_missing", detail: "The catalog no longer lists this path." });
272
+ 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." });
273
+ 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." });
274
+ 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." });
275
+ else files.push({ path: entry.path, artifactId: entry.artifactId, status: "match", sizeBytes: current.size, ...(parsed.version === 1 ? { upgrade: current } : {}) });
276
+ }
277
+ const ok = files.every(file => file.status === "match");
278
+ return { schema: LOCK_CHECK_SCHEMA, ok, lockSchema: parsed.schema, files,
279
+ ...(parsed.version === 1 && ok ? { upgradedLock: buildLockV2(files.map(file => file.upgrade)).text } : {}),
280
+ 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." };
281
+ }
282
+
283
+ // Public reader for the stdio server and tests: plain fetch against the site.
284
+ export function publicDownloadIo({ fetchImpl = fetch, site = LOCK_SITE, headers = {}, timeoutMs = 15000 } = {}) {
285
+ const common = { Accept: "application/json", DNT: "1", "Sec-GPC": "1", ...headers };
286
+ return {
287
+ async readPlan(reference) {
288
+ let id = reference;
289
+ if (!ARTIFACT_ID.test(id)) {
290
+ // owner/repo or a Hub URL: resolve to the catalog id first.
291
+ const resolved = await fetchImpl(`${site}/api/v1/resolve?repo=${encodeURIComponent(reference)}`, { headers: common, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
292
+ const body = resolved.ok ? await resolved.json().catch(() => null) : null;
293
+ 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 });
294
+ id = body.artifactId;
295
+ }
296
+ const response = await fetchImpl(`${site}/api/v1/artifacts/${encodeURIComponent(id)}/download-plan`, { headers: common, redirect: "follow", signal: AbortSignal.timeout(timeoutMs) });
297
+ const text = await response.text();
298
+ if (!response.ok) throw Object.assign(new Error(`plan_http_${response.status}`), { status: response.status });
299
+ return JSON.parse(text);
300
+ },
301
+ async openDownload(pathAndQuery) {
302
+ const response = await fetchImpl(`${site}${pathAndQuery}`, { headers: { ...common, Accept: "*/*" }, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) });
303
+ try { await response.body?.cancel(); } catch {}
304
+ return { status: response.status, location: response.headers.get("location"), header: name => response.headers.get(name) };
305
+ },
306
+ };
307
+ }
308
+
309
+ // MCP CallToolResult for get_download / verify_lock, shared by hosted and
310
+ // stdio. The file is also offered as a resource_link (2025-06-18+) carrying
311
+ // its SHA-256 and size; servers strip resource_link for 2025-03-26 clients.
312
+ export function agentDownloadResult(name, called) {
313
+ const content = [{ type: "text", text: JSON.stringify(called) }];
314
+ if (name === "get_download" && called?.resource && called.sha256) {
315
+ content.push({ type: "resource_link", uri: called.resource, name: called.path, mimeType: "application/json",
316
+ description: `${formatBytes(called.sizeBytes)}, SHA-256 ${called.sha256}. Reading returns the file record, not the bytes.`,
317
+ _meta: { "xyz.huggingbay/file": { sha256: called.sha256, sizeBytes: called.sizeBytes, revision: called.revision, license: called.license } } });
318
+ }
319
+ const lockText = name === "get_download" ? called?.hbLock?.text : called?.upgradedLock;
320
+ if (lockText) content.push({ type: "resource", resource: { uri: "huggingbay://receipts/hb.lock", mimeType: "application/json", text: lockText } });
321
+ const isError = name === "get_download" ? Boolean(called?.error) : ["invalid_lock", "too_many_artifacts"].includes(called?.error);
322
+ return { content, structuredContent: called, isError };
323
+ }