@hivey/cli 0.9.63 → 0.9.65

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivey/cli",
3
- "version": "0.9.63",
3
+ "version": "0.9.65",
4
4
  "description": "All your AI swarms, one terminal: a workspace and lead agent for teams of Claude Code and Codex agents",
5
5
  "keywords": [
6
6
  "hivey",
@@ -182,18 +182,23 @@ hivey agent-map schedule install [--at 06:30] [--model sonnet] # | remove | st
182
182
  ## Agent office (what every agent does now)
183
183
 
184
184
  `hivey agent-map office` (hivey menu → agent office) opens http://127.0.0.1:42817/office/: every live
185
- agent in hivey at a desk in a 3D office, one room per space. Solo agents, extra sessions in a space and
185
+ agent in hivey at a desk in a 3D office, one room per space, and one spaceship per hivey session (`hivey session list`: the default session flies the classic frigate, the others a carrier, an explorer or a recoloured frigate, their name painted on the hull; a stopped session's ship has cold engines and its agents asleep at their desks, read from its saved `session.json`; a running one's engines burn). Click an agent to open its session in a terminal: the one already showing it, or a new Terminal/iTerm window running `hivey session attach <name>`, which also starts a stopped session. Click the name painted on a ship's hull for its menu (hover shows its agent count): open/start the session, or stop it (a second click confirms; `hivey session stop` ends all its agents and closes its terminal; never the default session). The space outside is one of six scenes (violet, emerald, crimson, deep blue, golden twin suns, a singularity with its lensed accretion disk), chosen with the page's 🌌 setting: a new one on every load, or always the one you pick (saved with the ⏱ setting; `?space=1..6` in the address overrides it). Drag the hull name to move the ship; positions are kept in `~/.hivey/agent-map/office-settings.json` with the ⏱ setting. Open, compact and clear reach the agent through its own session's socket. After a /compact the context shown is the compacted size until the agent's next reply. Solo agents, extra sessions in a space and
186
186
  each swarm's coordinator get a desk; a swarm's workers and critics stand beside their coordinator's desk.
187
187
 
188
188
  - **Reads** each desk's terminal (`hivey pane read`, any CLI) and its Claude Code session log (context
189
189
  size = input + cache tokens of the last reply, model, last prompt, the session recap, last replies and
190
190
  tools). `office.py run` writes `~/.hivey/agent-map/reports/office/office.json`.
191
- - **Summarizes** with Sonnet (`claude -p --model sonnet`, no tools, no settings, no session saved), in
191
+ - **Summarizes** with Haiku (`claude -p --model haiku`, no tools, no settings, no session saved), in
192
192
  batches of 10, only the desks whose terminal or log changed (`~/.hivey/agent-map/office-cache.json`):
193
193
  current job, a speech-bubble line, up to 3 achievements, next step, what to answer when it waits
194
194
  for you, and keep / compact / clear advice. `--no-llm` (or a failed call) falls back to the recap.
