Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

12.3 KB
Raw Blame
/* Agent Gallery — gallery logic. No build step, no deps, no trackers.
   One BASE manifest per role; provider variants (claude/antigravity/codex) are
   generated by scripts/build-data.py and exposed on each card as a toggle, so
   a single role works on any CLI without maintaining three copies by hand. */

'use strict';

const { PROVIDERS, PROVIDER_LABEL, normalizeProvider, validate } = window.HireSpec;
/* Accent → pastel chip color, reusing the landing page's pastel tokens. */
const ACCENT_BG = {
  coral: 'var(--coral)', mint: 'var(--mint)', sky: 'var(--sky-soft)',
  lemon: 'var(--lemon)', lilac: 'var(--lilac)', peach: 'var(--peach)'
};

/* Function categories — same eight as munderdiffl.in's landing page, derived
   from each role's capability tags (no spec change needed). */
const CATEGORIES = {
  engineering: ['code', 'testing', 'qa', 'ci', 'debugging', 'code-review', 'git', 'refactoring', 'migrations', 'codemods', 'cleanup', 'dependencies', 'maintenance', 'security', 'audit', 'frontend'],
  marketing:   ['marketing', 'copywriting', 'social', 'seo', 'release-notes'],
  sales:       ['sales', 'outreach', 'lead-research', 'crm'],
  analysis:    ['data', 'sql', 'etl', 'reporting', 'validation', 'cost'],
  product:     ['product', 'prototyping', 'specs', 'roadmaps'],
  research:    ['research', 'competitive-intel', 'markets', 'literature'],
  writing:     ['docs', 'writing', 'markdown', 'readme', 'blogs'],
  operations:  ['operations', 'monitoring', 'compliance', 'licenses', 'triage', 'workflows', 'scripting']
};
function categoriesOf(m) {
  const caps = (m.capabilities || []).map((c) => c.toLowerCase());
  const out = [];
  for (const [cat, words] of Object.entries(CATEGORIES)) {
    if (caps.some((c) => words.includes(c))) out.push(cat);
  }
  return out.length ? out : ['operations'];
}

/* sel: per-role selected provider, keyed by base file name. */
const state = { hires: [], q: '', provider: null, category: null, sel: {} };

/* ── load ─────────────────────────────────────────────────────────────── */

/** Derive in-memory provider variants from a base manifest (mirror of
 *  scripts/build-data.py, used only when manifests-data.js isn't loaded). */
function deriveVariants(file, manifest) {
  const slug = file.replace('.hire.json', '');
  const baseProvider = normalizeProvider(manifest.provider) || 'claude';
  const variants = {};
  for (const p of PROVIDERS) {
    const v = { ...manifest, provider: p };
    if (p !== baseProvider) { delete v.model; delete v.commandFlags; }
    variants[p] = { file: 'variants/' + slug + '.' + p + '.hire.json', manifest: v };
  }
  return { file, manifest, baseProvider, variants };
}

async function load() {
  const grid = document.getElementById('grid');
  // Primary source: the generated manifests-data.js (works on file:// too).
  if (Array.isArray(window.HIRES_DATA) && window.HIRES_DATA.length > 0) {
    state.hires = window.HIRES_DATA.filter((h) => validate(h.manifest).ok);
    render();
    return;
  }
  // Fallback: fetch base manifests and derive variants in-memory.
  try {
    const files = await (await fetch('manifests/index.json')).json();
    const results = await Promise.allSettled(
      files.map(async (f) => {
        const m = await (await fetch('manifests/' + f)).json();
        return deriveVariants(f, m);
      })
    );
    state.hires = results
      .filter((r) => r.status === 'fulfilled')
      .map((r) => r.value)
      .filter((h) => validate(h.manifest).ok);
    render();
  } catch (e) {
    grid.innerHTML = '<p class="empty">could not load the fair — ' + esc(String(e)) + '</p>';
  }
}

/* ── render ───────────────────────────────────────────────────────────── */

