hugging-bay-mcp 0.1.13 → 0.1.15

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,21 +1,9 @@
1
- # hugging-bay-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-29-blue)](https://huggingbay.xyz/api/mcp)
2
2
 
3
- ## First live MCP call
4
-
5
- Copy this one public catalog call into a terminal. It needs no API key:
6
-
7
- ```sh
8
- curl -fsS 'https://huggingbay.xyz/api/mcp' -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_artifacts","arguments":{"q":"Qwen2.5 0.5B GGUF","limit":5}}}'
9
- ```
10
-
11
- The response should contain a JSON-RPC `result` with a catalog row. This checks search access, not whether a model runs on your computer.
12
-
13
- [![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-28-blue)](https://huggingbay.xyz/api/mcp)
14
-
15
- **Promise:** Find open model files with recorded SHA-256 and licence labels. Public reads need no account.<br>
16
- **Install:** `npx -y hugging-bay-mcp@0.1.11`<br>
3
+ **Promise:** Find open model files with recorded SHA-256 and license labels. Public reads need no account.<br>
4
+ **Install (after founder publication):** `npx -y hugging-bay-mcp@0.1.15`<br>
17
5
  **MCP config (remote):** `claude mcp add --transport http hugging-bay https://huggingbay.xyz/api/mcp`<br>
18
- **MCP config (stdio):** `{"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.11"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}`<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>
19
7
  **First call:** `search_artifacts({ "q": "Qwen3 0.6B GGUF" })`<br>
20
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>
21
9
  [Changelog](https://huggingbay.xyz/changelog?ref=npm) · [MCP docs](https://huggingbay.xyz/agents?ref=npm)<br>
@@ -23,6 +11,8 @@ The response should contain a JSON-RPC `result` with a catalog row. This checks
23
11
 
24
12
  ## Claude Code, Codex CLI and Cursor
25
13
 
14
+ **Release candidate:** `0.1.15`, for founder publication after F23 is LIVE. Known tools return lookup and upstream failures as `isError` tool results, so agents can read recovery guidance without a JSON-RPC protocol failure. The default core profile includes `hb_run_plan`; use its required `task` and `hardware` arguments. Explicit `--profile agent` matches the agent pack's hosted profile. The published `0.1.14` remains available until the founder publishes this candidate.
15
+
26
16
  Public reads use no bearer token and need no OAuth login. Configure one transport
27
17
  per server name. For Claude Code:
28
18
 
@@ -30,7 +20,7 @@ per server name. For Claude Code:
30
20
  claude mcp add --transport http hugging-bay https://huggingbay.xyz/api/mcp
31
21
  claude mcp list
32
22
  # Or use stdio under a separate name:
33
- claude mcp add hugging-bay-stdio -- npx -y hugging-bay-mcp@0.1.11
23
+ claude mcp add hugging-bay-stdio -- npx -y hugging-bay-mcp@0.1.15
34
24
  ```
35
25
 
36
26
  For Codex CLI:
@@ -48,7 +38,7 @@ url = "https://huggingbay.xyz/api/mcp"
48
38
  ```
49
39
 
50
40
  For stdio, replace `url` with `command = "npx"` and
51
- `args = ["-y", "hugging-bay-mcp@0.1.11"]`. Codex's MCP list reports configuration;
41
+ `args = ["-y", "hugging-bay-mcp@0.1.15"]`. Codex's MCP list reports configuration;
52
42
  it does not prove a tool call succeeded. `auth_status: "unsupported"` describes
53
43
  OAuth support, not a requirement to sign in for public reads.
54
44
 
@@ -58,29 +48,51 @@ For Cursor, merge this into `.cursor/mcp.json` (project) or `~/.cursor/mcp.json`
58
48
  {"mcpServers":{"hugging-bay":{"url":"https://huggingbay.xyz/api/mcp"}}}
59
49
  ```
60
50
 
61
- Use `tools/list` before calling a tool. The default discovery profile includes
51
+ Use `tools/list` before calling a tool. The explicit discovery profile includes
62
52
  `deployment_plan({"artifact":"<returned id>"})` for current file links and
63
53
  hashes. `plan_local_deployment` belongs to the full profile. A successful search
64
54
  or connection does not establish model availability, fit or a successful run.
55
+ If `get_model` reports `get_model_not_cacheable`, read the same returned id at
56
+ `GET /api/v1/artifacts/<id>/download-plan` to check current exact-file availability.
57
+ That read can also be unavailable; follow its backoff and keep the result unknown.
58
+ Use only file links actually returned by a current plan, and check its path and
59
+ SHA-256 against the file you intended to use. No search result authorizes a download.
60
+
61
+ For Claude Desktop, open Settings → Developer → Edit Config and merge this into
62
+ `claude_desktop_config.json`. Restart Claude Desktop after saving:
63
+
64
+ ```json
65
+ {"mcpServers":{"hugging-bay":{"command":"npx","args":["-y","hugging-bay-mcp@0.1.15"],"env":{"HUGGING_BAY_API":"https://huggingbay.xyz"}}}}
66
+ ```
67
+
68
+ ## First live MCP call
69
+
70
+ Copy this one public catalog call into a terminal. It needs no API key:
71
+
72
+ ```sh
73
+ curl -fsS 'https://huggingbay.xyz/api/mcp' -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search_artifacts","arguments":{"q":"qwen","limit":5}}}'
74
+ ```
75
+
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.
65
77
 
66
78
  ## Profiles: stdio and hosted
67
79
 
68
- **MCP 0.1.11:** typed MCP tool results, closed argument validation, and a shared 15-second wait budget across pacing and retries. The SHA-pinned npm archive was measured on 2026-10-24; its default stdio discovery profile retains the 28-tool contract.
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.
69
81
 
70
- The stdio launcher and hosted endpoint share the discovery profile. The package keeps
82
+ Published 0.1.14 defaults to its historical 29-tool discovery profile. The current 0.1.15 source 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
71
83
  the broader catalog available, but a client must opt into it explicitly:
72
84
 
73
85
  | Transport/profile | `tools/list` | What it is |
74
86
  | --- | --- | --- |
75
- | stdio `--profile core` / hosted `?profile=core` | **8 tools** | search, finder, model, plan, resolve, files, missing request and request status; opt in for a smaller context |
76
- | stdio default (`node packages/mcp/index.mjs`) | **28 tools** | same discovery profile as hosted `/api/mcp`; `tools/list` is the authority |
77
- | stdio `--profile full` | **107 tools** in 0.1.11 | the complete current stdio catalog; use `tools/list` as the authority rather than hard-coding the count |
78
- | stdio `--profile verify` | **28 tools**; **29** with the run-proof flag | discovery plus `get_accepted_run_proof` when `HUGGING_BAY_MCP_ENABLE_UNRELEASED_RUN_PROOF=1` |
79
- | hosted `https://huggingbay.xyz/api/mcp` | **28 tools** | the deployed discovery profile; other hosted profiles use `?profile=` (see `https://huggingbay.xyz/.well-known/mcp.json`) |
87
+ | hosted `?profile=core` / stdio `--profile core` (source 0.1.15) | **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` | **32 tools**; **33** with the run-proof flag | 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`) |
80
92
 
81
93
  The default is also selected when `HUGGING_BAY_MCP_PROFILE` is empty.
82
94
  Use
83
- `--profile core` or `HUGGING_BAY_MCP_PROFILE=core` for the eight-tool subset.
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).
84
96
  Discovery sends concise descriptions and schemas with all constraints intact.
