Spaces:
Running
Running
Add full expanded HuggingFace Hub module v2.0.0
Browse filesRebuilt from ChatSeed v12 (all API fixes) + expanded for HuggingBot
- modules_huggingface.js +682 -0
modules_huggingface.js
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// HuggingBot Module: HuggingFace Hub v2.0.0 (FULL + EXPANDED)
|
| 2 |
+
// ============================================================================
|
| 3 |
+
// Full remote control of the HuggingFace Hub from chat:
|
| 4 |
+
// auth, Spaces CRUD, file ops, secrets/hardware/sleep config, search,
|
| 5 |
+
// model inference (Inference API), Gradio Space API, repo browsing.
|
| 6 |
+
// Rebuilt for the HuggingBot ModuleSystem from ChatSeed v12 (all API fixes
|
| 7 |
+
// applied: flavor/gcTimeout keys, PUT /settings, paused-space delete pre-check,
|
| 8 |
+
// deep hardware name extraction) and expanded with:
|
| 9 |
+
// * hf_search_datasets
|
| 10 |
+
// * modern Gradio API routing (/api/{name} with /api/predict fallback)
|
| 11 |
+
// * pipeline-aware Inference API calls (task routing)
|
| 12 |
+
// * binary (image) inference response handling -> inline markdown
|
| 13 |
+
// * multi-repo-type support for file/repo operations (space|model|dataset)
|
| 14 |
+
// ============================================================================
|
| 15 |
+
(function(MS) {
|
| 16 |
+
'use strict';
|
| 17 |
+
|
| 18 |
+
var HF_API_BASE = 'https://huggingface.co';
|
| 19 |
+
var INFER_API_BASE = 'https://api-inference.huggingface.co';
|
| 20 |
+
var TOKEN_KEY = 'chatseed_hf_token';
|
| 21 |
+
|
| 22 |
+
// βββ Token helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
+
function getToken() { try { return localStorage.getItem(TOKEN_KEY) || ''; } catch (e) { return ''; } }
|
| 24 |
+
function setToken(t) { try { localStorage.setItem(TOKEN_KEY, t); } catch (e) {} }
|
| 25 |
+
function clearToken() { try { localStorage.removeItem(TOKEN_KEY); } catch (e) {} }
|
| 26 |
+
|
| 27 |
+
function authHeader() {
|
| 28 |
+
var t = getToken();
|
| 29 |
+
if (!t) throw new Error('No HuggingFace token set. Use hf_set_token or hf_login_ui to set your HF access token first.');
|
| 30 |
+
return { 'Authorization': 'Bearer ' + t };
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
// βββ Fetch helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
async function hfFetch(path, options) {
|
| 35 |
+
options = options || {};
|
| 36 |
+
var headers = Object.assign({ 'Content-Type': 'application/json' }, authHeader(), options.headers || {});
|
| 37 |
+
var res = await fetch(HF_API_BASE + path, Object.assign({}, options, { headers: headers }));
|
| 38 |
+
if (!res.ok) {
|
| 39 |
+
var msg = '';
|
| 40 |
+
try { var err = await res.json(); msg = err.error || JSON.stringify(err); }
|
| 41 |
+
catch (e) { try { msg = await res.text(); } catch (e2) { msg = res.statusText; } }
|
| 42 |
+
throw new Error('HF API ' + res.status + ': ' + msg);
|
| 43 |
+
}
|
| 44 |
+
if (res.status === 204) return null;
|
| 45 |
+
return (res.headers.get('content-type') || '').indexOf('application/json') > -1 ? res.json() : res.text();
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
async function hfFetchRaw(path) {
|
| 49 |
+
var token = getToken();
|
| 50 |
+
var headers = {};
|
| 51 |
+
if (token) headers['Authorization'] = 'Bearer ' + token;
|
| 52 |
+
var res = await fetch(HF_API_BASE + path, { headers: headers });
|
| 53 |
+
if (!res.ok) {
|
| 54 |
+
var msg = '';
|
| 55 |
+
try { var err = await res.json(); msg = err.error || JSON.stringify(err); } catch (e) { msg = res.statusText; }
|
| 56 |
+
throw new Error('HF API ' + res.status + ': ' + msg);
|
| 57 |
+
}
|
| 58 |
+
return res.text();
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
async function hfFetchHead(path) {
|
| 62 |
+
var token = getToken();
|
| 63 |
+
var headers = {};
|
| 64 |
+
if (token) headers['Authorization'] = 'Bearer ' + token;
|
| 65 |
+
var res = await fetch(HF_API_BASE + path, { method: 'HEAD', headers: headers });
|
| 66 |
+
return { ok: res.ok, status: res.status };
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
// βββ Repo helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
+
function repoTypePath(type) {
|
| 71 |
+
switch (type) {
|
| 72 |
+
case 'model': return 'models';
|
| 73 |
+
case 'dataset': return 'datasets';
|
| 74 |
+
case 'space': return 'spaces';
|
| 75 |
+
default: return 'spaces';
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function parseRepoId(repoId) {
|
| 80 |
+
var parts = String(repoId || '').split('/');
|
| 81 |
+
if (parts.length !== 2) throw new Error('Invalid repo_id. Use format "namespace/repo-name"');
|
| 82 |
+
return { namespace: parts[0], name: parts[1] };
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
async function commitFiles(repoType, namespace, repo, files, deletedEntries, summary, description) {
|
| 86 |
+
var body = {
|
| 87 |
+
summary: summary || 'Update via HuggingBot',
|
| 88 |
+
description: description || '',
|
| 89 |
+
files: (files || []).map(function (f) {
|
| 90 |
+
return { path: f.path, content: f.content, encoding: f.encoding || 'utf-8' };
|
| 91 |
+
})
|
| 92 |
+
};
|
| 93 |
+
if (deletedEntries && deletedEntries.length) body.deletedEntries = deletedEntries;
|
| 94 |
+
return hfFetch('/api/' + repoTypePath(repoType) + '/' + namespace + '/' + repo + '/commit/main', {
|
| 95 |
+
method: 'POST',
|
| 96 |
+
body: JSON.stringify(body)
|
| 97 |
+
});
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
// Centralized settings helper β routes ALL Space settings through
|
| 101 |
+
// PUT /api/spaces/{ns}/{name}/settings with the keys HF actually accepts.
|
| 102 |
+
async function updateSpaceSettings(namespace, repo, settings) {
|
| 103 |
+
return hfFetch('/api/spaces/' + namespace + '/' + repo + '/settings', {
|
| 104 |
+
method: 'PUT',
|
| 105 |
+
body: JSON.stringify(settings)
|
| 106 |
+
});
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
// Deep-extract a human-readable hardware name from varied API response shapes.
|
| 110 |
+
function extractHardwareName(hw) {
|
| 111 |
+
if (!hw) return 'cpu-basic';
|
| 112 |
+
if (typeof hw === 'string') return hw;
|
| 113 |
+
if (typeof hw === 'object') {
|
| 114 |
+
return hw.currentPrettyName
|
| 115 |
+
|| hw.requestedPrettyName
|
| 116 |
+
|| (hw.current ? (typeof hw.current === 'object' ? (hw.current.id || hw.current.name) : hw.current) : null)
|
| 117 |
+
|| (hw.requested ? (typeof hw.requested === 'object' ? (hw.requested.id || hw.requested.name) : hw.requested) : null)
|
| 118 |
+
|| hw.id || hw.name || hw.displayName
|
| 119 |
+
|| JSON.stringify(hw) || 'cpu-basic';
|
| 120 |
+
}
|
| 121 |
+
return String(hw);
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
function repoAppUrl(repoId) {
|
| 125 |
+
return 'https://' + repoId.replace(/\//g, '-') + '.hf.space';
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
function maskToken(t) {
|
| 129 |
+
return t.substring(0, 6) + 'β¦' + t.substring(t.length - 4);
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
function parseJsonArg(v) {
|
| 133 |
+
if (!v) return {};
|
| 134 |
+
if (typeof v === 'object') return v;
|
| 135 |
+
try { return JSON.parse(v); } catch (e) { throw new Error('Invalid JSON argument: ' + v); }
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
// βββ Secure Login Popup (token never passes through the model) ββββββββ
|
| 139 |
+
function openLoginPopup() {
|
| 140 |
+
var existing = document.getElementById('huggingbot-hf-login-overlay');
|
| 141 |
+
if (existing) existing.remove();
|
| 142 |
+
var overlay = document.createElement('div');
|
| 143 |
+
overlay.id = 'huggingbot-hf-login-overlay';
|
| 144 |
+
overlay.style.cssText = 'position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.7);z-index:10000;display:flex;align-items:center;justify-content:center;padding:16px;';
|
| 145 |
+
var box = document.createElement('div');
|
| 146 |
+
box.style.cssText = 'background:#111827;border:1px solid #374151;border-radius:16px;padding:24px;width:420px;max-width:100%;box-shadow:0 25px 50px rgba(0,0,0,.5);font-family:system-ui,sans-serif;';
|
| 147 |
+
var header = document.createElement('div');
|
| 148 |
+
header.style.cssText = 'display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;';
|
| 149 |
+
header.innerHTML = '<div style="display:flex;align-items:center;gap:8px;"><span style="font-size:1.4rem;">π€</span><span style="font-size:1.05rem;font-weight:600;color:#f3f4f6;">HuggingFace Login</span></div>' +
|
| 150 |
+
'<button id="huggingbot-hf-close" style="background:none;border:none;color:#9ca3af;font-size:1.2rem;cursor:pointer;">β</button>';
|
| 151 |
+
var body = document.createElement('div');
|
| 152 |
+
body.innerHTML =
|
| 153 |
+
'<p style="color:#d1d5db;font-size:.82rem;line-height:1.5;margin:0 0 14px;">Paste your HuggingFace access token.</p>' +
|
| 154 |
+
'<input id="huggingbot-hf-token" type="password" placeholder="hf_..." style="width:100%;box-sizing:border-box;padding:10px 12px;background:#030712;border:1px solid #4b5563;border-radius:8px;color:#f3f4f6;font-size:.9rem;outline:none;"/>' +
|
| 155 |
+
'<div style="margin-top:6px;display:flex;align-items:center;gap:6px;"><input id="huggingbot-hf-show" type="checkbox" style="accent-color:#059669;"><label for="huggingbot-hf-show" style="color:#6b7280;font-size:.75rem;cursor:pointer;">Show token</label></div>' +
|
| 156 |
+
'<div id="huggingbot-hf-status" style="display:none;font-size:.8rem;padding:8px 12px;border-radius:8px;margin-top:10px;"></div>' +
|
| 157 |
+
'<div style="display:flex;gap:10px;margin-top:14px;">' +
|
| 158 |
+
'<button id="huggingbot-hf-submit" style="flex:1;padding:10px;background:#059669;color:#fff;border:none;border-radius:10px;font-weight:500;cursor:pointer;">π Set Token</button>' +
|
| 159 |
+
'<button id="huggingbot-hf-cancel" style="padding:10px 16px;background:#374151;color:#d1d5db;border:none;border-radius:10px;cursor:pointer;">Cancel</button></div>' +
|
| 160 |
+
'<p style="color:#6b7280;font-size:.7rem;margin:12px 0 0;text-align:center;">Get a token at <a href="https://huggingface.co/settings/tokens" target="_blank" style="color:#60a5fa;">huggingface.co/settings/tokens</a></p>';
|
| 161 |
+
box.appendChild(header);
|
| 162 |
+
box.appendChild(body);
|
| 163 |
+
overlay.appendChild(box);
|
| 164 |
+
document.body.appendChild(overlay);
|
| 165 |
+
|
| 166 |
+
var input = document.getElementById('huggingbot-hf-token');
|
| 167 |
+
var statusEl = document.getElementById('huggingbot-hf-status');
|
| 168 |
+
var submitBtn = document.getElementById('huggingbot-hf-submit');
|
| 169 |
+
function close() { overlay.remove(); }
|
| 170 |
+
function showStatus(msg, color) {
|
| 171 |
+
statusEl.style.display = 'block';
|
| 172 |
+
statusEl.style.background = color + '18';
|
| 173 |
+
statusEl.style.border = '1px solid ' + color + '44';
|
| 174 |
+
statusEl.style.color = color;
|
| 175 |
+
statusEl.innerHTML = msg;
|
| 176 |
+
}
|
| 177 |
+
document.getElementById('huggingbot-hf-show').addEventListener('change', function () { input.type = this.checked ? 'text' : 'password'; });
|
| 178 |
+
document.getElementById('huggingbot-hf-close').addEventListener('click', close);
|
| 179 |
+
document.getElementById('huggingbot-hf-cancel').addEventListener('click', close);
|
| 180 |
+
submitBtn.addEventListener('click', async function () {
|
| 181 |
+
var token = input.value.trim();
|
| 182 |
+
if (!token) return showStatus('β οΈ Please enter a token.', '#f59e0b');
|
| 183 |
+
if (token.indexOf('hf_') !== 0) return showStatus('β οΈ Tokens should start with <code>hf_</code>.', '#f59e0b');
|
| 184 |
+
setToken(token);
|
| 185 |
+
submitBtn.disabled = true;
|
| 186 |
+
submitBtn.textContent = 'β³ Verifying...';
|
| 187 |
+
try {
|
| 188 |
+
var res = await fetch('https://huggingface.co/api/whoami-v2', { headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } });
|
| 189 |
+
if (res.ok) {
|
| 190 |
+
var info = await res.json();
|
| 191 |
+
showStatus('β
Authenticated as <strong>' + (info.name || info.user || 'unknown') + '</strong> (' + maskToken(token) + ')', '#059669');
|
| 192 |
+
setTimeout(close, 1200);
|
| 193 |
+
} else {
|
| 194 |
+
showStatus('β οΈ Token stored, but verification failed (' + res.status + ').', '#f59e0b');
|
| 195 |
+
submitBtn.disabled = false;
|
| 196 |
+
submitBtn.textContent = 'π Set Token';
|
| 197 |
+
}
|
| 198 |
+
} catch (e) {
|
| 199 |
+
showStatus('β οΈ Token stored locally, but could not verify: ' + e.message, '#f59e0b');
|
| 200 |
+
submitBtn.disabled = false;
|
| 201 |
+
submitBtn.textContent = 'π Set Token';
|
| 202 |
+
}
|
| 203 |
+
});
|
| 204 |
+
input.addEventListener('keydown', function (e) { if (e.key === 'Enter') submitBtn.click(); if (e.key === 'Escape') close(); });
|
| 205 |
+
setTimeout(function () { input.focus(); }, 100);
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
// βββ Tool schemas (exactly as registered in the runtime) ββββββββββββββ
|
| 209 |
+
var TOOLS = [
|
| 210 |
+
{ name: 'hf_set_token', description: 'Store your HuggingFace access token for this session. Get it from https://huggingface.co/settings/tokens', parameters: { type: 'object', properties: { token: { type: 'string', description: 'Your HF access token (hf_...). Required for all write operations.' } }, required: ['token'] } },
|
| 211 |
+
{ name: 'hf_login_ui', description: 'π Open a secure popup to enter your HF token. The token is stored directly in your browser β it never passes through the AI model.', parameters: { type: 'object', properties: {} } },
|
| 212 |
+
{ name: 'hf_logout', description: 'Clear your stored HuggingFace token from localStorage.', parameters: { type: 'object', properties: {} } },
|
| 213 |
+
{ name: 'hf_token_status', description: 'Check if a HF token is stored and who it belongs to (without revealing the token).', parameters: { type: 'object', properties: {} } },
|
| 214 |
+
{ name: 'hf_whoami', description: 'Check who you are authenticated as on HuggingFace Hub.', parameters: { type: 'object', properties: {} } },
|
| 215 |
+
{ name: 'hf_create_space', description: 'Create a new HuggingFace Space. Supports Gradio, Streamlit, Docker, or static SDKs.', parameters: { type: 'object', properties: { name: { type: 'string', description: 'Space name (e.g. "my-cool-demo"). Must be unique under your namespace.' }, sdk: { type: 'string', enum: ['gradio', 'streamlit', 'docker', 'static'], default: 'gradio', description: 'SDK/framework to use' }, type: { type: 'string', enum: ['space'], default: 'space' }, title: { type: 'string', description: 'Optional display title' }, license: { type: 'string', description: 'Optional license (e.g. "mit", "apache-2.0")' }, hardware: { type: 'string', description: 'Hardware upgrade (e.g. "t4-medium", "cpu-upgrade"). See HF docs for options.' }, secrets: { type: 'string', description: 'JSON object of secrets {"key": "value", ...}' }, variables: { type: 'string', description: 'JSON object of env variables {"KEY": "VALUE", ...}' }, sleep_time: { type: 'number', description: 'Sleep timeout in seconds (for GPU spaces)' }, private: { type: 'boolean', default: false, description: 'Create as private space?' }, org: { type: 'string', description: 'Organization namespace (if creating under an org)' } }, required: ['name'] } },
|
| 216 |
+
{ name: 'hf_duplicate_space', description: 'Duplicate an existing Space (useful for forking with custom config).', parameters: { type: 'object', properties: { from: { type: 'string', description: 'Source Space ID (e.g. "username/space-name")' }, name: { type: 'string', description: 'New Space name' }, org: { type: 'string', description: 'Optional org to duplicate into' }, hardware: { type: 'string', description: 'Hardware for the new Space' }, secrets: { type: 'string', description: 'JSON of secrets' }, variables: { type: 'string', description: 'JSON of env variables' }, sleep_time: { type: 'number', description: 'Sleep timeout in seconds' }, private: { type: 'boolean', default: false } }, required: ['from', 'name'] } },
|
| 217 |
+
{ name: 'hf_delete_space', description: 'Delete a Space repository from HuggingFace Hub.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID to delete (e.g. "username/my-space")' } }, required: ['repo_id'] } },
|
| 218 |
+
{ name: 'hf_upload_file', description: 'Upload a single file to a Space (app.py, requirements.txt, README.md, etc.). Triggers a rebuild.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID (e.g. "username/my-space")' }, path: { type: 'string', description: 'Path in the repo (e.g. "app.py" or "src/utils.py")' }, content: { type: 'string', description: 'File content as text' }, summary: { type: 'string', description: 'Commit message (default: "Update via HuggingBot")' }, description: { type: 'string', description: 'Optional commit description' } }, required: ['repo_id', 'path', 'content'] } },
|
| 219 |
+
{ name: 'hf_upload_app', description: 'Upload a complete Gradio/Streamlit app with requirements.txt in one go.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID (e.g. "username/my-space")' }, app_code: { type: 'string', description: 'The app.py (or app.js for static) source code' }, requirements: { type: 'string', description: 'Optional requirements.txt content (one package per line)' }, readme: { type: 'string', description: 'Optional README.md content' }, extra_files: { type: 'string', description: 'Optional JSON of extra files {"path": "content", ...}' }, summary: { type: 'string', description: 'Commit message' } }, required: ['repo_id', 'app_code'] } },
|
| 220 |
+
{ name: 'hf_delete_file', description: 'Delete a file from a Space repository.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID (e.g. "username/my-space")' }, path: { type: 'string', description: 'File path in the repo to delete' }, summary: { type: 'string', description: 'Commit message' } }, required: ['repo_id', 'path'] } },
|
| 221 |
+
{ name: 'hf_set_secret', description: 'Add or update a secret (environment variable) for a Space. Triggers a restart.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID (e.g. "username/my-space")' }, key: { type: 'string', description: 'Secret name (e.g. "HF_TOKEN", "API_KEY")' }, value: { type: 'string', description: 'Secret value' } }, required: ['repo_id', 'key', 'value'] } },
|
| 222 |
+
{ name: 'hf_delete_secret', description: 'Delete a secret from a Space.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID' }, key: { type: 'string', description: 'Secret name to delete' } }, required: ['repo_id', 'key'] } },
|
| 223 |
+
{ name: 'hf_set_hardware', description: 'Request a hardware upgrade/downgrade for a Space (e.g. CPU β GPU). Triggers a restart.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID' }, hardware: { type: 'string', description: 'Hardware tier: cpu-basic (free), cpu-upgrade ($0.03/hr), t4-small ($0.40), t4-medium ($0.60), l4-1x ($0.80), a10g-small ($1.00), a100-large ($2.50)', enum: ['cpu-basic', 'cpu-upgrade', 't4-small', 't4-medium', 'l4-1x', 'a10g-small', 'a10g-large', 'a100-large'] }, sleep_time: { type: 'number', description: 'Auto-sleep timeout in seconds (for GPU) - e.g. 7200 = 2h' } }, required: ['repo_id', 'hardware'] } },
|
| 224 |
+
{ name: 'hf_set_visibility', description: 'Change the visibility of a Space (public / private).', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID' }, visibility: { type: 'string', enum: ['public', 'private'], description: 'New visibility level' } }, required: ['repo_id', 'visibility'] } },
|
| 225 |
+
{ name: 'hf_set_sleep', description: 'Set auto-sleep timeout for a Space (useful for GPU spaces to save cost).', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID' }, sleep_time: { type: 'number', description: 'Sleep timeout in seconds (0 to disable, 300 = 5 min, 3600 = 1h, 7200 = 2h)' } }, required: ['repo_id', 'sleep_time'] } },
|
| 226 |
+
{ name: 'hf_pause_space', description: 'Pause a Space to stop billing. It can be restarted later with hf_restart_space.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID to pause' } }, required: ['repo_id'] } },
|
| 227 |
+
{ name: 'hf_restart_space', description: 'Restart a paused Space.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID to restart' } }, required: ['repo_id'] } },
|
| 228 |
+
{ name: 'hf_space_status', description: 'Get the runtime status, hardware, and stage of a Space.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID (e.g. "username/my-space")' } }, required: ['repo_id'] } },
|
| 229 |
+
{ name: 'hf_space_logs', description: 'Fetch the latest build/runtime logs from a Space.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Space ID' } }, required: ['repo_id'] } },
|
| 230 |
+
{ name: 'hf_search_spaces', description: 'Search for Spaces on the HuggingFace Hub by query.', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query' }, limit: { type: 'number', default: 5, description: 'Max results (1-25)' } }, required: ['query'] } },
|
| 231 |
+
{ name: 'hf_list_my_spaces', description: 'List all Spaces owned by your account.', parameters: { type: 'object', properties: { limit: { type: 'number', default: 10, description: 'Max results' } }, required: [] } },
|
| 232 |
+
{ name: 'hf_search_models', description: 'Search for models on the HuggingFace Hub.', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query' }, limit: { type: 'number', default: 5, description: 'Max results' } }, required: ['query'] } },
|
| 233 |
+
{ name: 'hf_call_space', description: 'Call a Gradio Space API endpoint (make predictions/inference via the Space API).', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Gradio Space ID (e.g. "abidlabs/en2fr")' }, api_name: { type: 'string', default: '/predict', description: 'API endpoint name (e.g. "/predict", "/generate")' }, data: { type: 'string', description: 'JSON array of input data (e.g. ["Hello world"])' } }, required: ['repo_id', 'data'] } },
|
| 234 |
+
{ name: 'hf_inference', description: 'Run inference on a HuggingFace model using the free Inference API.', parameters: { type: 'object', properties: { model: { type: 'string', description: 'Model ID (e.g. "gpt2", "meta-llama/Llama-3.2-3B-Instruct")' }, inputs: { type: 'string', description: 'Input text or JSON string of inputs' }, parameters: { type: 'string', description: 'Optional JSON string of generation parameters (max_length, temperature, etc.)' }, task: { type: 'string', description: 'Optional task type (e.g. "text-generation", "image-classification", "automatic-speech-recognition")' } }, required: ['model', 'inputs'] } },
|
| 235 |
+
{ name: 'hf_repo_info', description: 'Get detailed information about any HF repo (Space, Model, or Dataset).', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/repo-name")' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' } }, required: ['repo_id'] } },
|
| 236 |
+
{ name: 'hf_list_files', description: 'List files in a repository at a given path.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' }, path: { type: 'string', default: '', description: 'Subdirectory path (optional)' }, revision: { type: 'string', default: 'main', description: 'Branch/revision' } }, required: ['repo_id'] } },
|
| 237 |
+
{ name: 'hf_read_file', description: 'Read the content of a file from ANY HuggingFace repo (Space, Model, or Dataset), including PRIVATE repos.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/my-space")' }, path: { type: 'string', description: 'File path in the repo (e.g. "app.py", "config.json")' }, revision: { type: 'string', default: 'main', description: 'Branch/commit revision' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' } }, required: ['repo_id', 'path'] } },
|
| 238 |
+
{ name: 'hf_file_exists', description: 'Check if a file exists in a HuggingFace repo (including private repos).', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/my-space")' }, path: { type: 'string', description: 'File path to check (e.g. "app.py", "config.json")' }, revision: { type: 'string', default: 'main', description: 'Branch/revision' } }, required: ['repo_id', 'path'] } },
|
| 239 |
+
{ name: 'hf_repo_exists', description: 'Check if a HuggingFace repository exists (Space, Model, or Dataset). Works for private repos too.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/my-space")' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' } }, required: ['repo_id'] } },
|
| 240 |
+
{ name: 'hf_list_commits', description: 'View the commit history of a HuggingFace repository.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/my-space")' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' }, revision: { type: 'string', default: 'main', description: 'Branch/revision to view commits for' }, limit: { type: 'number', default: 10, description: 'Max commits to show (1-50)' } }, required: ['repo_id'] } },
|
| 241 |
+
{ name: 'hf_move_file', description: 'Rename or move a file in a HuggingFace repository.', parameters: { type: 'object', properties: { repo_id: { type: 'string', description: 'Repo ID (e.g. "username/my-space")' }, source_path: { type: 'string', description: 'Current file path (e.g. "old_name.py")' }, dest_path: { type: 'string', description: 'New file path (e.g. "new_name.py" or "subfolder/new_name.py")' }, summary: { type: 'string', description: 'Commit message (default: "Move/Rename file")' }, type: { type: 'string', enum: ['space', 'model', 'dataset'], default: 'space', description: 'Repo type' } }, required: ['repo_id', 'source_path', 'dest_path'] } },
|
| 242 |
+
// ββ Expanded (new in v2.0.0) ββββββββββββββββββββββββββββββββββββββββ
|
| 243 |
+
{ name: 'hf_search_datasets', description: 'Search for datasets on the HuggingFace Hub.', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query' }, limit: { type: 'number', default: 5, description: 'Max results (1-25)' } }, required: ['query'] } }
|
| 244 |
+
];
|
| 245 |
+
|
| 246 |
+
// βββ Tool implementations βββββββββββββββββββββββββββββββββββββββββββββ
|
| 247 |
+
var REGISTRY = {
|
| 248 |
+
hf_set_token: async function (a) {
|
| 249 |
+
var t = String(a.token || '').trim();
|
| 250 |
+
if (!t || t.indexOf('hf_') !== 0) return 'β οΈ Invalid token format. Tokens start with `hf_`. Get one at https://huggingface.co/settings/tokens';
|
| 251 |
+
setToken(t);
|
| 252 |
+
try {
|
| 253 |
+
var w = await hfFetch('/api/whoami-v2');
|
| 254 |
+
return 'β
**HuggingFace token stored** (' + maskToken(t) + ')\nπ€ Authenticated as: **' + (w.name || w.user || 'unknown') + '**\nYou can now use all HF tools.';
|
| 255 |
+
} catch (e) {
|
| 256 |
+
return 'β οΈ Token stored (' + maskToken(t) + ') but verification failed: ' + e.message + '. Check that the token is valid.';
|
| 257 |
+
}
|
| 258 |
+
},
|
| 259 |
+
hf_login_ui: async function () {
|
| 260 |
+
openLoginPopup();
|
| 261 |
+
return 'π **Secure Login Popup Opened**\n\nA popup has been opened where you can paste your HuggingFace token.\n\n> π‘οΈ Your token is stored directly in your browser\'s localStorage β it **never passes through this AI model**.\n\nπ‘ Tip: you can also paste your token directly in chat with `hf_set_token`, but the popup is more secure.\n\nπ Get a token at: https://huggingface.co/settings/tokens';
|
| 262 |
+
},
|
| 263 |
+
hf_logout: async function () {
|
| 264 |
+
var had = !!getToken();
|
| 265 |
+
clearToken();
|
| 266 |
+
return had ? 'πͺ **Logged out.** HuggingFace token removed from localStorage.' : 'π No token was stored. Nothing to clear.';
|
| 267 |
+
},
|
| 268 |
+
hf_token_status: async function () {
|
| 269 |
+
var t = getToken();
|
| 270 |
+
if (!t) return 'π **No token stored.** Use `hf_login_ui` (secure popup) or `hf_set_token` to log in.';
|
| 271 |
+
try {
|
| 272 |
+
var info = await hfFetch('/api/whoami-v2');
|
| 273 |
+
return ['π **Token Status:** Active (' + maskToken(t) + ')', 'π€ **Authenticated as:** ' + (info.name || info.user || 'unknown'), 'π§ **Email:** ' + (info.email || 'N/A'), 'π³ **Can Pay:** ' + (info.canPay ? 'Yes' : 'No'), '', 'π‘ Use `hf_logout` to clear your token.'].join('\n');
|
| 274 |
+
} catch (e) {
|
| 275 |
+
return 'β οΈ **Token stored** (' + maskToken(t) + ') but verification failed: ' + e.message;
|
| 276 |
+
}
|
| 277 |
+
},
|
| 278 |
+
hf_whoami: async function () {
|
| 279 |
+
try {
|
| 280 |
+
var info = await hfFetch('/api/whoami-v2');
|
| 281 |
+
var lines = ['**π€ HuggingFace User Info**', '**ID:** ' + (info.id || info.name || 'N/A'), '**Name:** ' + (info.name || info.user || 'N/A'), '**Email:** ' + (info.email || 'N/A'), '**Type:** ' + (info.type || info.org || 'user'), '**Can Pay:** ' + (info.canPay ? 'β
Yes' : 'β No'), '**Plan:** ' + (info.plan ? (info.plan.name || info.plan) : 'Free/Unknown')];
|
| 282 |
+
if (info.orgs && info.orgs.length) lines.push('**Organizations:** ' + info.orgs.map(function (o) { return o.name; }).join(', '));
|
| 283 |
+
if (info.usage && info.usage.inference) lines.push('**Inference Usage:** ' + JSON.stringify(info.usage.inference));
|
| 284 |
+
return lines.join('\n');
|
| 285 |
+
} catch (e) { return 'β Failed to get user info: ' + e.message; }
|
| 286 |
+
},
|
| 287 |
+
hf_create_space: async function (a) {
|
| 288 |
+
var me = await hfFetch('/api/whoami-v2');
|
| 289 |
+
var ns = a.org || me.name;
|
| 290 |
+
var payload = { name: a.name, type: 'space', sdk: a.sdk || 'gradio', private: !!a.private };
|
| 291 |
+
if (a.title) payload.title = a.title;
|
| 292 |
+
if (a.license) payload.license = a.license;
|
| 293 |
+
if (a.hardware) payload.hardware = a.hardware;
|
| 294 |
+
if (a.sleep_time) payload.sleep_time = a.sleep_time;
|
| 295 |
+
var secrets = parseJsonArg(a.secrets);
|
| 296 |
+
var variables = parseJsonArg(a.variables);
|
| 297 |
+
if (Object.keys(secrets).length) payload.secrets = secrets;
|
| 298 |
+
if (Object.keys(variables).length) payload.variables = variables;
|
| 299 |
+
await hfFetch('/api/repos/create', { method: 'POST', body: JSON.stringify(payload) });
|
| 300 |
+
var repoId = ns + '/' + a.name;
|
| 301 |
+
var out = ['β
**Space created successfully!**', '', '**Repo:** ' + repoId, '**SDK:** ' + (a.sdk || 'gradio'), '**Visibility:** ' + (a.private ? 'π Private' : 'π Public'), '**URL:** https://huggingface.co/spaces/' + repoId, '**App:** ' + repoAppUrl(repoId)];
|
| 302 |
+
if (a.hardware) out.push('β‘ Hardware requested: ' + a.hardware);
|
| 303 |
+
if (a.sleep_time) out.push('π€ Sleep timeout: ' + a.sleep_time + 's');
|
| 304 |
+
out.push('', 'π‘ **Next steps:** Upload files using `hf_upload_file` or `hf_upload_app`');
|
| 305 |
+
return out.join('\n');
|
| 306 |
+
},
|
| 307 |
+
hf_duplicate_space: async function (a) {
|
| 308 |
+
var me = await hfFetch('/api/whoami-v2');
|
| 309 |
+
var ns = a.org || me.name;
|
| 310 |
+
var body = { from: a.from, name: a.name, namespace: ns, private: !!a.private };
|
| 311 |
+
if (a.hardware) body.hardware = a.hardware;
|
| 312 |
+
if (a.sleep_time) body.sleep_time = a.sleep_time;
|
| 313 |
+
var secrets = parseJsonArg(a.secrets);
|
| 314 |
+
var variables = parseJsonArg(a.variables);
|
| 315 |
+
if (Object.keys(secrets).length) body.secrets = secrets;
|
| 316 |
+
if (Object.keys(variables).length) body.variables = variables;
|
| 317 |
+
await hfFetch('/api/spaces/duplicate', { method: 'POST', body: JSON.stringify(body) });
|
| 318 |
+
var repoId = ns + '/' + a.name;
|
| 319 |
+
var out = ['β
**Space duplicated!**', '', '**From:** ' + a.from, '**New Repo:** ' + repoId, '**URL:** https://huggingface.co/spaces/' + repoId, '**App:** ' + repoAppUrl(repoId)];
|
| 320 |
+
if (a.hardware) out.push('**Hardware:** ' + a.hardware);
|
| 321 |
+
if (a.sleep_time) out.push('**Sleep:** ' + a.sleep_time + 's');
|
| 322 |
+
return out.join('\n');
|
| 323 |
+
},
|
| 324 |
+
hf_delete_space: async function (a) {
|
| 325 |
+
var p = parseRepoId(a.repo_id);
|
| 326 |
+
try {
|
| 327 |
+
var rt = await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/runtime');
|
| 328 |
+
if (rt.stage === 'PAUSED' || rt.stage === 'SLEEPING') {
|
| 329 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/restart', { method: 'POST' });
|
| 330 |
+
await new Promise(function (r) { setTimeout(r, 2000); });
|
| 331 |
+
}
|
| 332 |
+
} catch (e) { /* best-effort */ }
|
| 333 |
+
try {
|
| 334 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name, { method: 'DELETE' });
|
| 335 |
+
return 'β
**Space deleted:** ' + a.repo_id;
|
| 336 |
+
} catch (e) {
|
| 337 |
+
try {
|
| 338 |
+
await hfFetch('/api/repos/' + p.namespace + '/' + p.name, { method: 'DELETE' });
|
| 339 |
+
return 'β
**Space deleted (via repos endpoint):** ' + a.repo_id;
|
| 340 |
+
} catch (e2) {
|
| 341 |
+
throw new Error('Could not delete space: ' + e.message + '. Try restarting it first with hf_restart_space.');
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
},
|
| 345 |
+
hf_upload_file: async function (a) {
|
| 346 |
+
var p = parseRepoId(a.repo_id);
|
| 347 |
+
await commitFiles('space', p.namespace, p.name, [{ path: a.path, content: a.content }], null, a.summary || 'Update via HuggingBot', a.description || '');
|
| 348 |
+
return ['β
**File uploaded:** `' + a.path + '` β `' + a.repo_id + '`', 'π ' + (a.summary || 'Update via HuggingBot'), '', 'π‘ The Space will now rebuild automatically. Check status with `hf_space_status`.'].join('\n');
|
| 349 |
+
},
|
| 350 |
+
hf_upload_app: async function (a) {
|
| 351 |
+
var p = parseRepoId(a.repo_id);
|
| 352 |
+
var files = [{ path: 'app.py', content: a.app_code }];
|
| 353 |
+
if (a.requirements) files.push({ path: 'requirements.txt', content: a.requirements });
|
| 354 |
+
if (a.readme) files.push({ path: 'README.md', content: a.readme });
|
| 355 |
+
if (a.extra_files) {
|
| 356 |
+
var extras = parseJsonArg(a.extra_files);
|
| 357 |
+
for (var k in extras) if (Object.prototype.hasOwnProperty.call(extras, k)) files.push({ path: k, content: String(extras[k]) });
|
| 358 |
+
}
|
| 359 |
+
await commitFiles('space', p.namespace, p.name, files, null, a.summary || 'Deploy app via HuggingBot', 'Uploaded app.py' + (a.requirements ? ' + requirements.txt' : '') + (a.readme ? ' + README.md' : ''));
|
| 360 |
+
return ['β
**App deployed to:** `' + a.repo_id + '`', 'π¦ **Files uploaded:** ' + files.map(function (f) { return '`' + f.path + '`'; }).join(', '), '', 'π **Space:** https://huggingface.co/spaces/' + a.repo_id, 'π **App URL:** ' + repoAppUrl(a.repo_id), '', 'π‘ The Space is now building. Use `hf_space_status ' + a.repo_id + '` to check progress.'].join('\n');
|
| 361 |
+
},
|
| 362 |
+
hf_delete_file: async function (a) {
|
| 363 |
+
var p = parseRepoId(a.repo_id);
|
| 364 |
+
await commitFiles('space', p.namespace, p.name, null, [{ path: a.path }], a.summary || ('Delete ' + a.path), '');
|
| 365 |
+
return 'β
**File deleted:** `' + a.path + '` from `' + a.repo_id + '`';
|
| 366 |
+
},
|
| 367 |
+
hf_set_secret: async function (a) {
|
| 368 |
+
var p = parseRepoId(a.repo_id);
|
| 369 |
+
try {
|
| 370 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/secrets', { method: 'PUT', body: JSON.stringify({ key: a.key, value: a.value }) });
|
| 371 |
+
} catch (e) {
|
| 372 |
+
if (String(e.message).indexOf('404') > -1 || String(e.message).indexOf('405') > -1) {
|
| 373 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/secrets', { method: 'POST', body: JSON.stringify({ key: a.key, value: a.value }) });
|
| 374 |
+
} else { throw e; }
|
| 375 |
+
}
|
| 376 |
+
return 'π **Secret set:** `' + a.key + '` in `' + a.repo_id + '`\nβ οΈ The Space will restart.';
|
| 377 |
+
},
|
| 378 |
+
hf_delete_secret: async function (a) {
|
| 379 |
+
var p = parseRepoId(a.repo_id);
|
| 380 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/secrets', { method: 'DELETE', body: JSON.stringify({ key: a.key }) });
|
| 381 |
+
return 'ποΈ **Secret deleted:** `' + a.key + '` from `' + a.repo_id + '`';
|
| 382 |
+
},
|
| 383 |
+
hf_set_hardware: async function (a) {
|
| 384 |
+
var p = parseRepoId(a.repo_id);
|
| 385 |
+
var settings = { flavor: a.hardware };
|
| 386 |
+
if (a.sleep_time) settings.gcTimeout = a.sleep_time;
|
| 387 |
+
await updateSpaceSettings(p.namespace, p.name, settings);
|
| 388 |
+
var out = ['β‘ **Hardware change requested for:** `' + a.repo_id + '`', '**New hardware:** ' + a.hardware];
|
| 389 |
+
if (a.sleep_time) out.push('**Sleep timeout:** ' + a.sleep_time + 's');
|
| 390 |
+
out.push('', 'β³ The Space is restarting. Check status with `hf_space_status`.');
|
| 391 |
+
return out.join('\n');
|
| 392 |
+
},
|
| 393 |
+
hf_set_visibility: async function (a) {
|
| 394 |
+
var p = parseRepoId(a.repo_id);
|
| 395 |
+
await updateSpaceSettings(p.namespace, p.name, { private: a.visibility === 'private' });
|
| 396 |
+
return (a.visibility === 'private' ? 'π' : 'π') + ' **Visibility changed to ' + a.visibility + ':** `' + a.repo_id + '`';
|
| 397 |
+
},
|
| 398 |
+
hf_set_sleep: async function (a) {
|
| 399 |
+
var p = parseRepoId(a.repo_id);
|
| 400 |
+
await updateSpaceSettings(p.namespace, p.name, { gcTimeout: a.sleep_time });
|
| 401 |
+
var status = a.sleep_time === 0 ? 'β Disabled (never sleeps)' : 'π€ ' + a.sleep_time + 's (' + Math.round(a.sleep_time / 60) + ' min)';
|
| 402 |
+
return 'β
**Sleep configured:** `' + a.repo_id + '` β ' + status;
|
| 403 |
+
},
|
| 404 |
+
hf_pause_space: async function (a) {
|
| 405 |
+
var p = parseRepoId(a.repo_id);
|
| 406 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/pause', { method: 'POST' });
|
| 407 |
+
return 'βΈοΈ **Space paused:** `' + a.repo_id + '`\nπ‘ Restart with `hf_restart_space ' + a.repo_id + '`';
|
| 408 |
+
},
|
| 409 |
+
hf_restart_space: async function (a) {
|
| 410 |
+
var p = parseRepoId(a.repo_id);
|
| 411 |
+
await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/restart', { method: 'POST' });
|
| 412 |
+
return 'βΆοΈ **Space restarting:** `' + a.repo_id + '`';
|
| 413 |
+
},
|
| 414 |
+
hf_space_status: async function (a) {
|
| 415 |
+
var p = parseRepoId(a.repo_id);
|
| 416 |
+
var runtime = await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/runtime');
|
| 417 |
+
var repoInfo = await hfFetch('/api/spaces/' + p.namespace + '/' + p.name);
|
| 418 |
+
var emoji = { 'NO_APP_FILE': 'π', 'BUILDING': 'π¨', 'RUNNING': 'β
', 'RUNNING_BUILDING': 'π', 'PAUSED': 'βΈοΈ', 'SLEEPING': 'π€', 'STOPPED': 'β', 'ERROR': 'β' };
|
| 419 |
+
var stage = runtime.stage || 'UNKNOWN';
|
| 420 |
+
var out = ['**π Space Status:** `' + a.repo_id + '`', '', '**Stage:** ' + (emoji[stage] || 'β') + ' ' + stage, '**SDK:** ' + (repoInfo.sdk || 'N/A'), '**Hardware:** ' + extractHardwareName(runtime.hardware), '**Requested HW:** ' + extractHardwareName(runtime.requestedHardware), '**Visibility:** ' + (repoInfo.private ? 'π Private' : 'π Public'), '**Likes:** β ' + (repoInfo.likes || 0), '**URL:** https://huggingface.co/spaces/' + a.repo_id, '**App:** ' + repoAppUrl(a.repo_id)];
|
| 421 |
+
return out.join('\n');
|
| 422 |
+
},
|
| 423 |
+
hf_space_logs: async function (a) {
|
| 424 |
+
var p = parseRepoId(a.repo_id);
|
| 425 |
+
var endpoints = [
|
| 426 |
+
'/api/spaces/' + p.namespace + '/' + p.name + '/runtime/logs',
|
| 427 |
+
'/api/spaces/' + p.namespace + '/' + p.name + '/logs',
|
| 428 |
+
'/api/spaces/' + p.namespace + '/' + p.name + '/runtime'
|
| 429 |
+
];
|
| 430 |
+
var lastError = null;
|
| 431 |
+
for (var i = 0; i < endpoints.length; i++) {
|
| 432 |
+
try {
|
| 433 |
+
var result = await hfFetch(endpoints[i]);
|
| 434 |
+
if (result && typeof result === 'object') {
|
| 435 |
+
var logsStr = result.logs || result.stdout || result.stderr || result.build || JSON.stringify(result, null, 2);
|
| 436 |
+
var truncated = logsStr.length > 5000 ? logsStr.slice(-5000) + '\n... (truncated, full: ' + logsStr.length + ' chars)' : logsStr;
|
| 437 |
+
return ['π **Build Logs for** `' + a.repo_id + '`', '```', truncated, '```'].join('\n');
|
| 438 |
+
}
|
| 439 |
+
} catch (e) { lastError = e; }
|
| 440 |
+
}
|
| 441 |
+
try {
|
| 442 |
+
var rt = await hfFetch('/api/spaces/' + p.namespace + '/' + p.name + '/runtime');
|
| 443 |
+
if (rt && rt.errorMessage) return 'β οΈ **Space has an error:**\n```\n' + rt.errorMessage + '\n```';
|
| 444 |
+
return 'βΉοΈ **Space is** ' + (rt.stage || 'unknown') + '. No logs available via REST API.\n\nπ‘ Logs can be viewed in the HF UI: https://huggingface.co/spaces/' + a.repo_id;
|
| 445 |
+
} catch (e2) { throw lastError || e2; }
|
| 446 |
+
},
|
| 447 |
+
hf_search_spaces: async function (a) {
|
| 448 |
+
var limit = Math.min(Math.max(a.limit || 5, 1), 25);
|
| 449 |
+
var results = await hfFetch('/api/spaces?search=' + encodeURIComponent(a.query) + '&limit=' + limit + '&sort=likes');
|
| 450 |
+
if (!results || !results.length) return 'π No Spaces found for "' + a.query + '"';
|
| 451 |
+
var lines = ['π **Spaces matching "' + a.query + '":**', ''];
|
| 452 |
+
results.forEach(function (s, i) {
|
| 453 |
+
var id = s.id || ((s.namespace || '?') + '/' + (s.name || '?'));
|
| 454 |
+
var sdk = s.sdk ? ' [' + s.sdk + ']' : '';
|
| 455 |
+
var likes = s.likes ? ' β' + s.likes : '';
|
| 456 |
+
var desc = s.description ? '\n > ' + s.description.substring(0, 150) : '';
|
| 457 |
+
lines.push((i + 1) + '. **' + id + '**' + sdk + likes);
|
| 458 |
+
if (desc) lines.push(desc);
|
| 459 |
+
lines.push(' https://huggingface.co/spaces/' + id);
|
| 460 |
+
lines.push('');
|
| 461 |
+
});
|
| 462 |
+
return lines.join('\n');
|
| 463 |
+
},
|
| 464 |
+
hf_list_my_spaces: async function () {
|
| 465 |
+
var userInfo = await hfFetch('/api/whoami-v2');
|
| 466 |
+
var name = userInfo.name || userInfo.user;
|
| 467 |
+
var results = await hfFetch('/api/spaces?author=' + encodeURIComponent(name) + '&limit=25&sort=lastModified');
|
| 468 |
+
if (!results || !results.length) return 'π No Spaces found under **' + name + '**.\nCreate one with `hf_create_space`!';
|
| 469 |
+
var lines = ['π **Your Spaces (' + name + '):**', ''];
|
| 470 |
+
results.forEach(function (s) {
|
| 471 |
+
var id = s.id || (s.namespace + '/' + s.name);
|
| 472 |
+
var sdk = s.sdk ? ' [' + s.sdk + ']' : '';
|
| 473 |
+
var vis = s.private ? 'π' : 'π';
|
| 474 |
+
var likes = s.likes ? ' β' + s.likes : '';
|
| 475 |
+
var stage = (s.runtime && s.runtime.stage) || '';
|
| 476 |
+
lines.push(vis + ' **' + id + '**' + sdk + likes + (stage ? ' β ' + stage : ''));
|
| 477 |
+
});
|
| 478 |
+
lines.push('', 'π‘ Use `hf_space_status <id>` for details on any Space.');
|
| 479 |
+
return lines.join('\n');
|
| 480 |
+
},
|
| 481 |
+
hf_search_models: async function (a) {
|
| 482 |
+
var limit = Math.min(Math.max(a.limit || 5, 1), 25);
|
| 483 |
+
var results = await hfFetch('/api/models?search=' + encodeURIComponent(a.query) + '&limit=' + limit + '&sort=likes');
|
| 484 |
+
if (!results || !results.length) return 'π No models found for "' + a.query + '"';
|
| 485 |
+
var lines = ['π **Models matching "' + a.query + '":**', ''];
|
| 486 |
+
results.forEach(function (m, i) {
|
| 487 |
+
var id = m.id || ((m.namespace || '?') + '/' + (m.name || '?'));
|
| 488 |
+
var pipeline = m.pipeline_tag ? ' [' + m.pipeline_tag + ']' : '';
|
| 489 |
+
var likes = m.likes ? ' β' + m.likes : '';
|
| 490 |
+
var downloads = m.downloads ? ' π₯' + (m.downloads / 1000).toFixed(0) + 'k' : '';
|
| 491 |
+
lines.push((i + 1) + '. **' + id + '**' + pipeline + likes + downloads);
|
| 492 |
+
lines.push(' https://huggingface.co/' + id);
|
| 493 |
+
});
|
| 494 |
+
return lines.join('\n');
|
| 495 |
+
},
|
| 496 |
+
hf_search_datasets: async function (a) {
|
| 497 |
+
var limit = Math.min(Math.max(a.limit || 5, 1), 25);
|
| 498 |
+
var results = await hfFetch('/api/datasets?search=' + encodeURIComponent(a.query) + '&limit=' + limit + '&sort=likes');
|
| 499 |
+
if (!results || !results.length) return 'π No datasets found for "' + a.query + '"';
|
| 500 |
+
var lines = ['π **Datasets matching "' + a.query + '":**', ''];
|
| 501 |
+
results.forEach(function (d, i) {
|
| 502 |
+
var id = d.id || ((d.namespace || '?') + '/' + (d.name || '?'));
|
| 503 |
+
var likes = d.likes ? ' β' + d.likes : '';
|
| 504 |
+
var downloads = d.downloads ? ' π₯' + (d.downloads / 1000).toFixed(0) + 'k' : '';
|
| 505 |
+
lines.push((i + 1) + '. **' + id + '**' + likes + downloads);
|
| 506 |
+
lines.push(' https://huggingface.co/datasets/' + id);
|
| 507 |
+
});
|
| 508 |
+
return lines.join('\n');
|
| 509 |
+
},
|
| 510 |
+
hf_call_space: async function (a) {
|
| 511 |
+
var p = parseRepoId(a.repo_id);
|
| 512 |
+
var inputs = parseJsonArg(a.data);
|
| 513 |
+
if (!Array.isArray(inputs)) inputs = [inputs];
|
| 514 |
+
var apiName = String(a.api_name || '/predict').replace(/^\//, '');
|
| 515 |
+
var host = repoAppUrl(a.repo_id);
|
| 516 |
+
// Modern Gradio: POST /api/{name} with {data:[...]}; older: /api/predict
|
| 517 |
+
var tryEndpoints = ['/api/' + apiName, '/api/predict'];
|
| 518 |
+
var lastError = null;
|
| 519 |
+
for (var i = 0; i < tryEndpoints.length; i++) {
|
| 520 |
+
try {
|
| 521 |
+
var res = await fetch(host + tryEndpoints[i], {
|
| 522 |
+
method: 'POST',
|
| 523 |
+
headers: { 'Content-Type': 'application/json' },
|
| 524 |
+
body: JSON.stringify({ data: inputs })
|
| 525 |
+
});
|
| 526 |
+
if (res.ok) {
|
| 527 |
+
var out = await res.json();
|
| 528 |
+
if (out && out.data !== undefined) return 'β
**Result from `' + a.repo_id + '`' + (tryEndpoints[i] === '/api/predict' ? ' (legacy /predict)' : '') + ':**\n\n' + JSON.stringify(out.data, null, 2);
|
| 529 |
+
return 'β
**Raw response from `' + a.repo_id + '`:**\n\n' + JSON.stringify(out, null, 2);
|
| 530 |
+
}
|
| 531 |
+
lastError = new Error('HTTP ' + res.status + ' ' + res.statusText);
|
| 532 |
+
} catch (e) { lastError = e; }
|
| 533 |
+
}
|
| 534 |
+
throw new Error('Could not call Gradio API on ' + host + ': ' + (lastError ? lastError.message : 'unknown error') + '. The Space may be paused/sleeping or api_name may differ.');
|
| 535 |
+
},
|
| 536 |
+
hf_inference: async function (a) {
|
| 537 |
+
var token = getToken();
|
| 538 |
+
if (!token) throw new Error('No HuggingFace token set. hf_inference uses your token for higher rate limits.');
|
| 539 |
+
var url = INFER_API_BASE + (a.task ? '/pipeline/' + encodeURIComponent(a.task) + '/' : '/models/') + a.model;
|
| 540 |
+
var payload = { inputs: a.inputs };
|
| 541 |
+
if (a.parameters) payload.parameters = parseJsonArg(a.parameters);
|
| 542 |
+
var res = await fetch(url, {
|
| 543 |
+
method: 'POST',
|
| 544 |
+
headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
|
| 545 |
+
body: JSON.stringify(payload)
|
| 546 |
+
});
|
| 547 |
+
if (!res.ok) {
|
| 548 |
+
var em = '';
|
| 549 |
+
try { var ej = await res.json(); em = ej.error || JSON.stringify(ej); } catch (e) { em = res.statusText; }
|
| 550 |
+
throw new Error('Inference API ' + res.status + ': ' + em);
|
| 551 |
+
}
|
| 552 |
+
var ct = res.headers.get('content-type') || '';
|
| 553 |
+
if (ct.indexOf('image/') > -1 || ct.indexOf('audio/') > -1) {
|
| 554 |
+
var buf = await res.arrayBuffer();
|
| 555 |
+
var bytes = new Uint8Array(buf);
|
| 556 |
+
var bin = '';
|
| 557 |
+
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
| 558 |
+
var b64 = btoa(bin);
|
| 559 |
+
var mime = ct.split(';')[0];
|
| 560 |
+
if (mime.indexOf('image') > -1) return 'β
**Generated ' + mime + '** (' + (bytes.length / 1024).toFixed(1) + ' KB)\n\n';
|
| 561 |
+
return 'β
**Generated ' + mime + '** (' + (bytes.length / 1024).toFixed(1) + ' KB)\n\n' + (mime.indexOf('audio') > -1 ? '[π Audio result](data:' + mime + ';base64,' + b64 + ')' : 'Binary result in base64: `' + b64.substring(0, 120) + 'β¦`');
|
| 562 |
+
}
|
| 563 |
+
var data = await res.json();
|
| 564 |
+
if (Array.isArray(data)) {
|
| 565 |
+
var parts = ['β
**Inference result from `' + a.model + '`:**', ''];
|
| 566 |
+
data.forEach(function (item) {
|
| 567 |
+
if (item && typeof item === 'object') {
|
| 568 |
+
var g = item.generated_text || item.label || item.answer || item.summary_text || item.translation_text || JSON.stringify(item);
|
| 569 |
+
parts.push(g);
|
| 570 |
+
} else { parts.push(String(item)); }
|
| 571 |
+
});
|
| 572 |
+
return parts.join('\n');
|
| 573 |
+
}
|
| 574 |
+
return 'β
**Inference result from `' + a.model + '`:**\n\n' + (typeof data === 'string' ? data : JSON.stringify(data, null, 2));
|
| 575 |
+
},
|
| 576 |
+
hf_repo_info: async function (a) {
|
| 577 |
+
var type = a.type || 'space';
|
| 578 |
+
var info = await hfFetch('/api/' + repoTypePath(type) + '/' + a.repo_id);
|
| 579 |
+
var lines = ['**π¦ Repo Info:** `' + a.repo_id + '` (' + type + ')', ''];
|
| 580 |
+
var fields = {
|
| 581 |
+
id: 'ID', name: 'Name', author: 'Author', pipeline_tag: 'Pipeline', library_name: 'Library',
|
| 582 |
+
sdk: 'SDK', sdk_version: 'SDK Version', likes: 'β Likes', downloads: 'π₯ Downloads',
|
| 583 |
+
license: 'License', private: 'Private', lastModified: 'Last Modified', createdAt: 'Created',
|
| 584 |
+
tags: 'Tags', description: 'Description', cardData: 'Card Data', sha: 'Commit SHA'
|
| 585 |
+
};
|
| 586 |
+
for (var k in fields) {
|
| 587 |
+
if (info[k] !== undefined && info[k] !== null && info[k] !== '') {
|
| 588 |
+
var v = info[k];
|
| 589 |
+
if (typeof v === 'object') v = JSON.stringify(v);
|
| 590 |
+
if (k === 'private') v = v ? 'π Yes' : 'π No';
|
| 591 |
+
if (String(v).length > 200) v = String(v).substring(0, 200) + 'β¦';
|
| 592 |
+
lines.push('**' + fields[k] + ':** ' + v);
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
lines.push('', 'π https://huggingface.co/' + type + 's/' + a.repo_id);
|
| 596 |
+
return lines.join('\n');
|
| 597 |
+
},
|
| 598 |
+
hf_list_files: async function (a) {
|
| 599 |
+
var type = a.type || 'space';
|
| 600 |
+
var path = a.path || '';
|
| 601 |
+
var rev = a.revision || 'main';
|
| 602 |
+
var url = '/api/' + repoTypePath(type) + '/' + a.repo_id + '/tree/' + encodeURIComponent(rev) + (path ? '/' + path.split('/').map(encodeURIComponent).join('/') : '') + '?recursive=false&expand=false';
|
| 603 |
+
var files = await hfFetch(url);
|
| 604 |
+
if (!files || !files.length) return 'π No files found at `' + (path || '/') + '` in `' + a.repo_id + '`';
|
| 605 |
+
var lines = ['π **Files in `' + a.repo_id + '`' + (path ? '/' + path : '') + ' (' + rev + '):**', ''];
|
| 606 |
+
files.forEach(function (f) {
|
| 607 |
+
var icon = f.type === 'directory' ? 'π' : 'π';
|
| 608 |
+
var size = f.size !== undefined && f.size !== null ? ' β ' + (f.size / 1024).toFixed(1) + ' KB' : '';
|
| 609 |
+
lines.push(icon + ' `' + (f.path || f.name) + '`' + (f.type === 'directory' ? '/' : '') + size);
|
| 610 |
+
});
|
| 611 |
+
return lines.join('\n');
|
| 612 |
+
},
|
| 613 |
+
hf_read_file: async function (a) {
|
| 614 |
+
var type = a.type || 'space';
|
| 615 |
+
var rev = a.revision || 'main';
|
| 616 |
+
var rawPath = a.path.split('/').map(encodeURIComponent).join('/');
|
| 617 |
+
var text = await hfFetchRaw('/' + repoTypePath(type) + '/' + a.repo_id + '/raw/' + encodeURIComponent(rev) + '/' + rawPath);
|
| 618 |
+
var truncated = text.length > 6000 ? text.substring(0, 6000) + '\n\n⦠(truncated, full: ' + text.length + ' chars)' : text;
|
| 619 |
+
return 'π **`' + a.path + '`** from `' + a.repo_id + '` (' + rev + '):\n\n```\n' + truncated + '\n```';
|
| 620 |
+
},
|
| 621 |
+
hf_file_exists: async function (a) {
|
| 622 |
+
var type = a.type || 'space';
|
| 623 |
+
var rev = a.revision || 'main';
|
| 624 |
+
var rawPath = a.path.split('/').map(encodeURIComponent).join('/');
|
| 625 |
+
var head = await hfFetchHead('/' + repoTypePath(type) + '/' + a.repo_id + '/raw/' + encodeURIComponent(rev) + '/' + rawPath);
|
| 626 |
+
return head.ok
|
| 627 |
+
? 'β
**File exists:** `' + a.path + '` in `' + a.repo_id + '` (HTTP ' + head.status + ')'
|
| 628 |
+
: 'β **File not found:** `' + a.path + '` in `' + a.repo_id + '` (HTTP ' + head.status + ')';
|
| 629 |
+
},
|
| 630 |
+
hf_repo_exists: async function (a) {
|
| 631 |
+
var type = a.type || 'space';
|
| 632 |
+
try {
|
| 633 |
+
var info = await hfFetch('/api/' + repoTypePath(type) + '/' + a.repo_id);
|
| 634 |
+
return 'β
**Repo exists:** `' + a.repo_id + '` (' + type + (info.private ? ', π private' : ', π public') + ')';
|
| 635 |
+
} catch (e) {
|
| 636 |
+
return 'β **Repo not found or inaccessible:** `' + a.repo_id + '` (' + e.message + ')';
|
| 637 |
+
}
|
| 638 |
+
},
|
| 639 |
+
hf_list_commits: async function (a) {
|
| 640 |
+
var type = a.type || 'space';
|
| 641 |
+
var rev = a.revision || 'main';
|
| 642 |
+
var limit = Math.min(Math.max(a.limit || 10, 1), 50);
|
| 643 |
+
var commits = await hfFetch('/api/' + repoTypePath(type) + '/' + a.repo_id + '/commits/' + encodeURIComponent(rev) + '?limit=' + limit);
|
| 644 |
+
if (!commits || !commits.length) return 'π No commits found for `' + a.repo_id + '`';
|
| 645 |
+
var lines = ['ποΈ **Commit history for `' + a.repo_id + '` (' + rev + '):**', ''];
|
| 646 |
+
commits.forEach(function (c, i) {
|
| 647 |
+
var date = c.createdAt ? new Date(c.createdAt).toLocaleString() : '?';
|
| 648 |
+
var short = (c.id || '').substring(0, 7);
|
| 649 |
+
lines.push((i + 1) + '. **' + short + '** β ' + c.title + '');
|
| 650 |
+
lines.push(' π
' + date + (c.author ? ' | π€ ' + c.author.name : ''));
|
| 651 |
+
});
|
| 652 |
+
return lines.join('\n');
|
| 653 |
+
},
|
| 654 |
+
hf_move_file: async function (a) {
|
| 655 |
+
var p = parseRepoId(a.repo_id);
|
| 656 |
+
var type = a.type || 'space';
|
| 657 |
+
var rev = 'main';
|
| 658 |
+
// Move = read raw source, write to dest, delete source (works for all repo types via commit API)
|
| 659 |
+
var src = a.source_path.split('/').map(encodeURIComponent).join('/');
|
| 660 |
+
var content = await hfFetchRaw('/' + repoTypePath(type) + '/' + a.repo_id + '/raw/' + rev + '/' + src);
|
| 661 |
+
await commitFiles(type, p.namespace, p.name, [{ path: a.dest_path, content: content }], [{ path: a.source_path }], a.summary || 'Move/Rename file', 'Moved ' + a.source_path + ' β ' + a.dest_path);
|
| 662 |
+
return 'π¦ **File moved:** `' + a.source_path + '` β `' + a.dest_path + '` in `' + a.repo_id + '`';
|
| 663 |
+
}
|
| 664 |
+
};
|
| 665 |
+
|
| 666 |
+
// βββ Register module βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 667 |
+
MS.register('huggingface', {
|
| 668 |
+
name: 'HuggingFace Hub',
|
| 669 |
+
description: 'Full HuggingFace Hub control: auth, Spaces CRUD, file ops, secrets/hardware/sleep config, hub search, model inference, Gradio API calls, and repo browsing (expanded).',
|
| 670 |
+
tools: TOOLS.map(function (t) { return { type: 'function', function: t }; }),
|
| 671 |
+
handleToolCall: async function (tn, args) {
|
| 672 |
+
var fn = REGISTRY[tn];
|
| 673 |
+
if (!fn) return null;
|
| 674 |
+
try {
|
| 675 |
+
var out = await fn(args || {});
|
| 676 |
+
return typeof out === 'string' ? out : JSON.stringify(out, null, 2);
|
| 677 |
+
} catch (e) {
|
| 678 |
+
return 'β ' + (e && e.message ? e.message : String(e));
|
| 679 |
+
}
|
| 680 |
+
}
|
| 681 |
+
});
|
| 682 |
+
})(ModuleSystem);
|