@hivey/cli 0.9.60 → 0.9.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/native/darwin-arm64/hivey +0 -0
  2. package/package.json +1 -1
  3. package/repo/skills/hivey/scripts/new_wiki.py +12 -0
  4. package/repo/skills/hivey-agent-map/SKILL.md +36 -3
  5. package/repo/skills/hivey-agent-map/scripts/agent_map.py +16 -6
  6. package/repo/skills/hivey-agent-map/scripts/office/OutlineEffect.js +539 -0
  7. package/repo/skills/hivey-agent-map/scripts/office/RoomEnvironment.js +148 -0
  8. package/repo/skills/hivey-agent-map/scripts/office/loaders/GLTFLoader.js +4663 -0
  9. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-kenney-space-kit.txt +23 -0
  10. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-kenney-space-station-kit.txt +28 -0
  11. package/repo/skills/hivey-agent-map/scripts/office/models/LICENSE-robot.txt +2 -0
  12. package/repo/skills/hivey-agent-map/scripts/office/models/astronautA.glb.b64 +1 -0
  13. package/repo/skills/hivey-agent-map/scripts/office/models/astronautB.glb.b64 +1 -0
  14. package/repo/skills/hivey-agent-map/scripts/office/models/barrels.glb.b64 +1 -0
  15. package/repo/skills/hivey-agent-map/scripts/office/models/barrels_rail.glb.b64 +1 -0
  16. package/repo/skills/hivey-agent-map/scripts/office/models/craft_cargoA.glb.b64 +1 -0
  17. package/repo/skills/hivey-agent-map/scripts/office/models/craft_racer.glb.b64 +1 -0
  18. package/repo/skills/hivey-agent-map/scripts/office/models/craft_speederA.glb.b64 +1 -0
  19. package/repo/skills/hivey-agent-map/scripts/office/models/desk_chairArms.glb.b64 +1 -0
  20. package/repo/skills/hivey-agent-map/scripts/office/models/desk_computer.glb.b64 +1 -0
  21. package/repo/skills/hivey-agent-map/scripts/office/models/machine_generator.glb.b64 +1 -0
  22. package/repo/skills/hivey-agent-map/scripts/office/models/machine_generatorLarge.glb.b64 +1 -0
  23. package/repo/skills/hivey-agent-map/scripts/office/models/machine_wireless.glb.b64 +1 -0
  24. package/repo/skills/hivey-agent-map/scripts/office/models/robot.glb.b64 +1 -0
  25. package/repo/skills/hivey-agent-map/scripts/office/models/satelliteDish_detailed.glb.b64 +1 -0
  26. package/repo/skills/hivey-agent-map/scripts/office/models/satelliteDish_large.glb.b64 +1 -0
  27. package/repo/skills/hivey-agent-map/scripts/office/models/station/Textures/colormap.png.b64 +1 -0
  28. package/repo/skills/hivey-agent-map/scripts/office/models/station/chair-cushion-headrest.glb.b64 +1 -0
  29. package/repo/skills/hivey-agent-map/scripts/office/models/station/computer-system.glb.b64 +1 -0
  30. package/repo/skills/hivey-agent-map/scripts/office/models/station/computer-wide.glb.b64 +1 -0
  31. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-flat.glb.b64 +1 -0
  32. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-tall.glb.b64 +1 -0
  33. package/repo/skills/hivey-agent-map/scripts/office/models/station/container-wide.glb.b64 +1 -0
  34. package/repo/skills/hivey-agent-map/scripts/office/models/station/display-wall-wide.glb.b64 +1 -0
  35. package/repo/skills/hivey-agent-map/scripts/office/models/station/pipe-ring-colored.glb.b64 +1 -0
  36. package/repo/skills/hivey-agent-map/scripts/office/music/README.txt +2 -0
  37. package/repo/skills/hivey-agent-map/scripts/office/music/space.mp3.b64 +1 -0
  38. package/repo/skills/hivey-agent-map/scripts/office/office.html +179 -0
  39. package/repo/skills/hivey-agent-map/scripts/office/office.js +754 -0
  40. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/EffectComposer.js +231 -0
  41. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/MaskPass.js +104 -0
  42. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/OutputPass.js +95 -0
  43. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/Pass.js +95 -0
  44. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/RenderPass.js +99 -0
  45. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/ShaderPass.js +77 -0
  46. package/repo/skills/hivey-agent-map/scripts/office/postprocessing/UnrealBloomPass.js +415 -0
  47. package/repo/skills/hivey-agent-map/scripts/office/shaders/CopyShader.js +45 -0
  48. package/repo/skills/hivey-agent-map/scripts/office/shaders/LuminosityHighPassShader.js +66 -0
  49. package/repo/skills/hivey-agent-map/scripts/office/shaders/OutputShader.js +81 -0
  50. package/repo/skills/hivey-agent-map/scripts/office/ship.js +578 -0
  51. package/repo/skills/hivey-agent-map/scripts/office/three.module.min.js +6 -0
  52. package/repo/skills/hivey-agent-map/scripts/office/utils/BufferGeometryUtils.js +1375 -0
  53. package/repo/skills/hivey-agent-map/scripts/office/utils/SkeletonUtils.js +413 -0
  54. package/repo/skills/hivey-agent-map/scripts/office.py +522 -0
  55. package/repo/skills/hivey-agent-map/scripts/report.py +105 -2
  56. package/repo/skills/hivey-agent-map/scripts/serve.py +190 -9
  57. package/repo/skills/hivey-create-wiki/SKILL.md +27 -2
  58. package/repo/skills/hivey-swarm-creator/SKILL.md +4 -0
  59. package/repo/skills/hivey-swarm-creator/references/wiki-memory.md +3 -0
  60. package/repo/skills/hivey-wiki-lint/SKILL.md +7 -2