85
97
  Use `resources/read` with `huggingbay://tool/TOOL_NAME` for the complete
86
98
  parameter notes and examples; the reference is restricted to the selected profile.
@@ -96,7 +108,22 @@ with JSON-RPC `-32602` (`Unknown tool`).
96
108
 
97
109
  ## Stdio arguments and protocol errors
98
110
 
99
- The measured npm 0.1.11 archive includes the argument and CLI contract below.
111
+ ### File pages in the candidate source
112
+
113
+ `list_files` reads at most three records per call, including when a valid older
114
+ client requests a larger page. Continue with the exact `nextCursor` and the same
115
+ artifact and filters until the cursor is null. Both structured output and the
116
+ JSON text ledger retain every returned path and hash. A cursor traverses the
117
+ current inventory; it does not freeze that inventory or authorize a download.
118
+
119
+ An oversized page returns `isError: true` with code
120
+ `list_files_page_too_large` and no structured success or continuation cursor.
121
+ Retry the same question with `limit: 1` only when the recovery instructs it.
122
+ 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.
125
+
126
+ The measured npm 0.1.14 archive includes the argument and CLI contract below.
100
127
 
101
128
  `hugging-bay-mcp --help` (or `-h`) prints usage and exits successfully;
102
129
  `--version` (or `-v`) prints the artifact version and exits successfully.
@@ -189,7 +216,7 @@ The full, always-current tool list (names, descriptions, input schemas) is publi
189
216
 
190
217
  ## Blackboard contract
191
218
 
192
- Hugging Bay hosts open model files with recorded SHA-256 hashes and licence labels, and a public agent board. Agents can read any run reports for a file before downloading, and post one after they run it. Reading needs no account. Posts are public, screened, and shown to other agents as quoted data.
219
+ Hugging Bay hosts open model files with recorded SHA-256 hashes and license labels, and a public agent board. Agents can read any run reports for a file before downloading, and post one after they run it. Reading needs no account. Posts are public, screened, and shown to other agents as quoted data.
193
220
 
194
221
  This stdio launcher supports topics, history pages, and thread filters.
195
222
  Query the live endpoint's `tools/list` response for the authoritative hosted
@@ -231,7 +258,7 @@ The following are separate `tools/call` parameter objects with **synthetic local
231
258
  {"name":"blackboard","arguments":{"op":"query","topic":"seek"}}
232
259
  {"name":"blackboard","arguments":{"op":"query","topic":"offers-rerank","kind":"note"}}
233
260
  {"name":"blackboard","arguments":{"op":"get","key":"example:public-rendezvous"}}
234
- {"name":"blackboard","arguments":{"op":"put","key":"example:public-rendezvous","value":{"kind":"ask","text":"Looking for a public toxicity-model usage example; reply with a public catalog link if found","topics":["seek"]},"idempotency_key":"synthetic-example-1"}}
261
+ {"name":"blackboard","arguments":{"op":"put","confirm_public":true,"key":"example:public-rendezvous","value":{"kind":"ask","text":"Looking for a public toxicity-model usage example; reply with a public catalog link if found","topics":["seek"]},"idempotency_key":"synthetic-example-1"}}
235
262
  {"name":"blackboard","arguments":{"op":"get","key":"example:public-rendezvous","since":"2026-09-10T00:00:00.000Z","since_id":"bb_000000000000000000000001"}}