function selectedProvider(h) { return state.sel[h.file] || h.baseProvider || 'claude'; }
function selectedVariant(h) {
  const p = selectedProvider(h);
  return (h.variants && h.variants[p]) || { file: h.file, manifest: h.manifest };
}

function matches(h) {
  // The provider filter matches any role (every role has all variants), so it
  // instead PRESELECTS that provider on the cards; search matches base text.
  const m = h.manifest;
  if (state.category && !categoriesOf(m).includes(state.category)) return false;
  if (!state.q) return true;
  const hay = [m.name, m.description, m.goal, m.author, m.model, ...(m.capabilities || [])]
    .join(' ').toLowerCase();
  return state.q.toLowerCase().split(/\s+/).every((t) => hay.includes(t));
}

function render() {
  const grid = document.getElementById('grid');
  const empty = document.getElementById('empty');
  const shown = state.hires.filter(matches);
  empty.hidden = shown.length > 0;
  grid.innerHTML = shown.map(cardHtml).join('');

  grid.querySelectorAll('[data-act]').forEach((btn) => {
    btn.addEventListener('click', (ev) => {
      ev.preventDefault();
      const h = shown[Number(btn.dataset.idx)];
      if (!h) return;
      const act = btn.dataset.act;
      if (act === 'prov') {
        state.sel[h.file] = btn.dataset.prov;
        render();
      } else if (act === 'json') showModal(h);
      else if (act === 'dl') download(h);
    });
  });
}

function cardHtml(h, i) {
  const sel = selectedProvider(h);
  const v = selectedVariant(h);
  const m = v.manifest;
  const accentBg = ACCENT_BG[m.accent] || 'var(--tan)';
  const initials = esc(m.name.split(/\s+/).map((w) => w[0]).join('').slice(0, 2).toUpperCase());
  const caps = (m.capabilities || []).slice(0, 5)
    .map((c) => '<span class="badge">' + esc(c) + '</span>').join('');
  const provChips = PROVIDERS.map((p) =>
    '<button class="chip chip-sm" data-act="prov" data-prov="' + p + '" data-idx="' + i + '"' +
    ' aria-pressed="' + (p === sel) + '" title="hire this role on ' + esc(PROVIDER_LABEL[p]) + '">' +
    esc(PROVIDER_LABEL[p]) + '</button>'
  ).join('');
  return (
    '<article class="card">' +
      '<div class="card-head">' +
        '<div class="avatar" style="background:' + accentBg + '">' + initials + '</div>' +
        '<div><h3>' + esc(m.name) + '</h3>' +
        '<p class="role">' + esc(m.description || '') + '</p></div>' +
      '</div>' +
      '<div class="badges">' + provChips + '</div>' +
      '<div class="badges">' +
        (m.model
          ? '<span class="badge">' + esc(m.model) + '</span>'
          : '<span class="badge">' + esc(PROVIDER_LABEL[sel]) + ' default model</span>') +
        (m.isolate ? '<span class="badge">worktree</span>' : '') +
        (m.tokenCap ? '<span class="badge">' + fmtTokens(m.tokenCap) + ' cap</span>' : '') +
      '</div>' +
      (caps ? '<div class="badges">' + caps + '</div>' : '') +
      (m.goal ? '<p class="goal">' + esc(m.goal) + '</p>' : '') +
      (m.author ? '<p class="card-meta">by ' + esc(m.author) + '</p>' : '') +
      '<div class="card-actions">' +
        '<button class="btn btn-primary" data-act="dl" data-idx="' + i + '" title="download manifest">⤓ download</button>' +
        '<button class="btn" data-act="json" data-idx="' + i + '">view json</button>' +
      '</div>' +
    '</article>'
  );
}

/* ── download (always the SELECTED provider's variant) ────────────────── */

function variantBlobUrl(m) {
  return URL.createObjectURL(new Blob([JSON.stringify(m, null, 2)], { type: 'application/json' }));
}

function download(h) {
  const v = selectedVariant(h);
  const a = document.createElement('a');
  a.href = variantBlobUrl(v.manifest); // blob: works on file:// and https alike
  a.download = v.file.split('/').pop();
  a.click();
  toast('downloaded — in the app: Add agent → import hire… → pick this .json, review every field, then spawn. import never runs anything on its own.');
}

