2Btainment commited on
Commit
450c3f0
·
verified ·
1 Parent(s): e009425

P4.2: resumable jobs

Browse files
Files changed (9) hide show
  1. app.js +6 -6
  2. avatar.js +1 -1
  3. index.html +2 -2
  4. master.js +1 -1
  5. server/agents.py +23 -2
  6. server/infer.py +10 -4
  7. server/main.py +1 -1
  8. video.js +2 -2
  9. workspace.js +35 -15
app.js CHANGED
@@ -1,11 +1,11 @@
1
  import * as THREE from './vendor/three.module.min.js';
2
  import { STUDIOS, stopLoops } from './widgets.js?v=50';
3
- import './real.js?v=85';
4
- import './avatar.js?v=85';
5
- import './master.js?v=85';
6
- import './video.js?v=85';
7
- import './workspace.js?v=85';
8
- import { icon } from './icons.js?v=85';
9
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
10
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
11
  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=87';
4
+ import './avatar.js?v=87';
5
+ import './master.js?v=87';
6
+ import './video.js?v=87';
7
+ import './workspace.js?v=87';
8
+ import { icon } from './icons.js?v=87';
9
  import { RoomEnvironment } from './vendor/addons/environments/RoomEnvironment.js';
10
  import { EffectComposer } from './vendor/addons/postprocessing/EffectComposer.js';
11
  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=85';
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=87';
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=85">
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=85"></script>
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=87">
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=87"></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=85';
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=87';
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 CHANGED
@@ -238,8 +238,10 @@ def make_agents_router(session, need, bid, client_for):
238
  return {"step": st, "job": save(s, j)}
239
 
240
  @r.post("/api/jobs/{jid}/steps/{n}/{decision}")
241
- def job_decide(jid: str, n: int, decision: str, req: Request, bucket: str = ""):
242
- s = need(req); j = job_of(s, jid, bucket)
 
 
243
  if decision not in ("approve", "reject", "done", "error"): raise HTTPException(400, "decision")
244
  if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
245
  st = j["steps"][n - 1]
@@ -250,6 +252,7 @@ def make_agents_router(session, need, bid, client_for):
250
  else:
251
  if st["state"] != "approved": raise HTTPException(409, "step not approved")
252
  st["state"] = decision; st["finished"] = int(time.time())
 
253
  return {"step": st, "job": save(s, j)}
254
 
255
  @r.get("/api/jobs/{jid}/steps/{n}")
@@ -258,6 +261,24 @@ def make_agents_router(session, need, bid, client_for):
258
  if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
259
  return {"step": j["steps"][n - 1], "job": pub(j)}
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  @r.post("/api/jobs/{jid}/finish")
262
  async def job_finish(jid: str, req: Request):
263
  b = await req.json(); s = need(req); j = job_of(s, jid, b.get("bucket"))
 
238
  return {"step": st, "job": save(s, j)}
239
 
240
  @r.post("/api/jobs/{jid}/steps/{n}/{decision}")
241
+ async def job_decide(jid: str, n: int, decision: str, req: Request, bucket: str = ""):
242
+ try: body = await req.json()
243
+ except Exception: body = {}
244
+ s = need(req); j = job_of(s, jid, bucket or body.get("bucket"))
245
  if decision not in ("approve", "reject", "done", "error"): raise HTTPException(400, "decision")
246
  if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
247
  st = j["steps"][n - 1]
 
252
  else:
253
  if st["state"] != "approved": raise HTTPException(409, "step not approved")
254
  st["state"] = decision; st["finished"] = int(time.time())
255
+ if isinstance(body.get("result"), dict): st["result"] = {k: (v[:600] if isinstance(v, str) else v) for k, v in body["result"].items() if k in ("kind", "url", "path", "text", "name", "error")}
256
  return {"step": st, "job": save(s, j)}
257
 
258
  @r.get("/api/jobs/{jid}/steps/{n}")
 
261
  if not 0 < n <= len(j["steps"]): raise HTTPException(404, "step")
262
  return {"step": j["steps"][n - 1], "job": pub(j)}
263
 