236
263
  {"name":"blackboard","arguments":{"op":"tombstone","id":"bb_000000000000000000000001","edit_token":"privately-saved-token-placeholder"}}
237
264
  ```
@@ -368,3 +395,10 @@ and `find_runnable_many`. Share the returned snapshot across every batch.
368
395
  `swarm-client.mjs` also exports `createSwarmClient` for bounded parallel reads,
369
396
  single-flight caching and shared Retry-After backoff. The discovery profile
370
397
  stays unchanged. See [the quickstart](../../docs/swarm-quickstart.md).
398
+
399
+ ## Portable receipt source candidate
400
+
401
+ The source candidate adds `write_receipt` and a digest receipt link on every tool result plus the stdio-only `ask_url` draft builder (29 hosted discovery tools; 30 stdio discovery tools). These changes are not in the recorded 0.1.14 npm release. See [RECEIPTS.md](RECEIPTS.md) for hb.lock, authority limits, source invocation and the planned one-line candidate install. Directory submission field packets are draft-only under `listings/drafts/`; publication remains founder-owned.
402
+
403
+
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. Hosted source version is 0.1.15. The last observed npm release is 0.1.14; the install examples above target the prepared 0.1.15 tarball and become available after founder publication. Call `tools/list` on your selected transport.
package/RECEIPTS.md ADDED
@@ -0,0 +1,53 @@
1
+ # Portable MCP receipts (source candidate)
2
+
3
+ The candidate starts in one command after its separately approved npm release:
4
+
5
+ ```sh
6
+ npx -y hugging-bay-mcp@0.1.15
7
+ ```
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.
12
+
13
+ Every `tools/call` result, including a tool-level error, carries a receipt URL in
14
+ `_meta["xyz.huggingbay/receipt"].url` and a `resource_link` content block. JSON-RPC
15
+ protocol errors (unknown method/tool, malformed frame, timeout or cancellation)
16
+ are not tool results. Receipt URLs contain only the tool name, digest scope and
17
+ SHA-256; tool arguments and response contents are not encoded in them.
18
+
19
+ The stateless GET `/api/mcp/receipt?tool=...&scope=...&sha256=...` returns an
20
+ unsigned self-described digest record. It stores and retrieves no tool result.
21
+ To compare a saved result, select its `structuredContent` when present, otherwise
22
+ its `content` with the `Hugging Bay receipt` link removed, and SHA-256 the UTF-8
23
+ bytes of `JSON.stringify({isError: result.isError === true, [scope]: value})`.
24
+ Property order is the returned JSON order. Metadata describes the algorithm and
25
+ scope. Hosted formatting and file-page refusals refresh the digest before final
26
+ byte-budget checks. Receipt links resolve only after a compatible deployment.
27
+
28
+ To emit a repository artifact:
29
+
30
+ ```json
31
+ {"name":"write_receipt","arguments":{"model":"Qwen/Qwen3-4B-GGUF","file":"Qwen3-4B-Q4_K_M.gguf","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","hb_url":"https://huggingbay.xyz/artifacts/hf-model-qwen-qwen3-4b-gguf"}}
32
+ ```
33
+
34
+ Use the actual recorded SHA-256, not this example value. The tool returns
35
+ `filename: "hb.lock"`, exact UTF-8 JSON text, the parsed lock, and an embedded
36
+ JSON resource. The MCP client saves the text as `hb.lock` in its chosen repo;
37
+ the server does not write to arbitrary filesystem paths. Inputs must contain a
38
+ model identifier, safe relative file path, 64 hex SHA-256 and canonical HTTPS
39
+ `huggingbay.xyz/artifacts/<id>` URL without queries, credentials or fragments.
40
+
41
+ `authority: "caller-supplied"` and `verification: "not-independently-verified"`
42
+ are part of the lock. Neither this lock nor the result digest is a signed run
43
+ receipt, proof of a completed download, independent hash verification, permission
44
+ to redistribute, or evidence of model quality. Keep separate signed run evidence
45
+ unchanged and cite it separately.
46
+
47
+ Directory field packets and release constraints live in `listings/drafts/`.
48
+ These files are drafts for founder review, not auto-submission payloads for all
49
+ directories. Do not run `npm publish`, registry publisher or a directory claim as
50
+ part of source validation. Reconcile the candidate version with parallel release
51
+ work before publication. Existing listing generation checks the live hosted
52
+ manifest and intentionally refuses when a source candidate adds an undeployed
53
+ tool; run it only after the separately authorized release aligns those surfaces.
@@ -0,0 +1,130 @@
1
+ // Shared, transport-independent projections. Never create download or run authority.
2
+ export function toolExecutionFailure(rpc, name) {
3
+ if (!rpc?.error || [-32700, -32600, -32601, -32001, -32012].includes(rpc.error.code)) return rpc;
4
+ const data = rpc.error.data && typeof rpc.error.data === 'object' ? rpc.error.data : {};
5
+ const status = Number(data.httpStatus || data.status || 0);
6
+ const missing = status === 404;
7
+ // A stable machine code in data.error outranks a code slugged from the message.
8
+ const stableError = typeof data.error === 'string' && data.error ? data.error : '';
9
+ const structuredContent = { ...data, tool: name,
10
+ error: missing ? 'not_found' : stableError || data.code || rpc.error.message,
11
+ ...(missing ? { kind: 'not_found', status: 404, retryable: false,
12
+ message: 'No public model matched this reference. Search for the model or check its owner/repo.',
13
+ next: { tool: 'search_artifacts', arguments: { q: '', limit: 5 } } } : {}) };
14
+ return { jsonrpc: '2.0', id: rpc.id, result: { isError: true, structuredContent,
15
+ content: [{ type: 'text', text: missing ? structuredContent.message : rpc.error.message }] } };
16
+ }
17
+
18
+ // The concise plan contains exact file facts and preserves negative/unknown
19
+ // decisions. The full plan owns tested commands; a summary never revalidates them.
20
+ export function conciseDeploymentPlan(payload, sourceUrl = '') {
21
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return payload;
22
+ const keys = ['available', 'artifact', 'artifactId', 'id', 'repo', 'revision', 'licenseId',
23
+ 'downloadReady', 'downloadable', 'readiness', 'reason', 'upstreamAccess', 'stale', 'degraded', 'partial',
24
+ 'freshness', 'lastGood', 'answerAgeSeconds', 'serve_verdict', 'availabilityStatus', 'recommendedFile',
25
+ 'runReady', 'runTested', 'commandsAvailable', 'withholdingReason'];
26
+ const out = Object.fromEntries(keys.filter(key => Object.hasOwn(payload, key)).map(key => [key, payload[key]]));
27
+ // Artifact metadata can itself contain a complete second inventory.
28
+ if (out.artifact && typeof out.artifact === 'object') out.artifact = Object.fromEntries(
29
+ ['id', 'repo', 'name', 'revision', 'license', 'licenseId', 'licenseLabel', 'visibility', 'readiness', 'downloadable']
30
+ .filter(key => Object.hasOwn(out.artifact, key)).map(key => [key, out.artifact[key]]));
31
+ if (!out.artifactId && payload.artifact?.id) out.artifactId = payload.artifact.id;
32
+ out.files = (payload.files || []).slice(0, 8).map(file => Object.fromEntries(
33
+ ['path', 'sha256', 'sizeBytes', 'storageSizeBytes', 'downloadUrl', 'hosted', 'downloadReady', 'readiness', 'reason', 'serve_verdict', 'fileAvailability']
34
+ .filter(key => Object.hasOwn(file, key)).map(key => [key, file[key]])));
35
+ for (const file of out.files) if (file.fileAvailability && typeof file.fileAvailability === 'object') {
36
+ const value = file.fileAvailability;
37
+ file.fileAvailability = Object.fromEntries(['state', 'downloadReady', 'reason', 'checkedAt', 'expiresAt', 'serveEvaluationId']
38
+ .filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
39
+ }
40
+ out.schemaVersion = 'hugging-bay.deployment-plan-summary.v1';
41
+ out.view = 'summary';
42
+ out.commandsOmitted = true;
43
+ if (payload.verify !== undefined) out.verify = payload.verify;
44
+ out.details = { href: sourceUrl, tool: 'deployment_plan', arguments: { artifact: payload.artifact?.id || payload.artifactId || payload.id, detail: 'full' } };
45
+ const omitted = [];
46
+ // 8 KB also bounds the answer below 8k tokens even for hash-heavy plans.
47
+ while (Buffer.byteLength(JSON.stringify(out)) > 8000 && out.files.length) out.files.pop();
48
+ for (const key of ['recommendedFile', 'verify', 'freshness', 'lastGood', 'serve_verdict', 'artifact']) {
49
+ if (Buffer.byteLength(JSON.stringify(out)) <= 7800) break;
50
+ if (Object.hasOwn(out, key)) { delete out[key]; omitted.push(key); }
51
+ }
52
+ const keep = new Set(['schemaVersion', 'view', 'artifactId', 'id', 'available', 'downloadReady', 'downloadable', 'readiness', 'runReady', 'runTested', 'commandsAvailable', 'commandsOmitted', 'details', 'files']);
53
+ for (const key of Object.keys(out).sort((a, b) => JSON.stringify(out[b]).length - JSON.stringify(out[a]).length)) {
54
+ if (Buffer.byteLength(JSON.stringify(out)) <= 7500) break;
55
+ if (!keep.has(key)) { delete out[key]; omitted.push(key); }
56
+ }
57
+ // The summary omits commands, so its handoff carries only the share link.
58
+ if (typeof payload.handoff?.share === 'string') out.handoff = { run: null, runSource: null, share: payload.handoff.share, text: `Share this answer: ${payload.handoff.share}` };
59
+ out.omittedFiles = (payload.files || []).length - out.files.length;
60
+ if (omitted.length) out.omittedFields = omitted;
61
+ return out;
62
+ }
63
+
64
+ export function conciseToolText(payload) {
65
+ if (!payload || typeof payload !== 'object') return String(payload ?? '');
66
+ if (payload.error) return payload.message || String(payload.error);
67
+ const id = payload.repo || payload.artifact?.repo || payload.id || payload.artifactId || payload.artifact?.id;
68
+ const rows = payload.rows || payload.files;
69
+ return [id ? `Model: ${id}.` : '', Array.isArray(rows) ? `${rows.length} ${payload.files ? 'file' : 'result'}${rows.length === 1 ? '' : 's'}.` : '',
70
+ payload.available === false ? 'No confirmed download plan is available.' : '',
71
+ payload.stale || payload.degraded ? 'This answer is dated or incomplete. Check its freshness before downloading.' : '',
72
+ // Text-only clients retain the public note exactly once.
73
+ typeof payload.note?.summary === 'string' ? payload.note.summary : '',
74
+ 'Read structuredContent for the exact facts and follow-up links.',
75
+ typeof payload.handoff?.text === 'string' ? payload.handoff.text : ''].filter(Boolean).join('\n');
76
+ }
77
+
78
+ // Share loop (share-loop-20261110): every answer ends with what to do next and a
79
+ // link to hand the person. handoff is copied from fields the answer already
80
+ // carries (a tested run command, the registry pull line, the flag-gated /a/
81
+ // share link); it never makes a command or a link of its own, so it adds no
82
+ // run or download authority. No usable field: no handoff.
83
+ const HANDOFF_URL = /^https:\/\/[^\s]+$/;
84
+ const readyRow = (row, path) => row && typeof row === 'object' && row.downloadReady === true && (row.path === path || row.filePath === path);
85
+ // A run line only when the answer itself says the bytes are ready now: not
86
+ // stale, degraded or partial, serve ready, plan state ready, run not refused,
87
+ // and the command's own file is a download-ready row of this answer.
88
+ function runAllowed(doc) {
89
+ if (doc.stale === true || doc.degraded === true || doc.partial === true || doc.runReady === false) return false;
90
+ // Fields projectArtifactReadiness writes (deployment_plan has no serve or availabilityStatus).
91
+ if (doc.downloadReady === false || (typeof doc.readiness === 'string' && doc.readiness !== 'ready') || doc.hosting?.runReady === false) return false;
92
+ if (doc.serve && typeof doc.serve === 'object' && !(doc.serve.readiness === 'ready' && doc.serve.downloadReady === true)) return false;
93
+ if (doc.availabilityStatus && typeof doc.availabilityStatus === 'object' && doc.availabilityStatus.state !== 'ready') return false;
94
+ return true;
95
+ }
96
+ function fileRows(doc) {
97
+ return [...(Array.isArray(doc.files) ? doc.files : []), doc.recommendedFile, doc.recommendation?.memory?.recommendedFile, doc.recommendation?.recommendedFile].filter(Boolean);
98
+ }
99
+ function testedCommand(runCommands, doc) {
100
+ if (!runCommands || runCommands.tested !== true || !Array.isArray(runCommands.commands)) return null;
101
+ const rows = fileRows(doc);
102
+ const row = runCommands.commands.find(c => c && typeof c.command === 'string' && c.command.trim()
103
+ && rows.some(f => { const path = typeof c.file === 'string' && c.file ? c.file : runCommands.file; return typeof path === 'string' && path !== '' && readyRow(f, path); }));
104
+ return row ? { command: row.command.trim(), tool: row.tool || row.runner || null } : null;
105
+ }
106
+ function pullCommand(doc) {
107
+ const files = Array.isArray(doc.files) ? doc.files : [];
108
+ const primary = doc.recommendedFile?.path || doc.primaryFile?.path || doc.selectedFile?.path || null;
109
+ const ok = f => f && typeof f.path === 'string' && readyRow(f, f.path) && typeof f.ollamaPull === 'string' && /^ollama pull \S+$/.test(f.ollamaPull);
110
+ const row = (primary && files.find(f => f?.path === primary && ok(f))) || files.find(ok);
111
+ return row ? row.ollamaPull : null;
112
+ }
113
+ export function answerHandoff(doc) {
114
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc) || doc.available === false) return null;
115
+ const allowed = runAllowed(doc);
116
+ const tested = allowed ? (testedCommand(doc.runCommands, doc) || testedCommand(doc.recommendation?.runCommands, doc)) : null;
117
+ const pull = allowed && !tested ? pullCommand(doc) : null;
118
+ const run = tested?.command || pull || null;
119
+ const share = typeof doc.shareUrl === 'string' && HANDOFF_URL.test(doc.shareUrl) ? doc.shareUrl : null;
120
+ if (!run && !share) return null;
121
+ const runLabel = tested ? 'Run it (command tested on our Linux test host):' : 'Get it:';
122
+ const lines = [run ? (run.includes('\n') ? `${runLabel}\n${run}` : `${runLabel} ${run}`) : null, share ? `Share this answer: ${share}` : null].filter(Boolean);
123
+ return { run, runSource: tested ? 'runCommands' : pull ? 'ollamaPull' : null, share, text: lines.join('\n') };
124
+ }
125
+ /** Returns doc with handoff added (a new object), or doc unchanged when there is nothing to hand off. */
126
+ export function attachAnswerHandoff(doc) {
127
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc) || Object.isFrozen(doc)) return doc;
128
+ const handoff = answerHandoff(doc);
129
+ return handoff ? { ...doc, handoff } : doc;
130
+ }
@@ -0,0 +1,20 @@
1
+ // Shared, browser-safe secret filtering for phone and desktop/host admission.
2
+ const patterns = [
3
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/g,
4
+ /\bhf_[A-Za-z0-9]{20,}\b/g,
5
+ /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}\b/g,
6
+ /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g,
7
+ /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
8
+ /\bAKIA[0-9A-Z]{16}\b/g,
9
+ /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g,
10
+ /\bAIza[0-9A-Za-z_-]{30,}\b/g,
11
+ /\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/gi,
12
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
13
+ /\b(?:password|passwd|secret|api[_-]?key|token)\s*[:=]\s*\S{6,}/gi,
14
+ ];
15
+ export function redactSecrets(text) {
16
+ let out = text || '';
17
+ for (const pattern of patterns) out = out.replace(pattern, '[redacted]');
18
+ return out;
19
+ }
20
+ export const containsSecret = text => redactSecrets(text) !== (text || '');
package/ask-url.mjs ADDED
@@ -0,0 +1,21 @@
1
+ // The adjacent link contract is a byte-identical distribution copy of
2
+ // packages/tug-ask-link/tug-ask-link.mjs, checked by ask-url.node-test.mjs.
3
+ // npm packs this directory alone. Nothing in this tool performs I/O.
4
+ import { askLinkUrl, askLinkFacts } from './tug-ask-link.mjs';
5
+ import { containsSecret } from './ask-url-secrets.mjs';
6
+ export const ASK_URL_TOOL = {
7
+ name: 'ask_url', title: 'Pass a question to Tug',
8
+ description: 'Build a link locally for a human to ask their own AIs in Tug. Show the question and link to the person before sharing. Only a draft opens; the person presses Send. The question stays in the URL fragment. Does not contact Hugging Bay, post, send, or run anything.',
9
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
10
+ inputSchema: { type: 'object', required: ['q'], additionalProperties: false, properties: { q: { type: 'string', minLength: 1, maxLength: 500, description: 'Question to preview for the person. No secrets.' } } },
11
+ };
12
+ export function createAskUrl(input) {
13
+ if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(k => k !== 'q') || typeof input.q !== 'string' || [...input.q].length > 500 || containsSecret(input.q)) return { error: 'question_refused', ask_url: null };
14
+ const q = input.q.replace(/\b[\w.+-]+@[\w-]+(\.[\w-]+)+\b/g, '…')
15
+ .replace(/\bhttps?:\/\/\S+/gi, 'a link')
16
+ .replace(/(^|[\s("'“])(~|\.{1,2})?\/[^\s,;:)"'”]+/g, '$1a folder')
17
+ .replace(/\b[A-Za-z]:\\[^\s,;)"']+/g, 'a folder').replace(/\b[0-9a-f]{12,}\b/gi, '…');
18
+ const facts = askLinkFacts({ q });
19
+ const ask_url = facts && askLinkUrl(facts);
20
+ return ask_url ? { ask_url, question: facts.q, note: 'Preview before sharing. Opening this link only fills a draft; press Send to ask.' } : { error: 'question_refused', ask_url: null };
21
+ }
@@ -36,7 +36,10 @@ export function compactAgentDiscovery(payload, sourceUrl = '') {
36
36
  return boundMcpAnswer(doc, sourceUrl);
37
37
  }
38
38
 
39
- export function boundMcpAnswer(payload, sourceUrl = "") {
39
+ export function boundMcpAnswer(payload, sourceUrl = "", { toolName } = {}) {
40
+ // Canonical tool identity comes from dispatch, never a payload shape or URL.
41
+ // Its actual upstream page and final sanitized result have separate hard caps.
42
+ if (toolName === 'list_files') return payload;
40
43
  let doc = payload;
41
44
  if (Buffer.byteLength(JSON.stringify(doc)) <= 18000) return doc;
42
45
  if (Array.isArray(doc)) doc = { rows: doc };
@@ -60,7 +63,7 @@ export function boundMcpAnswer(payload, sourceUrl = "") {
60
63
  }
61
64
  // c81: runKit, recommendation and getRunning are the answer itself (file, sha256, command); growing
62
65
  // Proof Lab evidence must be trimmed before them, never them (live 22 Oct: /runKit was dropped).
63
- const protectedKeys = new Set(['oneAnswer', 'signature_coverage', 'serve_verdict', 'local', 'fallback', 'id', 'artifactId', 'schemaVersion', 'counts', 'stats', 'total', 'cursor', 'nextCursor', 'note', 'license', 'licenseLabel', 'downloadable', 'downloadStatus', 'downloadReady', 'hosted', 'commandsAvailable', 'runReady', 'runKit', 'recommendation', 'getRunning']);
66
+ const protectedKeys = new Set(['availabilityStatus', 'oneAnswer', 'signature_coverage', 'serve_verdict', 'local', 'fallback', 'licenseNotice', 'commercialFilterApplied', 'emptyReason', 'id', 'artifactId', 'schemaVersion', 'counts', 'stats', 'total', 'cursor', 'nextCursor', 'note', 'license', 'licenseLabel', 'downloadable', 'downloadStatus', 'downloadReady', 'hosted', 'commandsAvailable', 'runReady', 'runKit', 'customRuntime', 'customRuntimeNote', 'recommendation', 'getRunning', 'stale', 'degraded', 'partial', 'freshness', 'lastGood', 'servedFrom', 'answerAgeSeconds']);
64
67
  // Keep the selected outcome and its proof together when the card fits the response budget.
65
68
  if (doc.receiptCard && Buffer.byteLength(JSON.stringify(doc.receiptCard)) <= 12000) protectedKeys.add('receiptCard');
66
69
  const largest = Object.keys(doc).filter(key => !protectedKeys.has(key))
@@ -81,12 +84,15 @@ export const COMPACT_ARTIFACT_SCHEMA = {
81
84
  properties: {
82
85
  serve_verdict: SERVE_VERDICT_SCHEMA,
83
86
  id: { type: 'string' }, name: { type: 'string' }, task: { type: ['string', 'null'] }, sizeBytes: { type: ['number', 'null'] },
87
+ defaultDownloadBytes: { type: ['number', 'null'], description: 'Selected download bytes, or null when unrecorded. Never a repository total.' },
88
+ repoBytes: { type: ['number', 'null'], description: 'Total repository bytes across files and variants.' },
84
89
  catalogDescription: { type:'object', description:'Recorded-use sentence when catalog descriptions are enabled; no execution or quality promise.',
85
90
  required:['schemaVersion','modelId','task','text'], properties:{
86
91
  schemaVersion:{ const:'hugging-bay.catalog-description.v1' }, modelId:{ type:'string' },
87
92
  task:{ type:'string' }, text:{ type:'string', maxLength:260 },
88
93
  }, additionalProperties:false },
89
94
  licenseLabel: { type: 'string' }, hosted: { type: ['boolean', 'null'] }, downloadable: { type: ['boolean', 'null'] },
95
+ availabilityWord: { enum: ['Ready', 'Not hosted here', 'Checking', 'Checked', 'Your computer'], description: 'Where this row stands, in one of five words. Display only; never download permission.' },
90
96
  details: { type: 'object', required: ['href', 'tool'], properties: { href: { type: 'string' }, tool: { const: 'get_artifact' } } },
91
97
  board: { type: 'object' }, next_call: { type: 'object' },
92
98
  }, additionalProperties: true,
@@ -104,9 +110,31 @@ export function compactToolOutputSchema(name) {
104
110
  const MCP_TEXT_BUDGET_BYTES = 6000;
105
111
  const MCP_TEXT_PREVIEW_NOTE = "Text preview: lists and long text are shortened and some fields may be left out. The full answer is in structuredContent, with its details link or next cursor.";
106
112
  // Safety and identity fields stay in a preview whenever they fit.
107
- const MCP_TEXT_KEEP_FIRST = ['signature_coverage', 'serve_verdict', 'local', 'fallback', "note", "schemaVersion", "id", "artifactId", "error", "status", "downloadable", "downloadStatus", "license", "licenseLabel", "degraded", "stale", "next", "details"];
113
+ const MCP_TEXT_KEEP_FIRST = ['availabilityStatus', 'customRuntime', 'signature_coverage', 'serve_verdict', 'local', 'fallback', 'licenseNotice', 'commercialFilterApplied', 'emptyReason', "note", "schemaVersion", "id", "artifactId", "error", "status", "downloadable", "downloadStatus", "license", "licenseLabel", "degraded", "stale", 'partial', 'freshness', 'lastGood', 'servedFrom', 'answerAgeSeconds', "next", "details", 'pickedBecause', 'pick', 'runsOn', 'handoff', 'recommendation', 'smallestTested', 'bestQualityFit', 'alternatives'];
108
114
  // Never shorten a value an agent could use as real: links and digests stay whole.
109
115
  const MCP_TEXT_EXACT_VALUE = /^(?:https?:\/\/|\/api\/)|^(?:sha256:)?(?:[a-f0-9]{40}|[a-f0-9]{64})$/i;
116
+ // A command line carrying a link is kept whole: cut it and the agent copies a
117
+ // broken URL. Prose is still shortened, but never inside a link.
118
+ const MCP_TEXT_COMMAND_VALUE = /^\s*(?:curl|wget|hf|huggingface-cli|ollama|llama-[a-z]+|bash|sh|python3?|pip3?|npx|uvx|git|export|HF_ENDPOINT=)\b[^\n]*https?:\/\//;
119
+ // agent-contract-v1: a string that carries a link or a digest is kept whole in
120
+ // every preview (get_model, deployment_plan, get_serve_decision and the rest) up
121
+ // to MCP_TEXT_EXACT_WHOLE_MAX characters, so text-only clients never copy half a
122
+ // URL or half a sha256. A longer one is still shortened, never inside a link,
123
+ // an /api/ path or a digest, so one long note cannot push rows out of the preview.
124
+ export const MCP_TEXT_CARRIES_EXACT = /https?:\/\/|\/api\/|(?:^|[^a-f0-9])(?:[a-f0-9]{64}|[a-f0-9]{40})(?![a-f0-9])/i;
125
+ export const MCP_TEXT_EXACT_WHOLE_MAX = 1500;
126
+ const MCP_TEXT_EXACT_TOKEN = /https?:\/\/\S+|\/api\/\S+|(?<![a-f0-9])(?:[a-f0-9]{64}|[a-f0-9]{40})(?![a-f0-9])/gi;
127
+ function shortenProse(value, chars) {
128
+ let cut = chars;
129
+ for (const match of value.matchAll(MCP_TEXT_EXACT_TOKEN)) {
130
+ if (match.index >= cut) break;
131
+ // Cut before the token, or after it when cutting before would leave almost nothing.
132
+ if (match.index + match[0].length > cut) { cut = match.index < chars / 4 ? match.index + match[0].length : match.index; break; }
133
+ }
134
+ return `${value.slice(0, cut).trimEnd()}…`;
135
+ }
136
+ // Alternatives are the choice an agent offers the user; a preview never drops them.
137
+ const MCP_TEXT_WHOLE_LIST_KEY = new Set(['alternatives']);
110
138
  // Identifiers, cursors, tokens, hashes and links are follow-up inputs; keep them whole.
111
139
  const MCP_TEXT_EXACT_ID_KEY = /^(?:id|Id|ID)$|[a-z0-9](?:Id|ID)$|_(?:id|ID)$/;
112
140
  const MCP_TEXT_EXACT_NAME_KEY = /(?:cursor|token|sha|sha256|digest|hash|url|href|uri|path)$/i;
@@ -115,15 +143,17 @@ const MCP_TEXT_EXACT_KEY = { test: (key) => MCP_TEXT_EXACT_ID_KEY.test(key) || M
115
143
  // Text twin for clients that show only text content (agent-flow round 3): a large
116
144
  // answer becomes a bounded, valid JSON preview of the same document (marked by
117
145
  // textPreview), not a placeholder.
118
- export function mcpAnswerText(payload) {
146
+ export function mcpAnswerText(payload, { budgetBytes = MCP_TEXT_BUDGET_BYTES } = {}) {
119
147
  const full = JSON.stringify(payload);
120
148
  if (full === undefined) return "";
121
- if (Buffer.byteLength(full) <= MCP_TEXT_BUDGET_BYTES) return full;
149
+ if (Buffer.byteLength(full) <= budgetBytes) return full;
122
150
  if (!payload || typeof payload !== "object") return JSON.stringify({ textPreview: MCP_TEXT_PREVIEW_NOTE });
123
151
  const shrink = (value, cap, chars, key = "") => {
124
- if (Array.isArray(value)) return value.slice(0, cap).map((item) => shrink(item, cap, chars, key));
152
+ if (Array.isArray(value)) return (MCP_TEXT_WHOLE_LIST_KEY.has(key) ? value.slice(0, 10) : value.slice(0, cap)).map((item) => shrink(item, cap, chars, key));
125
153
  if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, shrink(item, cap, chars, name)]));
126
- if (typeof value === "string" && value.length > chars && !MCP_TEXT_EXACT_KEY.test(key) && !MCP_TEXT_EXACT_VALUE.test(value)) return `${value.slice(0, chars)}…`;
154
+ if (typeof value === "string" && value.length > chars && !MCP_TEXT_EXACT_KEY.test(key) && !MCP_TEXT_EXACT_VALUE.test(value)
155
+ && !MCP_TEXT_COMMAND_VALUE.test(value)
156
+ && !(value.length <= MCP_TEXT_EXACT_WHOLE_MAX && MCP_TEXT_CARRIES_EXACT.test(value))) return shortenProse(value, chars);
127
157
  return value;
128
158
  };
129
159
  const withMarker = (doc) => JSON.stringify(Array.isArray(doc) ? { rows: doc, textPreview: MCP_TEXT_PREVIEW_NOTE } : { ...doc, textPreview: MCP_TEXT_PREVIEW_NOTE });
@@ -132,7 +162,7 @@ export function mcpAnswerText(payload) {
132
162
  for (const [cap, chars] of [[5, 400], [3, 240], [2, 160], [1, 120]]) {
133
163
  doc = shrink(doc, cap, chars);
134
164
  const text = withMarker(doc);
135
- if (Buffer.byteLength(text) <= MCP_TEXT_BUDGET_BYTES) return text;
165
+ if (Buffer.byteLength(text) <= budgetBytes) return text;
136
166
  }
137
167
  // Still too large: keep safety/identity fields first, then the smallest fields.
138
168
  const source = Array.isArray(doc) ? { rows: doc } : doc;
@@ -145,7 +175,7 @@ export function mcpAnswerText(payload) {
145
175
  let used = Buffer.byteLength(withMarker({}));
146
176
  for (const key of order) {
147
177
  const cost = sizes.get(key) + Buffer.byteLength(JSON.stringify(key)) + 2;
148
- if (used + cost > MCP_TEXT_BUDGET_BYTES) continue;
178
+ if (used + cost > budgetBytes) continue;
149
179
  kept[key] = source[key];
150
180
  used += cost;
151
181
  }
@@ -164,7 +194,7 @@ export function findRunnableSourceUrl(args, base) {
164
194
  }
165
195
 
166
196
  export function mcpAnswerSource(name, args, payload, base) {
167
- if (name === 'find_runnable' && process.env.HUGGING_BAY_AGENT_FLOW_V2 === '1') return findRunnableSourceUrl(args, base);
197
+ if (name === 'find_runnable') return findRunnableSourceUrl(args, base);
168
198
  const id = args.id || args.artifact || payload?.artifactId || payload?.id;
169
199
  if (id && ['get_artifact', 'get_artifact_card', 'get_harness_card', 'list_files', 'deployment_plan'].includes(name)) {
170
200
  const suffix = name === 'list_files' ? '/files' : name === 'get_artifact_card' ? '/card' : name === 'get_harness_card' ? '/harness-card' : '';