import m from '@garage44/mithril' import {highlight} from '@/lib/highlight' /** * An agent's Markdown as vnodes: paragraphs, headings, lists, fenced code, * quotes, rules, tables, and inline code, bold, italic and links. Built as elements, * never as HTML, so what an agent writes is text however it is written; a link * goes only to http(s), or to a session of this hub. A session named in the text * (`S123`, `s3`, `session-s3`) links to it, opened in this window. */ export function markdown(src: string): m.Children[] { const lines = src.replace(/\r\n/g, '\n').split('\n') const out: m.Children[] = [] let i = 0 while (i < lines.length) { const line = lines[i] const fence = line.match(/^\s*(```|~~~)\s*([\w+-]*)\s*$/) if (fence) { const body: string[] = [] i++ while (i < lines.length && !lines[i].trim().startsWith(fence[1])) body.push(lines[i++]) i++ if (fence[2] === 'analysis' || fence[2] === 'new-session' || fence[2] === 'impact') { out.push(panel(fence[2], body)) continue } out.push(
                    {highlight(body.join('\n'), fence[2] ?? '')}
                
, ) continue } if (!line.trim()) { i++ continue } const heading = line.match(/^(#{1,6})\s+(.*)$/) if (heading) { out.push(m(`h${Math.min(heading[1].length + 2, 6)}.md__h`, inline(heading[2]))) i++ continue } if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { out.push(
) i++ continue } const item = /^\s*([-*+]|\d+[.)])\s+/ if (item.test(line)) { const ordered = /^\s*\d/.test(line) const items: string[] = [] while (i < lines.length && (item.test(lines[i]) || (/^\s{2,}\S/.test(lines[i]) && items.length))) { if (item.test(lines[i])) items.push(lines[i].replace(item, '')) else items[items.length - 1] += ` ${lines[i].trim()}` i++ } out.push(m(ordered ? 'ol' : 'ul', items.map((t) =>
  • {inline(t)}
  • ))) continue } // A table: a row of cells, a line of dashes under it, then its rows. if (isRow(line) && i + 1 < lines.length && DIVIDER.test(lines[i + 1])) { const align = cells(lines[i + 1]).map((c) => (c.startsWith(':') && c.endsWith(':') ? 'center' : c.endsWith(':') ? 'right' : null)) const head = cells(line) i += 2 const rows: string[][] = [] while (i < lines.length && isRow(lines[i])) rows.push(cells(lines[i++])) const cell = (tag: 'th' | 'td', text: string, k: number) => m(tag, align[k] ? {style: {textAlign: align[k]}} : {}, ...inline(text)) out.push(
    {head.map((h, k) => cell('th', h, k))} {rows.map((r) => ( {head.map((_, k) => cell('td', r[k] ?? '', k))} ))}
    , ) continue } if (line.startsWith('>')) { const quote: string[] = [] while (i < lines.length && lines[i].startsWith('>')) quote.push(lines[i++].replace(/^>\s?/, '')) out.push(
    {markdown(quote.join('\n'))}
    ) continue } const para: string[] = [] const tableAt = (k: number) => isRow(lines[k]) && k + 1 < lines.length && DIVIDER.test(lines[k + 1]) while (i < lines.length && lines[i].trim() && !/^(\s*(```|~~~)|#{1,6}\s|>|\s*([-*+]|\d+[.)])\s)/.test(lines[i]) && !tableAt(i)) para.push(lines[i++]) if (!para.length) para.push(lines[i++]) out.push(

    {inline(para.join('\n'))}

    ) } return out } /** * A panel the session brief asks for, its Markdown set apart so the person knows * it at a glance: an analysis (a fence of language `analysis`, before a question), * a proposal to take a wish to a new session (`new-session`, before asking * whether to), or what a finished branch changes once it lands (`impact`, before * "Shall it land?"). The `### Recommendation` part, or an impact's * `### Before it works`, sits apart at its foot. */ function panel(kind: 'analysis' | 'new-session' | 'impact', body: string[]): m.Children { const foot = kind === 'impact' ? /^#{1,6}\s+before it works/i : /^#{1,6}\s+recommend/i const at = body.findIndex((l) => foot.test(l)) const parts = at < 0 ? [body, []] : [body.slice(0, at), body.slice(at)] return (
    {kind === 'analysis' ? ( ) : kind === 'new-session' ? ( ) : ( )} {kind === 'analysis' ? 'Analysis' : kind === 'new-session' ? 'New session?' : 'Once it lands'}
    {markdown(parts[0].join('\n'))} {parts[1].length ?
    {markdown(parts[1].join('\n'))}
    : null}
    ) } /** A table's line under its head: `|---|:--:|`, the outer pipes optional. */ const DIVIDER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/ const isRow = (line: string) => line.trim().includes('|') && line.trim().length > 1 /** A table row's cells, trimmed: the outer pipes dropped, `\|` a pipe inside a cell. */ function cells(line: string): string[] { const t = line.trim().replace(/^\|/, '').replace(/(? c.trim().replace(/\\\|/g, '|')) } const INLINE = /(`+)([\s\S]+?)\1|\*\*([\s\S]+?)\*\*|__([\s\S]+?)__|\*([^*\s][^*]*?)\*|_([^_\s][^_]*?)_(?!\w)|\[([^\]]+)\]\(([^)\s]+)\)|(https?:\/\/[^\s<>)]+)/g /** One line's (or paragraph's) inline Markdown. */ export function inline(text: string): m.Children[] { const out: m.Children[] = [] let last = 0 for (const x of text.matchAll(INLINE)) { const at = x.index ?? 0 if (at > last) out.push(...sessions(text.slice(last, at))) last = at + x[0].length if (x[2] != null) { // Code that is a session's name alone (`session-s3`) links too. const id = sessionOf(x[2].trim()) out.push(id ? sessionLink(id, {x[2]}) : {x[2]}) } else if (x[3] != null || x[4] != null) out.push({inline(x[3] ?? x[4])}) else if (x[5] != null || x[6] != null) out.push({inline(x[5] ?? x[6])}) else if (x[7] != null) out.push(link(x[8], {inline(x[7])})) else if (x[9] != null) out.push(link(x[9], x[9])) } if (last < text.length) out.push(...sessions(text.slice(last))) return out } /** Whether `s3` is a session of this hub; none is until the page says which are (`linkSessions`). */ let isSession: (id: string) => boolean = () => false /** Name the hub's sessions, so the text that names one links to it. */ export function linkSessions(known: (id: string) => boolean) { isSession = known } /** A session's name as the text says it — `S123`, `s3`, `session-s3` — and only one of this hub's. */ const SESSION = /\b(?:session-)?[sS](\d+)\b/g /** The session a whole word names (`s3`, `S3`, `session-s3`), if it is one of this hub's. */ function sessionOf(word: string): string | null { const x = word.match(/^(?:session-)?[sS](\d+)$/) return x && isSession(`s${x[1]}`) ? `s${x[1]}` : null } const sessionLink = (id: string, label: m.Children) => ( {label} ) /** Plain text with each session it names linked; the rest stays text. */ export function sessions(text: string): m.Children[] { const out: m.Children[] = [] let last = 0 for (const x of text.matchAll(SESSION)) { const id = `s${x[1]}` if (!isSession(id)) continue const at = x.index ?? 0 if (at > last) out.push(text.slice(last, at)) out.push(sessionLink(id, x[0])) last = at + x[0].length } if (last < text.length) out.push(text.slice(last)) return out } function link(href: string, label: m.Children) { const own = href.match(/^\/sessions\/(s\d+)$/) if (own) return sessionLink(own[1], label) return /^https?:\/\//i.test(href) ? ( {label} ) : ( label ) }