// The web channel (lab 08): a local chat page and a small HTTP API, built with Hono. // // GET / the chat page (static HTML, asks for the token) // GET /health status for monitoring (lab 12); no token needed // POST /api/chat {text} -> a stream of server-sent events: text, tool, done, error // POST /api/approvals/:id {decision, always?} -> the resumed turn, streamed the same way // GET /api/pending waiting approval requests, across all sessions // GET /api/history the web session's recent messages and the outbox // GET /api/events server-sent events for messages the assistant starts itself // POST /api/new start a new conversation // // Security, because this is a door into a program that can act on your machine: // - it listens on 127.0.0.1 only (config web.host), // - every /api request needs "Authorization: Bearer " (compared in constant time), // - the Host header must be the local address, which blocks DNS-rebinding attacks from web // pages you visit, // - the token is never put in a cookie, so other sites cannot ride on it (no CSRF). import { createHash, timingSafeEqual } from 'node:crypto'; import { Hono, type Context } from 'hono'; import { streamSSE, type SSEStreamingApi } from 'hono/streaming'; import type { AssistantResult } from '../core/assistant.ts'; import { NotOwnerError, type ChannelAdapter, type Gateway, type OutboundMessage, type TurnObserver, } from '../gateway/gateway.ts'; import { WEB_PAGE } from './web-page.ts'; export interface WebOptions { token: string; host: string; port: number; /** Extra status fields for /health (scheduler, spend, ...). */ health?: () => Promise>; } /** Pushes outbound messages to every page that has /api/events open. */ export class WebAdapter implements ChannelAdapter { readonly name = 'web'; private readonly listeners = new Set<(message: OutboundMessage) => void>(); deliver(message: OutboundMessage): void { for (const listener of this.listeners) listener(message); } subscribe(listener: (message: OutboundMessage) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } } function sameSecret(given: string, expected: string): boolean { const a = createHash('sha256').update(given).digest(); const b = createHash('sha256').update(expected).digest(); return timingSafeEqual(a, b); } export function createWebApp(gateway: Gateway, adapter: WebAdapter, options: WebOptions): Hono { const app = new Hono(); const startedAt = Date.now(); const allowedHosts = new Set([ `${options.host}:${options.port}`, `localhost:${options.port}`, `127.0.0.1:${options.port}`, ]); app.use('*', async (c, next) => { const host = c.req.header('host') ?? new URL(c.req.url).host; if (!allowedHosts.has(host)) return c.text('Forbidden host', 403); await next(); }); app.use('/api/*', async (c, next) => { const header = c.req.header('authorization') ?? ''; const token = header.startsWith('Bearer ') ? header.slice(7) : ''; if (!token || !sameSecret(token, options.token)) return c.json({ error: 'unauthorized' }, 401); await next(); }); app.get('/', (c) => c.html(WEB_PAGE)); app.get('/health', async (c) => c.json({ status: 'ok', uptimeSeconds: Math.round((Date.now() - startedAt) / 1000), ...gateway.stats(), ...(options.health ? await options.health() : {}), }), ); app.post('/api/chat', async (c) => { const body = (await c.req.json().catch(() => ({}))) as { text?: unknown }; const text = typeof body.text === 'string' ? body.text.trim() : ''; if (!text) return c.json({ error: 'text is required' }, 400); return streamTurn(c, (observer) => gateway.handleMessage({ channel: 'web', sender: 'owner', text }, observer), ); }); app.post('/api/approvals/:id', async (c) => { const body = (await c.req.json().catch(() => ({}))) as { decision?: unknown; always?: unknown }; if (body.decision !== 'approved' && body.decision !== 'denied') { return c.json({ error: 'decision must be "approved" or "denied"' }, 400); } const decision = body.decision; const id = c.req.param('id'); return streamTurn(c, async (observer) => { const answer = await gateway.answerApproval(id, decision, { channel: 'web', sender: 'owner', always: body.always === true, ...observer, }); if (answer.status === 'resumed') return answer.result; const note = answer.status === 'unknown' ? `No waiting request with id ${id}.` : `Noted. Still waiting for: ${answer.remaining.map((r) => r.approvalId).join(', ')}`; return { text: note, stop: 'other', added: [], usage: emptyUsage() }; }); }); app.get('/api/pending', async (c) => c.json(await gateway.pendingApprovals())); app.get('/api/history', async (c) => { const session = await gateway.session(gateway.sessionKeyFor('web')); const messages = session .messages() .slice(-40) .flatMap((m) => { if (m.role !== 'user' && m.role !== 'assistant') return []; if (typeof m.content === 'string') return [{ role: m.role, text: m.content }]; const blocks = (m.content ?? []) as { type: string; text?: string }[]; const visible = blocks .filter((b) => b.type === 'text' && b.text && !b.text.startsWith('')) .map((b) => b.text) .join(''); return visible ? [{ role: m.role, text: visible }] : []; }); return c.json({ messages, outbox: await gateway.outbox(20) }); }); app.get('/api/events', (c) => streamSSE(c, async (stream) => { const unsubscribe = adapter.subscribe((message) => { void stream.writeSSE({ event: 'outbound', data: JSON.stringify(message) }); }); const abort = c.req.raw.signal; while (!abort.aborted && !stream.aborted) { await stream.writeSSE({ event: 'ping', data: '{}' }); await stream.sleep(25_000); } unsubscribe(); }), ); app.post('/api/new', async (c) => { const session = await gateway.newConversation('web'); return c.json({ session: session.id }); }); return app; } /** Runs a turn and streams its progress as server-sent events. */ function streamTurn( c: Context, run: (observer: TurnObserver) => Promise, ): Response { return streamSSE(c, async (stream: SSEStreamingApi) => { // Writes are chained so events arrive in order even though callbacks are synchronous. let chain = Promise.resolve(); const send = (event: string, data: unknown) => { chain = chain.then(() => stream.writeSSE({ event, data: JSON.stringify(data) })); }; try { const result = await run({ signal: c.req.raw.signal, onText: (delta) => send('text', { delta }), onTool: (event) => send('tool', event), }); send('done', { stop: result.stop, text: result.text, approvals: result.approvals ?? [], }); } catch (err) { send('error', { message: err instanceof NotOwnerError ? 'not allowed' : (err as Error).message, }); } await chain; }); } function emptyUsage() { return { modelCalls: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, }; }