2Btainment commited on
Commit
4b138b2
·
verified ·
1 Parent(s): 80fa1a0

probe empire P1

Browse files
Files changed (1) hide show
  1. workspace.js +113 -0
workspace.js ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
2
+ import { MODULES } from './real.js?v=50';
3
+ const $ = (s, r = document) => r.querySelector(s);
4
+ const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
5
+ const ST = () => window.__studius.STUDIOS;
6
+ const kindOf = (mime = '', name = '') => /\.avatar\.json$/i.test(name) ? 'avatar' : /^image\//.test(mime) || /\.(png|jpe?g|webp|gif)$/i.test(name) ? 'image' : /^audio\//.test(mime) || /\.(wav|mp3|ogg|flac)$/i.test(name) ? 'audio' : /^video\//.test(mime) || /\.(mp4|webm|mov)$/i.test(name) ? 'video' : /^text\/|json/.test(mime) || /\.(txt|md|json|js|html|css)$/i.test(name) ? 'text' : 'file';
7
+ const W = { backend: false, me: null, bucket: localStorage.getItem('studius-bucket') || '' };
8
+ window.__ws = W;
9
+ async function api(path, opt = {}) { const r = await fetch(path, { credentials: 'include', ...opt }); const j = r.headers.get('content-type')?.includes('json') ? await r.json() : null; if (!r.ok) throw new Error(j?.detail || j?.error || r.status + ' ' + r.statusText); return j; }
10
+ const form = (o) => { const f = new FormData(); Object.entries(o).forEach(([k, v]) => f.append(k, v)); return f; };
11
+
12
+ /* HUD buttons */
13
+ $('#hud .hudr').insertAdjacentHTML('afterbegin', `<a id="signin" class="hbtn" href="/login" target="_blank" rel="noopener" hidden>🤗 Sign in with Hugging Face</a><button id="wsbtn" class="hbtn" aria-label="Workspace öffnen" hidden>▤ Workspace</button><span id="who" hidden></span>`);
14
+ document.body.insertAdjacentHTML('beforeend', `<aside id="wsp" hidden role="dialog" aria-label="Workspace"><div class="wh"><b>WORKSPACE</b><small id="wsb"></small><button class="x" aria-label="Workspace schließen">✕</button></div><div class="wbody"></div></aside>
15
+ <button id="beebtn" aria-label="Bee-Agenten öffnen" title="Bee-Agenten">🐝<span>Agents</span></button>
16
+ <aside id="bees" hidden role="dialog" aria-label="Bee-Agenten"><div class="wh"><b>BEE AGENTS</b><select id="agsel" aria-label="Agent wählen"></select><button class="x" aria-label="Agenten schließen">✕</button></div><div class="agcfg"></div><div class="blog" aria-live="polite"></div><div class="brow"><input id="bin" aria-label="Auftrag an Agent" placeholder="Auftrag… z.B. 'Male eine goldene Biene'"><button class="btn" id="bsend" aria-label="Senden">➤</button></div></aside>`);
17
+ ['#wsp', '#bees'].forEach(s => $(s).addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') $(s).hidden = true; }));
18
+ $('#wsp .x').onclick = () => $('#wsp').hidden = true; $('#bees .x').onclick = () => $('#bees').hidden = true;
19
+ $('#wsbtn').onclick = () => { $('#wsp').hidden = !$('#wsp').hidden; if (!$('#wsp').hidden) renderWS(); };
20
+ $('#beebtn').onclick = () => { $('#bees').hidden = !$('#bees').hidden; if (!$('#bees').hidden) { renderAgents(); $('#bin').focus(); } };
21
+
22
+ async function refreshMe() {
23
+ try { W.me = await api('/api/me'); W.backend = true; } catch (e) { W.backend = false; W.me = null; }
24
+ $('#signin').hidden = !W.backend || !!W.me?.signedIn || !W.me?.oauth; $('#wsbtn').hidden = !W.backend;
25
+ const who = $('#who'); who.hidden = !W.me?.signedIn; if (W.me?.signedIn) who.innerHTML = `${W.me.user.avatar ? `<img src="${esc(W.me.user.avatar)}" alt="">` : ''}${esc(W.me.user.name)}`;
26
+ }
27
+ window.__wsReady = refreshMe(); addEventListener('focus', refreshMe); if (/signedin=1/.test(location.search)) history.replaceState(null, '', '/');
28
+
29
+ /* Workspace panel */
30
+ async function renderWS() {
31
+ const b = $('#wsp .wbody'); $('#wsb').textContent = W.bucket || '';
32
+ if (!W.backend) { b.innerHTML = '<p>Workspace braucht das STUDIUS-Backend.</p>'; return; }
33
+ if (!W.me?.signedIn) { b.innerHTML = `<p>Melde dich mit deinem Hugging-Face-Konto an. Dein eigener <b>HF Storage Bucket</b> wird dann zum Workspace aller Studios.</p><a class="btn" href="/login" target="_blank" rel="noopener">🤗 Sign in with Hugging Face</a><p class="mut">Login öffnet einen neuen Tab (nötig im HF-iframe). Danach hierher zurückkehren.</p>`; return; }
34
+ if (!W.bucket) return connectUI(b);
35
+ b.innerHTML = `<div class="row"><label class="btn alt">⬆ Hochladen<input type="file" multiple hidden id="wsup"></label><button class="btn alt" id="wsre">↻</button><button class="btn alt" id="wsch">Bucket wechseln</button></div><div class="stat" id="wsst">Lade…</div><ul class="files"></ul><div class="pv"></div>`;
36
+ $('#wsre').onclick = renderWS; $('#wsch').onclick = () => { W.bucket = ''; localStorage.removeItem('studius-bucket'); renderWS(); };
37
+ $('#wsup').onchange = async (e) => { for (const f of e.target.files) { $('#wsst').textContent = 'Lade hoch: ' + f.name; try { await api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path: 'uploads/' + f.name, file: f }) }); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; return; } } renderWS(); };
38
+ try { const { files } = await api('/api/ws/list?bucket=' + encodeURIComponent(W.bucket)); W.files = files; $('#wsst').textContent = files.length + ' Dateien · ' + W.bucket;
39
+ $('#wsp .files').innerHTML = files.map((f, i) => { const k = kindOf(f.mime, f.path); const pins = f.meta?.pins || [];
40
+ return `<li><button class="fn" data-i="${i}" title="Vorschau">${{ image: '🖼', audio: '🎵', video: '🎬', text: '📄' }[k] || '📦'} ${esc(f.path)}</button><small>${(f.size / 1024).toFixed(0)} KB${f.meta?.studio ? ' · ' + esc(f.meta.studio) : ''}${f.meta?.v > 1 ? ' · v' + f.meta.v : ''}${pins.length ? ' · 📌' + esc(pins.join(',')) : ''}</small><span><select data-send="${i}" aria-label="An Studio senden"><option value="">→ Studio…</option>${targets(k).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><a class="ib" href="/api/ws/file?dl=1&bucket=${encodeURIComponent(W.bucket)}&path=${encodeURIComponent(f.path)}" aria-label="Download">⬇</a><button class="ib" data-del="${i}" aria-label="Löschen">🗑</button></span></li>`; }).join('') || '<li class="mut">Leer – speichere Ergebnisse mit „In Workspace“.</li>';
41
+ $('#wsp .files').onclick = async (e) => { const t = e.target.closest('button'); if (!t) return; const f = files[t.dataset.i ?? t.dataset.del];
42
+ if (t.dataset.del != null) { if (!confirm(`„${f.path}“ endgültig aus ${W.bucket} löschen?`)) return; try { await api('/api/ws/delete', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, confirm: f.path }) }); renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } return; }
43
+ preview(f); };
44
+ $('#wsp .files').onchange = (e) => { const s = e.target.closest('select[data-send]'); if (!s?.value) return; const f = files[s.dataset.send]; sendTo(s.value, wsAsset(f)); api('/api/ws/pin', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, studio: s.value }) }).catch(() => {}); s.value = ''; };
45
+ } catch (e) { $('#wsst').textContent = '⚠ ' + e.message; }
46
+ }
47
+ const fileUrl = (p) => '/api/ws/file?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(p);
48
+ const wsAsset = (f) => ({ kind: kindOf(f.mime, f.path), mime: f.mime, url: fileUrl(f.path), name: f.path.split('/').pop(), studio: f.meta?.studio || 'workspace' });
49
+ async function preview(f) { const k = kindOf(f.mime, f.path), u = fileUrl(f.path), pv = $('#wsp .pv');
50
+ pv.innerHTML = k === 'image' ? `<img alt="${esc(f.path)}" src="${u}">` : k === 'audio' ? `<audio controls src="${u}"></audio>` : k === 'video' ? `<video controls src="${u}"></video>` : k === 'text' ? `<pre>${esc((await (await fetch(u)).text()).slice(0, 4000))}</pre>` : '<p class="mut">Keine Vorschau</p>'; }
51
+ async function connectUI(b) {
52
+ const def = W.me.user.name + '/studius-workspace';
53
+ b.innerHTML = `<p><b>Workspace verbinden.</b> STUDIUS speichert alle Assets in <i>deinem</i> Hugging-Face Storage Bucket (privat). Wähle einen bestehenden Bucket oder lege einen neuen an.</p><input id="bkt" aria-label="Bucket-ID" value="${esc(def)}"><div class="row"><button class="btn" id="bcreate">Erstellen & verbinden</button><button class="btn alt" id="bconn">Nur verbinden</button></div><div class="stat" id="bst"></div><ul class="files" id="blist"></ul>`;
54
+ api('/api/ws/buckets').then(({ buckets }) => { $('#blist').innerHTML = buckets.map(x => `<li><button class="fn" data-b="${esc(x.id)}">🪣 ${esc(x.id)}</button><small>${x.private ? 'privat' : 'öffentlich'}</small></li>`).join(''); $('#blist').onclick = e => { const t = e.target.closest('[data-b]'); if (t) $('#bkt').value = t.dataset.b; }; }).catch(e => $('#bst').textContent = '⚠ ' + e.message);
55
+ const go = async (create) => { $('#bst').textContent = create ? 'Erstelle privaten Bucket…' : 'Verbinde…'; try { const r = await api('/api/ws/connect', { method: 'POST', body: form({ bucket: $('#bkt').value.trim(), create }) }); W.bucket = r.bucket; localStorage.setItem('studius-bucket', r.bucket); renderWS(); } catch (e) { $('#bst').textContent = '⚠ ' + e.message; } };
56
+ $('#bcreate').onclick = () => go(true); $('#bconn').onclick = () => go(false);
57
+ }
58
+
59
+ /* asset bus */
60
+ const targets = (kind) => ST().filter(s => s.accepts?.includes(kind));
61
+ export async function saveAsset(a) {
62
+ if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
63
+ if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
64
+ const path = `${a.studio || 'misc'}/${a.name}`;
65
+ if (a.url && /^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url)) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '' }) });
66
+ const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
67
+ return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
68
+ }
69
+ let inbox = null;
70
+ export function sendTo(id, asset) { const i = ST().findIndex(s => s.id === id); if (i < 0) return; inbox = { id, asset }; window.__studius.open(i); }
71
+ window.addEventListener('studius-opened', (e) => { if (!inbox || inbox.id !== e.detail.id) return; const { asset } = inbox; inbox = null; const s = ST().find(x => x.id === e.detail.id);
72
+ setTimeout(async () => { try { await s.accept(e.detail.el, asset); window.__handoff = { to: s.id, kind: asset.kind, ok: true }; } catch (er) { window.__handoff = { to: s.id, ok: false, err: er.message }; console.warn('hand-off', er); } }, 60); });
73
+ function actionRow(asset) {
74
+ const d = document.createElement('div'); d.className = 'row assetbar';
75
+ d.innerHTML = `<button class="btn alt sv">💾 In Workspace</button><select aria-label="Senden an Studio"><option value="">→ Öffnen in…</option>${targets(asset.kind).filter(s => s.id !== asset.studio).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><small class="st"></small>`;
76
+ d.querySelector('.sv').onclick = async () => { const st = d.querySelector('.st'); st.textContent = 'speichere…'; try { const r = await saveAsset(asset); st.textContent = '✔ ' + r.path; window.__saved = r; } catch (e) { st.textContent = '⚠ ' + e.message; } };
77
+ d.querySelector('select').onchange = (e) => e.target.value && sendTo(e.target.value, asset);
78
+ return d;
79
+ }
80
+ window.addEventListener('studius-result', (e) => { const { el, asset } = e.detail; if (!el?.isConnected) return; if (el.nextElementSibling?.classList?.contains('assetbar')) el.nextElementSibling.remove(); el.after(actionRow(asset)); });
81
+ window.__bus = { sendTo, saveAsset };
82
+
83
+ /* bee agents */
84
+ const DEF = [{ id: 'demo', name: 'Demo-Biene', modules: ['chat', 'image'] }];
85
+ let agents; try { agents = JSON.parse(localStorage.getItem('studius-agents')) || DEF; } catch (e) { agents = DEF; }
86
+ let cur = agents[0].id; const saveAg = () => localStorage.setItem('studius-agents', JSON.stringify(agents));
87
+ function renderAgents() { const sel = $('#agsel'); sel.innerHTML = agents.map(a => `<option value="${a.id}">🐝 ${esc(a.name)}</option>`).join('') + '<option value="+">+ Neuer Agent</option>'; sel.value = cur;
88
+ sel.onchange = () => { if (sel.value === '+') { const n = prompt('Name des Agenten?'); if (n) { agents.push({ id: 'a' + Date.now(), name: n.slice(0, 40), modules: ['chat'] }); cur = agents.at(-1).id; saveAg(); } } else cur = sel.value; renderAgents(); };
89
+ const a = agents.find(x => x.id === cur); $('#bees .agcfg').innerHTML = '<small>Module:</small>' + Object.values(MODULES).map(m => `<label><input type="checkbox" value="${m.id}" ${a.modules.includes(m.id) ? 'checked' : ''}> ${esc(m.name)}</label>`).join('');
90
+ $('#bees .agcfg').onchange = (e) => { const t = e.target; a.modules = t.checked ? [...new Set([...a.modules, t.value])] : a.modules.filter(m => m !== t.value); saveAg(); }; }
91
+ const blog = () => $('#bees .blog');
92
+ function say(who, html) { const p = document.createElement('div'); p.className = 'bm ' + who; p.innerHTML = (who === 'bee' ? '<i class="bee">🐝</i>' : '') + `<div>${html}</div>`; blog().append(p); blog().scrollTop = 1e6; return p.lastChild; }
93
+ const toolsOf = (a) => a.modules.flatMap(m => Object.entries(MODULES[m]?.actions || {}).map(([k, v]) => ({ name: m + '.' + k, desc: v.desc, params: v.params, run: v.run })));
94
+ async function plan(task, tools) {
95
+ const has = n => tools.find(t => t.name.startsWith(n));
96
+ if (/(bild|image|male|zeichne|foto|logo|picture)/i.test(task) && has('image')) return { tool: has('image').name, args: { prompt: task }, via: 'router' };
97
+ if (/(musik|music|song|beat|sound)/i.test(task) && has('music')) return { tool: has('music').name, args: { prompt: task }, via: 'router' };
98
+ if (tools.length > 1 && has('chat')) { // ambiguous → ask the LLM to route
99
+ const sys = `Du bist ein Werkzeug-Router. Werkzeuge:\n${tools.map(t => `- ${t.name}(${Object.keys(t.params).join(', ')}): ${t.desc}`).join('\n')}\nAntworte NUR mit JSON in einer Zeile: {"tool":"<name>","args":{"prompt":"<prompt>"}}\nAuftrag: ${task}`;
100
+ try { const r = await MODULES.chat.actions.reply.run({ prompt: sys }); const j = JSON.parse(r.text.match(/\{[\s\S]*\}/)[0]); if (tools.some(t => t.name === j.tool)) return { ...j, via: 'llm' }; } catch (e) {} }
101
+ return { tool: has('chat')?.name || tools[0].name, args: { prompt: task }, via: 'default' };
102
+ }
103
+ async function runAgent() { const inp = $('#bin'), task = inp.value.trim(); if (!task) return; inp.value = ''; const a = agents.find(x => x.id === cur); const tools = toolsOf(a);
104
+ say('me', esc(task)); const box = say('bee', '<span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> plane…'); window.__agent = { task, state: 'plan' };
105
+ if (!tools.length) { box.textContent = 'Diesem Agenten sind keine Module zugewiesen.'; return; }
106
+ try { const p = await plan(task, tools); const t = tools.find(x => x.name === p.tool) || tools[0];
107
+ box.innerHTML = `<span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> nutze <code>${esc(t.name)}</code> <small>(${p.via})</small> <small class="s"></small>`; window.__agent = { task, state: 'run', tool: t.name, via: p.via };
108
+ const res = await t.run({ prompt: p.args?.prompt || task }, { status: m => { const s = box.querySelector('.s'); if (s) s.textContent = m.stage + (m.position != null ? ' #' + (m.position + 1) : ''); }, data: txt => { box.innerHTML = `<code>${esc(t.name)}</code><p>${esc(txt)}</p>`; } });
109
+ box.innerHTML = `<code>${esc(t.name)}</code> ✔` + (res.kind === 'image' ? `<img alt="" src="${esc(res.url)}">` : res.kind === 'audio' ? `<audio controls src="${esc(res.url)}"></audio>` : `<p>${esc(res.text)}</p>`);
110
+ window.__agent = { task, state: 'done', tool: t.name, via: p.via, kind: res.kind, url: res.url, text: res.text?.slice(0, 200) };
111
+ window.dispatchEvent(new CustomEvent('studius-result', { detail: { el: box.lastElementChild, asset: res } }));
112
+ } catch (e) { box.innerHTML = `⚠ ${esc(e.message)}`; window.__agent = { task, state: 'error', err: e.message }; } }
113
+ $('#bsend').onclick = runAgent; $('#bin').addEventListener('keydown', e => { if (e.key === 'Enter') runAgent(); });