195
- - **Refreshes** every 5 minutes while the page is open (the server's office clock; the page polls every
196
- 15 s), or now with ⟳ / `r`.
195
+ - **Refreshes** while the page is open (the server's office clock; the page polls every 15 s): a live
196
+ pass every minute and when the page loads (`run --quick`: status, context and terminal are fresh,
197
+ only desks whose status changed go to the model) and a full pass every 5 minutes (every desk whose
198
+ terminal changed), or a full pass now with ⟳ / `r`. The page's ⏱ setting picks every minute (that),
199
+ every 5 min, 15 min or hour (full passes only) or on reload only (no clock: a full pass when the page loads or on ⟳),
200
+ saved in `~/.hivey/agent-map/office-settings.json`. The header shows the time of the last update, of
201
+ the last full summary pass and of the next update.
197
202
  - **Page**: Office (Three.js r160, MIT, vendored in `scripts/office/` with RoomEnvironment, OutlineEffect and the bloom
198
203
  post-processing; `ship.js` builds the scene: the deck of a spacecraft floating in front of a galaxy, viewports, hull
199
204
  light strips, an observation lounge with a holotable, galley, server racks, plant pods; the crew are mini robots,
@@ -1079,7 +1079,7 @@ def main() -> int:
1079
1079
  of = sub.add_parser("office", help="the agent office: what every live agent does now (open | run)")
1080
1080
  of.add_argument("action", choices=["open", "run"], nargs="?", default="open")
1081
1081
  of.add_argument("--no-llm", action="store_true", help="run: summaries from the session recap, no model")
1082
- of.add_argument("--model", default="sonnet")
1082
+ of.add_argument("--model", default="haiku")
1083
1083
  cx = sub.add_parser("context", help="context window per agent: list, or set standard | 1M")
1084
1084
  cx.add_argument("agents", nargs="*", help="agent names (as on the Sessions page) or folders")
1085
1085
  cx.add_argument("--set", choices=["standard", "1M", "1m"], help="standard = 200k, compacts early; 1M = large")
@@ -38,6 +38,8 @@ header{position:sticky;top:0;z-index:20;display:flex;flex-wrap:wrap;align-items:
38
38
  .seg button.on{background:var(--panel2);color:var(--text);box-shadow:inset 0 -2px 0 var(--honey)}
39
39
  .iconbtn{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:7px 11px}
40
40
  .iconbtn:hover{border-color:var(--honey)}
41
+ .every{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:7px 9px;color:inherit;font:inherit;cursor:pointer}
42
+ .every:hover{border-color:var(--honey)}
41
43
  .spin{display:inline-block;animation:spin 1s linear infinite}
42
44
  @keyframes spin{to{transform:rotate(360deg)}}
43
45
  /* ---------- needs-you inbox ---------- */
@@ -74,6 +76,19 @@ main{position:relative}
74
76
  .room-label{position:absolute;transform:translate(0,-50%);font-weight:700;font-size:13px;color:#cbd5e1;
75
77
  text-shadow:0 1px 6px #000;white-space:nowrap;letter-spacing:.2px}
76
78
  .lod-tiny .room-label{font-size:11px}
79
+ .ship-label{position:absolute;left:0;top:0;border-radius:8px;border:1px solid transparent;pointer-events:auto;transition:background .15s,border-color .15s}
80
+ .ship-label .cap{position:absolute;top:100%;left:50%;transform:translateX(-50%);margin-top:4px;white-space:nowrap;font-size:11px;color:#cfe0ff;
81
+ background:rgba(10,16,32,.8);border:1px solid rgba(120,170,255,.35);border-radius:999px;padding:2px 9px;opacity:0;transition:opacity .15s;pointer-events:none}
82
+ .ship-label:hover,.ship-label.dragging{background:rgba(255,200,80,.10);border-color:rgba(255,200,80,.55)}
83
+ .ship-label:hover .cap,.ship-label.dragging .cap{opacity:1}
84
+ .ship-menu{position:fixed;z-index:60;min-width:210px;background:rgba(12,18,34,.96);border:1px solid rgba(120,170,255,.45);border-radius:12px;padding:8px;
85
+ box-shadow:0 10px 30px rgba(0,0,0,.5);display:flex;flex-direction:column;gap:6px}
86
+ .ship-menu .t{font-weight:700;padding:2px 4px 4px;text-transform:uppercase;letter-spacing:.05em;font-size:12px;color:#cfe0ff}
87
+ .ship-menu button{text-align:left;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:7px 10px;color:inherit;cursor:pointer}
88
+ .ship-menu button:hover{border-color:var(--honey)}
89
+ .ship-menu button.danger{color:#fda4af}.ship-menu button.danger.arm{background:#7f1d1d;color:#fff;border-color:#fb7185}
90
+ .ship-menu .note{font-size:11px;color:#93a4c3;padding:0 4px}
91
+ .ship-label{cursor:grab;touch-action:none;user-select:none}.ship-label.dragging{cursor:grabbing;border-color:var(--honey)}
77
92
  #hud{position:absolute;left:14px;bottom:12px;display:flex;gap:8px;align-items:center;color:var(--muted);font-size:12px}
78
93
  #hud button{background:rgba(21,27,39,.9);border:1px solid var(--line);border-radius:9px;padding:5px 9px}
79
94
  #tip{position:fixed;z-index:30;pointer-events:none;max-width:340px;padding:11px 13px;border-radius:12px;background:rgba(21,27,39,.97);
@@ -156,11 +171,27 @@ td.j{max-width:420px}
156
171
  <div class="spacer"></div>
157
172
  <input class="search" id="q" placeholder="Search agents, jobs… ( / )" autocomplete="off">
158
173
  <div class="seg" id="views">
159
- <button data-v="office" title="3D office (1)">🏢 Office</button>
174
+ <button data-v="office" title="Your spaceships, one per hivey session (1)">🚀 Fleet</button>
160
175
  <button data-v="board" title="Cards by what needs you (2)">▦ Board</button>
161
176
  <button data-v="list" title="One row per agent, for hundreds (3)">☰ List</button>
162
177
  </div>
163
178
  <button class="iconbtn" id="music" title="Background music on/off (m)">🔇</button>
179
+ <select class="every" id="every" title="How the office updates itself">
180
+ <option value="minute">⏱ every minute</option>
181
+ <option value="5min">⏱ every 5 min</option>
182
+ <option value="15min">⏱ every 15 min</option>
183
+ <option value="1h">⏱ every hour</option>
184
+ <option value="reload">⏱ on reload only</option>
185
+ </select>
186
+ <select class="every" id="space" title="Background: a new space scene every time, or always one">
187
+ <option value="random">🌌 new each time</option>
188
+ <option value="1">🌌 violet</option>
189
+ <option value="2">🌌 emerald</option>
190
+ <option value="3">🌌 crimson</option>
191
+ <option value="4">🌌 deep blue</option>
192
+ <option value="5">🌌 golden suns</option>
193
+ <option value="6">🌌 singularity</option>
194
+ </select>
164
195
  <button class="iconbtn" id="refresh" title="Read every terminal and session log again now (r)">⟳</button>
165
196
  </header>
166
197
  <div id="inbox"></div>
@@ -26,7 +26,9 @@ const ui = JSON.parse(localStorage.getItem('hv-office-ship') || '{}');
26
26
  ui.view ||= 'office';
27
27
  ui.filter ||= null;
28
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 }));
29
+ const save = () => localStorage.setItem('hv-office-ship', JSON.stringify({ view: ui.view, filter: ui.filter, toon: ui.toon, music: ui.music, ships: ui.ships, space: ui.space }));
30
+ // ship positions also live on the office server, so every browser opens the fleet where you left it
31
+ const saveShips = () => { save(); fetch('/hv-office-settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ships: ui.ships || {} }) }).catch(() => {}); };
30
32
 
31
33
  // ---------------------------------------------------------------- helpers
32
34
  function hue(name) { let h = 0; for (const c of name || '') h = (h * 31 + c.charCodeAt(0)) >>> 0; return h % 360; }
@@ -84,20 +86,72 @@ function warpPing() {
84
86
  setTimeout(() => { fb.gain.value = 0; }, 900);
85
87
  } catch (e) { /* no audio: the flash is enough */ }
86
88
  }
89
+ // a ship's name tag opens a small menu: open (or start) the session, or stop it (a second click confirms)
90
+ function closeShipMenu() { document.querySelector('.ship-menu')?.remove(); }
91
+ function shipMenu(el, s, n) {
92
+ const was = document.querySelector('.ship-menu')?.dataset.name;
93
+ closeShipMenu();
94
+ if (was === s.name) return;
95
+ const m = document.createElement('div');
96
+ m.className = 'ship-menu'; m.dataset.name = s.name;
97
+ m.innerHTML = `<div class="t">${s.running ? '🚀' : '💤'} ${esc(s.name)}</div>` + (s.running
98
+ ? `<button data-k="open">▶ Open in a terminal</button>` + (s.default ? `<div class="note">the default session is stopped from hivey itself</div>`
99
+ : `<button data-k="stop" class="danger">⏹ Stop session</button>`)
100
+ : `<button data-k="open">▶ Start session</button>`)
101
+ + (ui.ships?.[s.name] ? `<button data-k="home">↺ Put back in line</button>` : `<div class="note">drag this tag to move the ship</div>`);
102
+ const r = el.getBoundingClientRect();
103
+ m.style.left = Math.min(r.left, innerWidth - 230) + 'px'; m.style.top = (r.bottom + 6) + 'px';
104
+ document.body.appendChild(m);
105
+ m.onclick = e => e.stopPropagation();
106
+ m.querySelector('[data-k="open"]').onclick = () => { closeShipMenu(); openSession(s.name, s.running); };
107
+ const home = m.querySelector('[data-k="home"]');
108
+ if (home) home.onclick = () => { closeShipMenu(); delete ui.ships[s.name]; saveShips(); renderAll(); };
109
+ const stop = m.querySelector('[data-k="stop"]');
110
+ if (stop) stop.onclick = () => {
111
+ if (!stop.classList.contains('arm')) {
112
+ stop.classList.add('arm'); stop.textContent = `Click again: ends its ${n} agent${n === 1 ? '' : 's'}`;
113
+ setTimeout(() => { if (stop.isConnected) { stop.classList.remove('arm'); stop.textContent = '⏹ Stop session'; } }, 3500);
114
+ return;
115
+ }
116
+ closeShipMenu(); stopSession(s.name);
117
+ };
118
+ }
119
+ document.addEventListener('click', closeShipMenu);
120
+ document.addEventListener('keydown', e => { if (e.key === 'Escape') closeShipMenu(); });
121
+ async function stopSession(name) {
122
+ toast(`Stopping session ${name}…`);
123
+ try {
124
+ const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'stop-session', session: name }) });
125
+ const j = await r.json();
126
+ toast(j.message || (j.ok ? `Session ${name} stopped` : `Could not stop session ${name}`));
127
+ if (j.ok) fetch('/hv-office-refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"quick":true}' }).then(() => setTimeout(poll, 2500));
128
+ } catch (e) { toast('The office server is not answering: run `hivey agent-map office` again'); }
129
+ }
130
+ // click on a ship's name tag: that hivey session in a terminal (a new one if none shows it; starts a stopped one)
131
+ async function openSession(name, running) {
132
+ warpPing();
133
+ toast(running ? `Opening session ${name}…` : `Starting session ${name}…`);
134
+ try {
135
+ const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'session', session: name }) });
136
+ const j = await r.json();
137
+ toast(j.message || (j.ok ? `Session ${name} opened` : `Could not open session ${name}`));
138
+ if (j.ok && !running) setTimeout(() => fetch('/hv-office-refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"quick":true}' }).then(() => setTimeout(poll, 2500)), 4000);
139
+ } catch (e) { toast('The office server is not answering: run `hivey agent-map office` again'); }
140
+ }
87
141
  async function act(a, action) {
88
- if (action === 'focus') {
142
+ if (action === 'focus' || action === 'compact') {
89
143
  warpPing();
90
- toast(`Opening ${a.name} in hivey…`);
144
+ toast(action === 'focus' ? `Opening ${a.name} in hivey…` : `Compacting ${a.name}…`);
91
145
  office.flash(a.id);
92
146
  document.querySelectorAll(`[data-id="${CSS.escape(a.id)}"]`).forEach(el => { el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash'); });
93
147
  }
94
148
  try {
95
- const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pane: a.pane, action }) });
149
+ const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: a.id, pane: a.pane, action }) });
96
150
  const j = await r.json();