264
+ @r.post("/api/jobs/{jid}/cursor")
265
+ async def job_cursor(jid: str, req: Request):
266
+ """Team progress pointer: which member is working (for resume)."""
267
+ b = await req.json(); s = need(req); j = job_of(s, jid, b.get("bucket"))
268
+ j["cursor"] = {"member": int(b.get("member", 0)), "agent": str(b.get("agent", ""))[:60]}
269
+ if isinstance(b.get("members"), list): j["members"] = [str(m)[:60] for m in b["members"]][:8]
270
+ return save(s, j)
271
+
272
+ @r.post("/api/jobs/{jid}/resume")
273
+ async def job_resume(jid: str, req: Request):
274
+ """Resume an interrupted/errored job: completed steps are kept, unfinished ones are superseded."""
275
+ b = await req.json(); s = need(req); j = job_of(s, jid, b.get("bucket"))
276
+ if j["state"] not in ("interrupted", "error", "running"): raise HTTPException(409, f"job is {j['state']}")
277
+ for st in j["steps"]:
278
+ if st["state"] in ("awaiting_approval", "approved"): st["state"] = "superseded"
279
+ j["state"] = "running"; j["resumed"] = j.get("resumed", 0) + 1; j.pop("finished", None)
280
+ return save(s, j)
281
+
282
  @r.post("/api/jobs/{jid}/finish")
283
  async def job_finish(jid: str, req: Request):
284
  b = await req.json(); s = need(req); j = job_of(s, jid, b.get("bucket"))
server/infer.py CHANGED
@@ -35,7 +35,13 @@ def tmp_put(src: str) -> str:
35
  def tmp_path(url: str):
36
  try: _, _, _, i, _ = url.split("/", 4)
37
  except ValueError: return None
38
- v = TMP.get(i); return v[0] if v and v[1] > time.time() else None
 
 
 
 
 
 
39
 
40
  def client(space, token):
41
  k = (space, token); c = CLIENTS.get(k)
@@ -107,7 +113,7 @@ def make_router(session):
107
 
108
  @router.get("/api/tmp/{i}/{name}")
109
  def tmp_file(i: str, name: str):
110
- v = TMP.get(i)
111
- if not v or v[1] < time.time() or Path(v[0]).name != name: raise HTTPException(404)
112
- return FileResponse(v[0], media_type=mimetypes.guess_type(name)[0] or "application/octet-stream", headers={"Cache-Control": "private, max-age=3600"})
113
  return router
 
35
  def tmp_path(url: str):
36
  try: _, _, _, i, _ = url.split("/", 4)
37
  except ValueError: return None
38
+ v = TMP.get(i)
39
+ if not v and i and "/" not in i and ".." not in i: # survive process restarts: re-index from disk (< 1 h old)
40
+ d = TMPDIR / i
41
+ if d.is_dir():
42
+ fs = [f for f in d.iterdir() if f.is_file()]
43
+ if fs and fs[0].stat().st_mtime + 3600 > time.time(): TMP[i] = v = (str(fs[0]), fs[0].stat().st_mtime + 3600)
44
+ return v[0] if v and v[1] > time.time() else None
45
 
46
  def client(space, token):
47
  k = (space, token); c = CLIENTS.get(k)
 
113
 
114
  @router.get("/api/tmp/{i}/{name}")
115
  def tmp_file(i: str, name: str):
116
+ p = tmp_path(f"/api/tmp/{i}/{name}")
117
+ if not p or Path(p).name != name: raise HTTPException(404)
118
+ return FileResponse(p, media_type=mimetypes.guess_type(name)[0] or "application/octet-stream", headers={"Cache-Control": "private, max-age=3600"})
119
  return router
server/main.py CHANGED
@@ -299,7 +299,7 @@ async def transcode(req: Request, file: UploadFile = File(...), name: str = Form
299
  Path(src).write_bytes(data)
300
  cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?",
301
  "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2:out_range=tv,fps=30,format=yuv420p", "-pix_fmt", "yuv420p", "-color_range", "tv", "-c:v", "libx264", "-profile:v", "high", "-level", "4.1", "-preset", "veryfast", "-crf", "20",
302
- "-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-ac", "2", "-movflags", "+faststart", out]
303
  p = await asyncio.to_thread(subprocess.run, cmd, capture_output=True, text=True, timeout=600)
