'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) => ``; async function agentsHome() { document.title = 'PyBot Data Explorer'; $app.className = 'wide'; $app.innerHTML = `
The PyBot swarm

Agents and their traces

 

Loading…

Every agent

${METRICS.map(([k, l], i) => ``).join('')}

Moments

  1. Loading…
`; 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 => ` ${esc(h.title)}${fmt(h.value)} ${esc(h.agent)} ${esc(h.lane || 'no trace')} ${spark(h.spark, hourAxis(d.run))}open trace →`).join(''); document.getElementById('moments').innerHTML = d.moments.map(m => `
  • ${time(m.ts).slice(0, 16)} ${esc(m.text)} ${esc(m.agent)}'s trace →${m.sha ? ` commit` : ''}
  • `).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 ``; } const RECON = 'reconstructed trace · may have gaps'; 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(` `); 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 = `${esc(a.name)} · ${esc(a.lane || 'no trace released')}
    ${METRICS.find(m => m[0] === metric)[1]}: ${a.has_trace || metric === 'posts' ? fmt(a[metric]) : 'no trace released'}`; 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 => ``).join(''); el.innerHTML = ` ${untraced ? ' no trace released' : ''}`; } // ---------- agent page ---------- async function agentPage(name) { $app.innerHTML = '

    Loading…

    '; 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) => `
    ${k}${v}
    `; $app.innerHTML = `
    Agent · ${esc(a.lane || 'lane unknown')}

    ${esc(a.name)}

    ${a.reconstructed ? RECON : ''}

    ${a.has_trace ? `trace ${time(a.first_ts).slice(0, 16)} → ${time(a.last_ts).slice(0, 16)} · ${d3.format(',')(a.records)} records · trace file ↗` : 'no trace released for this agent'}

    ${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))}
    ${a.has_trace ? `

    Activity by hour

    ${a.reconstructed ? RECON : ''}
    ` : ''}

    PRs · ${a.prs.length}

    ${listCap(a.prs, p => `
    #${p.pr} ${esc(p.state)} ${esc(p.title)}
    `)}

    Reviews · ${a.review_list.length}

    ${listCap(a.review_list.slice().reverse(), r => `
    #${r.pr} ${r.verdict === 'approve' ? 'approve' : 'changes'} ${time(r.ts).slice(0, 16)}
    `)}

    Recent posts

    ${listCap(a.recent_posts, m => `
    #${esc(m.channel)} ${time(m.ts).slice(5, 16)} ${esc(firstLine(m.body))}
    `)}
    `; 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 ? `

    +${items.length - n} more

    ` : '') : '

    None.

    '; let traceSeq = 0; async function loadHour(name, h) { const seq = ++traceSeq, box = document.getElementById('tturns'), more = document.getElementById('tmore'); box.innerHTML = '

    Loading…

    '; 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 ? '

    No messages in this hour.

    ' : '')); 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 => `` + 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
    ${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' : ''); }; }