/* ── modal ────────────────────────────────────────────────────────────── */

let modalHire = null;
function showModal(h) {
  modalHire = h;
  const v = selectedVariant(h);
  document.getElementById('modal-title').textContent = v.file.split('/').pop();
  document.getElementById('modal-json').textContent = JSON.stringify(v.manifest, null, 2);
  const dl = document.getElementById('modal-download');
  dl.href = variantBlobUrl(v.manifest);
  dl.setAttribute('download', v.file.split('/').pop());
  document.getElementById('modal').hidden = false;
}
document.getElementById('modal-close').addEventListener('click', () => {
  document.getElementById('modal').hidden = true;
});
document.getElementById('modal').addEventListener('click', (e) => {
  if (e.target === e.currentTarget) e.currentTarget.hidden = true;
});
document.getElementById('modal-copy').addEventListener('click', async () => {
  if (!modalHire) return;
  const v = selectedVariant(modalHire);
  await navigator.clipboard.writeText(JSON.stringify(v.manifest, null, 2));
  toast('copied.');
});

/* ── filters ──────────────────────────────────────────────────────────── */

document.getElementById('search').addEventListener('input', (e) => {
  state.q = e.target.value.trim();
  render();
});

const catChipsEl = document.getElementById('category-chips');
if (catChipsEl) {
  Object.keys(CATEGORIES).forEach((cat) => {
    const b = document.createElement('button');
    b.className = 'chip chip-sm';
    b.textContent = cat;
    b.setAttribute('aria-pressed', 'false');
    b.addEventListener('click', () => {
      state.category = state.category === cat ? null : cat;
      catChipsEl.querySelectorAll('.chip').forEach((c) =>
        c.setAttribute('aria-pressed', String(c === b && state.category === cat)));
      render();
    });
    catChipsEl.appendChild(b);
  });
}

const chipsEl = document.getElementById('provider-chips');
PROVIDERS.forEach((p) => {
  const b = document.createElement('button');
  b.className = 'chip';
  b.textContent = PROVIDER_LABEL[p];
  b.setAttribute('aria-pressed', 'false');
  b.addEventListener('click', () => {
    state.provider = state.provider === p ? null : p;
    // The global toggle preselects this provider on every card (roles are
    // provider-portable, so filtering them OUT would just empty the grid).
    chipsEl.querySelectorAll('.chip').forEach((c) =>
      c.setAttribute('aria-pressed', String(c === b && state.provider === p)));
    if (state.provider) for (const h of state.hires) state.sel[h.file] = state.provider;
    render();
  });
  chipsEl.appendChild(b);
});

/* ── validate panel (validator itself lives in validator.js) ──────────── */

document.getElementById('validate-btn').addEventListener('click', () => {
  const out = document.getElementById('validate-result');
  let parsed;
  try {
    parsed = JSON.parse(document.getElementById('validate-input').value);
  } catch {
    out.className = 'bad';
    out.textContent = '✕ not valid JSON';
    return;
  }
  const res = validate(parsed);
  out.className = res.ok ? 'ok' : 'bad';
  out.textContent = res.ok ? '✓ valid hire manifest — PR it!' : '✕ ' + res.errors.join('\n✕ ');
});

/* ── utils ────────────────────────────────────────────────────────────── */

function esc(s) {
  return String(s).replace(/[&<>"']/g, (c) =>
    ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}

function fmtTokens(n) {
  if (n >= 1e6) return (n / 1e6).toFixed(n % 1e6 ? 1 : 0) + 'M';
  if (n >= 1e3) return Math.round(n / 1e3) + 'K';
  return String(n);
}

let toastTimer = null;
function toast(msg) {
  document.querySelectorAll('.toast').forEach((t) => t.remove());
  const t = document.createElement('div');
  t.className = 'toast';
  t.textContent = msg;
  document.body.appendChild(t);
  clearTimeout(toastTimer);
  toastTimer = setTimeout(() => t.remove(), 5000);
}

load();