304
  if p.returncode != 0 or not os.path.exists(out): shutil.rmtree(d, ignore_errors=True); raise HTTPException(422, "ffmpeg: " + (p.stderr or "failed")[-300:])
305
  pr = await asyncio.to_thread(subprocess.run, ["ffprobe", "-v", "error", "-show_entries", "stream=codec_name,codec_type,width,height,profile,pix_fmt:format=duration", "-of", "json", out], capture_output=True, text=True)
 
299
  Path(src).write_bytes(data)
300
  cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?",
301
  "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2:out_range=tv,fps=30,format=yuv420p", "-pix_fmt", "yuv420p", "-color_range", "tv", "-c:v", "libx264", "-profile:v", "high", "-level", "4.1", "-preset", "veryfast", "-crf", "20",
302
+ "-c:a", "aac", "-b:a", "160k", "-ar", "48000", "-ac", "2", "-shortest", "-movflags", "+faststart", out]
303
  p = await asyncio.to_thread(subprocess.run, cmd, capture_output=True, text=True, timeout=600)
304
  if p.returncode != 0 or not os.path.exists(out): shutil.rmtree(d, ignore_errors=True); raise HTTPException(422, "ffmpeg: " + (p.stderr or "failed")[-300:])
305
  pr = await asyncio.to_thread(subprocess.run, ["ffprobe", "-v", "error", "-show_entries", "stream=codec_name,codec_type,width,height,profile,pix_fmt:format=duration", "-of", "json", out], capture_output=True, text=True)
video.js CHANGED
@@ -1,7 +1,7 @@
1
  // STUDIUS P3.4: Video Gen (LTX-Video, text→video + image→video), Video Edit (trim, soundtrack, title, fades → MP4/WebM export)
2
  // and Stems (Demucs split → synced mixer with gain/mute/solo → WAV mixdown). All results go on the asset bus (save / send).
3
- import { run, result, MODULES, esc, hf, stTxt, url, badge, timer, setS, S, keep } from './real.js?v=85';
4
- import { toWav } from './master.js?v=85';
5
  import { onStop } from './widgets.js?v=50';
6
 
7
  export const LTX = 'Lightricks/ltx-video-distilled';
 
1
  // STUDIUS P3.4: Video Gen (LTX-Video, text→video + image→video), Video Edit (trim, soundtrack, title, fades → MP4/WebM export)
2
  // and Stems (Demucs split → synced mixer with gain/mute/solo → WAV mixdown). All results go on the asset bus (save / send).
3
+ import { run, result, MODULES, esc, hf, stTxt, url, badge, timer, setS, S, keep } from './real.js?v=87';
4
+ import { toWav } from './master.js?v=87';
5
  import { onStop } from './widgets.js?v=50';
6
 
7
  export const LTX = 'Lightricks/ltx-video-distilled';
workspace.js CHANGED
@@ -1,6 +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, refreshQuota } from './real.js?v=85';
3
- import { Avatars } from './avatar.js?v=85';
4
  const $ = (s, r = document) => r.querySelector(s);
5
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
  const ST = () => window.__studius.STUDIOS;
@@ -104,7 +104,7 @@ const targets = (kind) => ST().filter(s => s.accepts?.includes(kind));
104
  export async function saveAsset(a) {
105
  if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
106
  if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
107
- const path = `${a.studio || 'misc'}/${a.name}`;
108
  if (a.url && (/^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url) || a.url.startsWith('/api/tmp/'))) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '', model: a.model || '' }) });
109
  const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
110
  return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
