// STUDIUS P6: Branding-Kit (shared) · Docs (Markdown → DOCX/PDF) · Telefon-Assistent (Avatar + IVR + Testanruf) // + Module API: brand.get, docs.write, phone.answer, shop.draft. Nothing is posted, published or dialled externally. import { STUDIOS } from './widgets.js?v=50'; import { MODULES, esc, hf, stTxt, result, badge, setS, keep, CHAT, FLUX } from './real.js?v=136'; import { Avatars } from './avatar.js?v=136'; import { bucket, wsFile, toBlob, slug, ts, upload, wsList, wsJson, saveJson, llm, dl, canvasBlob, loadImg, avOptions, PT, LINES, slugCode, eur, SOC, suggestPrice } from './studios5.js?v=136'; /* =================== BRANDING-KIT (one source of truth for Social, Whiteboard, Docs, Telefon) =================== */ const BK = 'projects/brand/brand.json'; const FONTS = ['Georgia', 'system-ui', 'Trebuchet MS', 'Verdana', 'Courier New', 'Impact', 'Palatino Linotype']; export const Brand = { kit: Object.assign({ name: 'STUDIUS', handle: '@einswarm', claim: 'Gemacht vom Schwarm', cta: 'Jetzt reinhören', link: '', c1: '#f2c94c', c2: '#0b0b0b', c3: '#fff4d6', font: 'Georgia', logoData: '' }, JSON.parse(localStorage.getItem('studius-brand') || '{}')), apply() { const k = this.kit; Object.assign(SOC.brand, { name: k.name, handle: k.handle, c1: k.c1, c2: k.c2, cta: k.cta, link: k.link, font: k.font }); window.__brand = { name: k.name, c1: k.c1, font: k.font, logo: !!k.logoData }; }, async load() { const k = await wsJson(BK, null); if (k) Object.assign(this.kit, k); this.apply(); return this.kit; }, async save() { localStorage.setItem('studius-brand', JSON.stringify(this.kit)); this.apply(); if (bucket()) { await saveJson(BK, { type: 'studius.brand', v: 1, ...this.kit, updated: Date.now() }, 'brand'); window.__brandSaved = BK; } else window.__brandSaved = 'local'; }, logo() { return this.kit.logoData ? loadImg(this.kit.logoData) : Promise.resolve(null); } }; Brand.apply(); window.__Brand = Brand; function monogram(k, size = 256) { const c = document.createElement('canvas'); c.width = c.height = size; const x = c.getContext('2d'), r = size * .46, m = size / 2; x.beginPath(); for (let i = 0; i < 6; i++) { const a = Math.PI / 3 * i + Math.PI / 6; x.lineTo(m + Math.cos(a) * r, m + Math.sin(a) * r); } x.closePath(); x.fillStyle = k.c2; x.fill(); x.lineWidth = size * .05; x.strokeStyle = k.c1; x.stroke(); x.fillStyle = k.c1; x.font = `700 ${size * .46}px ${k.font}, serif`; x.textAlign = 'center'; x.textBaseline = 'middle'; x.fillText((k.name || 'S').trim()[0].toUpperCase(), m, m + size * .03); return c; } async function squareData(blob, size = 256) { const i = await loadImg(URL.createObjectURL(blob)); const c = document.createElement('canvas'); c.width = c.height = size; const x = c.getContext('2d'); const s = Math.max(size / i.width, size / i.height); x.drawImage(i, (size - i.width * s) / 2, (size - i.height * s) / 2, i.width * s, i.height * s); return c.toDataURL('image/png'); } async function brandSheet(k) { const c = document.createElement('canvas'); c.width = 1200; c.height = 675; const x = c.getContext('2d'); x.fillStyle = k.c2; x.fillRect(0, 0, 1200, 675); const lg = await Brand.logo(); if (lg) x.drawImage(lg, 70, 70, 220, 220); x.fillStyle = k.c1; x.font = `700 72px ${k.font}, serif`; x.fillText(k.name, 330, 160); x.fillStyle = k.c3; x.font = `400 32px ${k.font}, serif`; x.fillText(k.claim, 330, 215); x.font = `400 24px system-ui`; x.fillText(`${k.handle} · Schrift: ${k.font} · CTA: ${k.cta}`, 330, 265); [k.c1, k.c2, k.c3].forEach((col, i) => { x.fillStyle = col; x.fillRect(70 + i * 360, 360, 320, 180); x.strokeStyle = k.c1; x.lineWidth = 2; x.strokeRect(70 + i * 360, 360, 320, 180); x.fillStyle = i === 1 ? k.c1 : k.c2; x.font = '600 26px monospace'; x.fillText(col.toUpperCase(), 90 + i * 360, 520); }); x.fillStyle = k.c3; x.font = '400 20px system-ui'; x.fillText('Brand-Kit · verwendet in Social, Whiteboard, Docs, Telefon-Assistent', 70, 620); return c; } STUDIOS.push({ id: 'brand', cat: 'Community', icon: '🎨', name: 'Branding-Kit', like: 'Logo · Farben · Schrift (geteilt)', real: 'API', accepts: ['image'], build(el) { el.innerHTML = `
REALEine Marke für alle Studios: Social-Mockups, Whiteboard, Docs-Export und Telefon-Assistent lesen dieses Kit
Marke
Farben & Schrift
Logo
Logo optional: ${hf(FLUX)} · Kit: ${esc(BK)} im Workspace-Bucket · Monogramm & Sheet lokal (Canvas)
`; keep(el); const q = (s) => el.querySelector(s), K = Brand.kit; const map = { kn: 'name', kh: 'handle', kl: 'link', kc: 'claim', kt: 'cta', k1: 'c1', k2: 'c2', k3: 'c3', kf: 'font' }; const fill = () => { for (const [c, k] of Object.entries(map)) q('.' + c).value = K[k] || ''; q('.lgv').innerHTML = K.logoData ? `Logo` : 'kein Logo'; }; el.addEventListener('input', () => { for (const [c, k] of Object.entries(map)) K[k] = q('.' + c).value; Brand.apply(); }); el.__setLogo = async (blob) => { K.logoData = await squareData(blob); fill(); Brand.apply(); setS(el, '✔ Logo gesetzt'); }; q('.lu').onchange = () => q('.lu').files[0] && el.__setLogo(q('.lu').files[0]); q('.lm').onclick = () => { K.logoData = monogram(K).toDataURL('image/png'); fill(); Brand.apply(); setS(el, '✔ Monogramm-Logo'); }; q('.lg').onclick = async (e) => { e.target.disabled = true; try { const a = await MODULES.image.actions.generate.run({ prompt: q('.lp').value }, { status: m => setS(el, 'Logo: ' + stTxt(m)) }); await el.__setLogo(await toBlob(a.url)); badge(el, 'REAL'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; q('.ks').onclick = async (e) => { e.target.disabled = true; try { await Brand.save(); window.__brandSaved = bucket() ? BK : 'local'; setS(el, bucket() ? '✔ Gespeichert: ' + BK : '✔ Lokal gespeichert (für Workspace anmelden)'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; q('.kp').onclick = async () => { const c = await brandSheet(K), blob = await canvasBlob(c), u = URL.createObjectURL(blob); q('.out').innerHTML = `Brand-Sheet`; result(q('.out'), { kind: 'image', mime: 'image/png', blob, url: u, name: `brand-sheet-${slug(K.name)}.png`, path: `projects/brand/brand-sheet.png`, studio: 'brand', prompt: K.name }); window.__brandSheet = true; setS(el, '✔ Brand-Sheet'); }; fill(); Brand.load().then(fill); }, accept: async (el, a) => { await el.__setLogo(a.blob || await toBlob(a.url)); return true; } }); MODULES.brand = { id: 'brand', name: 'Branding-Kit', backend: 'Workspace ' + BK, inputs: [], outputs: [{ kind: 'text' }], actions: { get: { desc: 'Liefert das Branding-Kit (Name, Handle, Claim, CTA, Farben, Schrift) als Text, damit Texte/Visuals zur Marke passen', params: {}, run: async () => { const k = await Brand.load(); const { logoData, ...t } = k; return { kind: 'text', mime: 'application/json', text: JSON.stringify(t), name: 'brand.json', studio: 'brand' }; } } } }; /* =================== DOCS (Markdown editor, workspace, DOCX/PDF export, full-text search) =================== */ export function mdHtml(md) { const out = []; let list = null; const inl = (t) => esc(t).replace(/\*\*([^*]+)\*\*/g, '$1').replace(/\*([^*]+)\*/g, '$1').replace(/`([^`]+)`/g, '$1'); for (const ln of String(md).split('\n')) { const h = ln.match(/^(#{1,3})\s+(.*)/), li = ln.match(/^\s*([-*]|\d+\.)\s+(.*)/); if (!li && list) { out.push(``); list = null; } if (h) out.push(`${inl(h[2])}`); else if (li) { const t = /\d/.test(li[1]) ? 'ol' : 'ul'; if (list !== t) { if (list) out.push(``); out.push(`<${t}>`); list = t; } out.push(`
  • ${inl(li[2])}
  • `); } else if (ln.trim()) out.push(`

    ${inl(ln)}

    `); } if (list) out.push(``); return out.join(''); } const TPL = { leer: '# Titel\n\n', presse: '# Pressemitteilung: {T}\n\n**Ort, Datum** – Einleitung in zwei Sätzen.\n\n## Worum es geht\n- Punkt 1\n- Punkt 2\n\n## Zitat\n"…"\n\n## Kontakt\n{B}', produkt: '# {T}\n\n## Beschreibung\n…\n\n## Details\n- Material:\n- Größen:\n- Preis:\n', release: '# Release: {T}\n\n## Neu\n- …\n\n## Credits\n- Produktion: {B}\n' }; const DOCS = { title: 'Neues Dokument', md: '', path: '' }; async function exportDoc(md, title, fmt) { const k = Brand.kit, f = new FormData(); f.append('md', md); f.append('title', title); f.append('fmt', fmt); f.append('accent', k.c1 === '#f2c94c' ? '#b8860b' : k.c1); f.append('brand', `${k.name} · ${k.handle}`); const r = await fetch('/api/doc/export', { method: 'POST', body: f, credentials: 'include' }); if (!r.ok) throw new Error('Export: ' + ((await r.json().catch(() => ({}))).detail || r.status)); return r.json(); } STUDIOS.push({ id: 'docs', cat: 'Community', icon: '📄', name: 'Docs', like: 'Markdown · DOCX · PDF', real: 'API', accepts: ['text'], build(el) { el.innerHTML = `
    REALDokumente im Workspace (projects/docs/) – Markdown bearbeiten, als DOCX/PDF im Marken-Look exportieren
    Workspace-Dokumente
    KI-Entwurf: ${hf(CHAT)} · Export: python-docx / fpdf2 (Server) · Akzentfarbe & Kopfzeile aus dem Branding-Kit
    `; keep(el); const q = (s) => el.querySelector(s); let files = []; const pv = () => { DOCS.md = q('.md').value; DOCS.title = q('.dt').value; q('.pv').innerHTML = mdHtml(DOCS.md); }; const set = (md, title, path = '') => { q('.md').value = md; if (title) q('.dt').value = title; DOCS.path = path; pv(); }; el.__set = set; set(DOCS.md || TPL.presse.replace('{T}', 'Honey Lofi').replace('{B}', Brand.kit.name + ' ' + Brand.kit.handle), DOCS.title === 'Neues Dokument' ? 'Honey Lofi – Pressetext' : DOCS.title, DOCS.path); q('.md').oninput = pv; q('.dt').oninput = pv; q('.tp').onchange = () => { const t = TPL[q('.tp').value]; if (t) set(t.replace(/\{T\}/g, q('.dt').value).replace(/\{B\}/g, Brand.kit.name + ' ' + Brand.kit.handle)); }; q('.ai').onclick = async (e) => { e.target.disabled = true; try { const t = await llm(`Schreibe ein Dokument auf Deutsch in Markdown (Überschriften mit #, Listen mit -, **fett**). Marke: ${Brand.kit.name} (${Brand.kit.claim}). Titel: ${q('.dt').value}. Auftrag: ${q('.pr').value || q('.dt').value}. Max. 250 Wörter, keine erfundenen Zahlen.`, { status: m => setS(el, 'Entwurf: ' + stTxt(m)) }); set(t); badge(el, 'REAL'); window.__docAI = t.length; setS(el, '✔ Entwurf (' + t.length + ' Zeichen)'); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; const path = () => DOCS.path || `projects/docs/${slug(q('.dt').value)}.md`; q('.dsv').onclick = async (e) => { pv(); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); e.target.disabled = true; try { await upload(path(), new Blob([DOCS.md], { type: 'text/markdown' }), 'docs'); DOCS.path = path(); window.__docSaved = DOCS.path; setS(el, '✔ ' + DOCS.path); list(true); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; const exp = (fmt) => async (e) => { pv(); e.target.disabled = true; setS(el, fmt.toUpperCase() + ' …'); try { const r = await exportDoc(DOCS.md, DOCS.title, fmt); const blob = await toBlob(r.url); q('.out').innerHTML = `⬇ ${esc(r.name)} ${(blob.size / 1024).toFixed(1)} KB`; if (bucket()) await upload(path().replace(/\.md$/, '.' + fmt), blob, 'docs'); (window.__docExp ||= {})[fmt] = blob.size; setS(el, `✔ ${fmt.toUpperCase()} ${bucket() ? '+ im Workspace' : ''}`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; q('.dx').onclick = exp('docx'); q('.dp').onclick = exp('pdf'); const show = (arr) => { q('.dl').innerHTML = arr.length ? arr.map(f => `
    ${f.hit ? ` … ${esc(f.hit)} …` : ''}
    `).join('') : 'keine Dokumente'; }; const list = async () => { files = (await wsList('projects/docs/')).filter(f => /\.md$/.test(f.path)); show(files); }; list(); q('.rl').onclick = list; q('.sr').onclick = async () => { const s = q('.sq').value.trim().toLowerCase(); if (!s) return show(files); setS(el, 'Suche…'); const hits = []; for (const f of files.slice(0, 40)) { const t = await (await fetch(wsFile(f.path), { credentials: 'include' })).text(); const i = t.toLowerCase().indexOf(s); if (i >= 0 || f.path.toLowerCase().includes(s)) hits.push({ ...f, hit: i >= 0 ? t.slice(Math.max(0, i - 30), i + 50).replace(/\s+/g, ' ') : '' }); } show(hits); window.__docSearch = hits.length; setS(el, `${hits.length} Treffer`); }; q('.dl').onclick = async (e) => { const b = e.target.closest('.op'); if (!b) return; const t = await (await fetch(wsFile(b.dataset.p), { credentials: 'include' })).text(); set(t, (t.match(/^#\s+(.*)/m)?.[1] || b.dataset.p.split('/').pop()).slice(0, 80), b.dataset.p); setS(el, 'Geöffnet: ' + b.dataset.p); }; q('.out').addEventListener('click', () => {}); // keep const sendBtn = document.createElement('div'); q('.out').after(sendBtn); const asText = () => result(sendBtn, { kind: 'text', mime: 'text/markdown', text: DOCS.md, name: slug(DOCS.title) + '.md', path: path(), studio: 'docs', prompt: DOCS.title }); q('.md').addEventListener('change', asText); asText(); }, accept: async (el, a) => { const t = a.text ?? await (await toBlob(a.url)).text(); el.__set(t, a.prompt || a.name || 'Dokument'); return true; } }); MODULES.docs = { id: 'docs', name: 'Docs', backend: CHAT + ' + python-docx/fpdf2', inputs: [{ name: 'prompt', type: 'text' }], outputs: [{ kind: 'text' }], actions: { write: { desc: 'Schreibt ein Markdown-Dokument (Pressetext, Produktblatt, Skript …) zum Auftrag; Archivar speichert es', params: { prompt: 'string', title: 'string' }, run: async ({ prompt, title = 'Dokument' }, on = {}) => { const t = await llm(`Schreibe auf Deutsch ein Markdown-Dokument (#-Überschriften, - Listen). Marke: ${Brand.kit.name}. Titel: ${title}. Auftrag: ${prompt}. Max. 200 Wörter.`, on); return { kind: 'text', mime: 'text/markdown', text: t, name: slug(title) + '.md', studio: 'docs', prompt }; } } } }; /* =================== TELEFON-ASSISTENT (Avatar + Wissensbasis + IVR, Testanruf im Browser) =================== */ const PH = { name: 'STUDIUS Hotline', avatar: '', voice: 'browser', greeting: 'Willkommen bei der STUDIUS Hotline. Für Musik und Radio drücken Sie die 1, für Shop und Merch die 2, für einen Rückruf die 0. Oder stellen Sie einfach Ihre Frage.', kbPath: '', kb: '', menu: [{ key: '1', label: 'Musik & Radio', type: 'ai', val: 'Musik, Radio STUDIUS FM, Releases' }, { key: '2', label: 'Shop & Merch', type: 'ai', val: 'Jenniisdriptees Merch, Preise, Versand' }, { key: '0', label: 'Rückruf', type: 'msg', val: 'Gern rufen wir Sie zurück. Bitte nennen Sie Namen und Nummer nach dem Ton. (Demo – es wird nichts gewählt.)' }, { key: '9', label: 'Auflegen', type: 'end', val: 'Danke für Ihren Anruf. Auf Wiederhören!' }] }; function dtmf(k) { const F = { 1: [697, 1209], 2: [697, 1336], 3: [697, 1477], 4: [770, 1209], 5: [770, 1336], 6: [770, 1477], 7: [852, 1209], 8: [852, 1336], 9: [852, 1477], '*': [941, 1209], 0: [941, 1336], '#': [941, 1477] }[k]; if (!F) return; try { const ac = new AudioContext(), g = ac.createGain(); g.gain.value = .12; g.connect(ac.destination); F.forEach(f => { const o = ac.createOscillator(); o.frequency.value = f; o.connect(g); o.start(); o.stop(ac.currentTime + .18); }); setTimeout(() => ac.close(), 400); } catch (e) {} } export async function phoneAnswer(question, topic = '', P = PH) { const av = P._av; return llm(`Du bist der Telefonassistent "${P.name}"${av ? ` mit der Persona ${av.name}: ${(av.persona || av.role || '').slice(0, 300)}` : ''}. Marke: ${Brand.kit.name}. Wissensbasis:\n${(P.kb || '(leer)').slice(0, 3000)}\n${topic ? 'Gewähltes Thema: ' + topic + '\n' : ''}Antworte in höchstens 2 kurzen, gesprochenen Sätzen auf Deutsch, ohne Aufzählungen und Emojis. Erfinde keine Fakten; wenn die Wissensbasis es nicht hergibt, sag das und biete einen Rückruf an (Taste 0). Anrufer: ${question}`); } STUDIOS.push({ id: 'phone', cat: 'Community', icon: '☎', name: 'Telefon-Assistent', like: 'Avatar-Hotline mit IVR & Testanruf', real: 'API', accepts: ['text'], build(el) { el.innerHTML = `
    REALAvatar-Telefonassistent: Begrüßung, Tastenmenü (IVR), Antworten aus der Wissensbasis – Testanruf im Browser. Keine echte Telefonie (Twilio/SIP wäre ein externer Dienst).
    Assistent
    Tastenmenü (IVR)
    TasteBezeichnungAktionThema / Ansage
    Wissensbasis
    📞 Testanruf
    bereit
    ${['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#'].map(k => ``).join('')}
    Antworten: ${hf(CHAT)} · Avatar-Stimme: Qwen3-TTS (Avatar-Studio) oder Browser-TTS · DTMF lokal (Web Audio) · Flow: projects/phone/ im Workspace
    `; keep(el); const q = (s) => el.querySelector(s); let live = false, t0 = 0, tick, log = [], node = 'root', topic = ''; const rows = () => { q('.ivr tbody').innerHTML = PH.menu.map((m, i) => ``).join(''); }; const read = () => { PH.name = q('.pn').value; PH.greeting = q('.pg').value; PH.voice = q('.pv2').value; PH.avatar = q('.pa').value; PH._av = (q('.pa')._list || []).find(a => a.id === PH.avatar) || null; if (!PH.kbPath) PH.kb = q('.kbt').value; PH.menu = [...q('.ivr tbody').children].map(r => ({ key: r.querySelector('.mk').value, label: r.querySelector('.ml').value, type: r.querySelector('.mt').value, val: r.querySelector('.mv').value })).filter(m => m.key); }; q('.pn').value = PH.name; q('.pg').value = PH.greeting; q('.pv2').value = PH.voice; q('.kbt').value = PH.kb; rows(); avOptions(q('.pa'), 'ohne Avatar').then(() => { q('.pa').value = PH.avatar; }); q('.ad').onclick = () => { read(); PH.menu.push({ key: '', label: '', type: 'ai', val: '' }); rows(); }; q('.ivr').onclick = (e) => { const b = e.target.closest('.rm'); if (!b) return; read(); PH.menu.splice(+b.closest('tr').dataset.i, 1); rows(); }; wsList('projects/docs/').then(l => { q('.kb').innerHTML += l.filter(f => /\.md$/.test(f.path)).map(f => ``).join(''); }); q('.kb').onchange = async () => { const p = q('.kb').value; PH.kbPath = p; if (!p) { PH.kb = q('.kbt').value; return; } PH.kb = await (await fetch(wsFile(p), { credentials: 'include' })).text(); q('.kbt').value = PH.kb.slice(0, 4000); q('.kbn').textContent = `${PH.kb.length} Zeichen aus ${p}`; }; const add = (who, text) => { const s = ((Date.now() - t0) / 1000).toFixed(0); log.push({ t: +s, who, text }); const d = document.createElement('div'); d.innerHTML = `${s}s ${who === 'bot' ? '🤖 ' + esc(PH.name) : '🙂 Anrufer'}: ${esc(text)}`; q('.tr').append(d); q('.tr').scrollTop = 1e6; window.__call = { n: log.length, last: text.slice(0, 80), node }; }; const say = async (text) => { add('bot', text); if (!live) return; if (PH.voice === 'avatar' && PH._av) { try { setS(el, 'Avatar-Stimme…'); const u = await Avatars.speak(PH._av, text, {}); const a = q('.pa2'); a.src = u; await a.play().catch(() => {}); await new Promise(r => { a.onended = r; setTimeout(r, 30000); }); setS(el, ''); return; } catch (e) { setS(el, 'Avatar-Stimme nicht verfügbar → Browser-Stimme', true); } } if ('speechSynthesis' in window) await new Promise(r => { const u = new SpeechSynthesisUtterance(text); u.lang = 'de-DE'; u.rate = 1.05; u.onend = r; u.onerror = r; speechSynthesis.speak(u); setTimeout(r, Math.min(20000, 600 + text.length * 70)); }); }; const ui = (on) => { el.querySelectorAll('.key,.qq,.qs,.mic,.hu').forEach(b => b.disabled = !on); q('.cl').disabled = on; }; const hang = async (msg) => { if (!live) return; if (msg) await say(msg); live = false; clearInterval(tick); speechSynthesis?.cancel?.(); ui(false); q('.ct').textContent = `aufgelegt · ${((Date.now() - t0) / 1000).toFixed(0)} s · ${log.length} Beiträge`; window.__callEnded = log.length; }; q('.cl').onclick = async () => { read(); log = []; q('.tr').innerHTML = ''; node = 'root'; topic = ''; live = true; t0 = Date.now(); ui(true); tick = setInterval(() => q('.ct').textContent = `● verbunden ${((Date.now() - t0) / 1000).toFixed(0)} s`, 500); dtmf('#'); await say(PH.greeting); }; q('.hu').onclick = () => hang(); q('.kp').onclick = async (e) => { const b = e.target.closest('.key'); if (!b || !live) return; const k = b.dataset.k; dtmf(k); add('caller', `[Taste ${k}]`); const m = PH.menu.find(x => x.key === k); if (!m) return say('Diese Taste ist nicht belegt. ' + PH.menu.map(x => `${x.label}: ${x.key}`).join(', ') + '.'); node = k; if (m.type === 'end') return hang(m.val || 'Auf Wiederhören!'); if (m.type === 'msg') return say(m.val); topic = m.val || m.label; await say(`${m.label}. Was möchten Sie wissen?`); }; const ask = async () => { const t = q('.qq').value.trim(); if (!t || !live) return; q('.qq').value = ''; add('caller', t); q('.qs').disabled = true; setS(el, 'denkt nach…'); try { const a = await phoneAnswer(t, topic, PH); await say(a); badge(el, 'REAL'); setS(el, ''); } catch (er) { await say('Entschuldigung, gerade gibt es eine Störung. Drücken Sie die 0 für einen Rückruf.'); setS(el, '⚠ ' + er.message, true); } finally { q('.qs').disabled = !live; } }; q('.qs').onclick = ask; q('.qq').onkeydown = (e) => e.key === 'Enter' && ask(); const SR = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SR) q('.mic').title = 'Spracheingabe in diesem Browser nicht verfügbar'; q('.mic').onclick = () => { if (!SR) return setS(el, 'Spracheingabe nicht verfügbar – bitte tippen', true); const r = new SR(); r.lang = 'de-DE'; r.onresult = (e) => { q('.qq').value = e.results[0][0].transcript; ask(); }; r.onerror = (e) => setS(el, '🎤 ' + e.error, true); r.start(); setS(el, '🎤 hört zu…'); }; const script = () => { read(); return `# Call-Skript: ${PH.name}\n\n## Begrüßung\n${PH.greeting}\n\n## Tastenmenü\n${PH.menu.map(m => `- **${m.key} – ${m.label}**: ${m.type === 'ai' ? 'KI-Antwort zum Thema ' + m.val : m.type === 'msg' ? 'Ansage: ' + m.val : 'Auflegen: ' + m.val}`).join('\n')}\n\n## Regeln\n- Antworten max. 2 Sätze, nur aus der Wissensbasis${PH.kbPath ? ' (' + PH.kbPath + ')' : ''}\n- Unklar → Rückruf anbieten (Taste 0)\n${log.length ? '\n## Protokoll Testanruf\n' + log.map(l => `- ${l.t}s ${l.who === 'bot' ? 'Bot' : 'Anrufer'}: ${l.text}`).join('\n') + '\n' : ''}`; }; q('.sd').onclick = () => { window.__bus?.sendTo ? window.__bus.sendTo('docs', { kind: 'text', text: script(), name: slug(PH.name) + '-call-skript.md', prompt: 'Call-Skript ' + PH.name, studio: 'phone' }) : setS(el, '⚠ Asset-Bus fehlt', true); }; q('.psv2').onclick = async (e) => { read(); if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); e.target.disabled = true; try { const base = `projects/phone/${slug(PH.name)}/`, { _av, ...flow } = PH; await saveJson(base + 'flow.json', { type: 'studius.phone', v: 1, ...flow, kb: PH.kbPath ? '' : PH.kb, updated: Date.now() }, 'phone'); if (log.length) await upload(base + `call-${ts()}.md`, new Blob([script()], { type: 'text/markdown' }), 'phone'); window.__phoneSaved = base; setS(el, '✔ ' + base + 'flow.json' + (log.length ? ' + Protokoll' : '')); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; wsJson('projects/phone/' + slug(PH.name) + '/flow.json', null).then(f => { if (f && !q('.tr').children.length) { Object.assign(PH, f); q('.pn').value = PH.name; q('.pg').value = PH.greeting; rows(); } }); }, accept: async (el, a) => { const t = a.text ?? await (await toBlob(a.url)).text(); PH.kb = t; PH.kbPath = ''; el.querySelector('.kbt').value = t.slice(0, 4000); el.querySelector('.kbn').textContent = 'Wissen aus ' + (a.studio || 'Bus'); return true; } }); MODULES.phone = { id: 'phone', name: 'Telefon-Assistent', backend: CHAT, inputs: [{ name: 'question', type: 'text' }], outputs: [{ kind: 'text' }], actions: { answer: { desc: 'Beantwortet eine Anruferfrage wie der Telefonassistent (kurz, aus der Wissensbasis)', params: { question: 'string' }, run: async ({ question }, on = {}) => ({ kind: 'text', mime: 'text/plain', text: await phoneAnswer(question), name: `antwort-${ts()}.txt`, studio: 'phone', prompt: question }) } } }; /* =================== shop.draft (Module API for the Shop Studio; approval-gated on the server) =================== */ MODULES.shop = { id: 'shop', name: 'Shop', backend: CHAT + ' + JDT-Preislogik', inputs: [{ name: 'title', type: 'text' }, { name: 'image', type: 'image-url' }], outputs: [{ kind: 'text' }], actions: { draft: { desc: 'Legt einen Produktentwurf für Jenniisdriptees an (T-Shirt/Hoodie/Tasse/Poster/Sticker; Titel, Text, Preis, SKU) – nur Entwurf in projects/shop/products.json, veröffentlicht nichts', params: { title: 'string', prompt: 'string', type: 'string', image: 'string' }, run: async ({ title, prompt = '', type = 'TEE', image = '' }, on = {}) => { if (!bucket()) throw new Error('Workspace nicht verbunden'); type = PT[type] ? type : 'TEE'; title = (title || prompt || 'Neues Produkt').slice(0, 60); const T = PT[type]; const t = await llm(`Produkttext für Streetwear-Marke Jenniisdriptees: ${T.l} "${title}". ${prompt}\nAntworte genau so:\nBESCHREIBUNG: <3 Sätze>\nTAGS: <10 Tags, kommagetrennt>`, on); const desc = (t.match(/BESCHREIBUNG\s*:\s*([\s\S]*?)(?:\n\s*TAGS|$)/i)?.[1] || t).trim(), tags = (t.match(/TAGS\s*:\s*(.*)/i)?.[1] || '').split(/[,;]/).map(s => s.trim().replace(/^#/, '')).filter(Boolean).slice(0, 13); const r = suggestPrice({ base: T.base, ship: T.ship, margin: 35, royalty: 0, inclShip: true }), sku = `JDT-OWN-${type}-${slugCode(title)}-001`, id = slug(title) + '-' + type.toLowerCase(), base = `projects/shop/${slug(title)}/`; let design = ''; if (image) { try { const b = await toBlob(image); if (/^image\//.test(b.type)) { design = base + 'design.png'; await upload(design, b, 'shop'); } } catch (e) {} } const P = { id, title, line: 'OWN', artist: '', type, colors: [T.colors[0][2]], margin: 35, royalty: 0, inclShip: true, desc, tags, link: '', status: 'entwurf', price: r.sug, sku, design, brand: 'Jenniisdriptees', source: 'agent', updated: Date.now(), variants: T.sizes.map(s => `${sku}-${slugCode(T.colors[0][2], 3)}-${slugCode(s, 4)}`) }; const PJ = 'projects/shop/products.json', list = (await wsJson(PJ, { products: [] })).products || []; const i = list.findIndex(x => x.id === id); i < 0 ? list.push(P) : (list[i] = P); await saveJson(PJ, { type: 'studius.shop', v: 1, brand: 'Jenniisdriptees', note: 'Entwürfe – Veröffentlichung nur nach Freigabe durch Rob im JDT-Studio/Printify', products: list }, 'shop'); return { kind: 'text', mime: 'text/plain', text: `Entwurf ${title} (${T.l}) · ${eur(r.sug)} · SKU ${sku} · Status: Entwurf\n${desc}`, name: id + '.txt', studio: 'shop', prompt: title, path: PJ }; } } } }; /* =================== WHITEBOARD (self-hosted @excalidraw/excalidraw 0.18, MIT) =================== */ let EXL = null; const BD = 'projects/boards/'; async function exLib() { if (EXL) return EXL; window.EXCALIDRAW_ASSET_PATH = location.origin + '/vendor/excalidraw/'; if (!document.querySelector('link[data-exc]')) { const l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/vendor/excalidraw/excalidraw.css'; l.dataset.exc = 1; document.head.append(l); } await import('./vendor/excalidraw/entry.js'); EXL = window.ExcalidrawLib; return EXL; } export function parseFlow(txt) { const edges = [], nodes = new Map(); const node = (n) => { n = n.replace(/^[\s\-*\d.)]+/, '').replace(/[\[\]"]/g, '').trim().slice(0, 60); if (n && !nodes.has(n)) nodes.set(n, { id: 'n' + nodes.size, label: n }); return nodes.get(n); }; for (const ln of String(txt).split('\n')) { const m = ln.match(/(.+?)\s*(?:-+>|→|=>)\s*([^:]+)(?::\s*(.*))?$/); if (!m) { const s = ln.trim(); if (s && !/[:]$/.test(s) && s.length < 60 && !edges.length && nodes.size < 1) node(s); continue; } const a = node(m[1]), b = node(m[2]); if (a && b && a !== b) edges.push({ a: a.id, b: b.id, label: (m[3] || '').trim().slice(0, 30) }); } const N = [...nodes.values()], lvl = Object.fromEntries(N.map(n => [n.id, 0])); for (let k = 0; k < N.length; k++) for (const e of edges) if (lvl[e.b] < lvl[e.a] + 1 && lvl[e.a] + 1 < N.length) lvl[e.b] = lvl[e.a] + 1; const rows = {}; N.forEach(n => (rows[lvl[n.id]] ||= []).push(n)); return { nodes: N, edges, lvl, rows }; } export function flowSkeleton(f, k = Brand.kit) { const out = [], W = 220, H = 74, GX = 270, GY = 150; for (const [l, row] of Object.entries(f.rows)) row.forEach((n, i) => { const dec = /\?$/.test(n.label); out.push({ type: dec ? 'diamond' : 'rectangle', id: n.id, x: (i - (row.length - 1) / 2) * GX - W / 2, y: +l * GY, width: W, height: dec ? H + 26 : H, strokeColor: k.c1, backgroundColor: dec ? '#3a2c0a' : '#1c1608', fillStyle: 'solid', roundness: dec ? null : { type: 3 }, label: { text: n.label, strokeColor: k.c3 || '#fff4d6', fontSize: 18 } }); }); for (const e of f.edges) out.push({ type: 'arrow', x: 0, y: 0, strokeColor: k.c3 || '#fff4d6', start: { id: e.a }, end: { id: e.b }, ...(e.label ? { label: { text: e.label, fontSize: 14, strokeColor: k.c1 } } : {}) }); return out; } async function flowText(prompt, on = {}) { if (/(-+>|→|=>)/.test(prompt)) return prompt; return llm(`Zerlege den folgenden Ablauf in ein Flussdiagramm. Antworte NUR mit Zeilen im Format "Schritt A -> Schritt B" oder "Frage? -> Schritt: ja". Kurze Schritte (max. 5 Wörter), max. 12 Zeilen, keine weiteren Texte.\nAblauf: ${prompt}`, on); } async function boardFromText(prompt, on = {}) { const L = await exLib(), t = await flowText(prompt, on), f = parseFlow(t); if (!f.nodes.length) throw new Error('Kein Ablauf erkannt'); return { elements: L.convertToExcalidrawElements(flowSkeleton(f), { regenerateIds: false }), flow: f, text: t }; } const BOARD = { title: 'Empire-Flow', scene: null }; STUDIOS.push({ id: 'board', cat: 'Community', icon: '✏', name: 'Whiteboard', like: 'Excalidraw: Skizzen, Flowcharts', real: 'API', accepts: ['image', 'text'], build(el) { el.innerHTML = `
    REALExcalidraw (MIT, selbst gehostet) – handgezeichnete Formen, Pfeile, Text, Freihand, Bibliotheken; Boards mit Versionen im Workspace
    Lade Excalidraw…
    Editor: @excalidraw/excalidraw 0.18 (MIT, self-hosted) · Flowchart-Text: ${hf(CHAT)} (oder direkt „A -> B“-Zeilen ohne KI) · Boards: ${BD}*.excalidraw (+Versionen)
    `; keep(el); const q = (s) => el.querySelector(s), k = Brand.kit; q('.bt').value = BOARD.title; let ui, api, L; const path = () => BD + slug(q('.bt').value) + '.excalidraw'; const fit = () => api && api.scrollToContent(undefined, { fitToContent: true, animate: false }); const fileOf = (blob) => new Promise(r => { const fr = new FileReader(); fr.onload = () => r(fr.result); fr.readAsDataURL(blob); }); const addImage = async (blob, name) => { const dataURL = await fileOf(blob), id = 'img-' + Date.now().toString(36), im = await loadImg(dataURL), s = Math.min(1, 420 / im.width); api.addFiles([{ id, dataURL, mimeType: blob.type || 'image/png', created: Date.now() }]); const [e] = L.convertToExcalidrawElements([{ type: 'image', fileId: id, x: 40, y: 40, width: im.width * s, height: im.height * s }]); api.updateScene({ elements: [...api.getSceneElements(), e] }); fit(); setS(el, '✔ Bild eingefügt: ' + name); window.__boardImg = true; }; const load = (scene) => { api.updateScene({ elements: scene.elements || [], appState: { ...(scene.appState || {}), collaborators: new Map() } }); if (scene.files) api.addFiles(Object.values(scene.files)); setTimeout(fit, 50); }; el.__ready = (async () => { L = await exLib(); const lib = await wsJson(BD + 'library.excalidrawlib', null); q('.exc').innerHTML = ''; ui = L.mount(q('.exc'), { theme: 'dark', langCode: 'de-DE', name: q('.bt').value, initialData: { elements: BOARD.scene?.elements || [], files: BOARD.scene?.files, libraryItems: lib?.libraryItems || [], appState: { viewBackgroundColor: '#0d0b07', currentItemStrokeColor: k.c1, currentItemFontFamily: 5, theme: 'dark' } }, UIOptions: { canvasActions: { saveToActiveFile: false, loadScene: true, export: { saveFileToDisk: true }, toggleTheme: false } }, onLibraryChange: async (items) => { if (bucket()) { try { await saveJson(BD + 'library.excalidrawlib', { type: 'excalidrawlib', version: 2, source: 'studius', libraryItems: items }, 'board'); window.__boardLib = items.length; } catch (e) {} } }, onChange: (els, st, files) => { BOARD.scene = { elements: els, files }; } }); for (let i = 0; i < 100 && !ui.api; i++) await new Promise(r => setTimeout(r, 100)); api = ui.api; window.__board = { api, L, unmount: () => { try { ui?.unmount(); } catch (e) {} ui = null; api = null; } }; el.__unmount = window.__board.unmount; if (BOARD.scene?.elements?.length) fit(); setS(el, '✔ Excalidraw bereit'); })().catch(e => setS(el, '⚠ Excalidraw: ' + e.message, true)); const scene = () => L.serializeAsJSON(api.getSceneElements(), api.getAppState(), api.getFiles(), 'local'); const lists = async () => { const l = (await wsList(BD)).filter(f => /\.excalidraw$/.test(f.path)); q('.bl').innerHTML = '' + l.map(f => ``).join(''); const im = (await wsList('')).filter(f => /\.(png|jpe?g|webp)$/i.test(f.path)).slice(0, 80); q('.wi').innerHTML = '' + im.map(f => ``).join(''); }; lists(); const versions = async (p) => { const r = await fetch(`/api/ws/versions?bucket=${encodeURIComponent(window.__ws.bucket)}&path=${encodeURIComponent(p)}`, { credentials: 'include' }); const j = r.ok ? await r.json() : { versions: [] }; q('.bv').hidden = !j.versions.length; q('.bv').innerHTML = `` + j.versions.map(v => ``).join(''); window.__boardVersions = j.versions.length; }; q('.bsv').onclick = async (e) => { await el.__ready; if (!bucket()) return setS(el, '⚠ Bitte anmelden + Workspace verbinden', true); e.target.disabled = true; try { const p = path(); await upload(p, new Blob([scene()], { type: 'application/json' }), 'board'); const png = await L.exportToBlob({ elements: api.getSceneElements(), appState: { ...api.getAppState(), exportBackground: true }, files: api.getFiles(), mimeType: 'image/png' }); await upload(p.replace(/\.excalidraw$/, '.png'), png, 'board'); window.__boardSaved = p; setS(el, '✔ ' + p + ' (+ Vorschau-PNG)'); await lists(); q('.bl').value = p; await versions(p); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; q('.bl').onchange = async () => { const p = q('.bl').value; if (!p) return; await el.__ready; const s = await (await fetch(wsFile(p), { credentials: 'include' })).json(); load(s); q('.bt').value = p.replace(BD, '').replace(/\.excalidraw$/, ''); await versions(p); window.__boardLoaded = s.elements?.length; setS(el, `✔ Geöffnet: ${p} (${s.elements?.length || 0} Elemente)`); }; q('.bv').onchange = async () => { const v = q('.bv').value || q('.bl').value; if (!v) return; const s = await (await fetch(wsFile(v), { credentials: 'include' })).json(); load(s); window.__boardVerLoaded = s.elements?.length; setS(el, `✔ ${q('.bv').value ? 'Version geladen' : 'Aktuelle Fassung'} (${s.elements?.length || 0} Elemente) – Speichern legt eine neue Version an`); }; q('.bn2').onclick = async () => { await el.__ready; api.resetScene(); q('.bt').value = 'Board ' + ts(); q('.bv').hidden = true; q('.bl').value = ''; }; q('.wi').onchange = async () => { const p = q('.wi').value; if (!p) return; await el.__ready; await addImage(await toBlob(wsFile(p)), p.split('/').pop()); q('.wi').value = ''; }; q('.fg').onclick = async (e) => { await el.__ready; e.target.disabled = true; try { const r = await boardFromText(q('.fp').value || 'Song komponieren -> Social-Post-Entwurf -> Merch-Entwurf -> Freigabe durch Rob?\nFreigabe durch Rob? -> Workspace speichern: ja', { status: m => setS(el, 'Flowchart: ' + stTxt(m)) }); api.updateScene({ elements: [...api.getSceneElements(), ...r.elements] }); fit(); window.__boardFlow = { nodes: r.flow.nodes.length, edges: r.flow.edges.length }; setS(el, `✔ Flowchart: ${r.flow.nodes.length} Schritte, ${r.flow.edges.length} Pfeile`); } catch (er) { setS(el, '⚠ ' + er.message, true); } finally { e.target.disabled = false; } }; const png = () => L.exportToBlob({ elements: api.getSceneElements(), appState: { ...api.getAppState(), exportBackground: true, exportWithDarkMode: false }, files: api.getFiles(), mimeType: 'image/png', exportPadding: 24 }); q('.xp').onclick = async () => { await el.__ready; const b = await png(); dl(b, slug(q('.bt').value) + '.png'); (window.__boardExp ||= {}).png = b.size; }; q('.xs').onclick = async () => { await el.__ready; const s = await L.exportToSvg({ elements: api.getSceneElements(), appState: { ...api.getAppState(), exportBackground: true }, files: api.getFiles() }); const b = new Blob([s.outerHTML], { type: 'image/svg+xml' }); dl(b, slug(q('.bt').value) + '.svg'); (window.__boardExp ||= {}).svg = b.size; }; q('.xj').onclick = async () => { await el.__ready; const b = new Blob([scene()], { type: 'application/json' }); dl(b, slug(q('.bt').value) + '.excalidraw'); (window.__boardExp ||= {}).json = b.size; }; q('.xb').onclick = async () => { await el.__ready; const b = await png(), u = URL.createObjectURL(b); q('.out').innerHTML = `Board`; result(q('.out'), { kind: 'image', mime: 'image/png', blob: b, url: u, name: slug(q('.bt').value) + '.png', path: BD + slug(q('.bt').value) + '.png', studio: 'board', prompt: q('.bt').value }); window.__boardPng = b.size; setS(el, '✔ PNG bereit – „Senden an…“ Image/Social/Shop'); }; el.__addImage = addImage; el.__flow = (t) => { q('.fp').value = t; q('.fg').click(); }; }, accept: async (el, a) => { await el.__ready; if (a.kind === 'text') { el.__flow(a.text ?? await (await toBlob(a.url)).text()); return true; } await el.__addImage(a.blob || await toBlob(a.url), a.name || 'bild'); return true; } }); MODULES.board = { id: 'board', name: 'Whiteboard', backend: 'Excalidraw (lokal) + ' + CHAT, inputs: [{ name: 'prompt', type: 'text' }], outputs: [{ kind: 'image' }], actions: { create: { desc: 'Erstellt ein Whiteboard (Excalidraw) mit einem Flussdiagramm aus einer Ablauf-Beschreibung, speichert es als Board im Workspace und liefert ein PNG', params: { prompt: 'string', title: 'string' }, run: async ({ prompt, title = 'Flowchart' }, on = {}) => { const L = await exLib(), r = await boardFromText(prompt, on), appState = { viewBackgroundColor: '#0d0b07', exportBackground: true, exportWithDarkMode: false }; const p = BD + slug(title) + '.excalidraw'; if (bucket()) await upload(p, new Blob([L.serializeAsJSON(r.elements, appState, {}, 'local')], { type: 'application/json' }), 'board'); const blob = await L.exportToBlob({ elements: r.elements, appState, files: {}, mimeType: 'image/png', exportPadding: 24 }); return { kind: 'image', mime: 'image/png', blob, url: URL.createObjectURL(blob), name: slug(title) + '.png', studio: 'board', prompt, path: BD + slug(title) + '.png', board: p }; } } } };