interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / public / js / hive.js

351 lines · 19672 bytes Raw Blame History
1/* Seeded Omega freshness decision; JS remains the explicit load-failure fallback. */
2(() => {
3 'use strict';
4 const hive = document.getElementById('hive');
5 if (!hive) return;
6 let wasmFresh = null;
7 function jsFresh(nowMs, generatedMs, previousMs, staleAfterMs, fetchOk) {
8 if (generatedMs < previousMs) return 2;
9 if (!fetchOk) return 3;
10 return Math.max(0, nowMs - generatedMs) > staleAfterMs ? 1 : 0;
11 }
12 window.hiveFresh = (nowMs, generatedMs, previousMs, staleAfterMs, fetchOk) => {
13 // Date timestamps and thresholds are integers; ceil preserves strict > for elapsed fractions.
14 const values = [Math.ceil(nowMs), generatedMs, previousMs, staleAfterMs];
15 const useWasm = wasmFresh && values.every(Number.isSafeInteger);
16 hive.dataset.freshEngine = useWasm ? 'wasm' : 'js';
17 const state = useWasm
18 ? wasmFresh(...values.map(BigInt), fetchOk ? 1 : 0)
19 : jsFresh(nowMs, generatedMs, previousMs, staleAfterMs, fetchOk);
20 hive.dataset.freshState = String(state);
21 return state;
22 };
23 window.hiveFreshReady = (async () => {
24 try {
25 const response = await fetch('/wasm/hive-fresh.wasm', { cache: 'no-cache', credentials: 'omit' });
26 if (!response.ok) throw new Error('Freshness module unavailable');
27 const fallback = response.clone();
28 let compiled;
29 try {
30 compiled = await WebAssembly.instantiateStreaming(response);
31 } catch (_) {
32 compiled = await WebAssembly.instantiate(await fallback.arrayBuffer());
33 }
34 if (typeof compiled.instance.exports.fresh !== 'function') throw new Error('Freshness export unavailable');
35 wasmFresh = compiled.instance.exports.fresh;
36 return true;
37 } catch (_) {
38 wasmFresh = null;
39 return false;
40 }
41 })();
42})();
43/* Generated by om/hive-page/hive-js.om. Never edit this artifact.
44 * Only same-origin edge-rendered HTML enters DOMParser; never render JSON here. */
45(() => {
46 'use strict';
47 const page = document.getElementById('hive');
48 if (!page) return;
49 const get = id => document.getElementById(id);
50 const tree = get('hive-tree'), chat = get('hive-chat'), search = get('hive-search');
51 const store = get('hive-manifest-cards'), panel = get('hive-manifest-body');
52 let selected = new URLSearchParams(location.hash.slice(1)).get('agent');
53 let scope = 'all', query = '', board = null, connected = false, regressed = false;
54 let advancedAt = 0, sourceAge = 0, trusted = false, active = false;
55 let searchOpen = null;
56 const say = (id, value) => { const node = get(id); if (node && node.textContent !== value) node.textContent = value; };
57
58 // Patch in place. Id-keyed nodes survive reordering; unkeyed structure is paired
59 // positionally. A stack avoids recursion through deeply nested mission trees.
60 function morph(target, source) {
61 const work = [[target, source]];
62 while (work.length) {
63 const [old, fresh] = work.pop();
64 if (old.isEqualNode(fresh)) continue;
65 if (old.nodeType !== fresh.nodeType || old.nodeName !== fresh.nodeName) { old.replaceWith(fresh.cloneNode(true)); continue; }
66 if (old.nodeType !== Node.ELEMENT_NODE) { old.nodeValue = fresh.nodeValue; continue; }
67 const preserve = name => (old.tagName === 'DETAILS' && name === 'open') || name === 'hidden' || name === 'data-selected';
68 for (const attr of [...old.attributes]) if (!preserve(attr.name) && !fresh.hasAttribute(attr.name)) old.removeAttribute(attr.name);
69 for (const attr of fresh.attributes) if (!preserve(attr.name) && old.getAttribute(attr.name) !== attr.value) old.setAttribute(attr.name, attr.value);
70 const keyed = new Map([...old.childNodes].filter(node => node.id).map(node => [node.id, node]));
71 const wanted = new Set();
72 let at = old.firstChild;
73 for (const child of fresh.childNodes) {
74 let node = child.id ? keyed.get(child.id) : at && !at.id && at.nodeName === child.nodeName ? at : null;
75 if (!node) node = child.cloneNode(true);
76 if (node !== at) old.insertBefore(node, at);
77 wanted.add(node);
78 work.push([node, child]);
79 at = node.nextSibling;
80 }
81 for (const child of [...old.childNodes]) if (!wanted.has(child)) child.remove();
82 }
83 }
84
85 function filters() {
86 const visible = new Set();
87 let hits = 0;
88 for (const row of tree.querySelectorAll('.hive-node')) {
89 const id = row.id.slice(5), card = get('manifest-' + id);
90 const matches = !query || (row.querySelector('summary')?.textContent + ' ' + card?.textContent).toLowerCase().includes(query);
91 if (matches) {
92 hits += 1;
93 for (let up = row; up && up !== tree; up = up.parentElement) {
94 if (up.matches('.hive-node')) visible.add(up);
95 if (query && up.tagName === 'DETAILS') up.open = true;
96 }
97 }
98 }
99 for (const row of tree.querySelectorAll('.hive-node')) row.hidden = !visible.has(row);
100 say('hive-search-count', query ? `${hits} matching agents` : '');
101 for (const item of chat.children) item.hidden = scope === 'selected' && item.dataset.agent !== selected;
102 get('hive-chat-all').setAttribute('aria-pressed', String(scope === 'all'));
103 get('hive-chat-selected').setAttribute('aria-pressed', String(scope === 'selected'));
104 }
105
106 function choose(id, fragment = true, reveal = true) {
107 if (panel.firstElementChild) store.append(panel.firstElementChild);
108 const card = get('manifest-' + id), row = get('node-' + id);
109 selected = id;
110 panel.hidden = !card;
111 get('hive-manifest-empty').hidden = Boolean(card);
112 if (card) { card.open = true; panel.append(card); }
113 for (const item of tree.querySelectorAll('.hive-node')) item.dataset.selected = String(item === row);
114 if (row && reveal) for (let up = row.parentElement; up && up !== tree; up = up.parentElement) if (up.tagName === 'DETAILS') up.open = true;
115 if (fragment && row) { try { history.replaceState(null, '', '#agent=' + encodeURIComponent(id)); } catch (_) {} }
116 filters();
117 }
118
119 function freshness() {
120 if (!board) { page.dataset.fresh = 'false'; return; }
121 const elapsed = Math.max(0, performance.now() - advancedAt);
122 const state = window.hiveFresh(sourceAge + elapsed, 0, regressed ? 1 : 0, Number(board.dataset.staleAfter), connected);
123 const stale = state === 1;
124 page.dataset.fresh = String(connected && !stale && trusted);
125 say('hive-connection', !connected ? regressed ? 'Snapshot timestamp moved backwards; last observation retained' : 'Connection interrupted; last snapshot retained' : stale ? 'Source stale; last observation retained' : !trusted ? 'Connected; source age not verified' : 'Receiving source observations');
126 say('hive-freshness', `${Math.floor(elapsed / 1000)}s since the source timestamp advanced. Last observation retained on interruption.`);
127 }
128
129 function ingest(markup, serverDate) {
130 const document = new DOMParser().parseFromString(markup, 'text/html');
131 const incoming = document.getElementById('hive-board');
132 const generated = Date.parse(incoming?.dataset.generated || '');
133 if (!incoming || !Number.isFinite(generated) || incoming.dataset.staleAfter !== '15000' || !/^s-[0-9a-f]{0,256}$/.test(incoming.dataset.sequence || '')) throw new Error('Invalid edge board');
134 if (board && window.hiveFresh(generated, generated, Date.parse(board.dataset.generated), Number(incoming.dataset.staleAfter), true) === 2) { regressed = true; throw new Error('Snapshot moved backwards'); }
135 for (const id of ['hive-tree', 'hive-chat', 'hive-manifest-cards', 'hive-source-time', 'hive-counts', 'hive-coverage']) if (!incoming.querySelector('#' + id)) throw new Error('Incomplete edge board');
136 if (!board || generated > Date.parse(board.dataset.generated)) {
137 advancedAt = performance.now();
138 const server = Date.parse(serverDate || '');
139 trusted = Number.isFinite(server) && generated <= server + 2000;
140 sourceAge = trusted ? Math.max(0, server - generated) : 0;
141 }
142 regressed = false;
143 const focused = window.document.activeElement;
144 const scroll = [chat.scrollTop, tree.parentElement.scrollTop, panel.parentElement.scrollTop];
145 if (panel.firstElementChild) store.append(panel.firstElementChild);
146 for (const id of ['hive-tree', 'hive-chat', 'hive-manifest-cards', 'hive-source-time', 'hive-counts', 'hive-coverage']) morph(get(id), incoming.querySelector('#' + id));
147 board = incoming;
148 for (const name of ['generated', 'sequence', 'staleAfter']) page.dataset[name] = incoming.dataset[name];
149 connected = true;
150 get('hive-tree-empty').hidden = tree.children.length > 0;
151 get('hive-chat-empty').hidden = chat.children.length > 0;
152 say('hive-fetch-time', new Date().toISOString());
153 choose(selected, false, false);
154 [chat.scrollTop, tree.parentElement.scrollTop, panel.parentElement.scrollTop] = scroll;
155 if (focused?.isConnected && window.document.activeElement !== focused) focused.focus({ preventScroll: true });
156 freshness();
157 }
158
159 async function poll() {
160 if (active) return;
161 active = true;
162 const controller = new AbortController();
163 const timeout = setTimeout(() => controller.abort(), 4500);
164 try {
165 const response = await fetch('/hive/board/', { cache: 'no-store', credentials: 'omit', signal: controller.signal, headers: { Accept: 'text/html' } });
166 if (!response.ok || !response.headers.get('content-type')?.toLowerCase().includes('text/html')) throw new Error('Board unavailable');
167 ingest(await response.text(), response.headers.get('date'));
168 } catch (_) {
169 connected = false;
170 if (!board) say('hive-connection', 'Telemetry unavailable; no source observation received');
171 freshness();
172 } finally { clearTimeout(timeout); active = false; }
173 }
174
175 search.addEventListener('input', () => {
176 query = search.value.trim().toLowerCase();
177 if (query && !searchOpen) searchOpen = new Map([...tree.querySelectorAll('details[id]')].map(node => [node.id, node.open]));
178 if (!query && searchOpen) { for (const [id, open] of searchOpen) { const node = get(id); if (node) node.open = open; } searchOpen = null; }
179 filters();
180 });
181 tree.addEventListener('click', event => { const link = event.target.closest('a[data-agent]'); if (link) { event.preventDefault(); choose(link.dataset.agent); } });
182 get('hive-chat-all').addEventListener('click', () => { scope = 'all'; filters(); });
183 get('hive-chat-selected').addEventListener('click', () => { scope = 'selected'; filters(); });
184 addEventListener('hashchange', () => choose(new URLSearchParams(location.hash.slice(1)).get('agent'), false));
185 setInterval(freshness, 1000);
186 setInterval(poll, 1000);
187 poll();
188})();
189/* Hive universe: every observed agent as a world, read from the edge-rendered tree. */
190(() => {
191 'use strict';
192 const tree = document.getElementById('hive-tree');
193 const anchor = document.getElementById('hive-tree-section');
194 if (!tree || !anchor || !window.SVGElement) return;
195 const NS = 'http://www.w3.org/2000/svg';
196 const section = document.createElement('section');
197 section.id = 'hive-universe-section';
198 section.className = 'hive-section hive-section-full hive-panel hive-universe';
199 section.setAttribute('aria-labelledby', 'hive-universe-title');
200 section.innerHTML = `<div class="hive-panel-head"><p class="hive-eyebrow">Universe</p><h2 id="hive-universe-title">Every agent, as a world</h2><p class="hive-note">Each coding session is a star and the workers it started orbit it. Hold Ctrl and scroll, pinch, or use the buttons to zoom; drag to move, select a world to open it. A solid amber ring means the agent is idle because its provider's usage limit was reached; a dashed one means the provider was at capacity.</p></div><div class="hive-universe-tools" role="group" aria-label="Universe zoom"><button type="button" data-zoom="in" aria-label="Zoom in">+</button><button type="button" data-zoom="out" aria-label="Zoom out">&#8722;</button><button type="button" data-zoom="fit">Show all</button><span class="hive-universe-count" aria-live="polite"></span></div>`;
201 const sky = document.createElementNS(NS, 'svg');
202 sky.setAttribute('class', 'hive-universe-sky');
203 sky.setAttribute('role', 'group');
204 sky.setAttribute('aria-label', 'Agent universe');
205 sky.setAttribute('height', '560');
206 sky.setAttribute('preserveAspectRatio', 'xMidYMid meet');
207 section.append(sky);
208 anchor.before(section);
209 const count = section.querySelector('.hive-universe-count');
210 let last = '';
211 let view = null, bounds = { x: -200, y: -200, w: 400, h: 400 }, fitted = true;
212
213 function read() {
214 const all = new Map(), roots = [];
215 for (const li of tree.querySelectorAll('li.hive-node')) {
216 const s = li.querySelector('summary');
217 if (!s) continue;
218 const pick = c => (s.querySelector(c) || {}).textContent || '';
219 const node = { id: li.id.slice(5), name: pick('.hive-select'), status: pick('.hive-pill').trim().toLowerCase(), activity: pick('.hive-activity'), kids: [] };
220 all.set(li, node);
221 const up = li.parentElement && li.parentElement.closest('li.hive-node');
222 (up && all.get(up) ? all.get(up).kids : roots).push(node);
223 }
224 return { roots, total: all.size };
225 }
226 function cls(n) {
227 let c = 'hive-world st-' + (n.status.replace(/[^a-z]/g, '') || 'unknown');
228 if (n.activity.startsWith('Idle: provider usage limit')) c += ' is-limited';
229 else if (n.activity.startsWith('Idle: provider at capacity')) c += ' is-capacity';
230 return c;
231 }
232 function el(name, attrs, parent) {
233 const e = document.createElementNS(NS, name);
234 for (const k in attrs) e.setAttribute(k, attrs[k]);
235 if (parent) parent.append(e);
236 return e;
237 }
238 function world(n, x, y, r, parent) {
239 const a = el('a', { href: '#agent=' + encodeURIComponent(n.id), class: cls(n) }, parent);
240 el('title', {}, a).textContent = [n.name, n.status, n.activity].filter(Boolean).join(' | ');
241 el('circle', { cx: x.toFixed(1), cy: y.toFixed(1), r: r.toFixed(1) }, a);
242 return a;
243 }
244 function radius(n, depth) {
245 const own = depth ? Math.max(3, 9 - depth * 3) : 16;
246 if (!n.kids.length) return own;
247 const ring = own + 12 + n.kids.length * (depth ? 2 : 4);
248 return ring + Math.max(...n.kids.map(k => radius(k, depth + 1)));
249 }
250 function system(n, x, y, depth, parent) {
251 const own = depth ? Math.max(3, 9 - depth * 3) : 16;
252 if (n.kids.length) {
253 const ring = own + 12 + n.kids.length * (depth ? 2 : 4);
254 el('circle', { cx: x.toFixed(1), cy: y.toFixed(1), r: ring.toFixed(1), class: 'hive-orbit-path' }, parent);
255 const g = el('g', { class: 'hive-orbit' }, parent);
256 n.kids.forEach((k, i) => {
257 const t = 2 * Math.PI * i / n.kids.length;
258 system(k, x + ring * Math.cos(t), y + ring * Math.sin(t), depth + 1, g);
259 });
260 }
261 world(n, x, y, own, parent);
262 }
263 function draw() {
264 const { roots, total } = read();
265 const sig = JSON.stringify(roots);
266 if (sig === last) return;
267 last = sig;
268 const held = sky.contains(document.activeElement) ? document.activeElement.getAttribute('href') : null;
269 sky.replaceChildren();
270 count.textContent = total === 1 ? '1 agent' : total + ' agents';
271 if (!roots.length) { bounds = { x: -200, y: -200, w: 400, h: 400 }; apply(); return; }
272 const step = 2.4 * Math.max(...roots.map(r => radius(r, 0)));
273 let lo = [Infinity, Infinity], hi = [-Infinity, -Infinity];
274 roots.forEach((r, i) => {
275 const d = i ? step * Math.sqrt(i) : 0, t = i * 2.39996;
276 const x = d * Math.cos(t), y = d * Math.sin(t), m = radius(r, 0) + 24;
277 const g = el('g', { class: 'hive-system' }, sky);
278 system(r, x, y, 0, g);
279 const label = el('text', { x: x.toFixed(1), y: (y + 30).toFixed(1), class: 'hive-world-label' }, g);
280 label.textContent = r.name.length > 28 ? r.name.slice(0, 27) + '...' : r.name;
281 lo = [Math.min(lo[0], x - m), Math.min(lo[1], y - m)];
282 hi = [Math.max(hi[0], x + m), Math.max(hi[1], y + m)];
283 });
284 bounds = { x: lo[0], y: lo[1], w: hi[0] - lo[0], h: hi[1] - lo[1] };
285 apply();
286 if (held) { const again = [...sky.querySelectorAll('a')].find(a => a.getAttribute('href') === held); if (again) again.focus({ preventScroll: true }); }
287 }
288 function apply() {
289 const r = sky.getBoundingClientRect();
290 const aspect = r.width > 0 && r.height > 0 ? r.height / r.width : 1;
291 if (fitted || !view) {
292 const w = Math.max(bounds.w, bounds.h / aspect);
293 view = { x: bounds.x + bounds.w / 2 - w / 2, y: bounds.y + bounds.h / 2 - w * aspect / 2, w, h: w * aspect };
294 } else view.h = view.w * aspect;
295 sky.setAttribute('viewBox', [view.x, view.y, view.w, view.h].map(v => v.toFixed(1)).join(' '));
296 }
297 function zoom(f, cx, cy) {
298 if (!view) return;
299 const w = Math.min(Math.max(view.w * f, 20), Math.max(bounds.w, bounds.h) * 4);
300 const k = w / view.w;
301 if (cx === undefined) { cx = view.x + view.w / 2; cy = view.y + view.h / 2; }
302 view = { x: cx - (cx - view.x) * k, y: cy - (cy - view.y) * k, w, h: view.h * k };
303 fitted = false; apply();
304 }
305 function point(e) {
306 const r = sky.getBoundingClientRect();
307 if (!(r.width > 0 && r.height > 0)) return [view.x + view.w / 2, view.y + view.h / 2];
308 return [view.x + (e.clientX - r.left) / r.width * view.w, view.y + (e.clientY - r.top) / r.height * view.h];
309 }
310 section.querySelector('.hive-universe-tools').addEventListener('click', e => {
311 const b = e.target.closest('button');
312 if (!b) return;
313 if (b.dataset.zoom === 'fit') { fitted = true; apply(); }
314 else zoom(b.dataset.zoom === 'in' ? 0.7 : 1 / 0.7);
315 });
316 sky.addEventListener('wheel', e => { if (!e.ctrlKey && !e.metaKey) return; e.preventDefault(); const [x, y] = point(e); zoom(e.deltaY < 0 ? 0.85 : 1 / 0.85, x, y); }, { passive: false });
317 sky.addEventListener('dblclick', e => { const [x, y] = point(e); zoom(0.5, x, y); });
318 const down = new Map();
319 let pinch = 0, moved = false;
320 sky.addEventListener('pointerdown', e => { down.set(e.pointerId, [e.clientX, e.clientY]); moved = false; });
321 sky.addEventListener('pointermove', e => {
322 const last = down.get(e.pointerId);
323 if (!last || !view) return;
324 const r = sky.getBoundingClientRect();
325 if (!(r.width > 0 && r.height > 0)) return;
326 if (down.size === 1) {
327 const dx = e.clientX - last[0], dy = e.clientY - last[1];
328 if (!moved && Math.hypot(dx, dy) < 4) return;
329 if (!moved) sky.setPointerCapture(e.pointerId);
330 moved = true;
331 view.x -= dx / r.width * view.w; view.y -= dy / r.height * view.h; fitted = false; apply();
332 }
333 down.set(e.pointerId, [e.clientX, e.clientY]);
334 if (down.size === 2) {
335 const [p, q] = [...down.values()], d = Math.hypot(p[0] - q[0], p[1] - q[1]);
336 if (pinch) zoom(pinch / d);
337 pinch = d; moved = true;
338 }
339 });
340 const up = e => { down.delete(e.pointerId); if (down.size < 2) pinch = 0; };
341 sky.addEventListener('pointerup', up);
342 sky.addEventListener('pointercancel', up);
343 sky.addEventListener('click', e => { if (moved) { e.preventDefault(); moved = false; } }, true);
344 let queued = false;
345 new MutationObserver(() => { if (!queued) { queued = true; requestAnimationFrame(() => { queued = false; draw(); }); } })
346 .observe(tree, { childList: true, subtree: true, characterData: true });
347 // Refit only when the element's box really changed: the viewBox never feeds back into its size.
348 let box = '';
349 if (window.ResizeObserver) new ResizeObserver(() => { const r = sky.getBoundingClientRect(); const now = Math.round(r.width) + 'x' + Math.round(r.height); if (now !== box) { box = now; apply(); } }).observe(sky);
350 draw();
351})();