Spaces:
Running
Running
v0.2: in-weights option (Meta Muse Glimmer 30B + ViKernel, mode A/B)
Browse files4 unmodified lines567891011 unmodified lines22232425262718 unmodified lines4647484950515253545556572 unmodified lines60616263646526 unmodified lines9293949596976 unmodified lines1041051061071081091101111121131141151161171181191201211224 unmodified lines'use strict';const S = {en: {agName: 'Agent Guard (Meta Muse)',agIntro: 'A Meta Muse agent. Every tool call it proposes is sent to the ViKernel Secure OS first. Denied or halted actions never run.',agChat: 'Agent chat', agDec: 'ViKernel decisions', agAudit: 'Audit chain',11 unmodified linesagStats: 'Live counters', agMedGate: 'median gate', agMedModel: 'median model turn', agTok: 'tokens', agFoot: 'All tools are mocks with fake data. The kernel runs as a private service on VIDRAFT infrastructure.',},ko: {agName: 'Agent Guard (Meta Muse)',agIntro: 'Meta Muse 에이전트입니다. 에이전트가 제안하는 모든 도구 호출은 먼저 ViKernel 시큐어 OS 로 갑니다. 거부되거나 정지된 행동은 실행되지 않습니다.',agChat: '에이전트 대화', agDec: 'ViKernel 판정', agAudit: '감사 사슬',18 unmodified lineswindow.VK_AG = ({el, t, toast}) => ({id: 'guard', name: () => t('agName'), color: '#0866FF', icon: ICON, w: 900, h: 560,render(b) {let LIVE = false, REPLAY = null, busy = false;const SID = 's' + Math.random().toString(36).slice(2, 8);const call = async (path, body) => {const ctl = new AbortController(); const to = setTimeout(() => ctl.abort(), 120000);try {const r = await fetch('api/ag/' + path, body === undefined ? {cache:'no-store', signal:ctl.signal} :{method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body), signal:ctl.signal});if (r.status === 429) { toast(t('agRate')); throw new Error('rate'); }if (!r.ok) throw new Error('http ' + r.status);2 unmodified lines};const mode = el('span', {class:'tag rec'}, '...');const stateTag = el('span', {class:'tag none'}, 'kernel: ...');const chat = el('div', {class:'agchat'}), stream = el('div', {class:'agstream'}), audit = el('div', {class:'agaudit mono small'});const msg = el('input', {class:'aginput', placeholder:t('agPh'), autocomplete:'off'});const key = el('input', {class:'aginput mono', type:'password', placeholder:t('agKey'), style:'flex:1 1 90px;max-width:160px;min-width:80px'});26 unmodified linesconst lines = Object.entries(r).filter(([k]) => !['pass', 'note', 'first_error', 'seconds'].includes(k)).map(([k, v]) => k + ': ' + (typeof v === 'object' ? JSON.stringify(v) : v));say('s', [el('b', {style:`color:${r.pass ? '#065F46' : 'var(--rose)'}`}, (r.pass ? 'PASS ' : 'FAIL ') + name), '\n' + lines.join('\n')]); };const refresh = async () => { if (!LIVE) return;try { const s = await call('status'); stateTag.textContent = 'kernel: ' + s.kernel_state; stateTag.className = 'tag ' + (s.kernel_state === 'RUN' ? 'allow' : 'deny');const a = await call('audit'); const v = a.verify; audit.innerHTML = '';audit.append(el('div', {style:`font-weight:700;color:${v.ok ? '#065F46' : 'var(--rose)'}`}, (v.ok ? t('agOk') : t('agBroken')) + ' (' + v.n + ' ' + t('agRecords') + ')'),6 unmodified linesconst lock = on => { busy = on; b.querySelectorAll('button').forEach(x => x.disabled = on); };const scen = async name => { if (busy) return; lock(true); say('s', '--- ' + name + ' ---');try {if (LIVE) { try { const r = await call('scenario', {name}); show(r.events); result(name, r.result); } catch (e) { if (e.message !== 'rate') { await goReplay(); } } }if (!LIVE) { const s = REPLAY.scenarios[name]; if (s) { for (const e of s.events) { show([e]); await new Promise(r => setTimeout(r, 300)); } result(name, s.result); } }} finally { lock(false); refresh(); } };const send = async () => { const m = msg.value.trim(); if (!m || busy) return; msg.value = '';if (!LIVE) { say('s', t('agReplayChat')); return; }lock(true); say('s', t('agThinking'));try { const r = await call('chat', {message:m, session:SID}); show(r.events); } catch (e) { if (e.message !== 'rate') say('s', t('agCold')); }finally { lock(false); refresh(); } };msg.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.isComposing) send(); });const btn = (k, f, cls) => el('button', {class:'btn ' + (cls || ''), onclick:f}, t(k));b.append(el('div', {class:'aggrid'},el('div', {class:'agcol'},el('div', {class:'row', style:'margin-bottom:6px;flex-wrap:wrap;gap:6px'}, el('b', {}, t('agChat')), mode, el('span', {class:'tag none', id:'agModel'}, 'Meta Muse Spark 1.3')),el('div', {class:'row', style:'flex-wrap:wrap;gap:6px;margin-bottom:6px'}, ['a_normal', 'b_injection', 'c_persuasion', 'd_kill', 'e_tamper'].map((s, i) => btn('ag' + 'ABCDE'[i], () => scen(s)))),el('p', {class:'small muted', style:'margin:0 0 6px'}, t('agIntro')),el('details', {class:'card small', style:'margin:0 0 6px;padding:6px 10px', open:''}, el('summary', {style:'font-weight:700;cursor:pointer'}, t('agTry')),4 unmodified lines56789101111 unmodified lines2324252627282918 unmodified lines484950515253545556575859602 unmodified lines6364656667686970717273747576777826 unmodified lines1051061071081091101116 unmodified lines1181191201211221231241251261271281291301311321331341351364 unmodified lines'use strict';const S = {en: {agGraftCold: 'The in-weights backend (GPU) is starting. Try again in a few minutes.', agEGate: 'E checks the audit chain of the ViKernel gate.', agModeA: 'Mode A: the ViKernel kernel runs inside the model weights (a chip circuit grafted into the decoder). Each turn takes about 20 to 60 seconds.',agName: 'Agent Guard (Meta Muse)',agIntro: 'A Meta Muse agent. Every tool call it proposes is sent to the ViKernel Secure OS first. Denied or halted actions never run.',agChat: 'Agent chat', agDec: 'ViKernel decisions', agAudit: 'Audit chain',11 unmodified linesagStats: 'Live counters', agMedGate: 'median gate', agMedModel: 'median model turn', agTok: 'tokens', agFoot: 'All tools are mocks with fake data. The kernel runs as a private service on VIDRAFT infrastructure.',},ko: {agGraftCold: '가중치 내장 백엔드(GPU)가 시작 중입니다. 몇 분 뒤 다시 시도하세요.', agEGate: 'E 는 ViKernel 게이트의 감사 사슬을 검사합니다.', agModeA: '모드 A: ViKernel 커널이 모델 가중치 안(디코더에 접목한 칩 회로)에서 동작합니다. 한 번에 약 20~60초 걸립니다.',agName: 'Agent Guard (Meta Muse)',agIntro: 'Meta Muse 에이전트입니다. 에이전트가 제안하는 모든 도구 호출은 먼저 ViKernel 시큐어 OS 로 갑니다. 거부되거나 정지된 행동은 실행되지 않습니다.',agChat: '에이전트 대화', agDec: 'ViKernel 판정', agAudit: '감사 사슬',18 unmodified lineswindow.VK_AG = ({el, t, toast}) => ({id: 'guard', name: () => t('agName'), color: '#0866FF', icon: ICON, w: 900, h: 560,render(b) {let LIVE = false, REPLAY = null, busy = false, SEL = 'spark';const GRAFT = () => SEL !== 'spark', MODE = () => SEL === 'graftA' ? 'A' : 'B';const SID = 's' + Math.random().toString(36).slice(2, 8);const call = async (path, body, spark) => {const ctl = new AbortController(); const to = setTimeout(() => ctl.abort(), 320000);try {const r = await fetch((GRAFT() && !spark ? 'api/agx/' : 'api/ag/') + path, body === undefined ? {cache:'no-store', signal:ctl.signal} :{method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body), signal:ctl.signal});if (r.status === 429) { toast(t('agRate')); throw new Error('rate'); }if (!r.ok) throw new Error('http ' + r.status);2 unmodified lines};const mode = el('span', {class:'tag rec'}, '...');const stateTag = el('span', {class:'tag none'}, 'kernel: ...');const sel = el('select', {class:'aginput', style:'flex:0 1 auto;height:28px;max-width:100%', 'aria-label':'model'},el('option', {value:'spark'}, '1. Meta Muse Spark 1.3 (API) + ViKernel gate'),el('option', {value:'graftB'}, '2. Meta Muse Glimmer 30B + ViKernel in-weights, mode B'),el('option', {value:'graftA'}, '3. Meta Muse Glimmer 30B + ViKernel in-weights, mode A (kernel runs inside the weights, slow)'));sel.onchange = async () => { const want = sel.value;if (want !== 'spark') { const prev = SEL; SEL = want; let h = null; try { h = await call('health'); } catch {}if (!h || !h.live) { SEL = prev; sel.value = prev; toast(t('agGraftCold')); return; } }SEL = want; LIVE = true; REPLAY = null; mode.textContent = t('agLive'); mode.className = 'tag allow';b.querySelector('#agModel').textContent = sel.options[sel.selectedIndex].text.replace(/^\d\. /, '');say('s', '--- ' + sel.options[sel.selectedIndex].text + ' ---' + (want === 'graftA' ? '\n' + t('agModeA') : '')); audit.innerHTML = ''; refresh(); };const chat = el('div', {class:'agchat'}), stream = el('div', {class:'agstream'}), audit = el('div', {class:'agaudit mono small'});const msg = el('input', {class:'aginput', placeholder:t('agPh'), autocomplete:'off'});const key = el('input', {class:'aginput mono', type:'password', placeholder:t('agKey'), style:'flex:1 1 90px;max-width:160px;min-width:80px'});26 unmodified linesconst lines = Object.entries(r).filter(([k]) => !['pass', 'note', 'first_error', 'seconds'].includes(k)).map(([k, v]) => k + ': ' + (typeof v === 'object' ? JSON.stringify(v) : v));say('s', [el('b', {style:`color:${r.pass ? '#065F46' : 'var(--rose)'}`}, (r.pass ? 'PASS ' : 'FAIL ') + name), '\n' + lines.join('\n')]); };const refresh = async () => { if (!LIVE) return;if (GRAFT()) { try { const s = await call('status'); stateTag.textContent = 'kernel (in weights): ' + s.kernel_state; stateTag.className = 'tag ' + (s.kernel_state === 'RUN' ? 'allow' : 'deny'); } catch {} return; }try { const s = await call('status'); stateTag.textContent = 'kernel: ' + s.kernel_state; stateTag.className = 'tag ' + (s.kernel_state === 'RUN' ? 'allow' : 'deny');const a = await call('audit'); const v = a.verify; audit.innerHTML = '';audit.append(el('div', {style:`font-weight:700;color:${v.ok ? '#065F46' : 'var(--rose)'}`}, (v.ok ? t('agOk') : t('agBroken')) + ' (' + v.n + ' ' + t('agRecords') + ')'),6 unmodified linesconst lock = on => { busy = on; b.querySelectorAll('button').forEach(x => x.disabled = on); };const scen = async name => { if (busy) return; lock(true); say('s', '--- ' + name + ' ---');try {if (LIVE) { try { const ex = GRAFT() && name === 'e_tamper'; if (ex) say('s', t('agEGate')); const r = await call('scenario', {name, mode:MODE()}, ex); show(r.events); result(name, r.result); } catch (e) { if (e.message !== 'rate') { await goReplay(); } } }if (!LIVE) { const s = REPLAY.scenarios[name]; if (s) { for (const e of s.events) { show([e]); await new Promise(r => setTimeout(r, 300)); } result(name, s.result); } }} finally { lock(false); refresh(); } };const send = async () => { const m = msg.value.trim(); if (!m || busy) return; msg.value = '';if (!LIVE) { say('s', t('agReplayChat')); return; }lock(true); say('s', t('agThinking'));try { const r = await call('chat', {message:m, session:SID, mode:MODE()}); show(r.events); } catch (e) { if (e.message !== 'rate') say('s', t('agCold')); }finally { lock(false); refresh(); } };msg.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.isComposing) send(); });const btn = (k, f, cls) => el('button', {class:'btn ' + (cls || ''), onclick:f}, t(k));b.append(el('div', {class:'aggrid'},el('div', {class:'agcol'},el('div', {class:'row', style:'margin-bottom:6px;flex-wrap:wrap;gap:6px'}, el('b', {}, t('agChat')), mode, el('span', {class:'tag none', id:'agModel'}, 'Meta Muse Spark 1.3'), sel),el('div', {class:'row', style:'flex-wrap:wrap;gap:6px;margin-bottom:6px'}, ['a_normal', 'b_injection', 'c_persuasion', 'd_kill', 'e_tamper'].map((s, i) => btn('ag' + 'ABCDE'[i], () => scen(s)))),el('p', {class:'small muted', style:'margin:0 0 6px'}, t('agIntro')),el('details', {class:'card small', style:'margin:0 0 6px;padding:6px 10px', open:''}, el('summary', {style:'font-weight:700;cursor:pointer'}, t('agTry')),
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""ViKernel Desktop Space server: serves the static desktop and proxies /api/ag/* server-sideto a private Agent Guard backend. Backend credentials live in Space secrets and never reach the browser."""import json, os, time, urllib.error, urllib.requestfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerBACKEND = os.environ.get("BACKEND_URL", "").rstrip("/")HF_AUTH = os.environ.get("BACKEND_HF_TOKEN", "")BK_TOKEN = os.environ.get("BACKEND_TOKEN", "")RATE = int(os.environ.get("RATE_PER_10MIN", "20"))TIMEOUT = float(os.environ.get("BACKEND_TIMEOUT", "110"))GET_OK = {"health", "status", "audit"}POST_OK = {"chat", "scenario", "kill", "resume", "tamper", "reset"}STATIC = {"index.html", "app.js", "ag.js", "i18n.js", "demo_data.js", "styles.css", "ag_replay.json"}HITS = {}def limited(ip):now = time.time()h = [x for x in HITS.get(ip, []) if now - x < 600]full = len(h) >= RATEif not full:h.append(now)HITS[ip] = hif len(HITS) > 5000:HITS.clear()return fullclass H(SimpleHTTPRequestHandler):def _json(self, code, obj):b = json.dumps(obj).encode()self.send_response(code); self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(b))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(b)def _proxy(self, name, body=None):if not BACKEND:return self._json(503, {"error": "backend not configured"})h = {"Content-Type": "application/json", "X-Backend-Token": BK_TOKEN}if HF_AUTH:h["Authorization"] = "Bearer " + HF_AUTHreq = urllib.request.Request(BACKEND + "/api/" + name, data=body, headers=h, method="POST" if body is not None else "GET")try:with urllib.request.urlopen(req, timeout=8 if name == "health" else TIMEOUT) as r:data, code = r.read(), r.statusif not data.lstrip().startswith(b"{"):return self._json(503, {"error": "backend starting"})self.send_response(code); self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(data))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(data)except urllib.error.HTTPError as e:self._json(503 if e.code >= 500 or e.code in (401, 403, 404) else e.code, {"error": "backend unavailable"})except Exception: # noqa: BLE001self._json(503, {"error": "backend unavailable"})def do_GET(self):p = self.path.split("?")[0]if p.startswith("/api/ag/"):name = p[8:]return self._proxy(name) if name in GET_OK else self._json(404, {"error": "not found"})f = "index.html" if p == "/" else p.lstrip("/")if f not in STATIC:return self._json(404, {"error": "not found"})self.path = "/" + freturn super().do_GET()def do_POST(self):p = self.path.split("?")[0]name = p[8:] if p.startswith("/api/ag/") else ""if name not in POST_OK:return self._json(404, {"error": "not found"})ip = (self.headers.get("X-Forwarded-For") or self.client_address[0]).split(",")[0].strip()if limited(ip):return self._json(429, {"error": "rate limit"})n = int(self.headers.get("Content-Length", 0) or 0)if n > 4096:return self._json(413, {"error": "too large"})try:req = json.loads(self.rfile.read(n) or b"{}")except ValueError:return self._json(400, {"error": "bad json"})if "message" in req:req["message"] = str(req["message"])[:500]self._proxy(name, json.dumps(req).encode())def end_headers(self):self.send_header("X-Content-Type-Options", "nosniff")super().end_headers()def log_message(self, *a):passif __name__ == "__main__":os.chdir(os.path.dirname(os.path.abspath(__file__)))ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "7860"))), H).serve_forever()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100"""ViKernel Desktop Space server: serves the static desktop and proxies /api/ag/* server-sideto a private Agent Guard backend. Backend credentials live in Space secrets and never reach the browser."""import json, os, time, urllib.error, urllib.requestfrom http.server import SimpleHTTPRequestHandler, ThreadingHTTPServerBACKEND = os.environ.get("BACKEND_URL", "").rstrip("/")BACKEND2 = os.environ.get("BACKEND2_URL", "").rstrip("/") # in-weights graft backend (GPU)HF_AUTH = os.environ.get("BACKEND_HF_TOKEN", "")BK_TOKEN = os.environ.get("BACKEND_TOKEN", "")RATE = int(os.environ.get("RATE_PER_10MIN", "20"))TIMEOUT = float(os.environ.get("BACKEND_TIMEOUT", "300"))GET_OK = {"health", "status", "audit"}POST_OK = {"chat", "scenario", "kill", "resume", "tamper", "reset"}STATIC = {"index.html", "app.js", "ag.js", "i18n.js", "demo_data.js", "styles.css", "ag_replay.json"}HITS = {}def limited(ip):now = time.time()h = [x for x in HITS.get(ip, []) if now - x < 600]full = len(h) >= RATEif not full:h.append(now)HITS[ip] = hif len(HITS) > 5000:HITS.clear()return fullclass H(SimpleHTTPRequestHandler):def _json(self, code, obj):b = json.dumps(obj).encode()self.send_response(code); self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(b))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(b)def _proxy(self, name, body=None, base=None):base = base or BACKENDif not base:return self._json(503, {"error": "backend not configured"})h = {"Content-Type": "application/json", "X-Backend-Token": BK_TOKEN}if HF_AUTH:h["Authorization"] = "Bearer " + HF_AUTHreq = urllib.request.Request(base + "/api/" + name, data=body, headers=h, method="POST" if body is not None else "GET")try:with urllib.request.urlopen(req, timeout=8 if name == "health" else TIMEOUT) as r:data, code = r.read(), r.statusif not data.lstrip().startswith(b"{"):return self._json(503, {"error": "backend starting"})self.send_response(code); self.send_header("Content-Type", "application/json")self.send_header("Content-Length", str(len(data))); self.send_header("Cache-Control", "no-store"); self.end_headers(); self.wfile.write(data)except urllib.error.HTTPError as e:self._json(503 if e.code >= 500 or e.code in (401, 403, 404) else e.code, {"error": "backend unavailable"})except Exception: # noqa: BLE001self._json(503, {"error": "backend unavailable"})def do_GET(self):p = self.path.split("?")[0]if p.startswith("/api/ag/") or p.startswith("/api/agx/"):x = p.startswith("/api/agx/")name = p[9:] if x else p[8:]return self._proxy(name, base=BACKEND2 if x else None) if name in GET_OK else self._json(404, {"error": "not found"})f = "index.html" if p == "/" else p.lstrip("/")if f not in STATIC:return self._json(404, {"error": "not found"})self.path = "/" + freturn super().do_GET()def do_POST(self):p = self.path.split("?")[0]x = p.startswith("/api/agx/")name = p[9:] if x else (p[8:] if p.startswith("/api/ag/") else "")if name not in POST_OK:return self._json(404, {"error": "not found"})ip = (self.headers.get("X-Forwarded-For") or self.client_address[0]).split(",")[0].strip()if limited(ip):return self._json(429, {"error": "rate limit"})n = int(self.headers.get("Content-Length", 0) or 0)if n > 4096:return self._json(413, {"error": "too large"})try:req = json.loads(self.rfile.read(n) or b"{}")except ValueError:return self._json(400, {"error": "bad json"})if "message" in req:req["message"] = str(req["message"])[:500]if x and not BACKEND2:return self._json(503, {"error": "in-weights backend not configured"})self._proxy(name, json.dumps(req).encode(), base=BACKEND2 if x else None)def end_headers(self):self.send_header("X-Content-Type-Options", "nosniff")super().end_headers()def log_message(self, *a):passif __name__ == "__main__":os.chdir(os.path.dirname(os.path.abspath(__file__)))ThreadingHTTPServer(("0.0.0.0", int(os.environ.get("PORT", "7860"))), H).serve_forever()
ag.js+21-7
server.py+100-94