Spaces:
Paused
Paused
P2.5: agents, teams, function-calling, approval jobs
Browse files- app.js +5 -5
- avatar.js +1 -1
- index.html +2 -2
- master.js +1 -1
- server/agents.py +186 -0
- server/main.py +3 -1
- style.css +3 -0
- workspace.js +91 -30
app.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
import * as THREE from './vendor/three.module.min.js';
|
| 2 |
import { STUDIOS, stopLoops } from './widgets.js?v=50';
|
| 3 |
-
import './real.js?v=
|
| 4 |
-
import './avatar.js?v=
|
| 5 |
-
import './master.js?v=
|
| 6 |
-
import './workspace.js?v=
|
| 7 |
-
import { icon } from './icons.js?v=
|
| 8 |
import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
|
| 9 |
import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
|
| 10 |
import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
|
|
|
|
| 1 |
import * as THREE from './vendor/three.module.min.js';
|
| 2 |
import { STUDIOS, stopLoops } from './widgets.js?v=50';
|
| 3 |
+
import './real.js?v=66';
|
| 4 |
+
import './avatar.js?v=66';
|
| 5 |
+
import './master.js?v=66';
|
| 6 |
+
import './workspace.js?v=66';
|
| 7 |
+
import { icon } from './icons.js?v=66';
|
| 8 |
import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
|
| 9 |
import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
|
| 10 |
import { RenderPass } from './vendor/addons/postprocessing/RenderPass.js';
|
avatar.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
// Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
|
| 2 |
// avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
|
| 3 |
import { STUDIOS, onStop } from './widgets.js?v=50';
|
| 4 |
-
import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=
|
| 5 |
|
| 6 |
const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
|
| 7 |
const slug = (n) => (n || 'avatar').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'avatar';
|
|
|
|
| 1 |
// Avatar / Persona studio (DoD): persistent avatars as workspace asset type `avatar`
|
| 2 |
// avatars/<slug>/avatar.json + ref.webp + voice.wav · reused by Chat, Image (Kontext), agents.
|
| 3 |
import { STUDIOS, onStop } from './widgets.js?v=50';
|
| 4 |
+
import { run, result, MODULES, esc, hf, stTxt, url, badge, setS, keep, LS, FLUX, KONTEXT, TTS, CHAT, signedIn } from './real.js?v=66';
|
| 5 |
|
| 6 |
const LANGS = ['German', 'English', 'French', 'Spanish', 'Auto'];
|
| 7 |
const slug = (n) => (n || 'avatar').toLowerCase().normalize('NFKD').replace(/[^\w]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'avatar';
|
index.html
CHANGED
|
@@ -8,7 +8,7 @@
|
|
| 8 |
<title>STUDIUS · DAS Studio — Einswarm</title>
|
| 9 |
<link rel="icon" href="assets/einswarm-mascot.webp">
|
| 10 |
<link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
|
| 11 |
-
<link rel="stylesheet" href="style.css?v=
|
| 12 |
</head>
|
| 13 |
<body>
|
| 14 |
<canvas id="gl"></canvas>
|
|
@@ -49,6 +49,6 @@
|
|
| 49 |
|
| 50 |
<a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
|
| 51 |
<noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
|
| 52 |
-
<script type="module" src="app.js?v=
|
| 53 |
</body>
|
| 54 |
</html>
|
|
|
|
| 8 |
<title>STUDIUS · DAS Studio — Einswarm</title>
|
| 9 |
<link rel="icon" href="assets/einswarm-mascot.webp">
|
| 10 |
<link rel="preload" href="fonts/outfit-latin-wght.woff2" as="font" type="font/woff2" crossorigin>
|
| 11 |
+
<link rel="stylesheet" href="style.css?v=66">
|
| 12 |
</head>
|
| 13 |
<body>
|
| 14 |
<canvas id="gl"></canvas>
|
|
|
|
| 49 |
|
| 50 |
<a id="bmc" href="https://www.buymeacoffee.com/2btainment" target="_blank" rel="noopener noreferrer">Buy me a coffee</a>
|
| 51 |
<noscript><p style="color:#f2c94c;padding:2em">STUDIUS braucht JavaScript.</p></noscript>
|
| 52 |
+
<script type="module" src="app.js?v=66"></script>
|
| 53 |
</body>
|
| 54 |
</html>
|
master.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
// Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
|
| 2 |
// (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
|
| 3 |
import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
|
| 4 |
-
import { result, MODULES, esc, setS, keep } from './real.js?v=
|
| 5 |
|
| 6 |
/* ---------- BS.1770 loudness ---------- */
|
| 7 |
function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
|
|
|
|
| 1 |
// Mastering studio (DoD): client-side WebAudio chain EQ → compressor → limiter, loudness normalisation to target LUFS
|
| 2 |
// (ITU-R BS.1770-4 K-weighting + gating, measured offline), live meter, A/B, WAV/MP3 export, save to workspace.
|
| 3 |
import { STUDIOS, onStop, loop, cv } from './widgets.js?v=50';
|
| 4 |
+
import { result, MODULES, esc, setS, keep } from './real.js?v=66';
|
| 5 |
|
| 6 |
/* ---------- BS.1770 loudness ---------- */
|
| 7 |
function biquad(x, b0, b1, b2, a0, a1, a2) { const y = new Float32Array(x.length); b0 /= a0; b1 /= a0; b2 /= a0; a1 /= a0; a2 /= a0; let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
|
server/agents.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""P2.5 agents backend: agents/teams persisted in the user's bucket, real LLM function-calling
|
| 2 |
+
(Inference Providers `tools=` with the user's token; fallback: JSON tool-calls via the allow-listed
|
| 3 |
+
Llama ZeroGPU Space on the user's quota) and a server-side job list with approval gating for
|
| 4 |
+
external/persisting actions. Tokens never leave the server."""
|
| 5 |
+
import json, re, secrets, time, tempfile
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from fastapi import APIRouter, Request, HTTPException
|
| 8 |
+
from huggingface_hub import HfApi, InferenceClient
|
| 9 |
+
|
| 10 |
+
PROVIDER_MODELS = ["meta-llama/Llama-3.3-70B-Instruct", "Qwen/Qwen2.5-72B-Instruct"]
|
| 11 |
+
LLAMA = "huggingface-projects/llama-3.2-3B-Instruct"
|
| 12 |
+
EXTERNAL = {"workspace.save", "avatar.save"} # actions that persist/publish → need approval
|
| 13 |
+
JOBS: dict[str, dict] = {}
|
| 14 |
+
NOPROV: dict[str, float] = {} # token-hash -> until (provider returned 402: skip for a while) # job id -> job (scoped by user)
|
| 15 |
+
ID = re.compile(r"[a-z0-9][a-z0-9-]{0,47}")
|
| 16 |
+
|
| 17 |
+
def slug(s): return re.sub(r"[^a-z0-9]+", "-", (s or "").lower()).strip("-")[:48] or "x" + secrets.token_hex(3)
|
| 18 |
+
|
| 19 |
+
def to_schema(tools): # [{name, desc, params:{k:type}}] -> OpenAI tools
|
| 20 |
+
return [{"type": "function", "function": {"name": t["name"].replace(".", "__"), "description": t.get("desc", "")[:300],
|
| 21 |
+
"parameters": {"type": "object", "properties": {k: {"type": "number" if v == "number" else "string"} for k, v in (t.get("params") or {}).items()},
|
| 22 |
+
"required": list((t.get("params") or {}).keys())}}} for t in tools]
|
| 23 |
+
|
| 24 |
+
def parse_json(txt):
|
| 25 |
+
m = re.search(r"\{[\s\S]*\}", txt or "")
|
| 26 |
+
if not m: return None
|
| 27 |
+
s = m.group(0)
|
| 28 |
+
for end in range(len(s), 0, -1): # tolerate trailing junk
|
| 29 |
+
if s[end - 1] != "}": continue
|
| 30 |
+
try: return json.loads(s[:end])
|
| 31 |
+
except Exception: pass
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
def make_agents_router(session, need, bid, client_for):
|
| 35 |
+
r = APIRouter()
|
| 36 |
+
|
| 37 |
+
def uid(s): return s["user"]["name"]
|
| 38 |
+
|
| 39 |
+
# ---------- agents & teams in the bucket ----------
|
| 40 |
+
def kind_dir(kind):
|
| 41 |
+
if kind not in ("agents", "teams"): raise HTTPException(400, "kind")
|
| 42 |
+
return f".studius/{kind}/"
|
| 43 |
+
|
| 44 |
+
@r.get("/api/crew/{kind}")
|
| 45 |
+
def crew_list(kind: str, req: Request, bucket: str):
|
| 46 |
+
s = need(req); api = HfApi(token=s["token"]); bucket = bid(bucket, s); d = kind_dir(kind)
|
| 47 |
+
try:
|
| 48 |
+
files = [f.path for f in api.list_bucket_tree(bucket, prefix=d.rstrip("/"), recursive=True) if getattr(f, "type", "") == "file" and f.path.endswith(".json")]
|
| 49 |
+
out = []
|
| 50 |
+
with tempfile.TemporaryDirectory() as t:
|
| 51 |
+
api.download_bucket_files(bucket, [(p, f"{t}/{i}.json") for i, p in enumerate(files)])
|
| 52 |
+
for i, _ in enumerate(files):
|
| 53 |
+
try: out.append(json.loads(Path(f"{t}/{i}.json").read_text()))
|
| 54 |
+
except Exception: pass
|
| 55 |
+
return {kind: out}
|
| 56 |
+
except HTTPException: raise
|
| 57 |
+
except Exception as e: raise HTTPException(502, str(e)[:200])
|
| 58 |
+
|
| 59 |
+
@r.post("/api/crew/{kind}")
|
| 60 |
+
async def crew_save(kind: str, req: Request):
|
| 61 |
+
s = need(req); body = await req.json(); api = HfApi(token=s["token"]); bucket = bid(body.get("bucket"), s); d = kind_dir(kind)
|
| 62 |
+
obj = body.get("item") or {}
|
| 63 |
+
obj["id"] = obj.get("id") if ID.fullmatch(str(obj.get("id", ""))) else slug(obj.get("name"))
|
| 64 |
+
obj["name"] = str(obj.get("name", obj["id"]))[:60]; obj["updated"] = int(time.time())
|
| 65 |
+
if kind == "agents":
|
| 66 |
+
obj["modules"] = [m for m in obj.get("modules", []) if re.fullmatch(r"[a-z]{2,20}", str(m))][:12]
|
| 67 |
+
obj["role"] = str(obj.get("role", ""))[:400]; obj["avatar"] = str(obj.get("avatar", ""))[:60]
|
| 68 |
+
else:
|
| 69 |
+
obj["members"] = [m for m in obj.get("members", []) if ID.fullmatch(str(m))][:8]
|
| 70 |
+
try: api.batch_bucket_files(bucket, add=[(json.dumps(obj, indent=1, ensure_ascii=False).encode(), f"{d}{obj['id']}.json")])
|
| 71 |
+
except Exception as e: raise HTTPException(502, str(e)[:200])
|
| 72 |
+
return {"saved": obj}
|
| 73 |
+
|
| 74 |
+
# ---------- LLM function-calling ----------
|
| 75 |
+
def llama(token, prompt):
|
| 76 |
+
from gradio_client import Client # fresh session per step: the Space keeps chat history per session
|
| 77 |
+
c = Client(LLAMA, hf_token=token, verbose=False)
|
| 78 |
+
out = c.predict(prompt, 400, 0.2, 0.9, 50, 1.1, api_name="/generate")
|
| 79 |
+
return out if isinstance(out, str) else json.dumps(out)
|
| 80 |
+
|
| 81 |
+
@r.post("/api/agent/step")
|
| 82 |
+
async def step(req: Request):
|
| 83 |
+
"""One planning step. Body: {task, tools:[{name,desc,params}], history:[{tool,args,result}], system}.
|
| 84 |
+
Returns {call:{tool,args}} or {final:text}, plus via."""
|
| 85 |
+
s = session(req)
|
| 86 |
+
if not s: raise HTTPException(401, "not signed in")
|
| 87 |
+
b = await req.json(); tools = b.get("tools") or []; names = {t["name"] for t in tools}
|
| 88 |
+
hist = b.get("history") or []; system = str(b.get("system") or "")[:2000]; task = str(b.get("task") or "")[:2000]
|
| 89 |
+
if not tools: raise HTTPException(400, "no tools")
|
| 90 |
+
sysmsg = (system + "\n\n" if system else "") + "Du bist ein STUDIUS-Mitarbeiter. Erledige den Auftrag mit den Werkzeugen, Schritt für Schritt. Nutze Ergebnisse vorheriger Schritte (z. B. deren url) als Argumente. Wenn alles erledigt ist, antworte kurz ohne Werkzeug."
|
| 91 |
+
msgs = [{"role": "system", "content": sysmsg}, {"role": "user", "content": task}]
|
| 92 |
+
for i, h in enumerate(hist):
|
| 93 |
+
cid = f"c{i}"
|
| 94 |
+
msgs.append({"role": "assistant", "content": "", "tool_calls": [{"id": cid, "type": "function", "function": {"name": h["tool"].replace(".", "__"), "arguments": json.dumps(h.get("args", {}))}}]})
|
| 95 |
+
msgs.append({"role": "tool", "tool_call_id": cid, "content": json.dumps(h.get("result", {}))[:1500]})
|
| 96 |
+
errs = []; th = str(hash(s["token"]))
|
| 97 |
+
for m in ([] if NOPROV.get(th, 0) > time.time() else PROVIDER_MODELS): # native function-calling (needs Inference Providers credits/PRO)
|
| 98 |
+
try:
|
| 99 |
+
ic = InferenceClient(token=s["token"], timeout=60)
|
| 100 |
+
out = ic.chat_completion(model=m, messages=msgs, tools=to_schema(tools), tool_choice="auto", max_tokens=400)
|
| 101 |
+
msg = out.choices[0].message
|
| 102 |
+
if msg.tool_calls:
|
| 103 |
+
tc = msg.tool_calls[0].function; a = tc.arguments
|
| 104 |
+
a = json.loads(a) if isinstance(a, str) else (a or {})
|
| 105 |
+
name = tc.name.replace("__", ".")
|
| 106 |
+
if name in names: return {"call": {"tool": name, "args": a}, "via": f"tools:{m}"}
|
| 107 |
+
return {"final": msg.content or "", "via": f"tools:{m}"}
|
| 108 |
+
except Exception as e:
|
| 109 |
+
errs.append(f"{m}: {str(e)[:80]}")
|
| 110 |
+
if "402" in str(e): NOPROV[th] = time.time() + 600; break
|
| 111 |
+
# fallback: JSON function-calling via Llama Space (user's ZeroGPU quota)
|
| 112 |
+
tl = "\n".join(f'- {t["name"]}({", ".join(f"{k}: {v}" for k, v in (t.get("params") or {}).items())}): {t.get("desc", "")}' for t in tools)
|
| 113 |
+
done = "\n".join(f'{i+1}. {h["tool"]}({json.dumps(h.get("args", {}), ensure_ascii=False)}) -> {json.dumps(h.get("result", {}), ensure_ascii=False)[:300]}' for i, h in enumerate(hist)) or "(noch nichts)"
|
| 114 |
+
prompt = (f"{sysmsg}\n\nWerkzeuge:\n{tl}\n\nAuftrag: {task}\n\nBisher ausgeführt:\n{done}\n\n"
|
| 115 |
+
'Antworte NUR mit einem JSON-Objekt in einer Zeile. Nächster Werkzeugaufruf: {"tool":"<name>","args":{...}} '
|
| 116 |
+
'oder, wenn der Auftrag vollständig erledigt ist: {"final":"<kurze Zusammenfassung>"}. Rufe kein Werkzeug doppelt mit gleichen Argumenten auf.')
|
| 117 |
+
txt = None
|
| 118 |
+
for k in range(2):
|
| 119 |
+
try: txt = llama(s["token"], prompt); break
|
| 120 |
+
except Exception as e: err = e
|
| 121 |
+
if txt is None: raise HTTPException(502, "LLM nicht erreichbar: " + str(err)[:150])
|
| 122 |
+
j = parse_json(txt) or {}
|
| 123 |
+
for _ in range(2):
|
| 124 |
+
if not (b.get("require_tool") and j.get("tool") not in names): break
|
| 125 |
+
try: j = parse_json(llama(s["token"], prompt + "\nWICHTIG: Du hast noch KEIN Werkzeug benutzt. Antworte NUR mit {\"tool\":\"<eines der Werkzeuge>\",\"args\":{...}} – kein final.")) or j
|
| 126 |
+
except Exception: pass
|
| 127 |
+
if j.get("tool") in names: return {"call": {"tool": j["tool"], "args": j.get("args") or {}}, "via": "json:llama-3.2-3B", "provider_errors": errs}
|
| 128 |
+
if "final" in j: return {"final": str(j["final"]), "via": "json:llama-3.2-3B", "provider_errors": errs}
|
| 129 |
+
return {"final": None, "raw": txt[:300], "via": "json:llama-3.2-3B", "provider_errors": errs}
|
| 130 |
+
|
| 131 |
+
# ---------- server-side job list with approval ----------
|
| 132 |
+
def job_of(s, jid):
|
| 133 |
+
j = JOBS.get(jid)
|
| 134 |
+
if not j or j["user"] != uid(s): raise HTTPException(404, "job")
|
| 135 |
+
return j
|
| 136 |
+
|
| 137 |
+
def pub(j): return {k: v for k, v in j.items() if k != "user"}
|
| 138 |
+
|
| 139 |
+
@r.get("/api/jobs")
|
| 140 |
+
def jobs(req: Request):
|
| 141 |
+
s = need(req); return {"jobs": [pub(j) for j in sorted(JOBS.values(), key=lambda x: -x["created"]) if j["user"] == uid(s)][:50]}
|
| 142 |
+
|
| 143 |
+
@r.post("/api/jobs")
|
| 144 |
+
async def job_new(req: Request):
|
| 145 |
+
s = need(req); b = await req.json(); jid = "j" + secrets.token_hex(5)
|
| 146 |
+
JOBS[jid] = {"id": jid, "user": uid(s), "task": str(b.get("task", ""))[:500], "agent": str(b.get("agent", ""))[:60], "team": str(b.get("team", ""))[:60],
|
| 147 |
+
"state": "running", "steps": [], "created": int(time.time())}
|
| 148 |
+
return pub(JOBS[jid])
|
| 149 |
+
|
| 150 |
+
@r.post("/api/jobs/{jid}/step")
|
| 151 |
+
async def job_step(jid: str, req: Request):
|
| 152 |
+
"""Register a tool call. External actions are held as 'awaiting_approval' until approved."""
|
| 153 |
+
s = need(req); j = job_of(s, jid); b = await req.json(); tool = str(b.get("tool", ""))[:60]
|
| 154 |
+
st = {"n": len(j["steps"]) + 1, "tool": tool, "agent": str(b.get("agent", ""))[:60], "args": b.get("args") or {}, "external": tool in EXTERNAL,
|
| 155 |
+
"state": "awaiting_approval" if tool in EXTERNAL else "approved", "t": int(time.time())}
|
| 156 |
+
j["steps"].append(st)
|
| 157 |
+
if st["external"]: j["state"] = "awaiting_approval"
|
| 158 |
+
return {"step": st, "job": pub(j)}
|
| 159 |
+
|
| 160 |
+
@r.post("/api/jobs/{jid}/steps/{n}/{decision}")
|
| 161 |
+
def job_decide(jid: str, n: int, decision: str, req: Request):
|
| 162 |
+
s = need(req); j = job_of(s, jid)
|
| 163 |
+
if decision not in ("approve", "reject", "done", "error"): raise HTTPException(400, "decision")
|
| 164 |
+
if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
|
| 165 |
+
st = j["steps"][n - 1]
|
| 166 |
+
if decision in ("approve", "reject"):
|
| 167 |
+
if st["state"] != "awaiting_approval": raise HTTPException(409, "not awaiting approval")
|
| 168 |
+
st["state"] = "approved" if decision == "approve" else "rejected"; st["decided"] = int(time.time())
|
| 169 |
+
j["state"] = "running" if decision == "approve" else "rejected"
|
| 170 |
+
else:
|
| 171 |
+
if st["state"] != "approved": raise HTTPException(409, "step not approved")
|
| 172 |
+
st["state"] = decision
|
| 173 |
+
return {"step": st, "job": pub(j)}
|
| 174 |
+
|
| 175 |
+
@r.get("/api/jobs/{jid}/steps/{n}")
|
| 176 |
+
def job_poll(jid: str, n: int, req: Request):
|
| 177 |
+
s = need(req); j = job_of(s, jid)
|
| 178 |
+
if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
|
| 179 |
+
return {"step": j["steps"][n - 1], "job": pub(j)}
|
| 180 |
+
|
| 181 |
+
@r.post("/api/jobs/{jid}/finish")
|
| 182 |
+
async def job_finish(jid: str, req: Request):
|
| 183 |
+
s = need(req); j = job_of(s, jid); b = await req.json()
|
| 184 |
+
j["state"] = b.get("state") if b.get("state") in ("done", "error", "rejected") else "done"; j["summary"] = str(b.get("summary", ""))[:1000]; j["finished"] = int(time.time())
|
| 185 |
+
return pub(j)
|
| 186 |
+
return r
|
server/main.py
CHANGED
|
@@ -7,7 +7,8 @@ from fastapi import FastAPI, Request, UploadFile, File, Form, HTTPException
|
|
| 7 |
from fastapi.responses import RedirectResponse, JSONResponse, FileResponse, Response, StreamingResponse
|
| 8 |
from fastapi.staticfiles import StaticFiles
|
| 9 |
from huggingface_hub import HfApi
|
| 10 |
-
from .infer import make_router, tmp_path
|
|
|
|
| 11 |
|
| 12 |
ROOT = Path(__file__).resolve().parent.parent
|
| 13 |
HF = os.getenv("OPENID_PROVIDER_URL", "https://huggingface.co").rstrip("/")
|
|
@@ -279,4 +280,5 @@ async def nocache(req, call_next):
|
|
| 279 |
return r
|
| 280 |
|
| 281 |
app.include_router(make_router(session))
|
|
|
|
| 282 |
app.mount("/", StaticFiles(directory=ROOT, html=True), name="static")
|
|
|
|
| 7 |
from fastapi.responses import RedirectResponse, JSONResponse, FileResponse, Response, StreamingResponse
|
| 8 |
from fastapi.staticfiles import StaticFiles
|
| 9 |
from huggingface_hub import HfApi
|
| 10 |
+
from .infer import make_router, tmp_path, client as gr_client
|
| 11 |
+
from .agents import make_agents_router
|
| 12 |
|
| 13 |
ROOT = Path(__file__).resolve().parent.parent
|
| 14 |
HF = os.getenv("OPENID_PROVIDER_URL", "https://huggingface.co").rstrip("/")
|
|
|
|
| 280 |
return r
|
| 281 |
|
| 282 |
app.include_router(make_router(session))
|
| 283 |
+
app.include_router(make_agents_router(session, need, bid, gr_client))
|
| 284 |
app.mount("/", StaticFiles(directory=ROOT, html=True), name="static")
|
style.css
CHANGED
|
@@ -221,3 +221,6 @@ body:not(.live) #beebtn{display:none}
|
|
| 221 |
#pop .avref{width:96px;height:96px;object-fit:cover;border:1px solid var(--line2);border-radius:4px;margin-top:6px}#pop .avout{width:100%;margin-top:6px;border-radius:4px}
|
| 222 |
#pop .speak{margin:2px 0 6px}#pop .chat audio{width:100%;height:32px}
|
| 223 |
.vers{margin-top:8px;font-size:12px}.vers .vr{display:flex;gap:6px;align-items:center;padding:2px 0}.vers .vl b{display:block;margin:6px 0 2px}
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
#pop .avref{width:96px;height:96px;object-fit:cover;border:1px solid var(--line2);border-radius:4px;margin-top:6px}#pop .avout{width:100%;margin-top:6px;border-radius:4px}
|
| 222 |
#pop .speak{margin:2px 0 6px}#pop .chat audio{width:100%;height:32px}
|
| 223 |
.vers{margin-top:8px;font-size:12px}.vers .vr{display:flex;gap:6px;align-items:center;padding:2px 0}.vers .vl b{display:block;margin:6px 0 2px}
|
| 224 |
+
#bees{height:min(560px,76vh)}.agrow{display:flex;gap:6px;margin-bottom:4px}.agrow .role{flex:1;min-width:0}.tm>div{display:flex;gap:4px;margin:3px 0}.tm select{flex:1}
|
| 225 |
+
.jw{border-top:1px solid var(--line);padding:4px 12px;max-height:120px;overflow:auto}.jw summary{cursor:pointer;color:var(--gold);font-size:10.5px}.job{padding:2px 0;font-size:10.5px}.job small{display:block;opacity:.7}
|
| 226 |
+
.bm .row{display:flex;gap:6px;margin-top:6px}
|
workspace.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 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=
|
|
|
|
| 3 |
const $ = (s, r = document) => r.querySelector(s);
|
| 4 |
const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
| 5 |
const ST = () => window.__studius.STUDIOS;
|
|
@@ -13,11 +14,11 @@ const form = (o) => { const f = new FormData(); Object.entries(o).forEach(([k, v
|
|
| 13 |
$('#hud .hudr').insertAdjacentHTML('afterbegin', `<a id="signin" class="hbtn" href="/login" target="_blank" rel="noopener" hidden>🤗<span class="t"> Sign in with Hugging Face</span><span class="s"> Login</span></a><button id="wsbtn" class="hbtn" aria-label="Workspace öffnen" hidden>▤<span class="t"> Workspace</span></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; }
|
|
@@ -87,34 +88,94 @@ function actionRow(asset) {
|
|
| 87 |
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)); });
|
| 88 |
window.__bus = { sendTo, saveAsset };
|
| 89 |
|
| 90 |
-
/* bee agents */
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
let agents; try { agents = JSON.parse(localStorage.getItem('studius-agents')) || DEF; } catch (e) { agents = DEF; }
|
| 93 |
-
let
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
const blog = () => $('#bees .blog');
|
| 99 |
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; }
|
| 100 |
-
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 })));
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
$('#bsend').onclick = runAgent; $('#bin').addEventListener('keydown', e => { if (e.key === 'Enter') runAgent(); });
|
|
|
|
| 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=66';
|
| 3 |
+
import { Avatars } from './avatar.js?v=66';
|
| 4 |
const $ = (s, r = document) => r.querySelector(s);
|
| 5 |
const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
| 6 |
const ST = () => window.__studius.STUDIOS;
|
|
|
|
| 14 |
$('#hud .hudr').insertAdjacentHTML('afterbegin', `<a id="signin" class="hbtn" href="/login" target="_blank" rel="noopener" hidden>🤗<span class="t"> Sign in with Hugging Face</span><span class="s"> Login</span></a><button id="wsbtn" class="hbtn" aria-label="Workspace öffnen" hidden>▤<span class="t"> Workspace</span></button><span id="who" hidden></span>`);
|
| 15 |
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>
|
| 16 |
<button id="beebtn" aria-label="Bee-Agenten öffnen" title="Bee-Agenten">🐝<span>Agents</span></button>
|
| 17 |
+
<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><details class="jw"><summary>Jobs (Server)</summary><div class="jobs"></div></details><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>`);
|
| 18 |
['#wsp', '#bees'].forEach(s => $(s).addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') $(s).hidden = true; }));
|
| 19 |
$('#wsp .x').onclick = () => $('#wsp').hidden = true; $('#bees .x').onclick = () => $('#bees').hidden = true;
|
| 20 |
$('#wsbtn').onclick = () => { $('#wsp').hidden = !$('#wsp').hidden; if (!$('#wsp').hidden) renderWS(); };
|
| 21 |
+
$('#beebtn').onclick = () => { $('#bees').hidden = !$('#bees').hidden; if (!$('#bees').hidden) { renderAgents(true).then(renderJobs); $('#bin').focus(); } };
|
| 22 |
|
| 23 |
async function refreshMe() {
|
| 24 |
try { W.me = await api('/api/me'); W.backend = true; } catch (e) { W.backend = false; W.me = null; }
|
|
|
|
| 88 |
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)); });
|
| 89 |
window.__bus = { sendTo, saveAsset };
|
| 90 |
|
| 91 |
+
/* bee agents: Mitarbeiter-Team (agents + teams in the bucket), real LLM function-calling (server), server job list with approval */
|
| 92 |
+
MODULES.workspace = { id: 'workspace', name: 'Workspace', backend: 'HF Storage Bucket', inputs: [{ name: 'url', type: 'asset-url' }], outputs: [{ kind: 'file' }],
|
| 93 |
+
actions: {
|
| 94 |
+
save: { desc: 'SPEICHERT ein Ergebnis (url aus der Übergabe) dauerhaft im Workspace. Benutze dies zum Speichern/Archivieren. Braucht Freigabe durch den Menschen', params: { url: 'string' }, external: true, run: async ({ url: u }, on = {}) => { const a = on.assetFor?.(u); if (!a) throw new Error('kein Ergebnis zu dieser url'); const r = await saveAsset(a); return { kind: 'text', text: 'Gespeichert: ' + r.path, saved: r.path, name: 'saved.txt', studio: 'workspace' }; } },
|
| 95 |
+
list: { desc: 'Zeigt nur vorhandene Dateien an (prefix, sonst leer lassen). Speichert NICHTS', params: { prefix: 'string' }, run: async ({ prefix = '' } = {}) => { const r = await api('/api/ws/list?bucket=' + encodeURIComponent(W.bucket) + '&prefix=' + encodeURIComponent(prefix || '')); const t = r.files.slice(0, 20).map(f => f.path).join('\n'); return { kind: 'text', text: t || '(leer)', name: 'list.txt', studio: 'workspace' }; } },
|
| 96 |
+
} };
|
| 97 |
+
const DEF = [{ id: 'demo', name: 'Demo-Biene', role: 'Allrounder', modules: ['chat', 'image'] }];
|
| 98 |
let agents; try { agents = JSON.parse(localStorage.getItem('studius-agents')) || DEF; } catch (e) { agents = DEF; }
|
| 99 |
+
let teams = []; try { teams = JSON.parse(localStorage.getItem('studius-teams')) || []; } catch (e) {}
|
| 100 |
+
let cur = agents[0].id; const cloud = () => !!(W.backend && W.me?.signedIn && W.bucket);
|
| 101 |
+
const saveAg = async (a) => { localStorage.setItem('studius-agents', JSON.stringify(agents)); if (a && cloud()) { try { await api('/api/crew/agents', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bucket: W.bucket, item: a }) }); window.__agSaved = a.id; } catch (e) { say('bee', '⚠ ' + esc(e.message)); } } };
|
| 102 |
+
const saveTeam = async (t) => { localStorage.setItem('studius-teams', JSON.stringify(teams)); if (cloud()) { try { await api('/api/crew/teams', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bucket: W.bucket, item: t }) }); window.__teamSaved = t.id; } catch (e) { say('bee', '⚠ ' + esc(e.message)); } } };
|
| 103 |
+
async function loadCrew() { if (!cloud()) return; try { const [A, T] = await Promise.all([api('/api/crew/agents?bucket=' + encodeURIComponent(W.bucket)), api('/api/crew/teams?bucket=' + encodeURIComponent(W.bucket))]);
|
| 104 |
+
if (A.agents.length) { const ids = new Set(A.agents.map(x => x.id)); agents = [...A.agents, ...agents.filter(x => !ids.has(x.id) && x.id !== 'demo')]; if (!agents.some(x => x.id === cur)) cur = agents[0].id; }
|
| 105 |
+
if (T.teams.length) teams = T.teams; window.__crew = { agents: agents.map(a => a.id), teams: teams.map(t => t.id) }; } catch (e) {} }
|
| 106 |
+
const slugify = (s) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'a' + Date.now();
|
| 107 |
+
let avList = []; const loadAv = async () => { try { avList = await Avatars.list(); } catch (e) { avList = []; } };
|
| 108 |
+
async function renderAgents(reload) { if (reload) { await loadCrew(); await loadAv(); }
|
| 109 |
+
const sel = $('#agsel'); sel.innerHTML = agents.map(a => `<option value="${a.id}">🐝 ${esc(a.name)}</option>`).join('') + teams.map(t => `<option value="team:${t.id}">👥 ${esc(t.name)}</option>`).join('') + '<option value="+">+ Neuer Agent</option><option value="+t">+ Neues Team</option>'; sel.value = cur;
|
| 110 |
+
sel.onchange = async () => { if (sel.value === '+') { const n = prompt('Name des Mitarbeiters?'); if (n) { const a = { id: slugify(n), name: n.slice(0, 40), role: '', modules: ['chat'], avatar: '' }; agents.push(a); cur = a.id; await saveAg(a); } }
|
| 111 |
+
else if (sel.value === '+t') { const n = prompt('Name des Teams?'); if (n) { const t = { id: slugify(n), name: n.slice(0, 40), members: agents.slice(0, 2).map(a => a.id) }; teams.push(t); cur = 'team:' + t.id; await saveTeam(t); } }
|
| 112 |
+
else cur = sel.value; renderAgents(); };
|
| 113 |
+
const cfg = $('#bees .agcfg');
|
| 114 |
+
if (cur.startsWith('team:')) { const t = teams.find(x => 'team:' + x.id === cur); if (!t) { cur = agents[0].id; return renderAgents(); }
|
| 115 |
+
cfg.innerHTML = `<small>Team-Reihenfolge (Übergabe von oben nach unten):</small><div class="tm">${t.members.map((m, i) => `<div><select data-m="${i}" aria-label="Mitglied ${i + 1}">${agents.map(a => `<option value="${a.id}" ${a.id === m ? 'selected' : ''}>${esc(a.name)}</option>`).join('')}</select><button class="ib" data-rm="${i}" aria-label="Entfernen">✕</button></div>`).join('')}</div><button class="ib" data-add aria-label="Mitglied hinzufügen">+ Mitglied</button>`;
|
| 116 |
+
cfg.onchange = (e) => { const s = e.target.closest('[data-m]'); if (s) { t.members[+s.dataset.m] = s.value; saveTeam(t); } };
|
| 117 |
+
cfg.onclick = (e) => { if (e.target.closest('[data-add]')) { t.members.push(agents[0].id); saveTeam(t); renderAgents(); } const r = e.target.closest('[data-rm]'); if (r) { t.members.splice(+r.dataset.rm, 1); saveTeam(t); renderAgents(); } };
|
| 118 |
+
return; }
|
| 119 |
+
const a = agents.find(x => x.id === cur) || agents[0];
|
| 120 |
+
cfg.innerHTML = `<div class="agrow"><input class="role" aria-label="Rolle" placeholder="Rolle, z. B. Mastering-Engineer" value="${esc(a.role || '')}"><select class="agav" aria-label="Avatar"><option value="">ohne Avatar</option>${avList.map(v => `<option value="${esc(v.id)}" ${v.id === a.avatar ? 'selected' : ''}>👤 ${esc(v.name)}</option>`).join('')}</select></div><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('');
|
| 121 |
+
cfg.onchange = (e) => { const t = e.target; if (t.classList.contains('role')) a.role = t.value.slice(0, 300); else if (t.classList.contains('agav')) a.avatar = t.value; else a.modules = t.checked ? [...new Set([...a.modules, t.value])] : a.modules.filter(m => m !== t.value); saveAg(a); };
|
| 122 |
+
cfg.onclick = null; }
|
| 123 |
const blog = () => $('#bees .blog');
|
| 124 |
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; }
|
| 125 |
+
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, external: !!v.external })));
|
| 126 |
+
const jpost = (u, b) => api(u, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(b || {}) });
|
| 127 |
+
const show = (res) => res.kind === 'image' ? `<img alt="" src="${esc(res.url)}">` : res.kind === 'audio' ? `<audio controls src="${esc(res.url)}"></audio>` : `<p>${esc((res.text || '').slice(0, 600))}</p>`;
|
| 128 |
+
function approval(job, st, box) { return new Promise((ok) => {
|
| 129 |
+
box.innerHTML = `<b>Freigabe nötig</b> · <code>${esc(st.tool)}</code><br><small>${esc(JSON.stringify(st.args).slice(0, 200))}</small><div class="row"><button class="btn ap">Freigeben</button><button class="btn alt rj">Ablehnen</button></div>`;
|
| 130 |
+
window.__approval = { job: job.id, n: st.n, tool: st.tool };
|
| 131 |
+
const go = async (d) => { box.querySelectorAll('button').forEach(b => b.disabled = true); try { const r = await jpost(`/api/jobs/${job.id}/steps/${st.n}/${d}`); ok(r.step.state === 'approved'); } catch (e) { ok(false); } };
|
| 132 |
+
box.querySelector('.ap').onclick = () => go('approve'); box.querySelector('.rj').onclick = () => go('reject'); }); }
|
| 133 |
+
async function work(job, a, task, shared, maxSteps) { // one agent's function-calling loop; shared = {history, assets}
|
| 134 |
+
const tools = toolsOf(a); if (!tools.length) { say('bee', `${esc(a.name)}: keine Module zugewiesen.`); return null; }
|
| 135 |
+
let system = a.role ? `Deine Rolle: ${a.role}.` : ''; const av = a.avatar && avList.find(v => v.id === a.avatar); if (av) system = Avatars.persona(av) + ' ' + system;
|
| 136 |
+
let final = null;
|
| 137 |
+
for (let i = 0; i < maxSteps; i++) {
|
| 138 |
+
const box = say('bee', `<b>${esc(a.name)}</b> <span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> plant…`);
|
| 139 |
+
const p = await jpost('/api/agent/step', { task, system, tools: tools.map(({ name, desc, params }) => ({ name, desc, params })), history: shared.history, require_tool: i === 0 && !(shared.team === false && a.modules.includes('chat')) });
|
| 140 |
+
window.__agent = { ...window.__agent, via: p.via, state: 'plan' };
|
| 141 |
+
if (!p.call) { final = p.final || 'fertig';
|
| 142 |
+
// solo chat agent answering directly is fine – treat final as a chat result
|
| 143 |
+
if (!shared.history.length && (a.modules.includes('chat') || a.modules.includes('avatar')) && final && final !== 'fertig') {
|
| 144 |
+
const res = { kind: 'text', text: final, name: 'agent-' + Date.now() + '.txt', studio: 'chat' }; shared.assets.push(res);
|
| 145 |
+
shared.history.push({ tool: 'chat.reply', args: { prompt: task }, result: { kind: 'text', text: final.slice(0, 300) } });
|
| 146 |
+
box.innerHTML = `<b>${esc(a.name)}</b> · <code>chat.reply</code> ✔` + show(res) + ` <small>(${esc(p.via)})</small>`;
|
| 147 |
+
} else box.innerHTML = `<b>${esc(a.name)}</b> ✔ ${esc(final)} <small>(${esc(p.via)})</small>`;
|
| 148 |
+
break; }
|
| 149 |
+
const t = tools.find(x => x.name === p.call.tool); const args = { ...p.call.args };
|
| 150 |
+
const last = shared.assets.at(-1); // resolve bad/missing url args to the latest result (hand-off)
|
| 151 |
+
for (const k of ['url', 'source']) if (k in (t.params || {}) && !shared.assets.some(x => x.url === args[k]) && last) args[k] = last.url;
|
| 152 |
+
if (t.name === 'master.master' && !args.source && last) args.source = last.url;
|
| 153 |
+
if (shared.history.some(h => h.tool === t.name && JSON.stringify(h.args) === JSON.stringify(args))) { final = 'fertig'; box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; break; }
|
| 154 |
+
const { step } = await jpost(`/api/jobs/${job.id}/step`, { tool: t.name, args, agent: a.id });
|
| 155 |
+
if (step.state === 'awaiting_approval') { const okd = await approval(job, step, box); if (!okd) { box.innerHTML = `<b>${esc(a.name)}</b> ✋ <code>${esc(t.name)}</code> abgelehnt – nichts ausgeführt.`; shared.history.push({ tool: t.name, args, result: { rejected: true } }); return 'abgelehnt'; } }
|
| 156 |
+
box.innerHTML = `<b>${esc(a.name)}</b> → <code>${esc(t.name)}</code> <small>(${esc(p.via)})</small> <small class="s"></small>`; window.__agent = { ...window.__agent, state: 'run', tool: t.name };
|
| 157 |
+
try { const res = await t.run(args, { status: m => { const s = box.querySelector('.s'); if (s) s.textContent = m.stage + (m.position != null ? ' #' + (m.position + 1) : ''); }, data: () => {}, assetFor: (u) => shared.assets.find(x => x.url === u) || shared.assets.at(-1) });
|
| 158 |
+
if (res.url) shared.assets.push(res); shared.history.push({ tool: t.name, args, result: { kind: res.kind, url: res.url, text: (res.text || '').slice(0, 300) } });
|
| 159 |
+
box.innerHTML = `<b>${esc(a.name)}</b> · <code>${esc(t.name)}</code> ✔` + show(res); await jpost(`/api/jobs/${job.id}/steps/${step.n}/done`);
|
| 160 |
+
if (res.url) window.dispatchEvent(new CustomEvent('studius-result', { detail: { el: box.lastElementChild, asset: res } }));
|
| 161 |
+
} catch (e) { box.innerHTML = `<b>${esc(a.name)}</b> ⚠ ${esc(t.name)}: ${esc(e.message)}`; await jpost(`/api/jobs/${job.id}/steps/${step.n}/error`).catch(() => {}); shared.history.push({ tool: t.name, args, result: { error: e.message } }); }
|
| 162 |
+
}
|
| 163 |
+
return final; }
|
| 164 |
+
async function runAgent() { const inp = $('#bin'), task = inp.value.trim(); if (!task) return; inp.value = '';
|
| 165 |
+
if (!W.me?.signedIn) { say('bee', 'Bitte zuerst mit Hugging Face anmelden – Agenten planen serverseitig mit deiner HF-Quota.'); return; }
|
| 166 |
+
const team = cur.startsWith('team:') ? teams.find(t => 'team:' + t.id === cur) : null; const crew = team ? team.members.map(m => agents.find(a => a.id === m)).filter(Boolean) : [agents.find(x => x.id === cur)];
|
| 167 |
+
say('me', esc(task)); window.__agent = { task, state: 'plan', team: team?.id };
|
| 168 |
+
const job = await jpost('/api/jobs', { task, agent: team ? '' : crew[0].id, team: team?.id || '' }); window.__agent.job = job.id;
|
| 169 |
+
const shared = { history: [], assets: [], team: !!team }; let sum = '';
|
| 170 |
+
try { for (const [i, a] of crew.entries()) {
|
| 171 |
+
const sub = team ? `${task}\n\n(Du bist Mitglied ${i + 1}/${crew.length} im Team „${team.name}“. Dein Teil: ${a.role || 'siehe Werkzeuge'}. Erledige NUR deinen Teil mit deinen Werkzeugen${shared.assets.length ? '; Übergabe vom Vorgänger: ' + shared.assets.at(-1).url : ''}. Dann antworte ohne Werkzeug.)` : task;
|
| 172 |
+
if (team && i) say('bee', `↪ Übergabe an <b>${esc(a.name)}</b>`);
|
| 173 |
+
const r = await work(job, a, sub, shared, team ? 2 : 4); sum += `${a.name}: ${r || '-'}\n`; if (r === 'abgelehnt') break; }
|
| 174 |
+
const st = shared.history.some(h => h.result?.rejected) ? 'rejected' : 'done';
|
| 175 |
+
await jpost(`/api/jobs/${job.id}/finish`, { state: st, summary: sum });
|
| 176 |
+
window.__agent = { ...window.__agent, state: 'done', steps: shared.history.map(h => h.tool), kinds: shared.history.map(h => h.result?.kind || (h.result?.rejected ? 'rejected' : h.result?.error ? 'error' : '')), url: shared.assets.at(-1)?.url, text: shared.history.at(-1)?.result?.text };
|
| 177 |
+
} catch (e) { say('bee', '⚠ ' + esc(e.message)); window.__agent = { ...window.__agent, state: 'error', err: e.message }; jpost(`/api/jobs/${job.id}/finish`, { state: 'error', summary: e.message }).catch(() => {}); }
|
| 178 |
+
renderJobs(); }
|
| 179 |
+
async function renderJobs() { const el = $('#bees .jobs'); if (!el || !W.me?.signedIn) return; try { const { jobs } = await api('/api/jobs'); window.__jobs = jobs;
|
| 180 |
+
el.innerHTML = jobs.slice(0, 8).map(j => `<div class="job"><b>${{ done: '✔', running: '⏳', awaiting_approval: '✋', rejected: '⛔', error: '⚠' }[j.state] || '·'}</b> ${esc(j.task.slice(0, 50))} <small>${j.steps.map(s => esc(s.tool) + (s.external ? '🔒' : '') + ':' + s.state).join(' → ')}</small></div>`).join('') || '<small class="mut">Noch keine Jobs.</small>'; } catch (e) {} }
|
| 181 |
$('#bsend').onclick = runAgent; $('#bin').addEventListener('keydown', e => { if (e.key === 'Enter') runAgent(); });
|