Something went wrong. Try again.
Open source agent hosting on the AT Protocol
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522// `/admin`: the installation owner's page for the people they invited. Each owner's model budget// (what their agents' calls on the service's model keys may cost, in US dollars), with forms to add// credit, set the budget, or lift it; and a form for a new invite. Plain forms, no script.//// Only the installation owner ever sees it: the server answers everyone else with the not-found page.
import QRCode from 'qrcode'import { FUNNEL_SINCE, type FunnelEvent, type FunnelRow, type FunnelTime } from './funnel.ts'import { messageBody } from './inbox-page.ts'import { MESSAGE_LIMITS, type InboxMessage } from './messages.ts'import { KINDS, LEVELS, RETENTION_DAYS, type OpsEvent } from './ops.ts'import type { CreditGrant } from './billing.ts'import type { FeedbackItem } from './telemetry.ts'import type { UsageSummary } from './usage.ts'import type { Visit } from './visits.ts'import { esc, page, type Page } from './web.ts'
/** A QR code of `url`: SVG markup to show on the page, and a 1024px PNG as a data URL to download. */export async function inviteQr(url: string) { const svg = await QRCode.toString(url, { type: 'svg', margin: 2, errorCorrectionLevel: 'M' }) const png = await QRCode.toDataURL(url, { width: 1024, margin: 2, errorCorrectionLevel: 'M' }) return { svg, png }}
export interface AdminOwner { did: string handle: string createdAt: string budgetUsd?: number spentUsd: number /** What those calls cost at the provider; spentUsd less this is Languid's margin. */ providerCostUsd?: number agents: { name: string; handle: string }[] /** Their cloud sandbox and volume: paid (through Stripe), given (by the installation owner), or none. */ sandbox?: 'paid' | 'given' volume?: 'paid' | 'given'}
export interface AdminView { /** Cloud sandboxes are offered, so they can be given. */ sandboxes?: boolean owners: AdminOwner[] openInvites: number notice?: { text: string; error?: boolean } /** A new invite's sign-up link, shown once, right after it's made. */ invite?: { url: string; expiresAt: string; budgetUsd?: number; uses?: number; qr?: { svg: string; png: string } } /** A new Test onboarding link, shown once. */ testLink?: string /** How many test owners there are (left out of `owners` and the funnel). */ tests?: number /** How far each owner got, newest sign-up first. Undefined when the funnel couldn't be read. */ funnel?: FunnelRow[] /** Sign-ups that failed before an account was made, newest first. */ failedSignups?: FunnelEvent[] /** The funnel's cohort (a key of COHORTS); empty for all owners. */ cohort?: string}
/** A short UTC date and time. */const short = (at: string) => `<span class="num">${esc(at.replace('T', ' ').slice(5, 16))}</span>`
/** When, as a short UTC date and time; `before`: done before the funnel was recorded. */const when = (at?: string) => (!at ? '<span class="muted">·</span>' : at === 'before' ? '✓' : short(at))
/** A step's cell: when, or that nothing could have recorded it, or (a dot) not reached. */function stepCell(r: FunnelRow, k: FunnelTime): string { const at = r[k] if (!at && r.unrecorded?.includes(k)) return '<span class="muted small">not recorded</span>' if (k === 'signedIn' && at && r.signedInDerived) return `${short(at)} <span class="muted small" title="From their sessions, not recorded at the time">derived</span>` if (k === 'onboardingOpened' && at && r.screens?.length) return `${when(at)}<br><span class="muted small">${r.screens.map(esc).join(', ')}</span>` return when(at)}
const failureCell = (f?: { at: string; detail?: string }) => (f ? `${short(f.at)} <span class="muted">${esc(f.detail ?? '')}</span>` : '')
/** Cohorts the funnel can be cut to: everyone, or owners who signed up since a day. */export const COHORTS: { key: string; label: string; days?: number; since?: string }[] = [ { key: '', label: 'All owners' }, { key: '7d', label: 'Last 7 days', days: 7 }, { key: '30d', label: 'Last 30 days', days: 30 }, { key: 'recorded', label: 'Since the funnel began', since: FUNNEL_SINCE },]
/** The first sign-up time a cohort includes, if it's cut. */export function cohortSince(key: string | undefined, now = Date.now()): string | undefined { const c = COHORTS.find((x) => x.key === key) if (!c) return undefined return c.since ?? (c.days ? new Date(now - c.days * 86400_000).toISOString() : undefined)}
/** The funnel: how many owners reached each step, then one row per owner, then failed sign-ups. */function funnelSection(all: FunnelRow[], cohort = '', failed: FunnelEvent[] = []): string { const since = cohortSince(cohort) const rows = since ? all.filter((r) => (r.signedUp ?? '') >= since) : all const steps: [FunnelTime, string][] = [ ['signedUp', 'Signed up'], ['signInStarted', 'Went to sign in'], ['signedIn', 'Signed in'], ['onboardingOpened', 'Saw onboarding'], ['onboarded', 'Onboarded'], ['firstAgentFormOpened', 'Saw agent form'], ['firstAgent', 'Agent'], ['firstChat', 'Chatted'], ] const label = COHORTS.find((c) => c.key === cohort)?.label ?? 'All owners' const cohorts = `<p class="filters"><span class="muted">Cohort</span> ` + COHORTS.map((c) => (c.key === cohort ? `<b>${esc(c.label)}</b>` : `<a href="/admin${c.key ? `?cohort=${c.key}` : ''}#funnel">${esc(c.label)}</a>`)).join(' ') + '</p>' const counts = steps .map(([k, l]) => { const n = rows.filter((r) => r[k]).length const unknown = rows.filter((r) => !r[k] && r.unrecorded?.includes(k)).length return `<li><b>${n}</b> ${l.toLowerCase()}${unknown ? ` <span class="muted small">(${unknown} not recorded)</span>` : ''}</li>` }) .join('') const body = rows .map( (r) => `<tr><td class="handle"><a href="/admin/owners/${encodeURIComponent(r.handle)}">${esc(r.handle)}</a></td>${steps.map(([k]) => `<td>${stepCell(r, k)}</td>`).join('')}` + `<td>${r.lastSeenAt ? short(r.lastSeenAt) : '<span class="muted">·</span>'}</td>` + `<td>${[['Sign-in', r.lastFailure], ['Agent', r.lastAgentFailure], ['Chat', r.lastChatFailure]].filter(([, f]) => f).map(([l, f]) => `<div><span class="muted">${l}</span> ${failureCell(f as { at: string; detail?: string })}</div>`).join('')}</td></tr>`, ) .join('') const signups = failed.length ? `<h3>Failed sign-ups</h3><div class="owners-wrap"><table class="owners funnel"><thead><tr><th>When</th><th>Handle asked for</th><th>Why</th></tr></thead><tbody>` + failed.slice(0, 50).map((e) => `<tr><td>${short(e.createdAt)}</td><td class="handle">${esc(e.handle ?? '')}</td><td class="muted">${esc(e.detail ?? '')}</td></tr>`).join('') + `</tbody></table></div>` : '' return ( `<h2 id="funnel">Funnel</h2><p class="muted">How far each owner got (UTC). Recording began Nov 19 19:38; “not recorded” marks steps an owner who signed up earlier may have reached unseen, a dot a step not reached.</p>` + cohorts + `<p class="muted small">${esc(label)}: ${rows.length} owner${rows.length === 1 ? '' : 's'}</p>` + `<ul class="counts">${counts}</ul>` + `<div class="owners-wrap"><table class="owners funnel"><thead><tr><th>Owner</th>${steps.map(([, l]) => `<th>${l}</th>`).join('')}<th>Last seen</th><th>Last failures</th></tr></thead><tbody>${body}</tbody></table></div>` + signups )}
export const ADMIN_CSS = '<style>' + '.owners-wrap{overflow-x:auto;margin:1rem 0}.owners{width:100%;border-collapse:collapse;font-size:.92rem}.owners .handle{white-space:nowrap}' + '.owners th{text-align:left;font-weight:500;font-size:.8rem;color:var(--muted);padding:.4rem .5rem;border-bottom:1px solid var(--line)}' + '.owners td{padding:.6rem .5rem;border-bottom:1px solid var(--line);vertical-align:top}' + '.owners .num{font-variant-numeric:tabular-nums;white-space:nowrap}' + '.owners .out{color:var(--fg);font-weight:500}' + '.owners form{display:flex;gap:.4rem;align-items:center;margin:0 0 .4rem}.owners td.change{min-width:15.5rem}' + '.owners input[type=text]{flex:none;width:5rem;padding:.25rem .65rem}' + 'button.small{padding:.25rem .8rem;font-size:.85rem;white-space:nowrap}' + '.muted{color:var(--muted)}.small{font-size:.8rem}.filters{margin:.25rem 0}.filters a,.filters b{margin-right:.5rem}.did{font-size:.75rem;white-space:nowrap}' + '.notice{border-left:3px solid var(--green);padding:.25rem .75rem;margin:1rem 0}.notice.error{border-color:#dc2626}' + '.invite label{display:block;margin:.6rem 0 .25rem;font-size:.9rem}.invite input{max-width:12rem}' + '.link{word-break:break-all;user-select:all}' + '.counts{display:flex;flex-wrap:wrap;gap:.25rem 1.25rem;list-style:none;padding:0;margin:.5rem 0}.counts li::before{content:none}.funnel td{white-space:nowrap}' + '.qr{margin:1rem 0}.qr .code{display:block;width:min(100%,70vh);background:#fff;border:1px solid var(--line)}.qr .code svg{display:block;width:100%;height:auto}' + '.qr p{margin:.5rem 0 0;display:flex;gap:1rem}' + '@media (max-width:700px){.owners thead{display:none}.owners tr,.owners td{display:block}.owners td{border:0;padding:.25rem 0}.owners tr{border-bottom:1px solid var(--line);padding:.5rem 0}}' + '</style>'
const money = (n: number) => `$${n.toFixed(2)}`
/** The invite's QR code, big enough to project, with both files to download. Nothing is saved: the link is the invite. */const qrFigure = (qr: { svg: string; png: string }) => `<figure class="qr"><span class="code" role="img" aria-label="QR code of the invite link">${qr.svg}</span>` + `<p><a href="${qr.png}" download="languid-invite.png">Download PNG</a><a href="data:image/svg+xml;base64,${Buffer.from(qr.svg).toString('base64')}" download="languid-invite.svg">Download SVG</a></p></figure>`const hidden = (name: string, value: string) => `<input type="hidden" name="${esc(name)}" value="${esc(value)}">`
function plans(o: AdminOwner, form: (action: string, body: string) => string): string { const one = (plan: 'sandbox' | 'volume', label: string) => { const s = o[plan] if (s === 'paid') return `<div>${label}: paid</div>` if (s === 'given') return form('take', `<input type="hidden" name="plan" value="${plan}"><span>${label}: given</span> <button class="small">Take back</button>`) if (plan === 'volume' && !o.sandbox) return '' return form('give', `<input type="hidden" name="plan" value="${plan}"><button class="small">Give ${label.toLowerCase()}</button>`) } return one('sandbox', 'Sandbox') + one('volume', 'Volume')}
function row(o: AdminOwner, sandboxes = false): string { const left = o.budgetUsd === undefined ? undefined : o.budgetUsd - o.spentUsd const budget = o.budgetUsd === undefined ? `<span class="muted">unlimited</span>` : `${money(o.budgetUsd)}<br><span class="${left! <= 0 ? 'out' : 'muted'}">${left! <= 0 ? 'used up' : `${money(left!)} left`}</span>` const agents = o.agents.length ? o.agents.map((a) => `<span class="handle">${esc(a.handle)}</span>`).join('<br>') : '<span class="muted">none</span>' const form = (action: string, body: string) => `<form method="post" action="/admin">${hidden('action', action)}${hidden('owner', o.did)}${body}</form>` const forms = form('add', `<input type="text" name="usd" inputmode="decimal" placeholder="5.00" aria-label="Dollars to add for ${esc(o.handle)}" required><button class="small">Add credit</button>`) + form('set', `<input type="text" name="usd" inputmode="decimal" placeholder="${o.budgetUsd ?? '20'}" aria-label="New budget for ${esc(o.handle)}" required><button class="small">Set budget</button>`) + (o.budgetUsd === undefined ? '' : form('unlimited', `<button class="small">Make unlimited</button>`)) return ( `<tr><td><a class="handle" href="/admin/owners/${encodeURIComponent(o.handle)}">${esc(o.handle)}</a><br><span class="muted did">${esc(o.did)}</span></td>` + `<td>${agents}</td><td class="num">${money(o.spentUsd)}${o.providerCostUsd ? `<br><span class="muted">${money(o.providerCostUsd)} at cost</span>` : ''}</td><td class="num">${budget}</td>` + (sandboxes ? `<td class="change">${plans(o, form)}</td>` : '') + `<td class="change">${forms}</td></tr>` )}
export function adminPage(v: AdminView): Page { const notice = v.notice ? `<p class="notice${v.notice.error ? ' error' : ''}" role="${v.notice.error ? 'alert' : 'status'}">${esc(v.notice.text)}</p>` : '' const invite = v.invite ? `<section class="notice" role="status"><p><b>New invite</b> (${v.invite.budgetUsd === undefined ? 'unlimited' : `${money(v.invite.budgetUsd)} budget`}, ` + `expires ${esc(v.invite.expiresAt.slice(0, 10))}). Shown once, works ${(v.invite.uses ?? 1) > 1 ? `for ${v.invite.uses} people` : 'once'}:</p><p class="link"><code>${esc(v.invite.url)}</code></p>${v.invite.qr ? qrFigure(v.invite.qr) : ''}</section>` : '' const table = v.owners.length ? `<div class="owners-wrap"><table class="owners"><thead><tr><th>Owner</th><th>Agents</th><th>Spent</th><th>Budget</th>${v.sandboxes ? '<th>Cloud</th>' : ''}<th>Change</th></tr></thead><tbody>${v.owners.map((o) => row(o, v.sandboxes)).join('')}</tbody></table></div>` : `<p class="muted">No one has signed up yet.</p>` return page( 200, 'Admin · Languid', ADMIN_CSS + `<h1>Admin</h1>` + `<p><a href="/admin/control">Control room</a> · <a href="/admin/logs">Logs</a> · <a href="/admin/feedback">Feedback</a> · <a href="/admin/messages">Messages</a></p>` + `<p class="muted">Invited owners and their spend on the service's model keys. Their own ChatGPT or Anthropic keys don't count.</p>` + notice + invite + (v.testLink ? `<section class="notice" role="status"><p><b>Test sign-up link</b>, works once for a day. Open it in a private window so you stay signed in here:</p><p class="link"><code>${esc(v.testLink)}</code></p></section>` : '') + table + (v.funnel ? funnelSection(v.funnel, v.cohort, v.failedSignups) : `<h2>Funnel</h2><p class="muted">The funnel couldn't be read from the PDS just now.</p>`) + `<h2>Invite someone</h2>` + `<form method="post" action="/admin" class="invite">${hidden('action', 'invite')}` + `<label for="invite-usd">Budget in dollars (empty for unlimited)</label><input id="invite-usd" type="text" name="usd" inputmode="decimal" placeholder="10.00" value="5">` + `<label for="invite-uses">People it signs up</label><input id="invite-uses" type="text" name="uses" inputmode="numeric" value="1">` + `<label for="invite-days">Link good for (days)</label><input id="invite-days" type="text" name="days" inputmode="numeric" value="7">` + `<p><button>Make invite link</button></p></form>` + `<p class="muted">${v.openInvites} sign-up${v.openInvites === 1 ? '' : 's'} left on open invites.</p>` + `<h2>Test onboarding</h2>` + `<p class="muted">Sign up as a brand-new person with a throwaway account. Test accounts have a $5 budget and stay out of the owner list and the funnel.</p>` + `<form method="post" action="/admin">${hidden('action', 'test-signup')}<button>New test sign-up</button></form>` + (v.tests ? `<form method="post" action="/admin">${hidden('action', 'delete-tests')}<p><button class="small">Delete ${v.tests} test account${v.tests === 1 ? '' : 's'}</button> <span class="muted">with their agents, for good</span></p></form>` : ''), { path: '/admin', app: true }, )}
export interface AdminOwnerView { did: string handle: string createdAt?: string lastSeenAt?: string budgetUsd?: number spentUsd: number providerCostUsd?: number /** Their agents, by name only. */ agents: string[] /** Their funnel steps, oldest first. */ funnel: FunnelEvent[] /** Ops events whose subject is their DID or one of their agents, newest first. */ events: OpsEvent[] /** The ops space couldn't be read; events are this process's only. */ fromMemory?: boolean /** Their sessions still kept: kind and when only. */ sessions: { kind: string; createdAt: string }[] /** Model spend over the last 30 days. */ usage: UsageSummary grants: CreditGrant[] /** They share usage (Share usage with Languid); visits and browser errors are kept only then. */ sharing: boolean /** Their daily visits, newest day first; undefined when they couldn't be read. */ visits?: Visit[]}
/** Ops events as /admin/logs shows them. */function eventRows(events: OpsEvent[]): string { const at = (s: string) => `<span class="num">${esc(s.replace('T', ' ').slice(5, 19))}</span>` return ( `<div class="owners-wrap"><table class="owners logs"><thead><tr><th>When (UTC)</th><th>Level</th><th>Kind</th><th>What</th></tr></thead><tbody>` + events .map( (e) => `<tr class="${esc(e.level)}"><td>${at(e.createdAt)}${e.count && e.count > 1 ? `<br><span class="muted">×${e.count}, last ${at(e.lastAt ?? e.createdAt)}</span>` : ''}</td>` + `<td>${esc(e.level)}</td><td>${esc(e.kind)}</td>` + `<td>${e.name ? `<code>${esc(e.name)}</code> ` : ''}${esc(e.message)}` + `${e.subject || e.method ? `<br><span class="muted">${[e.subject, e.method].filter(Boolean).map((x) => esc(x!)).join(' · ')}</span>` : ''}` + `${e.version ? ` <span class="muted">${esc(e.version.slice(0, 7))}</span>` : ''}` + `${e.stack ? `<details><summary>Stack</summary><pre>${esc(e.stack)}</pre></details>` : ''}${e.detail ? `<details><summary>Output and note</summary><pre>${esc(e.detail)}</pre></details>` : ''}</td></tr>`, ) .join('') + `</tbody></table></div>` )}
/** `/admin/owners/<handle>`: one owner, from the ops space and the service's own state. Never their agents' spaces. */export function adminOwnerPage(v: AdminOwnerView): Page { const dl = (pairs: [string, string][]) => `<dl class="facts">${pairs.map(([k, x]) => `<dt>${esc(k)}</dt><dd>${x}</dd>`).join('')}</dl>` const facts = dl([ ['DID', `<span class="did">${esc(v.did)}</span>`], ['Signed up', v.createdAt ? short(v.createdAt) : '<span class="muted">·</span>'], ['Last seen', v.lastSeenAt ? short(v.lastSeenAt) : '<span class="muted">not yet recorded</span>'], ['Spent', `${money(v.spentUsd)}${v.providerCostUsd ? ` <span class="muted">(${money(v.providerCostUsd)} at cost)</span>` : ''}`], ['Budget', v.budgetUsd === undefined ? '<span class="muted">unlimited</span>' : money(v.budgetUsd)], ['Agents', v.agents.length ? v.agents.map((a) => `<span class="handle">${esc(a)}</span>`).join(', ') : '<span class="muted">none</span>'], ]) const funnel = v.funnel.length ? `<ol class="steps">${v.funnel.map((e) => `<li>${short(e.createdAt)} <b>${esc(e.step)}</b>${e.detail ? ` <span class="muted">${esc(e.detail)}</span>` : ''}</li>`).join('')}</ol>` : `<p class="muted">No steps recorded.</p>` const sessions = v.sessions.length ? `<ul class="plain">${v.sessions.map((x) => `<li>${short(x.createdAt)} <span class="muted">${esc(x.kind)}</span></li>`).join('')}</ul>` : `<p class="muted">None kept.</p>` const t = v.usage.total const usedDays = v.usage.days.filter((d) => d.totals.calls) const usage = t.calls ? `<p>${t.calls} call${t.calls === 1 ? '' : 's'}, ${money(t.charged)} charged (${money(t.cost)} at cost) in the last 30 days.</p>` + `<div class="owners-wrap"><table class="owners"><thead><tr><th>By agent</th><th>Calls</th><th>Charged</th></tr></thead><tbody>${v.usage.byAgent.map((a) => `<tr><td class="handle">${esc(a.name)}</td><td class="num">${a.totals.calls}</td><td class="num">${money(a.totals.charged)}</td></tr>`).join('')}</tbody></table></div>` + `<div class="owners-wrap"><table class="owners"><thead><tr><th>By model</th><th>Calls</th><th>Charged</th></tr></thead><tbody>${v.usage.byModel.map((a) => `<tr><td>${esc(a.name)}</td><td class="num">${a.totals.calls}</td><td class="num">${money(a.totals.charged)}</td></tr>`).join('')}</tbody></table></div>` + `<div class="owners-wrap"><table class="owners"><thead><tr><th>Day</th><th>Calls</th><th>Charged</th></tr></thead><tbody>${usedDays.reverse().map((d) => `<tr><td class="num">${esc(d.day)}</td><td class="num">${d.totals.calls}</td><td class="num">${money(d.totals.charged)}</td></tr>`).join('')}</tbody></table></div>` : `<p class="muted">No model calls in the last 30 days.</p>` const grants = v.grants.length ? `<ul class="plain">${v.grants.map((g) => `<li>${short(g.at)} <span class="num">${money(g.usd)}</span> <span class="muted">${esc(g.source)}</span></li>`).join('')}</ul>` : `<p class="muted">None.</p>` const client = v.events.filter((e) => e.kind === 'client') const others = v.events.filter((e) => e.kind !== 'client') const events = others.length ? eventRows(others.slice(0, 200)) : `<p class="muted">No ops events about them or their agents.</p>` const off = v.sharing ? '' : `<p class="muted">They don't share usage, so nothing new is kept here.</p>` const visits = v.visits === undefined ? `<p class="muted">Visits couldn't be read just now.</p>` : v.visits.length ? `<div class="owners-wrap"><table class="owners"><thead><tr><th>Day (UTC)</th><th>Pages</th><th>First – last</th><th>Top pages</th></tr></thead><tbody>` + v.visits .map( (d) => `<tr><td class="num">${esc(d.day)}</td><td class="num">${d.count}</td><td class="num">${esc(d.firstAt.slice(11, 16))} – ${esc(d.lastAt.slice(11, 16))}</td>` + `<td>${Object.entries(d.routes).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([r, n]) => `<code>${esc(r)}</code> ${n}`).join(', ')}</td></tr>`, ) .join('') + `</tbody></table></div>` : `<p class="muted">No visits recorded.</p>` const errors = client.length ? eventRows(client.slice(0, 100)) : `<p class="muted">No browser errors.</p>` return page( 200, `${v.handle} · Admin · Languid`, ADMIN_CSS + '<style>.facts{display:grid;grid-template-columns:max-content 1fr;gap:.25rem 1rem;margin:1rem 0}.facts dt{color:var(--muted);font-size:.85rem}.facts dd{margin:0}' + '.steps,.plain{list-style:none;padding:0;margin:.5rem 0}.steps li,.plain li{padding:.2rem 0}.steps li::before,.plain li::before{content:none}' + '.logs tr.error td:nth-child(2){color:#dc2626;font-weight:500}.logs pre{white-space:pre-wrap;font-size:.75rem}</style>' + `<h1>${esc(v.handle)}</h1>` + `<p><a href="/admin">Admin</a> · <a href="/admin/logs">Logs</a></p>` + `<p class="muted">From the ops space and the service's records of this owner. Nothing here is read from their agents' spaces.</p>` + facts + `<h2>Funnel</h2>${funnel}` + // Daily run counts go here once the ops space has them (the run-history work): read them in // adminOwnerRequest and add a section; counts only, never what the runs said. `<h2>Visits</h2>${off}${visits}` + `<h2>Browser errors</h2>${errors}` + `<h2>Runs</h2><p class="muted">Daily run counts aren't in the ops space yet.</p>` + `<h2>Model spend</h2>${usage}` + `<h2>Credit</h2>${grants}` + `<h2>Sessions</h2>${sessions}` + `<h2>Ops events</h2>` + (v.fromMemory ? `<p class="notice error" role="alert">The ops space couldn't be read; these are only what this process saw since it started.</p>` : '') + events, { path: '/admin', app: true }, )}
export interface AdminLogsView { events: OpsEvent[] /** The PDS couldn't be read: these are only what this process saw since it started. */ fromMemory: boolean level?: string kind?: string}
/** `/admin/logs`: the service's ops events (src/ops.ts), newest first, filtered by level and kind. */export function adminLogsPage(v: AdminLogsView): Page { const shown = v.events.filter((e) => (!v.level || e.level === v.level) && (!v.kind || e.kind === v.kind)).slice(0, 500) const link = (level?: string, kind?: string) => { const q = new URLSearchParams({ ...(level ? { level } : {}), ...(kind ? { kind } : {}) }).toString() return `/admin/logs${q ? `?${q}` : ''}` } const filter = (label: string, values: readonly string[], current: string | undefined, href: (x?: string) => string) => `<p class="filters"><span class="muted">${label}</span> ` + [undefined, ...values].map((x) => (x === current ? `<b>${x ?? 'all'}</b>` : `<a href="${esc(href(x))}">${x ?? 'all'}</a>`)).join(' ') + '</p>' const at = (s: string) => `<span class="num">${esc(s.replace('T', ' ').slice(5, 19))}</span>` const rows = shown.length ? `<div class="owners-wrap"><table class="owners logs"><thead><tr><th>When (UTC)</th><th>Level</th><th>Kind</th><th>What</th></tr></thead><tbody>` + shown .map( (e) => `<tr class="${esc(e.level)}"><td>${at(e.createdAt)}${e.count && e.count > 1 ? `<br><span class="muted">×${e.count}, last ${at(e.lastAt ?? e.createdAt)}</span>` : ''}</td>` + `<td>${esc(e.level)}</td><td>${esc(e.kind)}</td>` + `<td>${e.name ? `<code>${esc(e.name)}</code> ` : ''}${esc(e.message)}` + `${e.subject || e.method ? `<br><span class="muted">${[e.subject, e.method].filter(Boolean).map((x) => esc(x!)).join(' · ')}</span>` : ''}` + `${e.version ? ` <span class="muted">${esc(e.version.slice(0, 7))}</span>` : ''}` + `${e.stack ? `<details><summary>Stack</summary><pre>${esc(e.stack)}</pre></details>` : ''}${e.detail ? `<details><summary>Output and note</summary><pre>${esc(e.detail)}</pre></details>` : ''}</td></tr>`, ) .join('') + `</tbody></table></div>` : `<p class="muted">Nothing logged${v.level || v.kind ? ' with these filters' : ''}.</p>` return page( 200, 'Logs · Languid', ADMIN_CSS + '<style>.filters{margin:.25rem 0}.filters a,.filters b{margin-right:.5rem}.logs tr.error td:nth-child(2){color:#dc2626;font-weight:500}.logs pre{white-space:pre-wrap;font-size:.75rem}</style>' + `<h1>Logs</h1>` + `<p class="muted">The service's errors and lifecycle, kept in the ops space for ${RETENTION_DAYS} days. Live output: <code>fly logs -a languid-nimbus</code>. Agents' own error reports are on <a href="/errors">Error reports</a>. Problems people report from their computers (the Windows installer, setup, <code>languid report</code>) are kind <a href="/admin/logs?kind=report">report</a>.</p>` + (v.fromMemory ? `<p class="notice error" role="alert">The ops space couldn't be read; these are only what this process saw since it started.</p>` : '') + filter('Level', LEVELS, v.level, (x) => link(x, v.kind)) + filter('Kind', KINDS, v.kind, (x) => link(v.level, x)) + rows, { path: '/admin', app: true }, )}
export interface AdminFeedbackView { /** Newest first, from every agent whose owner shares it. */ feedback: (Omit<FeedbackItem, 'rkey'> & { rkey?: string; agent?: string; handle: string; triage?: import('./feedback-triage.ts').FeedbackTriage })[] /** Agents that share, and agents that don't (their feedback stays in their own space). */ sharing: number notSharing: number /** The account it's shared with (ops.languid.ai). */ destination: string kind?: string status?: string notice?: { text: string; error?: boolean } /** Only feedback with no reply to the agent yet. */ open?: boolean}
/** `/admin/feedback`: what agents sent the maintainer with their feedback tool. */export function adminFeedbackPage(v: AdminFeedbackView): Page { const kinds = ['bug', 'idea', 'other'] const shown = v.feedback .filter((f) => (!v.kind || f.kind === v.kind) && (!v.status || v.status === 'all' || (f.triage?.status ?? 'open') === v.status) && (!v.open || !f.reply)) .slice(0, 500) const link = (kind?: string, status?: string, open = v.open) => '/admin/feedback?' + new URLSearchParams({ ...(kind ? { kind } : {}), ...(status ? { status } : {}), ...(open ? { open: '1' } : {}) }) const filter = `<p class="filters"><span class="muted">Kind</span> ` + [undefined, ...kinds].map((x) => (x === v.kind ? `<b>${x ?? 'all'}</b>` : `<a href="${esc(link(x, v.status))}">${x ?? 'all'}</a>`)).join(' ') + '</p>' + '<p class="filters"><span class="muted">Triage</span> ' + [undefined, 'open', 'resolved'].map((x) => x === v.status ? `<b>${x ?? 'all'}</b>` : `<a href="${esc(link(v.kind, x))}">${x ?? 'all'}</a>`).join(' ') + '</p>' + '<p class="filters"><span class="muted">Reply</span> ' + [false, true].map((o) => (o === !!v.open ? `<b>${o ? 'open only' : 'any'}</b>` : `<a href="${esc(link(v.kind, v.status, o))}">${o ? 'open only' : 'any'}</a>`)).join(' ') + '</p>' const status = (f: Pick<FeedbackItem, 'reply'>) => f.reply ? `${esc(f.reply.status)}${f.reply.version ? ` <span class="muted">${esc(f.reply.version)}</span>` : ''}<div class="text muted">${esc(f.reply.text)}</div>` : '<span class="muted">open</span>' const rows = shown.length ? `<div class="owners-wrap"><table class="owners logs"><thead><tr><th>When (UTC)</th><th>Kind</th><th>Agent</th><th>Feedback</th><th>Reply</th></tr></thead><tbody>` + shown .map( (f) => `<tr><td><span class="num">${esc(f.createdAt.replace('T', ' ').slice(5, 16))}</span></td><td>${esc(f.kind)}</td><td>${esc(f.handle)}${f.agent ? `<br><span class="muted">${esc(f.agent)} · ${esc(f.rkey ?? '')}</span>` : ''}</td>` + `<td><div class="text">${esc(f.text)}</div>` + (f.uri ? `<details><summary>${esc(f.triage?.status ?? 'open')} · Triage</summary><p>Reference: <code>${esc(f.uri)}</code></p><p>CID: <code>${esc(f.cid ?? '')}</code></p>` + `<form method="post" action="${esc(link(v.kind, v.status))}"><input type="hidden" name="feedback" value="${esc(f.uri)}"><label>Status <select name="status"><option value="open"${f.triage?.status !== 'resolved' ? ' selected' : ''}>Open / reopen</option><option value="resolved"${f.triage?.status === 'resolved' ? ' selected' : ''}>Resolved</option></select></label>` + `<label>Internal note (never sent)<textarea name="note" maxlength="4000">${esc(f.triage?.note ?? '')}</textarea></label><label>Fix link (HTTPS)<input name="fix" maxlength="1000" value="${esc(f.triage?.fix ?? '')}"></label><button>Save private triage</button></form></details>` : '') + `${f.model || f.version ? `<span class="muted">${[f.model ? `${f.provider}/${f.model}` : '', f.version ? f.version.slice(0, 7) : ''].filter(Boolean).map((x) => esc(x)).join(' · ')}</span>` : ''}</td>` + `<td>${status(f)}</td></tr>`, ) .join('') + `</tbody></table></div>` : `<p class="muted">No ${v.open ? 'unanswered ' : ''}feedback${v.kind || v.status ? ' matching this filter' : ''} yet.</p>` return page( 200, 'Feedback · Languid', ADMIN_CSS + '<style>.filters{margin:.25rem 0}.filters a,.filters b{margin-right:.5rem}.logs .text{white-space:pre-wrap;word-break:break-word}</style>' + `<h1>Feedback</h1>` + (v.notice ? `<p class="notice${v.notice.error ? ' error' : ''}" role="status">${esc(v.notice.text)}</p>` : '') + '<p class="muted">Triage notes are private to the maintainer, and resolving does not send a message. To answer an agent, run <code>languid feedback reply</code>; it hears back on its next turn.</p>' + `<p class="muted">From ${v.sharing} agent${v.sharing === 1 ? '' : 's'} whose owners share with ${esc(v.destination)}. ${v.notSharing} don't share yet. Error reports are on <a href="/errors">Error reports</a>.</p>` + filter + rows, { path: '/admin', app: true }, )}
export interface AdminMessagesView { messages: InboxMessage[] /** Owners who dismissed each message, by its key. */ dismissed: Map<string, number> /** Owners to pick from for a message to one person. */ owners: { did: string; handle: string }[] /** The ops account's handle, which the messages come from. */ from?: string notice?: { text: string; error?: boolean }}
/** `/admin/messages`: write a message to every owner's Inbox or to one owner's, and see what went out. */export function adminMessagesPage(v: AdminMessagesView): Page { const handleOf = new Map(v.owners.map((o) => [o.did, o.handle])) const notice = v.notice ? `<p class="notice${v.notice.error ? ' error' : ''}" role="${v.notice.error ? 'alert' : 'status'}">${esc(v.notice.text)}</p>` : '' const options = [`<option value="">Everyone</option>`, ...v.owners.map((o) => `<option value="${esc(o.did)}">${esc(o.handle)}</option>`)].join('') const sent = v.messages.length ? `<ul class="sent">` + v.messages .map( (m) => `<li><small>${esc(m.createdAt.replace('T', ' ').slice(0, 16))} UTC · to ${m.to ? esc(handleOf.get(m.to) ?? m.to) : 'everyone'} · ${v.dismissed.get(m.rkey) ?? 0} dismissed</small>` + `<h3>${esc(m.title)}</h3>${messageBody(m.body)}` + `<form method="post" action="/admin/messages">${hidden('action', 'delete')}${hidden('message', m.rkey)}<button class="small">Delete</button></form></li>`, ) .join('') + `</ul>` : `<p class="muted">Nothing sent yet.</p>` return page( 200, 'Messages · Admin · Languid', ADMIN_CSS + '<style>.compose label{display:block;margin:.75rem 0 .25rem}.compose :is(input[type=text],select,textarea){width:100%;max-width:40rem;box-sizing:border-box}.compose textarea{min-height:10rem;font:inherit}' + '.sent{list-style:none;padding:0}.sent li{padding:.75rem 0;border-bottom:1px solid var(--line)}.sent li::before{content:none}.sent small{color:var(--muted)}.sent h3{margin:.25rem 0}.sent p{margin:0 0 .5rem;overflow-wrap:anywhere}.sent form{margin:0}</style>' + `<h1>Messages</h1>` + `<p><a href="/admin">Admin</a></p>` + `<p class="muted">Messages show in owners’ Inbox${v.from ? ` from ${esc(v.from)}` : ''} until they dismiss them. A message to everyone reaches the owners who have signed up by the time you send it. Blank lines start paragraphs, and web addresses become links.</p>` + notice + `<form method="post" action="/admin/messages" class="compose">${hidden('action', 'send')}` + `<label for="msg-to">To</label><select id="msg-to" name="to">${options}</select>` + `<label for="msg-title">Title</label><input id="msg-title" type="text" name="title" maxlength="${MESSAGE_LIMITS.title}" required>` + `<label for="msg-body">Message</label><textarea id="msg-body" name="body" maxlength="${MESSAGE_LIMITS.body}" required></textarea>` + `<p><button>Send</button></p></form>` + `<h2>Sent</h2>` + sent, { path: '/admin', app: true }, )}