@@ -168,10 +168,10 @@ function approval(job, st, box) { return new Promise((ok) => {
168
  async function work(job, a, task, shared, maxSteps) { // one agent's function-calling loop; shared = {history, assets}
169
  const tools = toolsOf(a); if (!tools.length) { say('bee', `${esc(a.name)}: keine Module zugewiesen.`); return null; }
170
  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;
171
- let final = null; const startLen = shared.history.length; const mustTool = !(a.modules.length === 1 && a.modules[0] === 'chat');
172
  for (let i = 0; i < maxSteps; i++) {
173
  const box = say('bee', `<b>${esc(a.name)}</b> <span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> plant…`);
174
- let p = await jpost('/api/agent/step', { task, system, tools: tools.map(({ name, desc, params }) => ({ name, desc, params })), history: shared.history, known_urls: shared.assets.filter(x => x.url).map(x => x.url), require_tool: mustTool && shared.history.length === startLen });
175
  window.__agent = { ...window.__agent, via: p.via, state: 'plan', attempts: [...(window.__agent?.attempts || []), ...(p.attempts || [])] };
176
  if (!p.call) {
177
  // if this agent hasn't used a tool yet and has an external save available with a pending asset, force it
@@ -188,6 +188,7 @@ async function work(job, a, task, shared, maxSteps) { // one agent's function-ca
188
  }
189
  }
190
 
 
191
  const t = tools.find(x => x.name === p.call.tool); const args = { ...p.call.args };
192
  const last = shared.assets.at(-1); // resolve bad/missing url args to the latest result (hand-off)
193
  for (const k of ['url', 'source']) if (k in (t.params || {}) && !shared.assets.some(x => x.url === args[k]) && last) args[k] = last.url;
@@ -197,27 +198,46 @@ async function work(job, a, task, shared, maxSteps) { // one agent's function-ca
197
  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'; } }
198
  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 };
199
  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) });
 
200
  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) } });
201
- box.innerHTML = `<b>${esc(a.name)}</b> · <code>${esc(t.name)}</code> ✔` + show(res); await jpost(`/api/jobs/${job.id}/steps/${step.n}/done`);
 
202
  if (res.url) window.dispatchEvent(new CustomEvent('studius-result', { detail: { el: box.lastElementChild, asset: res } }));
203
  } 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 } }); }
204
  }
205
  return final; }
206
- async function runAgent() { const inp = $('#bin'), task = inp.value.trim(); if (!task) return; inp.value = '';
207
- if (!W.me?.signedIn) { say('bee', 'Bitte zuerst mit Hugging Face anmelden – Agenten planen serverseitig mit deiner HF-Quota.'); return; }
208
- 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)];
209
- say('me', esc(task)); window.__agent = { task, state: 'plan', team: team?.id };
210
- const job = await jpost('/api/jobs', { task, agent: team ? '' : crew[0].id, team: team?.id || '' }); window.__agent.job = job.id;
211
- const shared = { history: [], assets: [], team: !!team }; let sum = '';
212
- try { for (const [i, a] of crew.entries()) {
213
  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;
214
- if (team && i) say('bee', `↪ Übergabe an <b>${esc(a.name)}</b>`);
215
  const r = await work(job, a, sub, shared, team ? 2 : 4); sum += `${a.name}: ${r || '-'}\n`; if (r === 'abgelehnt') break; }
216
  const st = shared.history.some(h => h.result?.rejected) ? 'rejected' : 'done';
217
  await jpost(`/api/jobs/${job.id}/finish`, { state: st, summary: sum });
218
  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 };
219
  } 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(() => {}); }
