File size: 17,642 Bytes
a2222d5 862967c a2222d5 92da556 a2222d5 862967c a2222d5 862967c a2222d5 8c75e65 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 8c75e65 a2222d5 8c75e65 a2222d5 8c75e65 a2222d5 8c75e65 a2222d5 c0e2e7e a2222d5 8c75e65 a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 862967c a2222d5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | 'use strict';
// Agents view: the home page (totals, highlights, contribution graph, moments) and one page per agent.
// Uses helpers from app.js (esc, api, time, errBox, go, turn).
const fmt = v => v == null ? '—' : v >= 1e4 ? d3.format('.3~s')(v).replace('G', 'B') : d3.format(',')(v);
const METRICS = [['total_tokens', 'Total tokens'], ['output_tokens', 'Output tokens'], ['reasoning_tokens', 'Reasoning tokens'],
['model_calls', 'Model calls'], ['posts', 'Board posts']];
const hourOf = iso => new Date(Math.floor(Date.parse(iso) / 3600e3) * 3600e3).toISOString().replace('.000Z', 'Z');
const cssVar = k => getComputedStyle(document.documentElement).getPropertyValue(k).trim();
const agentLink = (name, at) => `/agent/${encodeURIComponent(name)}${at ? `?at=${hourOf(at)}` : ''}`;
let highlightsP = null, agentsP = null;
// The run's hours with its pauses cut out: pos[i] is the slot of hour i (null inside a pause), and each
// cut takes BREAK slots where a break mark is drawn. Hour i is first_hour + i hours.
const BREAK = 4;
function hourAxis(run) {
const t0 = Date.parse(run.first_hour), n = run.hours, pos = new Array(n).fill(null), breaks = [];
const gaps = (run.gaps || []).map(g => [(Date.parse(g.from) - t0) / 3600e3, (Date.parse(g.to) - t0) / 3600e3]);
let p = 0;
for (let i = 0; i < n; i++) {
const g = gaps.find(g => i >= g[0] && i < g[1]);
if (!g) pos[i] = p++;
else if (i === g[0]) { breaks.push(p + BREAK / 2); p += BREAK; }
}
const slots = pos.map((x, i) => [x, i]).filter(a => a[0] != null);
return {
t0, n, pos, breaks, total: p,
hourAt: x => new Date(t0 + d3.least(slots, a => Math.abs(a[0] + 0.5 - x))[1] * 3600e3).toISOString().replace('.000Z', 'Z'),
slotOf: iso => pos[Math.round((Date.parse(iso) - t0) / 3600e3)],
};
}
const breakMark = (x, y) => `<path class="brk" d="M${x - 4},${y + 4} l4,-8 M${x},${y + 4} l4,-8"/>`;
async function agentsHome() {
document.title = 'PyBot Data Explorer';
$app.className = 'wide';
$app.innerHTML = `
<div class="label">The PyBot swarm</div><h1>Agents and their traces</h1>
<p class="intro" id="totals"> </p>
<section class="hl" id="hl"><p class="muted">Loading…</p></section>
<section><div class="sec-head"><h2>Every agent</h2>
<div class="chips" role="group" aria-label="Colour by">${METRICS.map(([k, l], i) => `<button type="button" data-m="${k}" aria-pressed="${i === 0}">${l}</button>`).join('')}</div></div>
<div class="contrib" id="contrib"><div class="tip"></div></div><div class="legend" id="legend"></div></section>
<section><h2>Moments</h2><ol class="moments" id="moments"><li class="muted">Loading…</li></ol></section>`;
highlightsP = highlightsP || api('/api/highlights');
agentsP = agentsP || api('/api/agents?limit=1000');
highlightsP.then(renderHighlights).catch(e => { document.getElementById('hl').innerHTML = errBox(e); });
agentsP.then(d => drawContrib(d.items)).catch(e => { document.getElementById('contrib').innerHTML = errBox(e); });
}
function renderHighlights(d) {
const t = d.totals, el = document.getElementById('hl');
if (!el) return;
document.getElementById('totals').textContent =
`${d3.format(',')(t.agents)} agents · ${fmt(t.model_calls)} model calls · ${fmt(t.tokens)} tokens`;
el.innerHTML = d.highlights.map(h => `
<a class="hcard" data-nav href="${agentLink(h.agent, h.busiest_hour)}">
<span class="label">${esc(h.title)}</span><span class="hv">${fmt(h.value)}</span>
<span><b>${esc(h.agent)}</b> <span class="muted">${esc(h.lane || 'no trace')}</span></span>
${spark(h.spark, hourAxis(d.run))}<span class="go">open trace →</span></a>`).join('');
document.getElementById('moments').innerHTML = d.moments.map(m => `
<li><span class="muted">${time(m.ts).slice(0, 16)}</span> <span>${esc(m.text)}</span>
<a data-nav href="${agentLink(m.agent, m.ts)}">${esc(m.agent)}'s trace →</a>${m.sha ? ` <a data-nav href="/commits?sha=${m.sha}">commit</a>` : ''}</li>`).join('');
}
function spark(values, ax) {
const W = 200, x = d3.scaleLinear().domain([0, ax.total]).range([0, W]), max = d3.max(values) || 1, peak = values.indexOf(max);
const path = d3.line().defined((v, i) => ax.pos[i] != null).x((v, i) => x(ax.pos[i] + 0.5)).y(v => 28 - (v / max) * 26)(values);
return `<svg class="spark" viewBox="0 0 ${W} 32" preserveAspectRatio="none" aria-hidden="true">
<path d="${path}" vector-effect="non-scaling-stroke"/><line x1="${x(ax.pos[peak] + 0.5)}" x2="${x(ax.pos[peak] + 0.5)}" y1="0" y2="30" vector-effect="non-scaling-stroke"/>
${ax.breaks.map(b => breakMark(x(b), 28)).join('')}</svg>`;
}
const RECON = '<span class="recon">reconstructed trace · may have gaps</span>';
const SHORT = { conversation: 'convers.', uncertainty: 'uncert.', understanding: 'underst.', 'multi-turn': 'multi-t.', 'no trace': 'no trace' };
function drawContrib(items) {
const el = document.getElementById('contrib');
if (!el) return;
const tip = el.querySelector('.tip'), chips = document.querySelector('.sec-head .chips');
const lanes = d3.groups(items, a => a.lane || 'no trace').sort((a, b) => (a[0] === 'no trace') - (b[0] === 'no trace') || b[1].length - a[1].length);
let metric = 'total_tokens';
const draw = () => {
el.querySelector('svg')?.remove();
const W = el.clientWidth, narrow = W < 600, S = 11, P = 13, GAP = 6, L = narrow ? 70 : 150;
const cols = Math.max(8, Math.floor((W - L + 2) / P));
const vals = items.filter(a => a.has_trace && a[metric] > 0).map(a => a[metric]);
const color = d3.scaleSequentialLog(d3.interpolateRgbBasis([cssVar('--ramp0'), cssVar('--ramp1'), cssVar('--ramp2')]))
.domain([d3.min(vals) || 1, d3.max(vals) || 10]);
let y = 0;
const blocks = lanes.map(([lane, list]) => {
const sorted = list.slice().sort((a, b) => (b[metric] || 0) - (a[metric] || 0)), top = y;
y = top + Math.ceil(sorted.length / cols) * P + GAP;
return { lane, list: sorted, top };
});
y -= GAP;
const svg = d3.select(el).insert('svg', '.tip').attr('viewBox', `0 0 ${W} ${y}`).attr('height', y)
.attr('role', 'img').attr('aria-label', `One square per agent, grouped by lane, coloured by ${metric.replace('_', ' ')}`);
svg.append('defs').html(`<pattern id="hatch" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="4" height="4" fill="${cssVar('--page-bg')}"/><line x1="0" y1="0" x2="0" y2="4" stroke="${cssVar('--muted-color')}" stroke-width="1.5"/></pattern>`);
for (const b of blocks) {
const label = svg.append('text').attr('class', 'lane').attr('x', L - 10).attr('y', b.top + S - 1).attr('text-anchor', 'end');
if (narrow && b.list.length <= cols) label.text(`${SHORT[b.lane] || b.lane} ${b.list.length}`);
else if (narrow) { // two short lines: the name, then the count
label.append('tspan').text(SHORT[b.lane] || b.lane);
label.append('tspan').attr('x', L - 10).attr('dy', P).text(b.list.length);
} else label.text(`${b.lane} · ${b.list.length}`);
svg.append('g').selectAll('rect').data(b.list).join('rect')
.attr('x', (a, i) => L + (i % cols) * P).attr('y', (a, i) => b.top + Math.floor(i / cols) * P).attr('width', S).attr('height', S)
.attr('fill', a => !a.has_trace ? 'url(#hatch)' : a[metric] > 0 ? color(a[metric]) : cssVar('--ramp0'))
.attr('tabindex', 0).attr('role', 'link').attr('aria-label', a => `${a.name}, ${a.lane || 'no trace'}`)
.on('pointerenter focus', (ev, a) => {
ev.target.classList.add('on');
tip.innerHTML = `<b>${esc(a.name)}</b> · ${esc(a.lane || 'no trace released')}<br>${METRICS.find(m => m[0] === metric)[1]}: <b>${a.has_trace || metric === 'posts' ? fmt(a[metric]) : 'no trace released'}</b>`;
const r = ev.target.getBoundingClientRect(), box = el.getBoundingClientRect();
tip.style.left = Math.max(0, Math.min(r.left - box.left + 16, el.clientWidth - tip.offsetWidth)) + 'px';
tip.style.top = (r.top - box.top + 16) + 'px'; tip.style.opacity = 1;
})
.on('pointerleave blur', ev => { ev.target.classList.remove('on'); tip.style.opacity = 0; })
.on('click keydown', (ev, a) => { if (ev.type === 'click' || ev.key === 'Enter') go(agentLink(a.name)); });
}
legend(color, vals.length ? [d3.min(vals), d3.max(vals)] : null, items.some(a => !a.has_trace));
};
chips.onclick = e => {
const b = e.target.closest('button[data-m]');
if (!b) return;
metric = b.dataset.m;
chips.querySelectorAll('button').forEach(x => x.setAttribute('aria-pressed', x === b));
draw();
};
draw();
window.redrawChart = draw;
new ResizeObserver(() => window.redrawChart === draw && draw()).observe(el);
}
function legend(color, range, untraced) {
const el = document.getElementById('legend');
if (!el || !range) return;
const stops = d3.range(0, 1.01, 0.1).map(t => `<stop offset="${t}" stop-color="${color(Math.exp(Math.log(range[0]) + t * (Math.log(range[1]) - Math.log(range[0]))))}"/>`).join('');
el.innerHTML = `<svg width="210" height="34" aria-hidden="true"><defs><linearGradient id="ramp">${stops}</linearGradient></defs>
<rect x="0" y="2" width="200" height="10" fill="url(#ramp)"/>
<text x="0" y="28">${fmt(range[0])}</text><text x="100" y="28" text-anchor="middle">log scale</text><text x="200" y="28" text-anchor="end">${fmt(range[1])}</text></svg>
${untraced ? '<span class="nt"><svg width="11" height="11" aria-hidden="true"><rect width="11" height="11" fill="url(#hatch)"/></svg> no trace released</span>' : ''}`;
}
// ---------- agent page ----------
async function agentPage(name) {
$app.innerHTML = '<p class="muted">Loading…</p>';
let a;
try { a = await api('/api/agents/' + encodeURIComponent(name)); } catch (e) { $app.innerHTML = errBox(e); return; }
document.title = `${a.name} · PyBot Data Explorer`;
const rows = a.hours.rows, at = new URLSearchParams(location.search).get('at');
const stat = (k, v) => `<div><b>${k}</b>${v}</div>`;
$app.innerHTML = `
<div class="nav-row"><a data-nav href="/">← agents</a></div>
<div class="label">Agent · ${esc(a.lane || 'lane unknown')}</div><h1>${esc(a.name)}</h1>
${a.reconstructed ? RECON : ''}
<p class="meta-line">${a.has_trace ? `trace ${time(a.first_ts).slice(0, 16)} → ${time(a.last_ts).slice(0, 16)} · ${d3.format(',')(a.records)} records ·
<a href="${a.source}" target="_blank" rel="noopener">trace file ↗</a>` : 'no trace released for this agent'}</p>
<div class="meta">${stat('Model calls', fmt(a.model_calls))}${stat('Tool calls', fmt(a.tool_calls))}${stat('Input tokens', fmt(a.input_tokens))}
${stat('Output tokens', fmt(a.output_tokens))}${stat('Reasoning tokens', fmt(a.reasoning_tokens))}${stat('Board posts', fmt(a.posts))}
${stat('PRs opened / merged', `${a.prs_opened} / ${a.prs_merged}`)}${stat('Reviews given', fmt(a.reviews))}</div>
${a.has_trace ? `<h2>Activity by hour</h2><div class="astrip" id="astrip"><div class="tip"></div></div>
<section class="tb"><header><button type="button" id="hprev" aria-label="Previous active hour">◀</button>
<h3 id="hlabel"></h3><button type="button" id="hnext" aria-label="Next active hour">▶</button>${a.reconstructed ? RECON : ''}</header>
<div class="turns" id="tturns"></div><button class="more" id="tmore" hidden>More</button></section>` : ''}
<div class="alists">
<section><h2>PRs · ${a.prs.length}</h2>${listCap(a.prs, p => `<div class="one"><a data-nav href="${p.merged_sha ? `/commits?sha=${p.merged_sha}` : `/pr/${p.pr}`}">#${p.pr}</a>
<span class="muted">${esc(p.state)}</span> ${esc(p.title)}</div>`)}</section>
<section><h2>Reviews · ${a.review_list.length}</h2>${listCap(a.review_list.slice().reverse(), r => `<div class="one"><a data-nav href="/pr/${r.pr}">#${r.pr}</a>
<span class="verdict ${esc(r.verdict)}">${r.verdict === 'approve' ? 'approve' : 'changes'}</span> <span class="muted">${time(r.ts).slice(0, 16)}</span></div>`)}</section>
<section><h2>Recent posts</h2>${listCap(a.recent_posts, m => `<div class="one"><a data-nav href="/message/${m.id}">#${esc(m.channel)}</a>
<span class="muted">${time(m.ts).slice(5, 16)}</span> ${esc(firstLine(m.body))}</div>`)}</section>
</div>`;
if (!a.has_trace || !rows.length) return;
const active = rows.map(r => r[0]);
let hour = at && active.includes(hourOf(at)) ? hourOf(at) : at ? active.find(h => h >= hourOf(at)) || a.busiest_hour : a.busiest_hour;
const strip = drawStrip(a, h => show(h));
const show = h => {
hour = h;
const q = new URLSearchParams(location.search); q.set('at', h);
history.replaceState(null, '', location.pathname + '?' + q);
strip(h);
document.getElementById('hlabel').textContent = `${time(h).slice(0, 13)}:00 – ${time(new Date(Date.parse(h) + 3600e3).toISOString()).slice(11, 13)}:00 UTC`;
const i = active.indexOf(h);
document.getElementById('hprev').disabled = i <= 0;
document.getElementById('hnext').disabled = i < 0 || i >= active.length - 1;
loadHour(a.name, h);
};
document.getElementById('hprev').onclick = () => show(active[active.indexOf(hour) - 1]);
document.getElementById('hnext').onclick = () => show(active[active.indexOf(hour) + 1]);
show(hour);
}
const listCap = (items, row, n = 30) => items.length
? items.slice(0, n).map(row).join('') + (items.length > n ? `<p class="muted">+${items.length - n} more</p>` : '')
: '<p class="muted">None.</p>';
let traceSeq = 0;
async function loadHour(name, h) {
const seq = ++traceSeq, box = document.getElementById('tturns'), more = document.getElementById('tmore');
box.innerHTML = '<p class="muted">Loading…</p>'; more.hidden = true;
let cursor = 0;
const load = async first => {
const to = new Date(Date.parse(h) + 3600e3 - 1).toISOString();
let d;
for (let k = 0; k < 10; k++) { // keep reading past pages that come back empty
d = await api(`/api/traces/${encodeURIComponent(name)}?${new URLSearchParams({ from: h, to, limit: 40, cursor, messages_only: 'true' })}`);
cursor = d.next_cursor;
if (d.records.length || cursor == null) break;
}
if (seq !== traceSeq) return;
if (first) box.innerHTML = '';
box.insertAdjacentHTML('beforeend', d.records.map(turn).join('') || (first ? '<p class="muted">No messages in this hour.</p>' : ''));
more.hidden = cursor == null;
};
more.onclick = () => load(false).catch(e => box.insertAdjacentHTML('beforeend', errBox(e)));
try { await load(true); } catch (e) { if (seq === traceSeq) box.innerHTML = errBox(e); }
}
function drawStrip(a, onPick) {
const el = document.getElementById('astrip'), tip = el.querySelector('.tip'), ax = hourAxis(a.run);
const byHour = new Map(a.hours.rows.map(r => [r[0], r])), rows = a.hours.rows.filter(r => ax.slotOf(r[0]) != null);
let selected = null, svg;
const draw = () => {
el.querySelector('svg')?.remove();
const W = el.clientWidth, H = 64, B = H - 14;
const x = d3.scaleLinear().domain([0, ax.total]).range([0, W]);
const y = d3.scaleLinear().domain([0, d3.max(rows, r => r[4]) || 1]).range([B, 4]);
svg = d3.select(el).insert('svg', '.tip').attr('viewBox', `0 0 ${W} ${H}`).attr('height', H)
.attr('role', 'img').attr('aria-label', 'Output tokens per hour over the run (pauses cut out); click an hour to read the trace');
svg.append('line').attr('class', 'base').attr('x1', 0).attr('x2', W).attr('y1', B).attr('y2', B);
svg.append('g').attr('class', 'bars').selectAll('rect').data(rows).join('rect')
.attr('x', r => x(ax.slotOf(r[0]))).attr('width', Math.max(1, x(1) - x(0) - (W > 600 ? 1 : 0)))
.attr('y', r => y(r[4])).attr('height', r => B - y(r[4])).attr('class', r => r[0] === selected ? 'sel' : '');
let last = -1e9;
for (const tk of d3.utcDay.range(new Date(ax.t0), new Date(ax.t0 + ax.n * 3600e3))) {
const slot = ax.pos[(tk - ax.t0) / 3600e3];
if (slot == null || x(slot) - last < (W < 500 ? 56 : 44)) continue; // day ticks only where there is data
last = x(slot);
svg.append('line').attr('class', 'tick').attr('x1', last).attr('x2', last).attr('y1', B).attr('y2', B + 3);
svg.append('text').attr('x', last).attr('y', H - 2).text(d3.utcFormat('%b %-d')(tk));
}
svg.append('g').html(ax.breaks.map(b => `<rect class="gapbg" x="${x(b) - 6}" y="${B - 2}" width="12" height="5"/>` + breakMark(x(b), B)).join(''));
const hourAt = ev => ax.hourAt(x.invert(d3.pointer(ev)[0]));
svg.append('rect').attr('class', 'hit').attr('width', W).attr('height', H).attr('fill', 'transparent').style('cursor', 'pointer')
.on('pointermove', ev => {
const h = hourAt(ev), r = byHour.get(h);
tip.innerHTML = `${time(h).slice(0, 13)}:00 UTC<br>${r ? `${fmt(r[1])} model calls · ${fmt(r[4])} output tokens` : 'no activity'}`;
tip.style.left = Math.min(d3.pointer(ev)[0] + 12, el.clientWidth - tip.offsetWidth) + 'px'; tip.style.top = '66px'; tip.style.opacity = 1;
})
.on('pointerleave', () => { tip.style.opacity = 0; })
.on('click', ev => {
const target = Date.parse(hourAt(ev)); // the nearest hour this agent was active
onPick(d3.least(a.hours.rows.map(r => r[0]), h => Math.abs(Date.parse(h) - target)));
});
};
draw();
window.redrawChart = draw;
new ResizeObserver(() => window.redrawChart === draw && draw()).observe(el);
return h => { selected = h; svg.selectAll('.bars rect').attr('class', r => r[0] === h ? 'sel' : ''); };
}
|