97
- toast(j.ok ? (action === 'focus' ? `${a.name} is open in hivey ↗` : `${a.name}: ${j.message}`) : `${a.name}: ${j.message}`);
151
+ toast(j.ok && action === 'focus' && !/new terminal/.test(j.message || '') ? `${a.name} is open in hivey ↗` : `${a.name}: ${j.message}`);
98
152
  } catch (e) { toast('The office server is not answering: run `hivey agent-map office` again'); }
99
153
  }
100
- // compact / clear need a second click within 3 s (no browser dialogs)
154
+ // clear needs a second click within 3 s (no browser dialogs); compact goes at once
101
155
  function armed(btn, a, action) {
102
156
  if (btn.classList.contains('arm')) { btn.classList.remove('arm'); btn.textContent = btn.dataset.label; act(a, action); return; }
103
157
  btn.dataset.label = btn.textContent;
@@ -106,11 +160,11 @@ function armed(btn, a, action) {
106
160
  setTimeout(() => { if (btn.classList.contains('arm')) { btn.classList.remove('arm'); btn.textContent = btn.dataset.label; } }, 3000);
107
161
  }
108
162
  function actionButtons(a) {
109
- const busy = a.status === 'working' || a.status === 'blocked';
163
+ const busy = a.status === 'working' || a.status === 'blocked' || a.asleep;
110
164
  return `<div class="actions">
111
165
  <button class="primary" data-act="focus" title="Open its terminal in hivey">↗ Open</button>
112
- ${a.cli_id === 'claude' ? `<button data-act="compact" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /compact into it"'}>🗜 Compact</button>
113
- <button data-act="clear" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /clear into it"'}>🧹 Clear</button>` : ''}
166
+ ${a.cli_id === 'claude' ? `<button data-act="compact" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /compact into it and press Enter"'}>🗜 Compact</button>
167
+ <button data-act="clear" ${busy ? 'disabled title="Only when it is not working"' : 'title="Type /clear into it and press Enter (click twice)"'}>🧹 Clear</button>` : ''}
114
168
  <button data-act="info" title="Everything about it">ⓘ Details</button></div>`;
115
169
  }
116
170
  function wireActions(root) {
@@ -124,7 +178,7 @@ function wireActions(root) {
124
178
  if (b.disabled) return;
125
179
  const k = b.dataset.act;
126
180
  if (k === 'info') return openDrawer(a);
127
- if (k === 'focus') return act(a, 'focus');
181
+ if (k === 'focus' || k === 'compact') return act(a, k);
128
182
  armed(b, a, k);
129
183
  });
130
184
  el.addEventListener('contextmenu', e => { e.preventDefault(); openDrawer(a); });
@@ -143,18 +197,23 @@ function renderHeader() {
143
197
  $('#pills').querySelectorAll('.pill').forEach(p => p.onclick = () => { ui.filter = ui.filter === p.dataset.f ? null : p.dataset.f; save(); renderAll(); });
144
198
  tickSub();
145
199
  }
200
+ let every = 'minute'; // the refresh setting, kept by the office server (shared by every open page)
201
+ const EVERY_S = { minute: 60, '5min': 300, '15min': 900, '1h': 3600 };
146
202
  function tickSub() {
147
203
  if (!data) return;
148
- const next = Date.parse(data.generated) / 1000 + (data.refresh_every || 300) - Date.now() / 1000;
204
+ const next = Date.parse(data.generated) / 1000 + (EVERY_S[every] || 0) - Date.now() / 1000;
149
205
  const n = agents.length;
150
206
  const mm = Math.max(0, Math.floor(next / 60)), ss = Math.max(0, Math.floor(next % 60));
151
- $('#sub').innerHTML = `${n} agent${n === 1 ? '' : 's'} · updated ${ago(data.generated)} · ` +
152
- (refreshing ? '<span class="spin">⟳</span> reading terminals…' : next > 0 ? `next in ${mm}:${String(ss).padStart(2, '0')}` : 'refreshing soon') +
207
+ const at = iso => iso ? new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '?';
208
+ const full = data.full_at && data.full_at !== data.generated
209
+ ? ` · <span title="Last pass that re-summarized every agent whose terminal changed">summaries ${at(data.full_at)} (${ago(data.full_at)})</span>` : '';
210
+ $('#sub').innerHTML = `${n} agent${n === 1 ? '' : 's'} · <span title="Last time every terminal and session log was read">updated ${at(data.generated)} (${ago(data.generated)})</span>${full} · ` +
211
+ (refreshing ? '<span class="spin">⟳</span> reading terminals…' : every === 'reload' ? 'updates when you reload or press ⟳' : next > 0 ? `next ${at(new Date(Date.now() + next * 1000).toISOString())} (in ${mm}:${String(ss).padStart(2, '0')})` : 'refreshing soon') +
153
212
  (data.error ? ` · <span class="err" title="${esc(data.error)}">summaries from the recap (model call failed)</span>` : '');
154
213
  }
155
214
  function renderInbox() {
156
- const blocked = agents.filter(a => a.status === 'blocked');
157
- const asked = agents.filter(a => a.status !== 'blocked' && a.status !== 'working' && a.summary?.needs_you);
215
+ const blocked = agents.filter(a => a.status === 'blocked' && !a.asleep);
216
+ const asked = agents.filter(a => !a.asleep && a.status !== 'blocked' && a.status !== 'working' && a.summary?.needs_you);
158
217
  const need = [...blocked, ...asked];
159
218
  const lead = [blocked.length ? `✋ ${blocked.length} blocked` : '', asked.length ? `<span style="color:var(--honey)">💬 ${asked.length} asked you</span>` : ''].filter(Boolean).join('<br>');
160
219
  $('#inbox').innerHTML = need.length ? `<span class="lead">${lead}</span>` + need.map(a =>
@@ -251,7 +310,7 @@ function wireDrawer(a) {
251
310
  e.stopPropagation();
252
311
  if (b.disabled) return;
253
312
  const k = b.dataset.act;
254
- if (k === 'focus') return act(a, 'focus');
313
+ if (k === 'focus' || k === 'compact') return act(a, k);
255
314
  if (k === 'info') return;
256
315
  armed(b, a, k);
257
316
  });
@@ -262,7 +321,7 @@ function closeDrawer() { $('#drawer').classList.remove('open'); selected = null;
262
321
  const office = (() => {
263
322
  const host = $('#office'), labels = $('#labels');
264
323
  let renderer;
265
- try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); } catch (e) { return { ok: false, build() {}, markSelected() {}, resize() {}, fit() {}, flash() {} }; }
324
+ try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); } catch (e) { return { ok: false, build() {}, markSelected() {}, resize() {}, fit() {}, flash() {}, setSpace() {} }; }
266
325
  renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
267
326
  renderer.shadowMap.enabled = true;
268
327
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
@@ -382,7 +441,7 @@ const office = (() => {
382
441
  const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.scale.set(sx, sy, sz);
383
442
  m.castShadow = shadow; m.receiveShadow = true; return m;
384
443
  }
385
- const ship = createShip({ mesh, hue, st });
444
+ const ship = createShip({ mesh, hue, st, space: ui.space });
386
445
  scene.background = ship.background; // the ship floats in deep space
387
446
  [M.wall, M.floor, M.hit, holoMat].forEach(m => m.userData.outlineParameters = NO_LINE);
388
447
  Object.values(signs).forEach(m => m.userData.outlineParameters = NO_LINE);
@@ -445,9 +504,8 @@ const office = (() => {
445
504
  labels.appendChild(el);
446
505
  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) });
447
506
  }
448
- function build(list) {
449
- scene.remove(world); world = new THREE.Group(); scene.add(world);
450
- desks = []; labels.innerHTML = ''; tags = new Map(); roomTags = [];
507
+ // one spaceship (rooms, bridge, hull) for one hivey session's agents, built into grp around its origin
508
+ function buildShip(list, grp, style) {
451
509
  // the CEO's space gets the captain's bridge; everyone else gets team rooms
452
510
  const isCeo = a => /^ceo$/i.test(a.space || '');
453
511
  const ceo = list.filter(isCeo);
@@ -472,31 +530,97 @@ const office = (() => {
472
530
  sizes.forEach(r => {
473
531
  const h = hue(r.s[0].space), rx = ox + r.x, rz = oz + r.z;
474
532
  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);
475
- rug.rotation.x = -Math.PI / 2; world.add(rug);
476
- 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));
477
- ship.pod(world, rx + r.w - 0.6, rz + 0.6);
478
- 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));
533
+ rug.rotation.x = -Math.PI / 2; grp.add(rug);
534
+ grp.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));
535
+ ship.pod(grp, rx + r.w - 0.6, rz + 0.6);
536
+ grp.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));
479
537
  r.s.sort((a, b) => (b.team?.length || 0) - (a.team?.length || 0) || (order[a.status] ?? 9) - (order[b.status] ?? 9));
480
538
  r.s.forEach((a, i) => {
481
539
  const d = makeDesk(a, rx + PAD + DX / 2 + (i % 3) * DX, rz + PAD + 1.6 + Math.floor(i / 3) * DZ);
482
- world.add(d.g); desks.push(d); addTag(a, d);
540
+ grp.add(d.g); desks.push(d); addTag(a, d);
483
541
  });
484
542
  const rl = document.createElement('div');
485
543
  rl.className = 'room-label'; rl.textContent = `${r.s[0].emoji} ${r.s[0].space}`;
486
544
  labels.appendChild(rl); roomTags.push({ el: rl, p: new THREE.Vector3(rx + 0.3, 0.9, rz + r.d + 0.2) });
487
545
  });
488
- const e = ship.decorate(world, Math.max(W, 8), Math.max(D, 8));
489
- const br = ship.bridge(world, e);
546
+ const e = ship.decorate(grp, Math.max(W, 8), Math.max(D, 8), style);
547
+ const br = ship.bridge(grp, e);
490
548
  ceo.sort((a, b) => (a.role === 'session') - (b.role === 'session') || (order[a.status] ?? 9) - (order[b.status] ?? 9));
491
549
  ceo.slice(0, br.slots.length).forEach((a, i) => {
492
550
  const slot = br.slots[i], d = makeDesk(a, slot.x, slot.z);
493
551
  if (slot.captain) { d.g.scale.setScalar(1.18); d.anchor.y *= 1.18; }
494
- world.add(d.g); desks.push(d); addTag(a, d);
552
+ grp.add(d.g); desks.push(d); addTag(a, d);
495
553
  });
496
- const bl = document.createElement('div');
497
- bl.className = 'room-label'; bl.textContent = `${ceo[0]?.emoji || '👔'} ceo · captain's bridge`;
498
- labels.appendChild(bl); roomTags.push({ el: bl, p: br.label });
554
+ if (ceo.length) {
555
+ const bl = document.createElement('div');
556
+ bl.className = 'room-label'; bl.textContent = `${ceo[0]?.emoji || '👔'} ceo · captain's bridge`;
557
+ labels.appendChild(bl); roomTags.push({ el: bl, p: br.label });
558
+ }
499
559
  e.maxX = Math.max(e.maxX, br.bounds.maxX);
560
+ return e;
561
+ }
562
+ // one spaceship per hivey session, flying in a column (the default session first, stopped ones dark and empty)
563
+ function build(list, sessions) {
564
+ scene.remove(world); world = new THREE.Group(); scene.add(world);
565
+ desks = []; labels.innerHTML = ''; tags = new Map(); roomTags = [];
566
+ sessions = sessions?.length ? sessions : [{ name: 'default', running: true, default: true }];
567
+ const known = new Set(sessions.map(s => s.name));
568
+ const fleet = sessions.map(s => ({ s, list: list.filter(a => (a.hv_session || 'default') === s.name || (s.default && !known.has(a.hv_session || 'default'))) }));
569
+ const e = { minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity };
570
+ let zCur = 0;
571
+ const others = sessions.filter(s => !s.default).map(s => s.name).sort();
572
+ fleet.forEach(({ s, list }) => {
573
+ const grp = new THREE.Group(); world.add(grp);
574
+ const d0 = desks.length, r0 = roomTags.length;
575
+ // the default session flies the classic frigate; the others, in name order, each get their own design
576
+ const v = s.default ? 0 : 1 + others.indexOf(s.name);
577
+ const se = buildShip(list, grp, { v, name: s.name, running: s.running !== false });
578
+ const off = new THREE.Vector3(-(se.minX + se.maxX) / 2, 0, zCur - se.minZ);
579
+ const placed = ui.ships?.[s.name]; // where you dragged this ship last time
580
+ if (placed && isFinite(placed.x) && isFinite(placed.z)) off.set(placed.x, 0, placed.z);
581
+ grp.position.copy(off);
582
+ desks.slice(d0).forEach(d => d.anchor.add(off));
583
+ roomTags.slice(r0).forEach(t => t.p.add(off));
584
+ if (se.plate) { // the name painted on the hull is the ship's handle: click for its menu, drag to move it
585
+ const n = list.length, el = document.createElement('div');
586
+ el.className = 'ship-label' + (s.running ? '' : ' stopped');
587
+ el.innerHTML = `<span class="cap">${s.running ? '🚀' : '💤'} ${s.running ? `${n} agent${n === 1 ? '' : 's'}` : `stopped${n ? ` · ${n} asleep` : ''}`}</span>`;
588
+ el.title = s.running ? `hivey session "${s.name}": open or stop it` : `hivey session "${s.name}" is stopped: start it`;
589
+ el.onclick = e => { e.stopPropagation(); if (!el.dataset.dragged) shipMenu(el, s, n); };
590
+ // drag the name tag to move the ship anywhere in space (saved in this browser)
591
+ const crew = desks.slice(d0), marks = roomTags.slice(r0);
592
+ el.addEventListener('pointerdown', e => {
593
+ if (e.button !== 0) return;
594
+ e.stopPropagation(); e.preventDefault();
595
+ const start = worldAt(e), base = grp.position.clone(), sx = e.clientX, sy = e.clientY;
596
+ let moved = false;
597
+ const mv = ev => {
598
+ if (!moved && Math.hypot(ev.clientX - sx, ev.clientY - sy) < 5) return;
599
+ if (!moved) { moved = true; closeShipMenu(); el.classList.add('dragging'); }
600
+ const np = base.clone().add(worldAt(ev).sub(start)); np.y = 0;
601
+ const d = np.clone().sub(grp.position);
602
+ grp.position.copy(np);
603
+ crew.forEach(k => k.anchor.add(d)); marks.forEach(t => t.p.add(d)); shipTag.p.add(d); shipTag.p2.add(d);
604
+ dirty = true;
605
+ };
606
+ const up = () => {
607
+ removeEventListener('pointermove', mv); removeEventListener('pointerup', up);
608
+ el.classList.remove('dragging');
609
+ if (!moved) return;
610
+ ui.ships = { ...(ui.ships || {}), [s.name]: { x: +grp.position.x.toFixed(2), z: +grp.position.z.toFixed(2) } }; saveShips();
611
+ el.dataset.dragged = '1'; setTimeout(() => delete el.dataset.dragged, 0);
612
+ };
613
+ addEventListener('pointermove', mv); addEventListener('pointerup', up);
614
+ });
615
+ labels.appendChild(el);
616
+ const pc = new THREE.Vector3(off.x + se.plate.x, se.plate.y, off.z + se.plate.z);
617
+ const shipTag = { el, p: pc, p2: pc.clone().add(new THREE.Vector3(se.plate.w / 2, 0, 0)) };
618
+ roomTags.push(shipTag);
619
+ }
620
+ e.minX = Math.min(e.minX, off.x + se.minX); e.maxX = Math.max(e.maxX, off.x + se.maxX);
621
+ e.minZ = Math.min(e.minZ, off.z + se.minZ); e.maxZ = Math.max(e.maxZ, off.z + se.maxZ);
622
+ zCur += se.maxZ - se.minZ + 30; // room for the next ship's tower so it does not hide this one's name
623
+ })
500
624
  // measure each label once (bubble and plate), for the overlap pass in placeLabels
501
625
  tags.forEach(t => {
502
626
  const b = t.el.querySelector('.bubble'), pl = t.el.querySelector('.plate');
@@ -625,7 +749,7 @@ const office = (() => {
625
749
  const d = desks.find(x => x.a.id === id);
626
750
  if (!d) return;
627
751
  const g = new THREE.Group();
628
- g.position.copy(d.g.position).add(new THREE.Vector3(0, 0, -0.9 * d.g.scale.x));
752
+ d.g.getWorldPosition(g.position).add(new THREE.Vector3(0, 0, -0.9 * d.g.scale.x));
629
753
  const ring = mesh(G.ring, glowMat('#ffd36a'), 0, 0.06, 0, 1, 1, 1, false); ring.rotation.x = -Math.PI / 2;
630
754
  const ring2 = mesh(G.ring, glowMat('#7fe8ff'), 0, 0.07, 0, 1, 1, 1, false); ring2.rotation.x = -Math.PI / 2;
631
755
  const beam = mesh(beamGeo, glowMat('#7fe8ff'), 0, 3.5, 0, 1, 1, 1, false);
@@ -678,7 +802,16 @@ const office = (() => {
678
802
  placed.push(mode === 'full' ? [x - bw, y - t.ph - t.bh, x + bw, y] : [x - pw, y - t.ph, x + pw, y]);
679
803
  el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -100%)`;
680
804
  }
681
- 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)`; });
805
+ roomTags.forEach(({ el, p, p2 }) => {
806
+ v.copy(p).project(cam);
807
+ const x = (v.x + 1) / 2 * w, y = (1 - v.y) / 2 * h;
808
+ if (p2) { // the hull name's click area: as wide as the painted name at this zoom
809
+ v.copy(p2).project(cam);
810
+ const half = Math.hypot((v.x + 1) / 2 * w - x, (1 - v.y) / 2 * h - y);
811
+ el.style.width = `${Math.max(40, half * 2)}px`; el.style.height = `${Math.max(14, half * 0.32)}px`;
812
+ el.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
813
+ } else el.style.transform = `translate(${x}px, ${y}px)`;
814
+ });
682
815
  }
683
816
  // the hover class keeps a bubble visible while zoomed out
684
817
  const style = document.createElement('style');
@@ -690,14 +823,16 @@ const office = (() => {
690
823
  function frame(t) {
691
824
  requestAnimationFrame(frame);
692
825
  if (document.hidden || ui.view !== 'office') return;
693
- const moving = flashes.length > 0 || (!REDUCED && desks.some(d => d.a.status === 'working' || d.a.status === 'blocked' || d.team.some(m => m.status === 'working')));
826
+ const busy = flashes.length > 0 || (!REDUCED && desks.some(d => d.a.status === 'working' || d.a.status === 'blocked' || d.team.some(m => m.status === 'working')));
827
+ const moving = busy || (!REDUCED && ship.thrusting());
694
828
  const dt = Math.min(0.1, (t - (frame.prev || t)) / 1000); frame.prev = t;
695
829
  if (!moving && !dirty) return;
696
- if (moving && t - last < 33) return; // ~30 fps is plenty
830
+ if (moving && t - last < (busy ? 33 : 66)) return; // ~30 fps is plenty (15 when only engines burn)
697
831
  last = t;
698
832
  const s = t / 1000;
699
833
  if (moving) {
700
- const pl = ship.planet(); if (pl) pl.rotation.y = s * 0.4;
834
+ ship.planets().forEach(pl => { pl.rotation.y = s * 0.4; });
835
+ ship.thrust(s);
701
836
  if (t - lastCode > 110) { drawCode(); lastCode = t; }
702
837
  for (const d of desks) {
703
838
  const b = d.bot, ph = d.ph;
@@ -732,7 +867,15 @@ const office = (() => {
732
867
  new ResizeObserver(() => { resize(); }).observe(host);
733
868
  resize(); placeCam();
734
869
  requestAnimationFrame(frame);
735
- return { ok: true, build, markSelected, resize, fit, flash, ready: ship.load() };
870
+ // the 🌌 setting: show scene n (1..6) now, or a new random one
871
+ function setSpace(want) {
872
+ const old = scene.background;
873
+ scene.background = ship.space(want);
874
+ old?.dispose?.();
875
+ dirty = true;
876
+ return ship.spaceNo();
877
+ }
878
+ return { ok: true, build, markSelected, resize, fit, flash, setSpace, ready: ship.load() };
736
879
  })();
737
880
 
738
881
  // ---------------------------------------------------------------- views, polling, keys
@@ -746,7 +889,7 @@ function renderAll() {
746
889
  $('#office').style.display = ui.view === 'office' ? '' : 'none';
747
890
  $('#board').style.display = ui.view === 'board' ? 'block' : 'none';
748
891
  $('#list').style.display = ui.view === 'list' ? 'block' : 'none';
749
- if (ui.view === 'office') { office.build(agents.filter(visible)); office.resize(); }
892
+ if (ui.view === 'office') { office.build(agents.filter(visible), data.sessions); office.resize(); }
750
893
  if (ui.view === 'board') renderBoard();
751
894
  if (ui.view === 'list') renderList();
752
895
  if (selected) { const a = agents.find(x => x.id === selected); if (a && $('#drawer').classList.contains('open')) openDrawer(a); }
@@ -812,3 +955,31 @@ if (!office.ok) document.querySelector('#views [data-v="office"]').disabled = tr
812
955
  setInterval(poll, 15000);
813
956
  setInterval(tickSub, 1000);
814
957
  poll();
958
+ // opening or reloading the page reads every terminal again right away; the server answers with the
959
+ // refresh setting (every minute: a quick pass, the model only for changed statuses; otherwise a full pass)
960
+ const post = (path, body) => fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => r.json());
961
+ function showEvery(m) { if (EVERY_S[m] || m === 'reload') { every = m; $('#every').value = m; tickSub(); } }
962
+ // 🌌 background: a new scene on every load (random) or always the one you pick
963
+ const SPACE_NAMES = ['violet', 'emerald', 'crimson', 'deep blue', 'golden', 'singularity'];
964
+ $('#space').value = /^[1-6]$/.test(String(ui.space)) ? String(ui.space) : 'random';
965
+ $('#space').onchange = e => {
966
+ ui.space = e.target.value; save();
967
+ const n = office.setSpace(ui.space);
968
+ toast(ui.space === 'random' ? `A new space scene every time you open the page (now: ${SPACE_NAMES[n - 1] || '?'})` : `Background: ${SPACE_NAMES[n - 1]}, always`);
969
+ post('/hv-office-settings', { space: ui.space }).catch(() => {});
970
+ };
971
+ post('/hv-office-refresh', { load: true }).then(j => {
972
+ showEvery(j.every);
973
+ if (j.space && j.space !== String(ui.space || 'random')) { // the server's choice wins (set in another browser)
974
+ ui.space = j.space; save(); $('#space').value = j.space;
975
+ if (j.space !== 'random') office.setSpace(j.space);
976
+ } else if (!j.space && ui.space) post('/hv-office-settings', { space: String(ui.space) }).catch(() => {});
977
+ const server = j.ships || {}, local = ui.ships || {};
978
+ if (Object.keys(server).length) { // the server's positions win; rebuild if they differ from this browser's
979
+ if (JSON.stringify(server) !== JSON.stringify(local)) { ui.ships = server; save(); if (data) renderAll(); }
980
+ } else if (Object.keys(local).length) saveShips(); // first time: hand this browser's positions to the server
981
+ setTimeout(poll, 2500); setTimeout(poll, 8000);
982
+ }).catch(() => {});
983
+ $('#every').onchange = e => post('/hv-office-settings', { every: e.target.value })
984
+ .then(j => { showEvery(j.every); toast({ minute: 'Updates every minute (summaries only for agents that changed)', '5min': 'Updates every 5 minutes', '15min': 'Updates every 15 minutes', '1h': 'Updates every hour', reload: 'Updates only when you reload or press ⟳' }[j.every]); })
985
+ .catch(() => toast('The office server is not answering'));