220
  renderJobs(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  async function renderJobs() { const el = $('#bees .jobs'); if (!el || !W.me?.signedIn) return; try { const { jobs } = await api('/api/jobs' + (W.bucket ? '?bucket=' + encodeURIComponent(W.bucket) : '')); window.__jobs = jobs;
222
- el.innerHTML = jobs.slice(0, 8).map(j => `<div class="job"><b>${{ done: '✔', running: '⏳', awaiting_approval: '✋', rejected: '⛔', error: '⚠', interrupted: '⏸' }[j.state] || '·'}</b> ${esc(j.task.slice(0, 50))} <small class="mut">${new Date(j.created * 1000).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}${j.saved ? ' · 🪣' : ''}${j.restored ? ' · aus Bucket' : ''}</small> <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) {} }
 
223
  $('#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, refreshQuota } from './real.js?v=87';
3
+ import { Avatars } from './avatar.js?v=87';
4
  const $ = (s, r = document) => r.querySelector(s);
5
  const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
6
  const ST = () => window.__studius.STUDIOS;
 
104
  export async function saveAsset(a) {
105
  if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
106
  if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
107
+ const path = a.path || `${a.studio || 'misc'}/${a.name}`;
108
  if (a.url && (/^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url) || a.url.startsWith('/api/tmp/'))) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '', model: a.model || '' }) });
109
  const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
110
  return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
 
168
  async function work(job, a, task, shared, maxSteps) { // one agent's function-calling loop; shared = {history, assets}
169
  const tools = toolsOf(a); if (!tools.length) { say('bee', `${esc(a.name)}: keine Module zugewiesen.`); return null; }
170
  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;
171
+ let final = null; const startLen = shared.history.length; const mine = new Set(tools.map(t => t.name)); const did = () => shared.history.some(h => mine.has(h.tool) && !h.result?.error && !h.result?.rejected); const mustTool = !(a.modules.length === 1 && a.modules[0] === 'chat') && !did();
172
  for (let i = 0; i < maxSteps; i++) {
173
  const box = say('bee', `<b>${esc(a.name)}</b> <span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> plant…`);
174
+ let p; try { p = await jpost('/api/agent/step', { task, system, tools: tools.map(({ name, desc, params }) => ({ name, desc, params })), history: shared.history, known_urls: shared.assets.filter(x => x.url).map(x => x.url), require_tool: mustTool && !did() }); } catch (e) { if (did()) { box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; final = 'fertig'; break; } throw e; }
175
  window.__agent = { ...window.__agent, via: p.via, state: 'plan', attempts: [...(window.__agent?.attempts || []), ...(p.attempts || [])] };
176
  if (!p.call) {
177
  // if this agent hasn't used a tool yet and has an external save available with a pending asset, force it
 
188
  }
189
  }
190
 
191
+ if (shared.team && shared.history.some(h => h.tool === p.call.tool && !h.result?.error && !h.result?.rejected)) { final = 'fertig'; box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; break; }
192
  const t = tools.find(x => x.name === p.call.tool); const args = { ...p.call.args };
193
  const last = shared.assets.at(-1); // resolve bad/missing url args to the latest result (hand-off)
194
  for (const k of ['url', 'source']) if (k in (t.params || {}) && !shared.assets.some(x => x.url === args[k]) && last) args[k] = last.url;
 
198
  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'; } }
199
  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 };
200
  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) });
201
+ let keep = null; if (res.url && cloud()) { try { const sv = await saveAsset({ ...res, path: `jobs/${job.id}/step${step.n}-${res.name || 'result'}` }); keep = sv.path; } catch (e) { console.warn('step result not persisted', e.message); } }
202
  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) } });
203
+ box.innerHTML = `<b>${esc(a.name)}</b> · <code>${esc(t.name)}</code> ✔` + show(res);
204
+ await jpost(`/api/jobs/${job.id}/steps/${step.n}/done`, { result: { kind: res.kind, name: res.name, text: (res.text || '').slice(0, 300), ...(keep ? { path: keep, url: fileUrl(keep) } : res.url && !res.url.startsWith('blob:') ? { url: res.url } : {}) } });
205
  if (res.url) window.dispatchEvent(new CustomEvent('studius-result', { detail: { el: box.lastElementChild, asset: res } }));
206
  } 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 } }); }
207
  }
208
  return final; }
209
+ async function runJob(job, crew, team, task, shared, from = 0) {
210
+ let sum = '';
211
+ try { for (const [i, a] of crew.entries()) { if (i < from) continue;
212
+ jpost(`/api/jobs/${job.id}/cursor`, { member: i, agent: a.id, members: crew.map(c => c.id) }).catch(() => {});
 
 
 
213
  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;
214
+ if (team && i > from) say('bee', `↪ Übergabe an <b>${esc(a.name)}</b>`);
215
  const r = await work(job, a, sub, shared, team ? 2 : 4); sum += `${a.name}: ${r || '-'}\n`; if (r === 'abgelehnt') break; }
216
  const st = shared.history.some(h => h.result?.rejected) ? 'rejected' : 'done';
217
  await jpost(`/api/jobs/${job.id}/finish`, { state: st, summary: sum });
218
  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 };
219
  } 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(() => {}); }
220
  renderJobs(); }
221
+ async function runAgent() { const inp = $('#bin'), task = inp.value.trim(); if (!task) return; inp.value = '';
222
+ if (!W.me?.signedIn) { say('bee', 'Bitte zuerst mit Hugging Face anmelden – Agenten planen serverseitig mit deiner HF-Quota.'); return; }
223
+ 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)];
224
+ say('me', esc(task)); window.__agent = { task, state: 'plan', team: team?.id };
225
+ const job = await jpost('/api/jobs', { task, agent: team ? '' : crew[0].id, team: team?.id || '' }); window.__agent.job = job.id;
226
+ await runJob(job, crew, team, task, { history: [], assets: [], team: !!team }); }
227
+ async function resumeJob(id) {
228
+ const j0 = (window.__jobs || []).find(x => x.id === id); if (!j0) return;
229
+ const job = await jpost(`/api/jobs/${id}/resume`); const team = job.team ? teams.find(t => t.id === job.team) : null;
230
+ const ids = job.members || (team ? team.members : [job.agent]); const crew = ids.map(m => agents.find(a => a.id === m)).filter(Boolean);
231
+ if (!crew.length) { say('bee', '⚠ Mitarbeiter dieses Jobs nicht mehr vorhanden.'); return; }
232
+ const shared = { history: [], assets: [], team: !!team };
233
+ for (const st of job.steps.filter(s => s.state === 'done')) { const r = st.result || {}; shared.history.push({ tool: st.tool, args: st.args, result: { kind: r.kind, url: r.url, text: r.text } });
234
+ if (r.url) shared.assets.push({ kind: r.kind, url: r.url, name: r.name || (r.path || '').split('/').pop(), studio: 'job', path: r.path }); }
235
+ const from = job.cursor?.member || 0; $('#bees').hidden = false;
236
+ say('me', `↻ Fortsetzen: ${esc(job.task)}`); say('bee', `Fortsetzen ab <b>${esc(crew[from]?.name || '?')}</b> – ${shared.history.length} erledigte Schritt(e) übernommen${shared.assets.length ? ': ' + shared.assets.map(x => esc(x.name)).join(', ') : ''}.`);
237
+ window.__agent = { task: job.task, state: 'plan', team: job.team, job: id, resumed: true, from, carried: shared.history.map(h => h.tool) };
238
+ await runJob(job, crew, team, job.task, shared, from); }
239
+ window.__resumeJob = resumeJob;
240
  async function renderJobs() { const el = $('#bees .jobs'); if (!el || !W.me?.signedIn) return; try { const { jobs } = await api('/api/jobs' + (W.bucket ? '?bucket=' + encodeURIComponent(W.bucket) : '')); window.__jobs = jobs;
241
+ el.innerHTML = jobs.slice(0, 8).map(j => `<div class="job"><b>${{ done: '✔', running: '⏳', awaiting_approval: '✋', rejected: '⛔', error: '⚠', interrupted: '⏸' }[j.state] || '·'}</b> ${esc(j.task.slice(0, 50))} <small class="mut">${new Date(j.created * 1000).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}${j.saved ? ' · 🪣' : ''}${j.restored ? ' · aus Bucket' : ''}</small> <small>${j.steps.map(s => esc(s.tool) + (s.external ? '🔒' : '') + ':' + s.state).join(' → ')}</small>${['interrupted', 'error'].includes(j.state) ? `<button class="btn alt rs" data-rs="${esc(j.id)}">↻ Fortsetzen</button>` : ''}</div>`).join('') || '<small class="mut">Noch keine Jobs.</small>'; } catch (e) {} }
242
+ $('#bees .jobs').onclick = (e) => { const b = e.target.closest('[data-rs]'); if (b) { b.disabled = true; resumeJob(b.dataset.rs); } };
243
  $('#bsend').onclick = runAgent; $('#bin').addEventListener('keydown', e => { if (e.key === 'Enter') runAgent(); });