Something went wrong. Try again.
Open source agent hosting on the AT Protocol
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308// `/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 type { FunnelRow } 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 { Feedback } from './telemetry.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 } } /** How far each owner got, newest sign-up first. Undefined when the funnel couldn't be read. */ funnel?: FunnelRow[]}
/** 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' ? '✓' : `<span class="num">${esc(at.replace('T', ' ').slice(5, 16))}</span>`)
/** The funnel: how many owners reached each step, then one row per owner. */function funnelSection(rows: FunnelRow[]): string { const steps: [keyof FunnelRow, string][] = [ ['signedUp', 'Signed up'], ['signInStarted', 'Went to sign in'], ['signedIn', 'Signed in'], ['onboarded', 'Onboarded'], ['firstAgent', 'Agent'], ['firstChat', 'Chatted'], ] const counts = steps.map(([k, label]) => `<li><b>${rows.filter((r) => r[k]).length}</b> ${label.toLowerCase()}</li>`).join('') const body = rows .map( (r) => `<tr><td class="handle">${esc(r.handle)}</td>${steps.map(([k]) => `<td>${when(r[k] as string | undefined)}</td>`).join('')}` + `<td>${r.lastFailure ? `<span class="num">${esc(r.lastFailure.at.replace('T', ' ').slice(5, 16))}</span> <span class="muted">${esc(r.lastFailure.detail ?? '')}</span>` : ''}</td></tr>`, ) .join('') return ( `<h2>Funnel</h2><p class="muted">How far each owner got (UTC). Steps before Nov 19 weren't recorded, except sign-up and agents.</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 failed sign-in</th></tr></thead><tbody>${body}</tbody></table></div>` )}
const 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)}.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><span class="handle">${esc(o.handle)}</span><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', CSS + `<h1>Admin</h1>` + `<p><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 + table + (v.funnel ? funnelSection(v.funnel) : `<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>`, { 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>` : ''}</td></tr>`, ) .join('') + `</tbody></table></div>` : `<p class="muted">Nothing logged${v.level || v.kind ? ' with these filters' : ''}.</p>` return page( 200, 'Logs · Languid', 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>.</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: (Feedback & { handle: string })[] /** 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}
/** `/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).slice(0, 500) const filter = `<p class="filters"><span class="muted">Kind</span> ` + [undefined, ...kinds].map((x) => (x === v.kind ? `<b>${x ?? 'all'}</b>` : `<a href="/admin/feedback${x ? `?kind=${x}` : ''}">${x ?? 'all'}</a>`)).join(' ') + '</p>' 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></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)}</td>` + `<td><div class="text">${esc(f.text)}</div>` + `${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></tr>`, ) .join('') + `</tbody></table></div>` : `<p class="muted">No feedback${v.kind ? ' of this kind' : ''} yet.</p>` return page( 200, 'Feedback · Languid', 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>` + `<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', 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 }, )}