@@ -0,0 +1,754 @@
1
+ // hivey office: every live agent at a desk. Data: ./office.json (office.py, refreshed every 5 min by
2
+ // serve.py while this page is open). Three.js draws the office; the board and the list are plain HTML.
3
+ // Click an agent: open its terminal in hivey. Right-click (or ⓘ): details. Only working agents move.
4
+ import * as THREE from './three.module.min.js';
5
+ import { RoomEnvironment } from './RoomEnvironment.js';
6
+ import { OutlineEffect } from './OutlineEffect.js';
7
+ import { EffectComposer } from './postprocessing/EffectComposer.js';
8
+ import { RenderPass } from './postprocessing/RenderPass.js';
9
+ import { UnrealBloomPass } from './postprocessing/UnrealBloomPass.js';
10
+ import { OutputPass } from './postprocessing/OutputPass.js';
11
+ import { createShip } from './ship.js';
12
+
13
+ const $ = (s, el = document) => el.querySelector(s);
14
+ const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
15
+ const STATUS = {
16
+ blocked: { label: 'Needs you', emoji: '✋', color: '#fb7185' },
17
+ working: { label: 'Working', emoji: '⚡', color: '#38bdf8' },
18
+ done: { label: 'Done', emoji: '✅', color: '#4ade80' },
19
+ idle: { label: 'Idle', emoji: '💤', color: '#94a3b8' },
20
+ };
21
+ const st = s => STATUS[s] || { label: s || '?', emoji: '•', color: '#64748b' };
22
+ const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
23
+
24
+ let data = null, agents = [], selected = null;
25
+ const ui = JSON.parse(localStorage.getItem('hv-office-ship') || '{}');
26
+ ui.view ||= 'office';
27
+ ui.filter ||= null;
28
+ if (ui.toon === undefined) ui.toon = false;
29
+ const save = () => localStorage.setItem('hv-office-ship', JSON.stringify({ view: ui.view, filter: ui.filter, toon: ui.toon, music: ui.music }));
30
+
31
+ // ---------------------------------------------------------------- helpers
32
+ function hue(name) { let h = 0; for (const c of name || '') h = (h * 31 + c.charCodeAt(0)) >>> 0; return h % 360; }
33
+ function ago(iso) {
34
+ if (!iso) return '';
35
+ const s = Math.max(0, (Date.now() - Date.parse(iso)) / 1000);
36
+ return s < 60 ? 'just now' : s < 3600 ? `${Math.round(s / 60)}m ago` : s < 86400 ? `${Math.round(s / 3600)}h ago` : `${Math.round(s / 86400)}d ago`;
37
+ }
38
+ function ktok(n) { return n >= 1e6 ? (n / 1e6).toFixed(2) + 'M' : n >= 1e3 ? Math.round(n / 1e3) + 'k' : String(n || 0); }
39
+ function ctxColor(p) { return p >= 80 ? '#fb7185' : p >= 60 ? '#f5b83d' : '#4ade80'; }
40
+ function model(m) {
41
+ const k = /claude-(opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?(?!\d)/.exec(m || '');
42
+ return k ? `${k[1][0].toUpperCase() + k[1].slice(1)} ${k[2]}${k[3] ? '.' + k[3] : ''}` : (m || '').split('/').pop();
43
+ }
44
+ function ring(p, size = 18) {
45
+ const r = size / 2 - 2, c = 2 * Math.PI * r, v = Math.min(100, p || 0);
46
+ return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}" style="flex:none"><circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="none" stroke="#273246" stroke-width="3"/>` +
47
+ `<circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="none" stroke="${ctxColor(v)}" stroke-width="3" stroke-linecap="round" stroke-dasharray="${c * v / 100} ${c}" transform="rotate(-90 ${size / 2} ${size / 2})"/></svg>`;
48
+ }
49
+ function adviceBadge(a) {
50
+ const s = a.summary || {};
51
+ if (s.advice === 'compact') return `<span class="badge compact" title="${esc(s.advice_why)}">🗜 compact</span>`;
52
+ if (s.advice === 'clear') return `<span class="badge clear" title="${esc(s.advice_why)}">🧹 clear</span>`;
53
+ return '';
54
+ }
55
+ function toast(msg) { const t = $('#toast'); t.textContent = msg; t.classList.add('show'); clearTimeout(toast.t); toast.t = setTimeout(() => t.classList.remove('show'), 2600); }
56
+ function visible(a) {
57
+ if (ui.filter) {
58
+ if (ui.filter in STATUS && a.status !== ui.filter) return false;
59
+ if ((ui.filter === 'compact' || ui.filter === 'clear') && a.summary?.advice !== ui.filter) return false;
60
+ }
61
+ const q = $('#q').value.trim().toLowerCase();
62
+ if (!q) return true;
63
+ const s = a.summary || {};
64
+ return [a.name, a.space, a.cli, a.model, s.job, s.bubble, s.next, s.needs_you, ...(s.done || [])].join(' ').toLowerCase().includes(q);
65
+ }
66
+
67
+ // ---------------------------------------------------------------- actions
68
+ async function act(a, action) {
69
+ if (action === 'focus') toast(`Opening ${a.name} in hivey…`);
70
+ try {
71
+ const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pane: a.pane, action }) });
72
+ const j = await r.json();
73
+ toast(j.ok ? (action === 'focus' ? `${a.name} is open in hivey ↗` : `${a.name}: ${j.message}`) : `${a.name}: ${j.message}`);
74
+ } catch (e) { toast('The office server is not answering: run `hivey agent-map office` again'); }
75
+ }
76
+ // compact / clear need a second click within 3 s (no browser dialogs)
77
+ function armed(btn, a, action) {
78
+ if (btn.classList.contains('arm')) { btn.classList.remove('arm'); btn.textContent = btn.dataset.label; act(a, action); return; }
79
+ btn.dataset.label = btn.textContent;
80
+ btn.classList.add('arm');
81
+ btn.textContent = `Click again to ${action}`;
82
+ setTimeout(() => { if (btn.classList.contains('arm')) { btn.classList.remove('arm'); btn.textContent = btn.dataset.label; } }, 3000);
83
+ }
84
+ function actionButtons(a) {
85
+ const busy = a.status === 'working' || a.status === 'blocked';
86
+ return `<div class="actions">
87
+ <button class="primary" data-act="focus" title="Open its terminal in hivey">↗ Open</button>
88
+ ${a.cli_id === 'claude' ? `<button data-act="compact" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /compact into it"'}>🗜 Compact</button>
89
+ <button data-act="clear" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /clear into it"'}>🧹 Clear</button>` : ''}
90
+ <button data-act="info" title="Everything about it">ⓘ Details</button></div>`;
91
+ }
92
+ function wireActions(root) {
93
+ root.querySelectorAll('[data-id]').forEach(el => {
94
+ const a = agents.find(x => x.id === el.dataset.id);
95
+ if (!a) return;
96
+ el.addEventListener('click', e => {
97
+ const b = e.target.closest('button[data-act]');
98
+ if (!b) return act(a, 'focus');
99
+ e.stopPropagation();
100
+ if (b.disabled) return;
101
+ const k = b.dataset.act;
102
+ if (k === 'info') return openDrawer(a);
103
+ if (k === 'focus') return act(a, 'focus');
104
+ armed(b, a, k);
105
+ });
106
+ el.addEventListener('contextmenu', e => { e.preventDefault(); openDrawer(a); });
107
+ });
108
+ }
109
+
110
+ // ---------------------------------------------------------------- header, inbox
111
+ function renderHeader() {
112
+ const c = data.counts || {}, adv = data.advice || {};
113
+ const pills = [
114
+ ['blocked', '✋', 'needs you', c.blocked], ['working', '⚡', 'working', c.working], ['done', '✅', 'done', c.done],
115
+ ['idle', '💤', 'idle', c.idle], ['compact', '🗜', 'to compact', adv.compact], ['clear', '🧹', 'to clear', adv.clear],
116
+ ];
117
+ $('#pills').innerHTML = pills.map(([k, e, l, n]) =>
118
+ `<button class="pill ${k} ${ui.filter === k ? 'on' : ''}" data-f="${k}" title="Show only these">${e} <b>${n || 0}</b> ${l}</button>`).join('');
119
+ $('#pills').querySelectorAll('.pill').forEach(p => p.onclick = () => { ui.filter = ui.filter === p.dataset.f ? null : p.dataset.f; save(); renderAll(); });
120
+ tickSub();
121
+ }
122
+ function tickSub() {
123
+ if (!data) return;
124
+ const next = Date.parse(data.generated) / 1000 + (data.refresh_every || 300) - Date.now() / 1000;
125
+ const n = agents.length;
126
+ const mm = Math.max(0, Math.floor(next / 60)), ss = Math.max(0, Math.floor(next % 60));
127
+ $('#sub').innerHTML = `${n} agent${n === 1 ? '' : 's'} · updated ${ago(data.generated)} · ` +
128
+ (refreshing ? '<span class="spin">⟳</span> reading terminals…' : next > 0 ? `next in ${mm}:${String(ss).padStart(2, '0')}` : 'refreshing soon') +
129
+ (data.error ? ` · <span class="err" title="${esc(data.error)}">summaries from the recap (model call failed)</span>` : '');
130
+ }
131
+ function renderInbox() {
132
+ const blocked = agents.filter(a => a.status === 'blocked');
133
+ const asked = agents.filter(a => a.status !== 'blocked' && a.status !== 'working' && a.summary?.needs_you);
134
+ const need = [...blocked, ...asked];
135
+ const lead = [blocked.length ? `✋ ${blocked.length} blocked` : '', asked.length ? `<span style="color:var(--honey)">💬 ${asked.length} asked you</span>` : ''].filter(Boolean).join('<br>');
136
+ $('#inbox').innerHTML = need.length ? `<span class="lead">${lead}</span>` + need.map(a =>
137
+ `<div class="ask ${a.status === 'blocked' ? '' : 'soft'}" data-id="${esc(a.id)}" title="Click: open in hivey · right-click: details"><span class="em">${esc(a.emoji)}</span>
138
+ <div class="t"><b>${esc(a.name)}</b>${esc(a.summary?.needs_you || a.summary?.bubble || 'waiting in its terminal')}</div><span class="go">open ↗</span></div>`).join('') : '';
139
+ wireActions($('#inbox'));
140
+ }
141
+
142
+ // ---------------------------------------------------------------- board & list
143
+ function card(a) {
144
+ const s = a.summary || {}, h = hue(a.space), S = st(a.status);
145
+ return `<div class="card ${esc(a.status)}" data-id="${esc(a.id)}" title="Click: open in hivey · right-click: details">
146
+ <div class="top"><div class="avatar" style="--hue1:hsl(${h} 70% 62%);--hue2:hsl(${h} 55% 32%)">${esc(a.emoji)}<span class="st" style="background:${S.color}"></span></div>
147
+ <div style="min-width:0"><div class="name">${esc(a.name)}</div>
148
+ <div class="meta">${S.emoji} ${S.label} · ${esc(a.cli)}${a.model ? ' · ' + esc(model(a.model)) : ''}${a.team?.length ? ` · 👥 ${a.team.length}` : ''} · ${ago(a.last_activity)}</div></div></div>
149
+ <div class="say">${esc(s.bubble || '…')}</div>
150
+ <div class="job">📌 ${esc(s.job || '')}</div>
151
+ ${s.needs_you ? `<div class="need">✋ ${esc(s.needs_you)}</div>` : ''}
152
+ ${(s.done || []).length ? `<ul>${s.done.map(d => `<li>${esc(d)}</li>`).join('')}</ul>` : ''}
153
+ ${s.next ? `<div class="next">→ ${esc(s.next)}</div>` : ''}
154
+ <div class="ctx">🧠 <span class="bar"><i style="width:${Math.min(100, a.context_pct)}%;background:${ctxColor(a.context_pct)}"></i></span>
155
+ ${a.context ? `${a.context_pct}% of ${ktok(a.window)}` : 'no session log'} ${adviceBadge(a)}</div>
156
+ ${actionButtons(a)}</div>`;
157
+ }
158
+ function renderBoard() {
159
+ const list = agents.filter(visible);
160
+ const groups = [['blocked', '✋ Needs you'], ['working', '⚡ Working now'], ['done', '✅ Finished: review'], ['idle', '💤 Idle']];
161
+ const other = list.filter(a => !STATUS[a.status]);
162
+ $('#board').innerHTML = list.length ? groups.map(([k, t]) => {
163
+ const g = list.filter(a => a.status === k);
164
+ return g.length ? `<div class="section"><h2>${t} <span>· ${g.length}</span></h2><div class="grid">${g.map(card).join('')}</div></div>` : '';
165
+ }).join('') + (other.length ? `<div class="section"><h2>Other · ${other.length}</h2><div class="grid">${other.map(card).join('')}</div></div>` : '')
166
+ : '<div class="empty">No agent matches.</div>';
167
+ wireActions($('#board'));
168
+ }
169
+ let sortKey = 'status', sortDir = 1;
170
+ function renderList() {
171
+ const order = { blocked: 0, working: 1, done: 2, idle: 3 };
172
+ const key = {
173
+ status: a => order[a.status] ?? 9, name: a => a.name, space: a => a.space, job: a => a.summary?.job || '',
174
+ context: a => -a.context_pct, advice: a => ({ compact: 0, clear: 1 }[a.summary?.advice] ?? 2), active: a => -(Date.parse(a.last_activity) || 0),
175
+ }[sortKey];
176
+ const list = agents.filter(visible).sort((a, b) => { const x = key(a), y = key(b); return (x < y ? -1 : x > y ? 1 : 0) * sortDir; });
177
+ const th = (k, l) => `<th data-k="${k}">${l}${sortKey === k ? (sortDir > 0 ? ' ▲' : ' ▼') : ''}</th>`;
178
+ $('#list').innerHTML = `<table><thead><tr>${th('status', '')}${th('name', 'Agent')}${th('space', 'Space')}${th('job', 'Current job · says')}${th('context', 'Context')}${th('advice', 'Advice')}${th('active', 'Active')}<th></th></tr></thead><tbody>` +
179
+ list.map(a => { const s = a.summary || {}; return `<tr data-id="${esc(a.id)}" title="Click: open in hivey · right-click: details">
180
+ <td>${st(a.status).emoji}</td><td><b>${esc(a.name)}</b><div class="meta">${esc(a.cli)}${a.model ? ' · ' + esc(model(a.model)) : ''}${a.team?.length ? ' · 👥 ' + a.team.length : ''}</div></td>
181
+ <td>${esc(a.emoji)} ${esc(a.space)}</td><td class="j"><b>${esc(s.job)}</b><div class="meta">${esc(s.needs_you ? '✋ ' + s.needs_you : s.bubble)}</div></td>
182
+ <td><span style="display:flex;gap:6px;align-items:center">${ring(a.context_pct)} ${a.context ? a.context_pct + '%' : '–'}</span></td>
183
+ <td>${adviceBadge(a)}</td><td class="meta">${ago(a.last_activity)}</td><td><button class="iconbtn" data-act="info" style="padding:3px 8px">ⓘ</button></td></tr>`; }).join('') +
184
+ '</tbody></table>' + (list.length ? '' : '<div class="empty">No agent matches.</div>');
185
+ $('#list').querySelectorAll('th[data-k]').forEach(h => h.onclick = () => { sortDir = sortKey === h.dataset.k ? -sortDir : 1; sortKey = h.dataset.k; renderList(); });
186
+ wireActions($('#list'));
187
+ }
188
+
189
+ // ---------------------------------------------------------------- drawer
190
+ function openDrawer(a) {
191
+ selected = a.id;
192
+ const s = a.summary || {}, S = st(a.status);
193
+ $('#drawer').innerHTML = `<button class="x" title="Close (Esc)">✕</button>
194
+ <div style="display:flex;gap:12px;align-items:center"><div class="avatar" style="--hue1:hsl(${hue(a.space)} 70% 62%);--hue2:hsl(${hue(a.space)} 55% 32%)">${esc(a.emoji)}</div>
195
+ <div><h3>${esc(a.name)}</h3><div class="meta">${S.emoji} ${S.label} · ${esc(a.role)} · ${esc(a.cli)}${a.model ? ' · ' + esc(model(a.model)) : ''}</div></div></div>
196
+ <div class="say" style="margin:14px 0;padding:10px 12px;border-radius:12px;background:var(--panel2)">${esc(s.bubble)}</div>
197
+ ${s.needs_you ? `<div class="need" style="padding:8px 10px;border-radius:10px;background:rgba(251,113,133,.12);border:1px solid rgba(251,113,133,.35)">✋ ${esc(s.needs_you)}</div>` : ''}
198
+ <div class="gauge">${ring(a.context_pct, 64)}<div><b>${a.context ? a.context_pct + '% context' : 'no session log'}</b>
199
+ <div class="meta">${a.context ? `${ktok(a.context)} of ${ktok(a.window)} tokens` : 'context is read from Claude Code session logs'}</div>
200
+ <div style="margin-top:4px">${adviceBadge(a) || '<span class="badge">👍 keep</span>'} <span class="meta">${esc(s.advice_why)}</span></div></div></div>
201
+ ${actionButtons(a)}
202
+ <dl>
203
+ <dt>Current job</dt><dd>📌 ${esc(s.job)}</dd>
204
+ ${(s.done || []).length ? `<dt>Achieved</dt><dd>${s.done.map(d => '✓ ' + esc(d)).join('<br>')}</dd>` : ''}
205
+ ${s.next ? `<dt>Next</dt><dd>→ ${esc(s.next)}</dd>` : ''}
206
+ ${a.about ? `<dt>About</dt><dd>${esc(a.about)}</dd>` : ''}
207
+ ${a.team?.length ? `<dt>Swarm team</dt><dd>${a.team.map(m => `${st(m.status).emoji} ${esc(m.name)} <span class="meta">${esc(m.role)}</span>`).join('<br>')}</dd>` : ''}
208
+ ${a.last_prompt ? `<dt>Your last prompt</dt><dd>${esc(a.last_prompt)}</dd>` : ''}
209
+ ${a.recap ? `<dt>Session recap</dt><dd>${esc(a.recap)}</dd>` : ''}
210
+ ${a.tools?.length ? `<dt>Recent tools</dt><dd class="meta">${a.tools.map(esc).join('<br>')}</dd>` : ''}
211
+ <dt>Last active</dt><dd>${ago(a.last_activity) || '–'}${a.session_started ? ` · session since ${new Date(a.session_started).toLocaleString()}` : ''}</dd>
212
+ <dt>Where</dt><dd>${esc(a.space_label)} · pane ${esc(a.pane)} · ${esc(a.cwd)}</dd>
213
+ ${a.log ? `<dt>Session log</dt><dd class="meta">${esc(a.log)}</dd>` : ''}
214
+ <dt>Summary</dt><dd class="meta">by ${esc(s.by || '?')} · ${ago(a.summarized_at)}</dd>
215
+ </dl>
216
+ <div class="meta" style="margin-bottom:6px">Terminal (bottom of the screen at the last refresh)</div>
217
+ <pre>${esc(a.screen)}</pre>`;
218
+ $('#drawer').classList.add('open');
219
+ $('#drawer .x').onclick = closeDrawer;
220
+ const el = $('#drawer');
221
+ el.dataset.id = a.id;
222
+ wireDrawer(a);
223
+ office.markSelected();
224
+ }
225
+ function wireDrawer(a) {
226
+ $('#drawer').querySelectorAll('button[data-act]').forEach(b => b.onclick = e => {
227
+ e.stopPropagation();
228
+ if (b.disabled) return;
229
+ const k = b.dataset.act;
230
+ if (k === 'focus') return act(a, 'focus');
231
+ if (k === 'info') return;
232
+ armed(b, a, k);
233
+ });
234
+ }
235
+ function closeDrawer() { $('#drawer').classList.remove('open'); selected = null; office.markSelected(); }
236
+
237
+ // ---------------------------------------------------------------- the 3D office
238
+ const office = (() => {
239
+ const host = $('#office'), labels = $('#labels');
240
+ let renderer;
241
+ try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); } catch (e) { return { ok: false, build() {}, markSelected() {}, resize() {}, fit() {} }; }
242
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
243
+ renderer.shadowMap.enabled = true;
244
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
245
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
246
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
247
+ renderer.toneMappingExposure = 1.05;
248
+ host.prepend(renderer.domElement);
249
+ const scene = new THREE.Scene();
250
+ const envMap = new THREE.PMREMGenerator(renderer).fromScene(new RoomEnvironment(renderer), 0.04).texture;
251
+ // comic mode: three-tone cel shading + ink outlines (OutlineEffect = inverted hulls in the shader)
252
+ const outline = new OutlineEffect(renderer, { defaultThickness: 0.0045, defaultColor: [0.09, 0.07, 0.08], defaultAlpha: 1 });
253
+ const grad = new THREE.DataTexture(new Uint8Array([90, 90, 90, 255, 175, 175, 175, 255, 255, 255, 255, 255]), 3, 1, THREE.RGBAFormat);
254
+ grad.minFilter = grad.magFilter = THREE.NearestFilter; grad.needsUpdate = true;
255
+ const toonCache = new Map();
256
+ const NO_LINE = { visible: false };
257
+ function toonOf(m) {
258
+ if (!m.isMeshStandardMaterial) return m;
259
+ let t = toonCache.get(m);
260
+ if (!t) {
261
+ t = new THREE.MeshToonMaterial({ color: m.color, map: m.map, emissive: m.emissive, emissiveIntensity: m.emissiveIntensity, gradientMap: grad,
262
+ transparent: m.transparent, opacity: m.opacity, side: m.side, depthWrite: m.depthWrite });
263
+ t.userData.outlineParameters = m.userData.outlineParameters || (m.transparent ? NO_LINE : undefined);
264
+ toonCache.set(m, t);
265
+ }
266
+ return t;
267
+ }
268
+ function applyStyle(root) {
269
+ scene.environment = ui.toon ? null : envMap;
270
+ hemi.intensity = ui.toon ? 1.3 : 0.35;
271
+ sun.intensity = ui.toon ? 1.8 : 2.0;
272
+ renderer.toneMapping = ui.toon ? THREE.NoToneMapping : THREE.ACESFilmicToneMapping;
273
+ renderer.toneMappingExposure = 0.82;
274
+ if (!ui.toon) return;
275
+ root.traverse(o => { if (o.isMesh && o.material) o.material = toonOf(o.material); });
276
+ }
277
+ const cam = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 500);
278
+ const target = new THREE.Vector3();
279
+ const camDir = new THREE.Vector3(0.36, 0.82, 1.3).normalize();
280
+ let zoom = 1, bounds = { w: 20, d: 20, cx: 0, cz: 0 };
281
+ const hemi = new THREE.HemisphereLight(0xdfe8ff, 0x3a2f28, 0.45); scene.add(hemi);
282
+ const sun = new THREE.DirectionalLight(0xdfe9ff, 2.0);
283
+ sun.castShadow = true;
284
+ sun.shadow.mapSize.set(2048, 2048);
285
+ sun.shadow.bias = -0.0004;
286
+ sun.shadow.normalBias = 0.02;
287
+ sun.shadow.radius = 4;
288
+ scene.add(sun, sun.target);
289
+
290
+ // shared geometries and materials
291
+ const G = {
292
+ box: new THREE.BoxGeometry(1, 1, 1), body: new THREE.CapsuleGeometry(0.34, 0.42, 6, 14), head: new THREE.SphereGeometry(0.36, 22, 16),
293
+ visor: new THREE.SphereGeometry(0.37, 22, 12, -Math.PI * 0.42, Math.PI * 0.84, Math.PI * 0.3, Math.PI * 0.32),
294
+ eye: new THREE.SphereGeometry(0.055, 10, 8), arm: new THREE.CapsuleGeometry(0.07, 0.34, 4, 8), ant: new THREE.CylinderGeometry(0.018, 0.018, 0.3, 6),
295
+ tip: new THREE.SphereGeometry(0.06, 10, 8), wing: new THREE.CircleGeometry(0.32, 20), stripe: new THREE.TorusGeometry(0.345, 0.045, 8, 26),
296
+ plane: new THREE.PlaneGeometry(1, 1), cyl: new THREE.CylinderGeometry(0.05, 0.05, 1, 8), seat: new THREE.CylinderGeometry(0.34, 0.34, 0.08, 18),
297
+ hit: new THREE.BoxGeometry(2.4, 2.4, 2.4), ring: new THREE.RingGeometry(0.5, 0.62, 30),
298
+ mug: new THREE.CylinderGeometry(0.08, 0.07, 0.17, 12), pot: new THREE.CylinderGeometry(0.11, 0.09, 0.18, 10), leaf: new THREE.IcosahedronGeometry(0.2, 0),
299
+ };
300
+ const M = {
301
+ floor: new THREE.MeshStandardMaterial({ color: 0x0b0e15, roughness: 1 }),
302
+ wood: new THREE.MeshStandardMaterial({ color: 0xa47a52, roughness: 0.65 }),
303
+ dark: new THREE.MeshStandardMaterial({ color: 0x1d2433, roughness: 0.5, metalness: 0.3 }),
304
+ metal: new THREE.MeshStandardMaterial({ color: 0x8a94a6, roughness: 0.35, metalness: 0.7 }),
305
+ visor: new THREE.MeshStandardMaterial({ color: 0x0b1020, roughness: 0.15, metalness: 0.6 }),
306
+ stripe: new THREE.MeshStandardMaterial({ color: 0x151515, roughness: 0.6 }),
307
+ wing: new THREE.MeshStandardMaterial({ color: 0xdff3ff, transparent: true, opacity: 0.45, side: THREE.DoubleSide, roughness: 0.1 }),
308
+ hit: new THREE.MeshBasicMaterial({ visible: false }),
309
+ wall: new THREE.MeshStandardMaterial({ color: 0x6f8fb0, roughness: 0.1, metalness: 0.2, transparent: true, opacity: 0.12, depthWrite: false }),
310
+ leaf: new THREE.MeshStandardMaterial({ color: 0x3f9d5a, flatShading: true }),
311
+ };
312
+ const statusMat = {}, bodyMat = {}, rugMat = {};
313
+ const matFor = (cache, key, make) => cache[key] || (cache[key] = make());
314
+ const eyeMat = s => matFor(statusMat, s, () => new THREE.MeshStandardMaterial({ color: st(s).color, emissive: st(s).color, emissiveIntensity: s === 'idle' ? 0.25 : 1.4 }));
315
+ const bodyMatFor = h => matFor(bodyMat, h, () => new THREE.MeshStandardMaterial({ color: new THREE.Color(`hsl(${h}, 72%, 58%)`), roughness: 0.4, metalness: 0.1 }));
316
+ const rugMatFor = h => matFor(rugMat, h, () => { const m = new THREE.MeshStandardMaterial({ color: new THREE.Color(`hsl(${h}, 45%, 16%)`), roughness: 0.35, metalness: 0.5, transparent: true, opacity: 0.85 }); m.userData.outlineParameters = NO_LINE; return m; });
317
+ const accentMat = {};
318
+ const accentFor = h => matFor(accentMat, h, () => new THREE.MeshStandardMaterial({ color: `hsl(${h},70%,55%)`, emissive: `hsl(${h},85%,55%)`, emissiveIntensity: 1.25, toneMapped: false }));
319
+
320
+ // one animated "code" texture shared by every working agent's hologram screen
321
+ const codeCanvas = document.createElement('canvas');
322
+ codeCanvas.width = 256; codeCanvas.height = 160;
323
+ const cg = codeCanvas.getContext('2d');
324
+ const codeTex = new THREE.CanvasTexture(codeCanvas);
325
+ codeTex.colorSpace = THREE.SRGBColorSpace;
326
+ const codeLines = Array.from({ length: 14 }, () => [Math.random() * 30, 40 + Math.random() * 160, Math.random()]);
327
+ let codeScroll = 0;
328
+ function drawCode() {
329
+ cg.fillStyle = 'rgba(6,18,32,0.92)'; cg.fillRect(0, 0, 256, 160);
330
+ cg.strokeStyle = 'rgba(56,189,248,.8)'; cg.lineWidth = 3; cg.strokeRect(1.5, 1.5, 253, 157);
331
+ codeScroll = (codeScroll + 1) % 11;
332
+ codeLines.forEach(([x, w, c], i) => {
333
+ const y = 12 + i * 11 - codeScroll;
334
+ if (y < 6 || y > 152) return;
335
+ cg.fillStyle = c < 0.33 ? '#38bdf8' : c < 0.66 ? '#a5f3fc' : '#f5b83d';
336
+ cg.fillRect(10 + x, y, w, 5);
337
+ });
338
+ codeTex.needsUpdate = true;
339
+ }
340
+ drawCode();
341
+ const holoMat = new THREE.MeshBasicMaterial({ map: codeTex, transparent: true, opacity: 0.6, side: THREE.DoubleSide, toneMapped: false, depthWrite: false });
342
+ const lidMats = {};
343
+ const lidMat = s => matFor(lidMats, s, () => new THREE.MeshStandardMaterial({ color: 0x2a3344, emissive: st(s).color, emissiveIntensity: s === 'idle' ? 0.05 : 0.55, roughness: 0.4 }));
344
+ function signTexture(text, color) {
345
+ const c = document.createElement('canvas'); c.width = c.height = 128;
346
+ const g = c.getContext('2d');
347
+ g.fillStyle = color; g.beginPath(); g.arc(64, 64, 56, 0, Math.PI * 2); g.fill();
348
+ g.fillStyle = '#fff'; g.font = 'bold 76px system-ui'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(text, 64, 70);
349
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
350
+ }
351
+ const signs = {
352
+ blocked: new THREE.SpriteMaterial({ map: signTexture('!', '#f43f5e'), depthTest: false }),
353
+ done: new THREE.SpriteMaterial({ map: signTexture('✓', '#22c55e'), depthTest: false }),
354
+ idle: new THREE.SpriteMaterial({ map: signTexture('z', '#475569'), depthTest: false, opacity: 0.8, transparent: true }),
355
+ };
356
+
357
+ function mesh(geo, mat, x = 0, y = 0, z = 0, sx = 1, sy = 1, sz = 1, shadow = true) {
358
+ const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.scale.set(sx, sy, sz);
359
+ m.castShadow = shadow; m.receiveShadow = true; return m;
360
+ }
361
+ const ship = createShip({ mesh, hue, st });
362
+ scene.background = ship.background; // the ship floats in deep space
363
+ [M.wall, M.floor, M.hit, holoMat].forEach(m => m.userData.outlineParameters = NO_LINE);
364
+ Object.values(signs).forEach(m => m.userData.outlineParameters = NO_LINE);
365
+ // HD: glow on LEDs, screens and stars (bloom), then tone mapping
366
+ const composer = new EffectComposer(renderer);
367
+ composer.addPass(new RenderPass(scene, cam));
368
+ const bloom = new UnrealBloomPass(new THREE.Vector2(256, 256), 0.42, 0.4, 0.96);
369
+ composer.addPass(bloom);
370
+ composer.addPass(new OutputPass());
371
+
372
+
373
+ function makeDesk(a, x, z) {
374
+ const h = hue(a.space), g = new THREE.Group();
375
+ g.position.set(x, 0, z);
376
+ const station = ship.makeStation(g, a, h, holoMat);
377
+ const b = ship.makeRobot(h, a.status, false, a.name);
378
+ b.bot.position.set(0, b.hover ? 0.2 : 0.02, -0.9);
379
+ if (b.glb) b.bot.position.set(0, b.seated ? 0.36 : 0, b.seated ? -1.05 : -0.85);
380
+ if (b.hover) station.chair.visible = false;
381
+ g.add(b.bot);
382
+ // coordinator: its swarm team stands beside the desk
383
+ const team = [];
384
+ (a.team || []).slice(0, 6).forEach((m, i) => {
385
+ const t = ship.makeRobot(h, m.status, true, a.name + '/' + m.name);
386
+ t.bot.position.set(1.35 + (i % 2) * 0.45, 0, -0.75 + Math.floor(i / 2) * 0.5);
387
+ t.bot.rotation.y = -0.5; t.bot.position.y += t.hover ? 0.25 : 0.05;
388
+ g.add(t.bot); team.push({ ...t, status: m.status, ph: Math.random() * 6 });
389
+ });
390
+ // status things: hologram for working, a sign above everyone else
391
+ let holo = null, sign = null;
392
+ if (a.status === 'working') {
393
+ holo = station.screen;
394
+ } else if (signs[a.status]) {
395
+ sign = new THREE.Sprite(signs[a.status]); sign.position.set(0.85, 2.05, -0.9); sign.scale.setScalar(a.status === 'blocked' ? 0.55 : 0.4);
396
+ sign.renderOrder = 5; g.add(sign);
397
+ }
398
+ const ring = mesh(G.ring, new THREE.MeshBasicMaterial({ color: 0xf5b83d, transparent: true, opacity: 0, side: THREE.DoubleSide }), 0, 0.02, -0.85, 1.4, 1.4, 1.4, false);
399
+ ring.rotation.x = -Math.PI / 2; g.add(ring);
400
+ const hit = mesh(G.hit, M.hit, 0, 1.1, -0.4, 1, 1, 1, false); hit.userData.id = a.id; g.add(hit);
401
+ if (a.status === 'idle') { b.head.rotation.x = 0.08; b.arms.forEach(p => { p.rotation.x = -0.3; }); } // powered down: head bowed
402
+ if (a.status === 'done') { b.arms.forEach((p, i) => { p.rotation.x = -1.35; p.rotation.z = (i ? -1 : 1) * 0.9; }); } // arms folded
403
+ if (a.status === 'blocked' && b.arms[1]) { b.arms[1].rotation.x = -2.9; b.arms[1].rotation.z = 0.3; }
404
+ return { g, bot: b, holo, sign, team, ring, hit, a, ph: Math.random() * 6, anchor: new THREE.Vector3(x, 2.5, z - 0.9) };
405
+ }
406
+
407
+
408
+
409
+ let world = new THREE.Group(), desks = [], rooms = [], tags = new Map(), roomTags = [], ordered = [];
410
+ scene.add(world);
411
+ const floor = mesh(new THREE.PlaneGeometry(1, 1), M.floor, 0, -0.01, 0, 1, 1, 1, false);
412
+ floor.rotation.x = -Math.PI / 2; scene.add(floor);
413
+ const grid = new THREE.GridHelper(1, 1, 0x1f2838, 0x1a2230); scene.add(grid);
414
+
415
+ function addTag(a, d) {
416
+ const el = document.createElement('div');
417
+ el.className = `tag ${a.status} ${a.status === 'blocked' || a.status === 'working' ? 'hot' : ''}`;
418
+ const s = a.summary || {};
419
+ el.innerHTML = `<div class="bubble">${esc(s.needs_you && a.status === 'blocked' ? '✋ ' + s.needs_you : s.bubble || s.job || '…')}</div>
420
+ <div class="plate"><span class="dot" style="background:${st(a.status).color}"></span><b>${esc(a.name)}</b>${a.team?.length ? ` 👥${a.team.length}` : ''} ${a.context ? ring(a.context_pct, 14) + a.context_pct + '%' : ''}</div>`;
421
+ labels.appendChild(el);
422
+ tags.set(a.id, { el, d, prio: ({ blocked: 0, working: 1, done: 2, idle: 3 }[a.status] ?? 4) - (a.summary?.needs_you ? 0.5 : 0) });
423
+ }
424
+ function build(list) {
425
+ scene.remove(world); world = new THREE.Group(); scene.add(world);
426
+ desks = []; labels.innerHTML = ''; tags = new Map(); roomTags = [];
427
+ // the CEO's space gets the captain's bridge; everyone else gets team rooms
428
+ const isCeo = a => /^ceo$/i.test(a.space || '');
429
+ const ceo = list.filter(isCeo);
430
+ list = list.filter(a => !isCeo(a));
431
+ // rooms = spaces, most urgent first; desks in rows of 3 inside each room
432
+ const order = { blocked: 0, working: 1, done: 2, idle: 3 };
433
+ const bySpace = new Map();
434
+ list.forEach(a => { if (!bySpace.has(a.workspace)) bySpace.set(a.workspace, []); bySpace.get(a.workspace).push(a); });
435
+ const spaces = [...bySpace.values()].sort((x, y) => Math.min(...x.map(a => order[a.status] ?? 9)) - Math.min(...y.map(a => order[a.status] ?? 9)) || y.length - x.length);
436
+ const DX = 4.2, DZ = 4.4, PAD = 1.2, GAP = 1.6;
437
+ const sizes = spaces.map(s => { const cols = Math.min(3, s.length), rows = Math.ceil(s.length / 3), wide = s.some(a => a.team?.length);
438
+ return { s, cols, rows, w: cols * DX + PAD * 2 + (wide ? 1.2 : 0), d: rows * DZ + PAD * 2 }; });
439
+ const area = sizes.reduce((t, r) => t + (r.w + GAP) * (r.d + GAP), 0);
440
+ const maxW = Math.max(Math.sqrt(area) * 1.5, ...sizes.map(r => r.w));
441
+ let x = 0, z = 0, rowD = 0, W = 0;
442
+ sizes.forEach(r => {
443
+ if (x > 0 && x + r.w > maxW) { x = 0; z += rowD + GAP; rowD = 0; }
444
+ r.x = x; r.z = z; x += r.w + GAP; rowD = Math.max(rowD, r.d); W = Math.max(W, x - GAP);
445
+ });
446
+ const D = z + rowD;
447
+ const ox = -W / 2, oz = -D / 2;
448
+ sizes.forEach(r => {
449
+ const h = hue(r.s[0].space), rx = ox + r.x, rz = oz + r.z;
450
+ const rug = mesh(G.plane, rugMatFor(h), rx + r.w / 2, 0.006, rz + r.d / 2, r.w - 0.3, r.d - 0.3, 1, false);
451
+ rug.rotation.x = -Math.PI / 2; world.add(rug);
452
+ world.add(mesh(G.box, M.wall, rx + r.w / 2, 0.5, rz + 0.06, r.w, 1.0, 0.06, false), mesh(G.box, M.wall, rx + 0.06, 0.5, rz + r.d / 2, 0.06, 1.0, r.d, false));
453
+ ship.pod(world, rx + r.w - 0.6, rz + 0.6);
454
+ world.add(mesh(G.box, accentFor(h), rx + r.w / 2, 1.02, rz + 0.06, r.w, 0.05, 0.1, false), mesh(G.box, accentFor(h), rx + 0.06, 1.02, rz + r.d / 2, 0.1, 0.05, r.d, false));
455
+ r.s.sort((a, b) => (b.team?.length || 0) - (a.team?.length || 0) || (order[a.status] ?? 9) - (order[b.status] ?? 9));
456
+ r.s.forEach((a, i) => {
457
+ const d = makeDesk(a, rx + PAD + DX / 2 + (i % 3) * DX, rz + PAD + 1.6 + Math.floor(i / 3) * DZ);
458
+ world.add(d.g); desks.push(d); addTag(a, d);
459
+ });
460
+ const rl = document.createElement('div');
461
+ rl.className = 'room-label'; rl.textContent = `${r.s[0].emoji} ${r.s[0].space}`;
462
+ labels.appendChild(rl); roomTags.push({ el: rl, p: new THREE.Vector3(rx + 0.3, 0.9, rz + r.d + 0.2) });
463
+ });
464
+ const e = ship.decorate(world, Math.max(W, 8), Math.max(D, 8));
465
+ const br = ship.bridge(world, e);
466
+ ceo.sort((a, b) => (a.role === 'session') - (b.role === 'session') || (order[a.status] ?? 9) - (order[b.status] ?? 9));
467
+ ceo.slice(0, br.slots.length).forEach((a, i) => {
468
+ const slot = br.slots[i], d = makeDesk(a, slot.x, slot.z);
469
+ if (slot.captain) { d.g.scale.setScalar(1.18); d.anchor.y *= 1.18; }
470
+ world.add(d.g); desks.push(d); addTag(a, d);
471
+ });
472
+ const bl = document.createElement('div');
473
+ bl.className = 'room-label'; bl.textContent = `${ceo[0]?.emoji || '👔'} ceo · captain's bridge`;
474
+ labels.appendChild(bl); roomTags.push({ el: bl, p: br.label });
475
+ e.maxX = Math.max(e.maxX, br.bounds.maxX);
476
+ // measure each label once (bubble and plate), for the overlap pass in placeLabels
477
+ tags.forEach(t => {
478
+ const b = t.el.querySelector('.bubble'), pl = t.el.querySelector('.plate');
479
+ t.el.style.display = 'flex';
480
+ t.bw = b.offsetWidth; t.bh = b.offsetHeight + 4; t.pw = pl.offsetWidth; t.ph = pl.offsetHeight;
481
+ });
482
+ ordered = [...tags.values()].sort((x, y) => x.prio - y.prio);
483
+ bounds = { w: e.maxX - e.minX, d: e.maxZ - e.minZ, cx: (e.minX + e.maxX) / 2, cz: (e.minZ + e.maxZ) / 2 };
484
+ const big = Math.max(bounds.w, bounds.d) * 3 + 40;
485
+ floor.visible = false;
486
+ grid.visible = false;
487
+ const span = Math.max(bounds.w, bounds.d) * 0.62;
488
+ sun.position.set(bounds.cx + span * 0.55, span * 1.1 + 10, bounds.cz + span * 0.75); sun.target.position.set(bounds.cx, 0, bounds.cz);
489
+ Object.assign(sun.shadow.camera, { left: -span, right: span, top: span, bottom: -span, near: 1, far: span * 4 + 40 });
490
+ sun.shadow.camera.updateProjectionMatrix();
491
+ applyStyle(world);
492
+ markSelected();
493
+ if (!build.done) { fit(); build.done = true; }
494
+ dirty = true;
495
+ }
496
+
497
+ function resize() {
498
+ const w = host.clientWidth, h = host.clientHeight;
499
+ renderer.setSize(w, h);
500
+ composer.setPixelRatio(renderer.getPixelRatio()); composer.setSize(w, h);
501
+ const aspect = w / Math.max(1, h);
502
+ const half = 10 / zoom;
503
+ cam.left = -half * aspect; cam.right = half * aspect; cam.top = half; cam.bottom = -half;
504
+ cam.updateProjectionMatrix();
505
+ dirty = true;
506
+ }
507
+ function placeCam() {
508
+ cam.position.copy(target).addScaledVector(camDir, 120);
509
+ cam.lookAt(target);
510
+ dirty = true;
511
+ }
512
+ // fit = project the office's corners into the camera's view and frame them with a margin
513
+ function fit() {
514
+ target.set(bounds.cx, 0, bounds.cz);
515
+ placeCam(); cam.updateMatrixWorld();
516
+ const inv = cam.matrixWorldInverse, p = new THREE.Vector3();
517
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
518
+ for (const x of [-bounds.w / 2, bounds.w / 2]) for (const z of [-bounds.d / 2, bounds.d / 2]) for (const y of [0, 3.6]) {
519
+ p.set(bounds.cx + x, y, bounds.cz + z).applyMatrix4(inv);
520
+ x0 = Math.min(x0, p.x); x1 = Math.max(x1, p.x); y0 = Math.min(y0, p.y); y1 = Math.max(y1, p.y);
521
+ }
522
+ const aspect = host.clientWidth / Math.max(1, host.clientHeight);
523
+ const halfH = Math.max((y1 - y0) / 2, (x1 - x0) / 2 / aspect) * 1.08 + 0.6;
524
+ zoom = THREE.MathUtils.clamp(10 / halfH, 0.06, 3.5);
525
+ const right = new THREE.Vector3().setFromMatrixColumn(cam.matrixWorld, 0), up = new THREE.Vector3().setFromMatrixColumn(cam.matrixWorld, 1);
526
+ target.addScaledVector(right, (x0 + x1) / 2).addScaledVector(up, (y0 + y1) / 2);
527
+ resize(); placeCam();
528
+ }
529
+
530
+ // input: drag to pan, wheel to zoom at the cursor, click to open, right-click for details
531
+ const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
532
+ let drag = null, hovered = null, dirty = true;
533
+ const canvas = renderer.domElement;
534
+ function pick(e) {
535
+ const r = canvas.getBoundingClientRect();
536
+ ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
537
+ ray.setFromCamera(ndc, cam);
538
+ const hit = ray.intersectObjects(desks.map(d => d.hit), false)[0];
539
+ return hit ? desks.find(d => d.hit === hit.object) : null;
540
+ }
541
+ function worldAt(e) {
542
+ const r = canvas.getBoundingClientRect();
543
+ ndc.set(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
544
+ ray.setFromCamera(ndc, cam);
545
+ const p = new THREE.Vector3();
546
+ ray.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 1, 0), 0), p);
547
+ return p;
548
+ }
549
+ canvas.addEventListener('pointerdown', e => { if (e.button !== 0) return; drag = { x: e.clientX, y: e.clientY, p: worldAt(e), moved: false }; canvas.setPointerCapture(e.pointerId); });
550
+ canvas.addEventListener('pointermove', e => {
551
+ if (drag) {
552
+ if (Math.hypot(e.clientX - drag.x, e.clientY - drag.y) > 4) { drag.moved = true; canvas.classList.add('drag'); }
553
+ if (drag.moved) { const p = worldAt(e); target.sub(p.sub(drag.p)); placeCam(); }
554
+ return;
555
+ }
556
+ const d = pick(e);
557
+ setHover(d, e);
558
+ });
559
+ canvas.addEventListener('pointerup', e => {
560
+ canvas.classList.remove('drag');
561
+ if (drag && !drag.moved) { const d = pick(e); if (d) act(d.a, 'focus'); }
562
+ drag = null;
563
+ });
564
+ canvas.addEventListener('pointerleave', () => setHover(null));
565
+ canvas.addEventListener('contextmenu', e => { e.preventDefault(); const d = pick(e); if (d) openDrawer(d.a); });
566
+ canvas.addEventListener('dblclick', e => { const d = pick(e); if (!d) { const p = worldAt(e); target.copy(p); zoom = Math.min(3, zoom * 1.8); resize(); placeCam(); } });
567
+ canvas.addEventListener('wheel', e => {
568
+ e.preventDefault();
569
+ const before = worldAt(e);
570
+ zoom = THREE.MathUtils.clamp(zoom * Math.exp(-e.deltaY * 0.0015), 0.06, 3.5);
571
+ resize(); placeCam();
572
+ const after = worldAt(e);
573
+ target.add(before.sub(after)); placeCam();
574
+ }, { passive: false });
575
+ function setHover(d, e) {
576
+ const tip = $('#tip');
577
+ if (hovered && hovered !== d) { hovered.ring.material.opacity = selected === hovered.a.id ? 0.9 : 0; tags.get(hovered.a.id)?.el.classList.remove('hover'); }
578
+ hovered = d;
579
+ canvas.style.cursor = d ? 'pointer' : 'grab';
580
+ if (!d) { tip.style.display = 'none'; dirty = true; return; }
581
+ d.ring.material.opacity = 0.9;
582
+ const a = d.a, s = a.summary || {};
583
+ tip.innerHTML = `<h4>${esc(a.emoji)} ${esc(a.name)}</h4><div class="meta">${st(a.status).emoji} ${st(a.status).label} · ${esc(a.cli)}${a.model ? ' · ' + esc(model(a.model)) : ''} · ${ago(a.last_activity)}</div>
584
+ <div style="margin:7px 0">📌 <b>${esc(s.job)}</b></div><div>${esc(s.bubble)}</div>
585
+ ${s.needs_you ? `<div class="need" style="margin-top:6px;color:#fecdd3">✋ ${esc(s.needs_you)}</div>` : ''}
586
+ ${(s.done || []).length ? `<div style="margin-top:6px;color:#c7d0de">${s.done.map(x => '✓ ' + esc(x)).join('<br>')}</div>` : ''}
587
+ <div class="ctx">🧠 ${a.context ? `${a.context_pct}% of ${ktok(a.window)}` : 'no session log'} ${adviceBadge(a)}</div>
588
+ <div class="hint">click: open in hivey · right-click: details</div>`;
589
+ tip.style.display = 'block';
590
+ const x = Math.min(e.clientX + 16, innerWidth - 360), y = Math.min(e.clientY + 16, innerHeight - tip.offsetHeight - 10);
591
+ tip.style.left = x + 'px'; tip.style.top = y + 'px';
592
+ tags.get(a.id)?.el.classList.add('hover');
593
+ dirty = true;
594
+ if (!REDUCED) placeLabels();
595
+ }
596
+ function markSelected() {
597
+ desks.forEach(d => { d.ring.material.opacity = d.a.id === selected ? 0.9 : 0; tags.get(d.a.id)?.el.classList.toggle('sel', d.a.id === selected); });
598
+ dirty = true;
599
+ }
600
+
601
+ // labels follow their agents; level of detail by zoom so hundreds stay readable
602
+ const v = new THREE.Vector3();
603
+ function placeLabels() {
604
+ const w = host.clientWidth, h = host.clientHeight;
605
+ const px = zoom * h / 20; // pixels per world unit
606
+ labels.className = px < 7 ? 'lod-tiny' : '';
607
+ // most urgent first; a label that would cover one already placed drops its bubble, then its plate
608
+ const placed = [];
609
+ const hits = (x0, y0, x1, y1) => placed.some(r => x0 < r[2] && x1 > r[0] && y0 < r[3] && y1 > r[1]);
610
+ const first = ordered.filter(t => t.d.a.id === selected || t.el.classList.contains('hover'));
611
+ for (const t of [...first, ...ordered.filter(t => !first.includes(t))]) {
612
+ const { el, d } = t;
613
+ v.copy(d.anchor).project(cam);
614
+ const x = (v.x + 1) / 2 * w, y = (1 - v.y) / 2 * h;
615
+ if (x < -200 || x > w + 200 || y < -100 || y > h + 300) { el.style.display = 'none'; continue; }
616
+ const forced = first.includes(t);
617
+ const pw = t.pw / 2, bw = Math.max(t.bw, t.pw) / 2;
618
+ let mode = 'full';
619
+ if (!forced && (labels.className === 'lod-tiny' || hits(x - bw, y - t.ph - t.bh, x + bw, y))) mode = hits(x - pw, y - t.ph, x + pw, y) ? 'none' : 'plate';
620
+ if (mode === 'none' && d.a.status === 'blocked') mode = 'plate';
621
+ el.style.display = mode === 'none' ? 'none' : 'flex';
622
+ el.classList.toggle('nobubble', mode === 'plate');
623
+ if (mode === 'none') continue;
624
+ placed.push(mode === 'full' ? [x - bw, y - t.ph - t.bh, x + bw, y] : [x - pw, y - t.ph, x + pw, y]);
625
+ el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -100%)`;
626
+ }
627
+ roomTags.forEach(({ el, p }) => { v.copy(p).project(cam); el.style.transform = `translate(${(v.x + 1) / 2 * w}px, ${(1 - v.y) / 2 * h}px)`; });
628
+ }
629
+ // the hover class keeps a bubble visible while zoomed out
630
+ const style = document.createElement('style');
631
+ style.textContent = '.tag.nobubble .bubble{display:none}.tag.hover .bubble,.tag.sel .bubble{display:block!important}.tag.hover,.tag.sel{display:flex!important;z-index:2}';
632
+ document.head.appendChild(style);
633
+
634
+ // animation: only working agents (and their team) move; a waiting agent waves; the rest stand still
635
+ let last = 0, lastCode = 0;
636
+ function frame(t) {
637
+ requestAnimationFrame(frame);
638
+ if (document.hidden || ui.view !== 'office') return;
639
+ const moving = !REDUCED && desks.some(d => d.a.status === 'working' || d.a.status === 'blocked' || d.team.some(m => m.status === 'working'));
640
+ const dt = Math.min(0.1, (t - (frame.prev || t)) / 1000); frame.prev = t;
641
+ if (!moving && !dirty) return;
642
+ if (moving && t - last < 33) return; // ~30 fps is plenty
643
+ last = t;
644
+ const s = t / 1000;
645
+ if (moving) {
646
+ const pl = ship.planet(); if (pl) pl.rotation.y = s * 0.4;
647
+ if (t - lastCode > 110) { drawCode(); lastCode = t; }
648
+ for (const d of desks) {
649
+ const b = d.bot, ph = d.ph;
650
+ if (b.tick) { b.tick(dt, s); d.team.forEach(m => m.tick?.(dt, s)); if (d.holo) d.holo.position.y = 2.15 + Math.sin(s * 2 + ph) * 0.04; continue; }
651
+ if (d.a.status === 'working') {
652
+ b.body.position.y = Math.sin(s * 7 + ph) * 0.025;
653
+ b.arms[0].rotation.x = -1.15 + Math.sin(s * 16 + ph) * 0.28;
654
+ b.arms[1].rotation.x = -1.15 + Math.sin(s * 16 + ph + Math.PI) * 0.28;
655
+ b.head.rotation.y = Math.sin(s * 1.4 + ph) * 0.3;
656
+ b.head.rotation.x = -0.08 + Math.sin(s * 2.1 + ph) * 0.06;
657
+ if (b.scan) b.scan.position.x = Math.sin(s * 3.2 + ph) * 0.13;
658
+ if (b.hover) b.bot.position.y = 0.2 + Math.sin(s * 2.4 + ph) * 0.05;
659
+ b.wings.forEach((w, i) => w.rotation.y = (i ? -1 : 1) * (0.25 + Math.sin(s * 38 + ph) * 0.35));
660
+ if (d.holo) d.holo.position.y = 1.95 + Math.sin(s * 2 + ph) * 0.05;
661
+ } else if (d.a.status === 'blocked') {
662
+ b.arms[1].rotation.z = 0.3 + Math.sin(s * 6 + ph) * 0.35;
663
+ b.body.position.y = Math.abs(Math.sin(s * 3 + ph)) * 0.06;
664
+ if (d.sign) d.sign.scale.setScalar(0.5 + Math.sin(s * 5) * 0.07);
665
+ }
666
+ for (const m of d.team) {
667
+ if (m.status !== 'working') continue;
668
+ m.body.position.y = Math.abs(Math.sin(s * 5 + m.ph)) * 0.18;
669
+ m.wings.forEach((w, i) => w.rotation.y = (i ? -1 : 1) * (0.25 + Math.sin(s * 40 + m.ph) * 0.4));
670
+ }
671
+ }
672
+ }
673
+ if (ui.toon) outline.render(scene, cam); else composer.render();
674
+ placeLabels();
675
+ dirty = false;
676
+ }
677
+ new ResizeObserver(() => { resize(); }).observe(host);
678
+ resize(); placeCam();
679
+ requestAnimationFrame(frame);
680
+ return { ok: true, build, markSelected, resize, fit, ready: ship.load() };
681
+ })();
682
+
683
+ // ---------------------------------------------------------------- views, polling, keys
684
+ let lastGenerated = null, refreshing = false;
685
+ function renderAll() {
686
+ if (!data) return;
687
+ agents = data.agents || [];
688
+ renderHeader();
689
+ renderInbox();
690
+ document.querySelectorAll('#views button').forEach(b => b.classList.toggle('on', b.dataset.v === ui.view));
691
+ $('#office').style.display = ui.view === 'office' ? '' : 'none';
692
+ $('#board').style.display = ui.view === 'board' ? 'block' : 'none';
693
+ $('#list').style.display = ui.view === 'list' ? 'block' : 'none';
694
+ if (ui.view === 'office') { office.build(agents.filter(visible)); office.resize(); }
695
+ if (ui.view === 'board') renderBoard();
696
+ if (ui.view === 'list') renderList();
697
+ if (selected) { const a = agents.find(x => x.id === selected); if (a && $('#drawer').classList.contains('open')) openDrawer(a); }
698
+ }
699
+ async function poll() {
700
+ try {
701
+ if (office.ready) await office.ready.catch(() => {});
702
+ const r = await fetch('./office.json?ts=' + Date.now(), { cache: 'no-store' });
703
+ const j = await r.json();
704
+ if (j.generated !== lastGenerated) {
705
+ lastGenerated = j.generated; data = j;
706
+ if (refreshing && Date.parse(j.generated) > refreshing) { refreshing = false; $('#refresh').innerHTML = '⟳'; toast('Office updated'); }
707
+ renderAll();
708
+ }
709
+ } catch (e) { console.error('hivey office:', e); $('#sub').textContent = 'cannot read office.json: is the office server running? (hivey menu → agent office)'; }
710
+ }
711
+ async function refreshNow() {
712
+ if (refreshing) return;
713
+ refreshing = Date.now();
714
+ $('#refresh').innerHTML = '<span class="spin">⟳</span>';
715
+ tickSub();
716
+ try { await fetch('/hv-office-refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }); }
717
+ catch (e) { toast('The office server is not answering'); refreshing = false; $('#refresh').innerHTML = '⟳'; }
718
+ setTimeout(() => { if (refreshing) { refreshing = false; $('#refresh').innerHTML = '⟳'; } }, 180000);
719
+ }
720
+ document.querySelectorAll('#views button').forEach(b => b.onclick = () => { ui.view = b.dataset.v; save(); renderAll(); });
721
+ $('#refresh').onclick = refreshNow;
722
+ // background music: a MusicGen space ambient loop, off until you turn it on (browsers block autoplay)
723
+ const bgm = $('#bgm');
724
+ bgm.volume = 0.35;
725
+ function setMusic(on) {
726
+ ui.music = on; save();
727
+ $('#music').textContent = on ? '🎵' : '🔇';
728
+ $('#music').title = on ? 'Music on: click to mute (m)' : 'Background music on/off (m)';
729
+ if (on) bgm.play().catch(() => { $('#music').textContent = '🔇'; toast('Click 🔇 to start the music'); }); else bgm.pause();
730
+ }
731
+ $('#music').onclick = () => setMusic(!ui.music);
732
+ if (ui.music) addEventListener('pointerdown', () => { if (ui.music && bgm.paused) setMusic(true); }, { once: true });
733
+ $('#music').textContent = ui.music ? '🎵' : '🔇';
734
+ $('#fit').onclick = () => office.fit();
735
+ function toggleStyle() { ui.toon = !ui.toon; save(); $('#style').textContent = ui.toon ? '🎨 comic' : '✨ HD'; renderAll(); }
736
+ $('#style').onclick = toggleStyle;
737
+ $('#style').textContent = ui.toon ? '🎨 comic' : '✨ HD';
738
+ let qTimer;
739
+ $('#q').addEventListener('input', () => { clearTimeout(qTimer); qTimer = setTimeout(renderAll, 150); });
740
+ addEventListener('keydown', e => {
741
+ if (e.target.matches('input')) { if (e.key === 'Escape') { e.target.value = ''; e.target.blur(); renderAll(); } return; }
742
+ if (e.key === '/') { e.preventDefault(); $('#q').focus(); }
743
+ else if (e.key === 'Escape') closeDrawer();
744
+ else if (e.key === '1' || e.key === '2' || e.key === '3') { ui.view = ['office', 'board', 'list'][+e.key - 1]; save(); renderAll(); }
745
+ else if (e.key === 'r') refreshNow();
746
+ else if (e.key === 'f') office.fit();
747
+ else if (e.key === 't') toggleStyle();
748
+ else if (e.key === 'm') setMusic(!ui.music);
749
+ });
750
+ if (!office.ok && ui.view === 'office') ui.view = 'board';
751
+ if (!office.ok) document.querySelector('#views [data-v="office"]').disabled = true;
752
+ setInterval(poll, 15000);
753
+ setInterval(tickSub, 1000);
754
+ poll();