@hivey/cli 0.9.62 → 0.9.64
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.
- package/native/darwin-arm64/hivey +0 -0
- package/package.json +1 -1
- package/repo/skills/hivey-agent-map/SKILL.md +8 -3
- package/repo/skills/hivey-agent-map/scripts/agent_map.py +1 -1
- package/repo/skills/hivey-agent-map/scripts/office/office.html +11 -0
- package/repo/skills/hivey-agent-map/scripts/office/office.js +85 -12
- package/repo/skills/hivey-agent-map/scripts/office.py +32 -17
- package/repo/skills/hivey-agent-map/scripts/serve.py +94 -18
|
Binary file
|
package/package.json
CHANGED
|
@@ -188,12 +188,17 @@ each swarm's coordinator get a desk; a swarm's workers and critics stand beside
|
|
|
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
|
|
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**
|
|
196
|
-
|
|
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="
|
|
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 ---------- */
|
|
@@ -144,6 +146,8 @@ td.j{max-width:420px}
|
|
|
144
146
|
#toast.show{opacity:1;transform:translateX(-50%)}
|
|
145
147
|
.empty{padding:60px;text-align:center;color:var(--muted)}
|
|
146
148
|
.err{color:var(--block);font-size:12px}
|
|
149
|
+
.flash{animation:flash 1.4s ease-out}
|
|
150
|
+
@keyframes flash{0%,30%,60%{box-shadow:0 0 0 2px #ffd36a,0 0 28px 6px rgba(127,232,255,.75);background-color:rgba(127,232,255,.12)}15%,45%,75%{box-shadow:0 0 0 1px #7fe8ff,0 0 10px 2px rgba(255,211,106,.4)}100%{box-shadow:none}}
|
|
147
151
|
@media (prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
|
|
148
152
|
</style>
|
|
149
153
|
</head>
|
|
@@ -159,6 +163,13 @@ td.j{max-width:420px}
|
|
|
159
163
|
<button data-v="list" title="One row per agent, for hundreds (3)">☰ List</button>
|
|
160
164
|
</div>
|
|
161
165
|
<button class="iconbtn" id="music" title="Background music on/off (m)">🔇</button>
|
|
166
|
+
<select class="every" id="every" title="How the office updates itself">
|
|
167
|
+
<option value="minute">⏱ every minute</option>
|
|
168
|
+
<option value="5min">⏱ every 5 min</option>
|
|
169
|
+
<option value="15min">⏱ every 15 min</option>
|
|
170
|
+
<option value="1h">⏱ every hour</option>
|
|
171
|
+
<option value="reload">⏱ on reload only</option>
|
|
172
|
+
</select>
|
|
162
173
|
<button class="iconbtn" id="refresh" title="Read every terminal and session log again now (r)">⟳</button>
|
|
163
174
|
</header>
|
|
164
175
|
<div id="inbox"></div>
|
|
@@ -65,15 +65,39 @@ function visible(a) {
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
// ---------------------------------------------------------------- actions
|
|
68
|
+
// click sound: a short sci-fi "warp ping" made with Web Audio (two rising tones and an echo), no file
|
|
69
|
+
let audioCtx = null;
|
|
70
|
+
function warpPing() {
|
|
71
|
+
try {
|
|
72
|
+
audioCtx ||= new (window.AudioContext || window.webkitAudioContext)();
|
|
73
|
+
const ac = audioCtx, t = ac.currentTime, out = ac.createGain();
|
|
74
|
+
out.gain.value = 0.5;
|
|
75
|
+
const echo = ac.createDelay(), fb = ac.createGain();
|
|
76
|
+
echo.delayTime.value = 0.13; fb.gain.value = 0.32;
|
|
77
|
+
out.connect(ac.destination); out.connect(echo); echo.connect(fb); fb.connect(echo); echo.connect(ac.destination);
|
|
78
|
+
[['sine', 880, 1760, 0, 0.26, 0.32], ['triangle', 1320, 2640, 0.07, 0.12, 0.4], ['sine', 440, 660, 0, 0.1, 0.5]].forEach(([type, f0, f1, at, vol, len]) => {
|
|
79
|
+
const o = ac.createOscillator(), g = ac.createGain();
|
|
80
|
+
o.type = type; o.frequency.setValueAtTime(f0, t + at); o.frequency.exponentialRampToValueAtTime(f1, t + at + 0.16);
|
|
81
|
+
g.gain.setValueAtTime(0.0001, t + at); g.gain.exponentialRampToValueAtTime(vol, t + at + 0.02); g.gain.exponentialRampToValueAtTime(0.0001, t + at + len);
|
|
82
|
+
o.connect(g); g.connect(out); o.start(t + at); o.stop(t + at + len + 0.05);
|
|
83
|
+
});
|
|
84
|
+
setTimeout(() => { fb.gain.value = 0; }, 900);
|
|
85
|
+
} catch (e) { /* no audio: the flash is enough */ }
|
|
86
|
+
}
|
|
68
87
|
async function act(a, action) {
|
|
69
|
-
if (action === 'focus'
|
|
88
|
+
if (action === 'focus' || action === 'compact') {
|
|
89
|
+
warpPing();
|
|
90
|
+
toast(action === 'focus' ? `Opening ${a.name} in hivey…` : `Compacting ${a.name}…`);
|
|
91
|
+
office.flash(a.id);
|
|
92
|
+
document.querySelectorAll(`[data-id="${CSS.escape(a.id)}"]`).forEach(el => { el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash'); });
|
|
93
|
+
}
|
|
70
94
|
try {
|
|
71
95
|
const r = await fetch('/hv-office-action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pane: a.pane, action }) });
|
|
72
96
|
const j = await r.json();
|
|
73
97
|
toast(j.ok ? (action === 'focus' ? `${a.name} is open in hivey ↗` : `${a.name}: ${j.message}`) : `${a.name}: ${j.message}`);
|
|
74
98
|
} catch (e) { toast('The office server is not answering: run `hivey agent-map office` again'); }
|
|
75
99
|
}
|
|
76
|
-
//
|
|
100
|
+
// clear needs a second click within 3 s (no browser dialogs); compact goes at once
|
|
77
101
|
function armed(btn, a, action) {
|
|
78
102
|
if (btn.classList.contains('arm')) { btn.classList.remove('arm'); btn.textContent = btn.dataset.label; act(a, action); return; }
|
|
79
103
|
btn.dataset.label = btn.textContent;
|
|
@@ -85,8 +109,8 @@ function actionButtons(a) {
|
|
|
85
109
|
const busy = a.status === 'working' || a.status === 'blocked';
|
|
86
110
|
return `<div class="actions">
|
|
87
111
|
<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>` : ''}
|
|
112
|
+
${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>
|
|
113
|
+
<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>` : ''}
|
|
90
114
|
<button data-act="info" title="Everything about it">ⓘ Details</button></div>`;
|
|
91
115
|
}
|
|
92
116
|
function wireActions(root) {
|
|
@@ -100,7 +124,7 @@ function wireActions(root) {
|
|
|
100
124
|
if (b.disabled) return;
|
|
101
125
|
const k = b.dataset.act;
|
|
102
126
|
if (k === 'info') return openDrawer(a);
|
|
103
|
-
if (k === 'focus') return act(a,
|
|
127
|
+
if (k === 'focus' || k === 'compact') return act(a, k);
|
|
104
128
|
armed(b, a, k);
|
|
105
129
|
});
|
|
106
130
|
el.addEventListener('contextmenu', e => { e.preventDefault(); openDrawer(a); });
|
|
@@ -119,13 +143,18 @@ function renderHeader() {
|
|
|
119
143
|
$('#pills').querySelectorAll('.pill').forEach(p => p.onclick = () => { ui.filter = ui.filter === p.dataset.f ? null : p.dataset.f; save(); renderAll(); });
|
|
120
144
|
tickSub();
|
|
121
145
|
}
|
|
146
|
+
let every = 'minute'; // the refresh setting, kept by the office server (shared by every open page)
|
|
147
|
+
const EVERY_S = { minute: 60, '5min': 300, '15min': 900, '1h': 3600 };
|
|
122
148
|
function tickSub() {
|
|
123
149
|
if (!data) return;
|
|
124
|
-
const next = Date.parse(data.generated) / 1000 + (
|
|
150
|
+
const next = Date.parse(data.generated) / 1000 + (EVERY_S[every] || 0) - Date.now() / 1000;
|
|
125
151
|
const n = agents.length;
|
|
126
152
|
const mm = Math.max(0, Math.floor(next / 60)), ss = Math.max(0, Math.floor(next % 60));
|
|
127
|
-
|
|
128
|
-
|
|
153
|
+
const at = iso => iso ? new Date(iso).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '?';
|
|
154
|
+
const full = data.full_at && data.full_at !== data.generated
|
|
155
|
+
? ` · <span title="Last pass that re-summarized every agent whose terminal changed">summaries ${at(data.full_at)} (${ago(data.full_at)})</span>` : '';
|
|
156
|
+
$('#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} · ` +
|
|
157
|
+
(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') +
|
|
129
158
|
(data.error ? ` · <span class="err" title="${esc(data.error)}">summaries from the recap (model call failed)</span>` : '');
|
|
130
159
|
}
|
|
131
160
|
function renderInbox() {
|
|
@@ -227,7 +256,7 @@ function wireDrawer(a) {
|
|
|
227
256
|
e.stopPropagation();
|
|
228
257
|
if (b.disabled) return;
|
|
229
258
|
const k = b.dataset.act;
|
|
230
|
-
if (k === 'focus') return act(a,
|
|
259
|
+
if (k === 'focus' || k === 'compact') return act(a, k);
|
|
231
260
|
if (k === 'info') return;
|
|
232
261
|
armed(b, a, k);
|
|
233
262
|
});
|
|
@@ -238,7 +267,7 @@ function closeDrawer() { $('#drawer').classList.remove('open'); selected = null;
|
|
|
238
267
|
const office = (() => {
|
|
239
268
|
const host = $('#office'), labels = $('#labels');
|
|
240
269
|
let renderer;
|
|
241
|
-
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); } catch (e) { return { ok: false, build() {}, markSelected() {}, resize() {}, fit() {} }; }
|
|
270
|
+
try { renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); } catch (e) { return { ok: false, build() {}, markSelected() {}, resize() {}, fit() {}, flash() {} }; }
|
|
242
271
|
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
|
|
243
272
|
renderer.shadowMap.enabled = true;
|
|
244
273
|
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
|
|
@@ -593,6 +622,36 @@ const office = (() => {
|
|
|
593
622
|
dirty = true;
|
|
594
623
|
if (!REDUCED) placeLabels();
|
|
595
624
|
}
|
|
625
|
+
// click feedback: a gold ring bursts out, a cyan beam flashes and a light pulses at the agent (1.4 s)
|
|
626
|
+
const flashes = [];
|
|
627
|
+
const beamGeo = new THREE.CylinderGeometry(0.55, 0.55, 7, 28, 1, true);
|
|
628
|
+
const glowMat = color => new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false, side: THREE.DoubleSide });
|
|
629
|
+
function flash(id) {
|
|
630
|
+
const d = desks.find(x => x.a.id === id);
|
|
631
|
+
if (!d) return;
|
|
632
|
+
const g = new THREE.Group();
|
|
633
|
+
g.position.copy(d.g.position).add(new THREE.Vector3(0, 0, -0.9 * d.g.scale.x));
|
|
634
|
+
const ring = mesh(G.ring, glowMat('#ffd36a'), 0, 0.06, 0, 1, 1, 1, false); ring.rotation.x = -Math.PI / 2;
|
|
635
|
+
const ring2 = mesh(G.ring, glowMat('#7fe8ff'), 0, 0.07, 0, 1, 1, 1, false); ring2.rotation.x = -Math.PI / 2;
|
|
636
|
+
const beam = mesh(beamGeo, glowMat('#7fe8ff'), 0, 3.5, 0, 1, 1, 1, false);
|
|
637
|
+
const light = new THREE.PointLight('#9fe8ff', 0, 9, 1.4); light.position.y = 2.2;
|
|
638
|
+
g.add(ring, ring2, beam, light); world.add(g);
|
|
639
|
+
flashes.push({ g, ring, ring2, beam, light, t0: performance.now() });
|
|
640
|
+
tags.get(id)?.el.classList.add('hover');
|
|
641
|
+
setTimeout(() => tags.get(id)?.el.classList.remove('hover'), 1600);
|
|
642
|
+
dirty = true;
|
|
643
|
+
}
|
|
644
|
+
function stepFlashes(now) {
|
|
645
|
+
for (let i = flashes.length - 1; i >= 0; i--) {
|
|
646
|
+
const f = flashes[i], p = Math.min(1, (now - f.t0) / 1400), fade = 1 - p;
|
|
647
|
+
const blink = 0.55 + 0.45 * Math.sin(p * Math.PI * 10); // three quick blinks
|
|
648
|
+
f.ring.scale.setScalar(1 + p * 5); f.ring.material.opacity = fade;
|
|
649
|
+
f.ring2.scale.setScalar(1 + Math.max(0, p - 0.15) * 5); f.ring2.material.opacity = p > 0.15 ? fade * 0.8 : 0;
|
|
650
|
+
f.beam.material.opacity = 0.55 * fade * blink; f.beam.scale.set(1 - p * 0.5, 1, 1 - p * 0.5);
|
|
651
|
+
f.light.intensity = 40 * fade * blink;
|
|
652
|
+
if (p >= 1) { world.remove(f.g); [f.ring, f.ring2, f.beam].forEach(m => m.material.dispose()); flashes.splice(i, 1); }
|
|
653
|
+
}
|
|
654
|
+
}
|
|
596
655
|
function markSelected() {
|
|
597
656
|
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
657
|
dirty = true;
|
|
@@ -636,7 +695,7 @@ const office = (() => {
|
|
|
636
695
|
function frame(t) {
|
|
637
696
|
requestAnimationFrame(frame);
|
|
638
697
|
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'));
|
|
698
|
+
const moving = flashes.length > 0 || (!REDUCED && desks.some(d => d.a.status === 'working' || d.a.status === 'blocked' || d.team.some(m => m.status === 'working')));
|
|
640
699
|
const dt = Math.min(0.1, (t - (frame.prev || t)) / 1000); frame.prev = t;
|
|
641
700
|
if (!moving && !dirty) return;
|
|
642
701
|
if (moving && t - last < 33) return; // ~30 fps is plenty
|
|
@@ -670,6 +729,7 @@ const office = (() => {
|
|
|
670
729
|
}
|
|
671
730
|
}
|
|
672
731
|
}
|
|
732
|
+
if (flashes.length) stepFlashes(performance.now());
|
|
673
733
|
if (ui.toon) outline.render(scene, cam); else composer.render();
|
|
674
734
|
placeLabels();
|
|
675
735
|
dirty = false;
|
|
@@ -677,7 +737,7 @@ const office = (() => {
|
|
|
677
737
|
new ResizeObserver(() => { resize(); }).observe(host);
|
|
678
738
|
resize(); placeCam();
|
|
679
739
|
requestAnimationFrame(frame);
|
|
680
|
-
return { ok: true, build, markSelected, resize, fit, ready: ship.load() };
|
|
740
|
+
return { ok: true, build, markSelected, resize, fit, flash, ready: ship.load() };
|
|
681
741
|
})();
|
|
682
742
|
|
|
683
743
|
// ---------------------------------------------------------------- views, polling, keys
|
|
@@ -731,6 +791,11 @@ function setMusic(on) {
|
|
|
731
791
|
$('#music').onclick = () => setMusic(!ui.music);
|
|
732
792
|
if (ui.music) addEventListener('pointerdown', () => { if (ui.music && bgm.paused) setMusic(true); }, { once: true });
|
|
733
793
|
$('#music').textContent = ui.music ? '🎵' : '🔇';
|
|
794
|
+
// only while the page is in front of you: pause when you switch to the terminal or another app or tab
|
|
795
|
+
const inFront = () => !document.hidden && document.hasFocus();
|
|
796
|
+
function followFocus() { if (!ui.music) return; if (inFront()) bgm.play().catch(() => {}); else bgm.pause(); }
|
|
797
|
+
addEventListener('blur', followFocus); addEventListener('focus', followFocus);
|
|
798
|
+
document.addEventListener('visibilitychange', followFocus);
|
|
734
799
|
$('#fit').onclick = () => office.fit();
|
|
735
800
|
function toggleStyle() { ui.toon = !ui.toon; save(); $('#style').textContent = ui.toon ? '🎨 comic' : '✨ HD'; renderAll(); }
|
|
736
801
|
$('#style').onclick = toggleStyle;
|
|
@@ -752,3 +817,11 @@ if (!office.ok) document.querySelector('#views [data-v="office"]').disabled = tr
|
|
|
752
817
|
setInterval(poll, 15000);
|
|
753
818
|
setInterval(tickSub, 1000);
|
|
754
819
|
poll();
|
|
820
|
+
// opening or reloading the page reads every terminal again right away; the server answers with the
|
|
821
|
+
// refresh setting (every minute: a quick pass, the model only for changed statuses; otherwise a full pass)
|
|
822
|
+
const post = (path, body) => fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => r.json());
|
|
823
|
+
function showEvery(m) { if (EVERY_S[m] || m === 'reload') { every = m; $('#every').value = m; tickSub(); } }
|
|
824
|
+
post('/hv-office-refresh', { load: true }).then(j => { showEvery(j.every); setTimeout(poll, 2500); setTimeout(poll, 8000); }).catch(() => {});
|
|
825
|
+
$('#every').onchange = e => post('/hv-office-settings', { every: e.target.value })
|
|
826
|
+
.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]); })
|
|
827
|
+
.catch(() => toast('The office server is not answering'));
|
|
@@ -10,7 +10,7 @@ For each desk it reads two things:
|
|
|
10
10
|
context size (input + cache tokens of the last reply), model, your last prompt, the
|
|
11
11
|
session's recap (away_summary) and its last replies
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Haiku (`claude -p --model haiku`, no tools, no session saved) turns them into a short summary per
|
|
14
14
|
desk: the current job, a speech-bubble line, what it achieved, what it waits for and whether to keep,
|
|
15
15
|
/compact or /clear the conversation. Only desks whose terminal or log changed since the last run are
|
|
16
16
|
sent again, in batches, so 100 agents cost a few calls per refresh. Without a model (--no-llm, or the
|
|
@@ -19,7 +19,7 @@ call fails) the summary comes from the recap and the last prompt.
|
|
|
19
19
|
Output: ~/.hivey/agent-map/reports/office/office.json, read by office.html (Three.js, vendored), served
|
|
20
20
|
by serve.py, which reruns this every 5 minutes while the page is open. Python standard library only.
|
|
21
21
|
|
|
22
|
-
office.py run [--no-llm] [--model
|
|
22
|
+
office.py run [--no-llm] [--quick] [--model haiku] one refresh (--quick: the 1-minute live pass)
|
|
23
23
|
office.py open start the server, refresh if stale, open the page
|
|
24
24
|
"""
|
|
25
25
|
from __future__ import annotations
|
|
@@ -48,7 +48,7 @@ STATE = HOME / ".hivey" / "agent-map"
|
|
|
48
48
|
OUT = STATE / "reports" / "office"
|
|
49
49
|
CACHE = STATE / "office-cache.json"
|
|
50
50
|
LOCK = STATE / "office.lock"
|
|
51
|
-
RUN_DIR = STATE / "office-run" # neutral cwd for the
|
|
51
|
+
RUN_DIR = STATE / "office-run" # neutral cwd for the model calls (no CLAUDE.md, no project)
|
|
52
52
|
|
|
53
53
|
STANDARD_WINDOW = 200_000
|
|
54
54
|
LARGE_WINDOW = 1_000_000
|
|
@@ -305,7 +305,7 @@ def claude_token() -> str | None:
|
|
|
305
305
|
return None
|
|
306
306
|
|
|
307
307
|
|
|
308
|
-
def
|
|
308
|
+
def ask_model(batch: list[dict], model: str, token: str | None) -> list[dict]:
|
|
309
309
|
claude = shutil.which("claude") or str(HOME / ".local/bin/claude")
|
|
310
310
|
prompt = PROMPT + "\n\n".join(brief(d) for d in batch)
|
|
311
311
|
env = dict(os.environ)
|
|
@@ -382,7 +382,7 @@ def collect(hv: str) -> list[dict]:
|
|
|
382
382
|
return people
|
|
383
383
|
|
|
384
384
|
|
|
385
|
-
def run(model: str = "
|
|
385
|
+
def run(model: str = "haiku", use_llm: bool = True, quick: bool = False) -> int:
|
|
386
386
|
hv = hivey_bin()
|
|
387
387
|
if not hv:
|
|
388
388
|
print("office: hivey not found", file=sys.stderr)
|
|
@@ -397,34 +397,41 @@ def run(model: str = "sonnet", use_llm: bool = True) -> int:
|
|
|
397
397
|
print("office: a refresh is already running")
|
|
398
398
|
return 0
|
|
399
399
|
LOCK.unlink(missing_ok=True)
|
|
400
|
-
return run(model, use_llm)
|
|
400
|
+
return run(model, use_llm, quick)
|
|
401
401
|
try:
|
|
402
|
-
return _run(hv, model, use_llm)
|
|
402
|
+
return _run(hv, model, use_llm, quick)
|
|
403
403
|
finally:
|
|
404
404
|
LOCK.unlink(missing_ok=True)
|
|
405
405
|
|
|
406
406
|
|
|
407
|
-
def _run(hv: str, model: str, use_llm: bool) -> int:
|
|
407
|
+
def _run(hv: str, model: str, use_llm: bool, quick: bool = False) -> int:
|
|
408
|
+
"""quick: the 1-minute live pass. Status, context and screen are fresh; a desk whose terminal moved
|
|
409
|
+
but whose status did not keeps its last summary (re-summarized at the next full pass), and only
|
|
410
|
+
desks whose status changed (blocked -> working, working -> done...) are sent to the model now."""
|
|
408
411
|
start = time.time()
|
|
409
412
|
people = collect(hv)
|
|
410
413
|
try:
|
|
411
414
|
cache = json.loads(CACHE.read_text())
|
|
412
415
|
except (OSError, ValueError):
|
|
413
416
|
cache = {}
|
|
414
|
-
todo, error = [], ""
|
|
417
|
+
todo, error, stale = [], "", {}
|
|
415
418
|
for d in people:
|
|
416
419
|
d["fp"] = fingerprint(d)
|
|
417
420
|
hit = cache.get(d["id"])
|
|
418
421
|
if hit and hit.get("fp") == d["fp"] and (hit.get("by") != "fallback" or not use_llm):
|
|
419
422
|
d["summary"] = hit["summary"]
|
|
420
423
|
d["summarized_at"] = hit.get("at")
|
|
424
|
+
elif quick and hit and hit.get("status", d["status"]) == d["status"] and hit.get("by") != "fallback":
|
|
425
|
+
d["summary"] = hit["summary"]
|
|
426
|
+
d["summarized_at"] = hit.get("at")
|
|
427
|
+
stale[d["id"]] = hit # keep its old fingerprint so the next full pass re-summarizes it
|
|
421
428
|
else:
|
|
422
429
|
todo.append(d)
|
|
423
430
|
if todo and use_llm:
|
|
424
431
|
token = claude_token()
|
|
425
432
|
batches = [todo[i:i + BATCH] for i in range(0, len(todo), BATCH)]
|
|
426
433
|
with cf.ThreadPoolExecutor(max_workers=4) as pool:
|
|
427
|
-
futures = {pool.submit(
|
|
434
|
+
futures = {pool.submit(ask_model, b, model, token): b for b in batches}
|
|
428
435
|
for fut in cf.as_completed(futures):
|
|
429
436
|
try:
|
|
430
437
|
got = {s["id"]: s for s in fut.result()}
|
|
@@ -443,8 +450,9 @@ def _run(hv: str, model: str, use_llm: bool) -> int:
|
|
|
443
450
|
s["advice"], s["advice_why"] = "compact", f"context at {d['context_pct']}%"
|
|
444
451
|
if d["status"] in ("working", "blocked") and s.get("advice") == "clear":
|
|
445
452
|
s["advice"] = "keep"
|
|
446
|
-
CACHE.write_text(json.dumps({d["id"]:
|
|
447
|
-
|
|
453
|
+
CACHE.write_text(json.dumps({d["id"]: stale.get(d["id"]) or {
|
|
454
|
+
"fp": d["fp"], "summary": d["summary"], "at": d["summarized_at"], "by": d["summary"].get("by"),
|
|
455
|
+
"status": d["status"]} for d in people}))
|
|
448
456
|
for d in people:
|
|
449
457
|
log = d.pop("_log", {})
|
|
450
458
|
d["tools"] = log.get("tools", [])[-5:]
|
|
@@ -454,8 +462,14 @@ def _run(hv: str, model: str, use_llm: bool) -> int:
|
|
|
454
462
|
order = {"blocked": 0, "working": 1, "done": 2, "idle": 3}
|
|
455
463
|
people.sort(key=lambda d: (order.get(d["status"], 4), -d["context_pct"], d["name"]))
|
|
456
464
|
counts = {k: sum(1 for d in people if d["status"] == k) for k in ("working", "blocked", "done", "idle")}
|
|
457
|
-
|
|
458
|
-
|
|
465
|
+
full_at = now_iso()
|
|
466
|
+
if quick: # a live pass: the last full summary pass stays the one already on the page
|
|
467
|
+
try:
|
|
468
|
+
full_at = json.loads((OUT / "office.json").read_text()).get("full_at") or full_at
|
|
469
|
+
except (OSError, ValueError):
|
|
470
|
+
pass
|
|
471
|
+
data = {"generated": now_iso(), "kind": "quick" if quick else "full", "full_at": full_at, "seconds": round(time.time() - start, 1), "model": model if use_llm else None,
|
|
472
|
+
"summarized": len(todo) if use_llm else 0, "error": error, "refresh_every": 60,
|
|
459
473
|
"counts": counts, "agents": people,
|
|
460
474
|
"advice": {k: sum(1 for d in people if d["summary"].get("advice") == k) for k in ("compact", "clear")}}
|
|
461
475
|
write(data)
|
|
@@ -506,12 +520,13 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
506
520
|
sub = ap.add_subparsers(dest="cmd")
|
|
507
521
|
r = sub.add_parser("run")
|
|
508
522
|
r.add_argument("--no-llm", action="store_true")
|
|
509
|
-
r.add_argument("--
|
|
523
|
+
r.add_argument("--quick", action="store_true", help="live pass: summarize only desks whose status changed")
|
|
524
|
+
r.add_argument("--model", default="haiku")
|
|
510
525
|
o = sub.add_parser("open")
|
|
511
|
-
o.add_argument("--model", default="
|
|
526
|
+
o.add_argument("--model", default="haiku")
|
|
512
527
|
a = ap.parse_args(argv)
|
|
513
528
|
if a.cmd == "run":
|
|
514
|
-
return run(a.model, not a.no_llm)
|
|
529
|
+
return run(a.model, not a.no_llm, a.quick)
|
|
515
530
|
if a.cmd == "open":
|
|
516
531
|
return open_page(a.model)
|
|
517
532
|
ap.print_help()
|
|
@@ -12,7 +12,12 @@ trigger them:
|
|
|
12
12
|
terminal app forward); compact/clear type /compact or /clear into an agent
|
|
13
13
|
that is not working
|
|
14
14
|
|
|
15
|
-
While an office page is open (it polls /office/office.json),
|
|
15
|
+
While an office page is open (it polls /office/office.json), a live pass runs every minute (status,
|
|
16
|
+
context, screen; only desks whose status changed go to the model) and a full re-summary every 5 minutes.
|
|
17
|
+
The office page's ⏱ setting (POST /hv-office-settings {"every": "minute" | "5min" | "15min" | "1h" | "reload"}, saved in
|
|
18
|
+
~/.hivey/agent-map/office-settings.json) picks every minute (above), every 5 / 15 minutes or every hour (full passes only)
|
|
19
|
+
or on reload only (no clock). POST /hv-office-refresh: {} a full pass now (⟳), {"load": true} when a page
|
|
20
|
+
opens (a quick pass in minute mode, a full one otherwise), {"quick": true} a quick pass.
|
|
16
21
|
It stops after 2 hours unused. Python standard library only.
|
|
17
22
|
"""
|
|
18
23
|
from __future__ import annotations
|
|
@@ -30,6 +35,9 @@ import urllib.request
|
|
|
30
35
|
from pathlib import Path
|
|
31
36
|
|
|
32
37
|
STATE = Path.home() / ".hivey" / "agent-map"
|
|
38
|
+
OFFICE_SETTINGS = STATE / "office-settings.json" # {"every": "minute" | "5min" | "reload"}
|
|
39
|
+
EVERY_MODES = ("minute", "5min", "15min", "1h", "reload")
|
|
40
|
+
FULL_EVERY = {"minute": 300, "5min": 300, "15min": 900, "1h": 3600} # seconds between full passes per mode
|
|
33
41
|
REPORTS = STATE / "reports"
|
|
34
42
|
INFO = STATE / "server.json"
|
|
35
43
|
SCRIPTS = Path(__file__).resolve().parent
|
|
@@ -37,8 +45,9 @@ PREFERRED_PORT = 42817 # unregistered and below macOS's temporary-port range, s
|
|
|
37
45
|
IDLE_SECONDS = 2 * 3600
|
|
38
46
|
PING = "/hv-ping"
|
|
39
47
|
MARK = b"hivey-agent-map"
|
|
40
|
-
VERSION = b"office-
|
|
41
|
-
OFFICE_EVERY = 300 # seconds between office refreshes while its page is open
|
|
48
|
+
VERSION = b"office-5" # bump when the server gains actions, so `ensure` replaces an older one
|
|
49
|
+
OFFICE_EVERY = 300 # seconds between full office refreshes (every terminal re-summarized) while its page is open
|
|
50
|
+
OFFICE_LIVE = 60 # seconds between live passes (status, context, screen; only changed statuses summarized)
|
|
42
51
|
OFFICE_WATCHED = 600 # the page counts as open for this long after its last poll
|
|
43
52
|
OFFICE_JSON = REPORTS / "office" / "office.json"
|
|
44
53
|
PANE = re.compile(r"^[\w-]{1,24}:[\w-]{1,24}$")
|
|
@@ -51,9 +60,19 @@ def hivey_bin() -> str | None:
|
|
|
51
60
|
return exe if exe and os.path.isfile(exe) else shutil.which("hivey")
|
|
52
61
|
|
|
53
62
|
|
|
54
|
-
def
|
|
63
|
+
def office_every() -> str:
|
|
64
|
+
"""The office page's refresh setting (every minute by default)."""
|
|
65
|
+
try:
|
|
66
|
+
mode = json.loads(OFFICE_SETTINGS.read_text()).get("every")
|
|
67
|
+
except (OSError, ValueError, AttributeError):
|
|
68
|
+
mode = None
|
|
69
|
+
return mode if mode in EVERY_MODES else "minute"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def start_office_refresh(llm: bool = True, quick: bool = False) -> None:
|
|
55
73
|
"""office.py run in the background (it holds its own lock, so overlapping starts are dropped)."""
|
|
56
|
-
cmd = [sys.executable, "-I", str(SCRIPTS / "office.py"), "run"] + ([] if llm else ["--no-llm"])
|
|
74
|
+
cmd = [sys.executable, "-I", str(SCRIPTS / "office.py"), "run"] + ([] if llm else ["--no-llm"]) \
|
|
75
|
+
+ (["--quick"] if quick else [])
|
|
57
76
|
with open(STATE / "office.log", "a") as fh:
|
|
58
77
|
subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=fh, stderr=fh, start_new_session=True)
|
|
59
78
|
|
|
@@ -153,6 +172,43 @@ def live_status(hv: str, pane: str) -> str | None:
|
|
|
153
172
|
return None
|
|
154
173
|
|
|
155
174
|
|
|
175
|
+
def waiting_in_prompt(hv: str, pane: str, command: str) -> bool:
|
|
176
|
+
"""True while the command still sits typed in the agent's input box (its Enter not taken yet)."""
|
|
177
|
+
try:
|
|
178
|
+
out = subprocess.run([hv, "pane", "read", pane, "--source", "recent", "--lines", "15"],
|
|
179
|
+
capture_output=True, text=True, timeout=5).stdout
|
|
180
|
+
except (OSError, subprocess.SubprocessError):
|
|
181
|
+
return False
|
|
182
|
+
try: # the CLI answers JSON or plain text depending on the version
|
|
183
|
+
out = json.loads(out)["result"].get("text", out)
|
|
184
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
185
|
+
pass
|
|
186
|
+
return any(re.match(r"^[│|\s]*[>❯›]\s*" + re.escape(command) + r"\s*[│|]?\s*$", line)
|
|
187
|
+
for line in str(out).splitlines()[-10:])
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def send_command(hv: str, pane: str, command: str) -> tuple[bool, str]:
|
|
191
|
+
"""Type a slash command into an agent and press Enter as its own key press, so the CLI does not take
|
|
192
|
+
text and Enter as one paste (or let its slash-command menu swallow the Enter); press Enter again
|
|
193
|
+
while the command is still waiting in the input box."""
|
|
194
|
+
def call(*args: str) -> subprocess.CompletedProcess:
|
|
195
|
+
return subprocess.run([hv, "pane", *args], capture_output=True, text=True, timeout=10)
|
|
196
|
+
p = call("send-text", pane, command)
|
|
197
|
+
if p.returncode != 0:
|
|
198
|
+
return False, (p.stderr or p.stdout).strip()[-200:] or f"{command} failed"
|
|
199
|
+
for wait in (0.5, 1.2, 1.5):
|
|
200
|
+
time.sleep(wait)
|
|
201
|
+
if wait > 0.5 and not waiting_in_prompt(hv, pane, command):
|
|
202
|
+
return True, f"sent {command} and Enter"
|
|
203
|
+
p = call("send-keys", pane, "Enter")
|
|
204
|
+
if p.returncode != 0:
|
|
205
|
+
return False, (p.stderr or p.stdout).strip()[-200:] or "Enter failed"
|
|
206
|
+
time.sleep(1.5)
|
|
207
|
+
if waiting_in_prompt(hv, pane, command):
|
|
208
|
+
return False, f"{command} is typed but the agent has not taken it; press Enter in its terminal"
|
|
209
|
+
return True, f"sent {command} and Enter"
|
|
210
|
+
|
|
211
|
+
|
|
156
212
|
def office_action(pane: str, action: str) -> tuple[bool, str]:
|
|
157
213
|
hv = hivey_bin()
|
|
158
214
|
if not hv:
|
|
@@ -169,10 +225,7 @@ def office_action(pane: str, action: str) -> tuple[bool, str]:
|
|
|
169
225
|
status = live_status(hv, pane)
|
|
170
226
|
if status in ("working", "blocked"):
|
|
171
227
|
return False, f"it is {status} now; try when it is idle"
|
|
172
|
-
|
|
173
|
-
if p.returncode != 0:
|
|
174
|
-
return False, (p.stderr or p.stdout).strip()[-200:] or f"/{action} failed"
|
|
175
|
-
return True, f"sent /{action}"
|
|
228
|
+
return send_command(hv, pane, f"/{action}")
|
|
176
229
|
return False, "unknown action"
|
|
177
230
|
|
|
178
231
|
|
|
@@ -230,6 +283,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
230
283
|
busy = threading.Lock()
|
|
231
284
|
last_used = time.time()
|
|
232
285
|
office_polled = 0.0
|
|
286
|
+
office_full = 0.0 # last full (all re-summarized) office refresh started by this server
|
|
233
287
|
|
|
234
288
|
def __init__(self, *args, **kwargs):
|
|
235
289
|
super().__init__(*args, directory=str(REPORTS), **kwargs)
|
|
@@ -259,13 +313,30 @@ class Handler(http.server.SimpleHTTPRequestHandler):
|
|
|
259
313
|
def do_POST(self) -> None:
|
|
260
314
|
Handler.last_used = time.time()
|
|
261
315
|
port = self.server.server_address[1]
|
|
262
|
-
if self.path not in ("/hv-refresh", "/hv-office-refresh", "/hv-office-action"):
|
|
316
|
+
if self.path not in ("/hv-refresh", "/hv-office-refresh", "/hv-office-action", "/hv-office-settings"):
|
|
263
317
|
return self.answer(404, b'{"ok":false,"error":"not found"}')
|
|
264
318
|
if self.headers.get("Origin") not in (f"http://127.0.0.1:{port}", f"http://localhost:{port}"):
|
|
265
319
|
return self.answer(403, b'{"ok":false,"error":"only the agent map pages can do this"}')
|
|
266
|
-
if self.path
|
|
267
|
-
|
|
268
|
-
|
|
320
|
+
if self.path in ("/hv-office-refresh", "/hv-office-settings"):
|
|
321
|
+
try:
|
|
322
|
+
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
323
|
+
req = json.loads(self.rfile.read(length) or b"{}")
|
|
324
|
+
req = req if isinstance(req, dict) else {}
|
|
325
|
+
except ValueError:
|
|
326
|
+
req = {}
|
|
327
|
+
if self.path == "/hv-office-settings":
|
|
328
|
+
if req.get("every") not in EVERY_MODES:
|
|
329
|
+
return self.answer(400, b'{"ok":false,"error":"every: minute, 5min, 15min, 1h or reload"}')
|
|
330
|
+
OFFICE_SETTINGS.write_text(json.dumps({"every": req["every"]}))
|
|
331
|
+
return self.answer(200, json.dumps({"ok": True, "every": req["every"]}).encode())
|
|
332
|
+
every = office_every()
|
|
333
|
+
# a page load: a quick pass when updating every minute, a full one otherwise; ⟳: always full
|
|
334
|
+
quick = bool(req.get("quick")) or (bool(req.get("load")) and every == "minute")
|
|
335
|
+
Handler.office_polled = time.time()
|
|
336
|
+
if not quick:
|
|
337
|
+
Handler.office_full = time.time()
|
|
338
|
+
start_office_refresh(quick=quick)
|
|
339
|
+
return self.answer(200, json.dumps({"ok": True, "started": True, "every": every}).encode())
|
|
269
340
|
if self.path == "/hv-office-action":
|
|
270
341
|
try:
|
|
271
342
|
length = min(int(self.headers.get("Content-Length") or 0), 4096)
|
|
@@ -306,18 +377,23 @@ def serve() -> int:
|
|
|
306
377
|
return
|
|
307
378
|
|
|
308
379
|
def office_clock() -> None:
|
|
309
|
-
"""
|
|
380
|
+
"""While an office page is open: a live pass every minute, a full re-summary every 5 minutes."""
|
|
310
381
|
while True:
|
|
311
|
-
time.sleep(
|
|
312
|
-
|
|
382
|
+
time.sleep(10)
|
|
383
|
+
every = office_every()
|
|
384
|
+
if every == "reload" or time.time() - Handler.office_polled > OFFICE_WATCHED:
|
|
313
385
|
continue
|
|
314
386
|
try:
|
|
315
387
|
age = time.time() - OFFICE_JSON.stat().st_mtime
|
|
316
388
|
except OSError:
|
|
317
389
|
age = OFFICE_EVERY
|
|
318
|
-
if
|
|
390
|
+
if time.time() - Handler.office_full >= FULL_EVERY.get(every, OFFICE_EVERY):
|
|
391
|
+
Handler.office_full = time.time()
|
|
319
392
|
start_office_refresh()
|
|
320
|
-
time.sleep(
|
|
393
|
+
time.sleep(30) # give it time to write before checking the age again
|
|
394
|
+
elif every == "minute" and age >= OFFICE_LIVE:
|
|
395
|
+
start_office_refresh(quick=True)
|
|
396
|
+
time.sleep(20)
|
|
321
397
|
|
|
322
398
|
threading.Thread(target=watchdog, daemon=True).start()
|
|
323
399
|
threading.Thread(target=office_clock, daemon=True).start()
|