import { createHash } from "node:crypto"; import { homedir } from "node:os"; import { basename, sep } from "node:path"; import { getLanguageFromPath } from "@earendil-works/pi-coding-agent"; import { Marked } from "@earendil-works/pi-tui"; import highlight from "highlight.js"; import type { Entry } from "./schema.ts"; import type { CatalogueRecord, WorkSnapshot } from "./store.ts"; import type { LinkRule } from "../links/contract.ts"; import { referenceParts, referenceTarget, type ReferenceContext } from "./references.ts"; import type { ViewedFile } from "./files.ts"; import type { Transcript } from "./transcript.ts"; const escape = (text: string) => text.replace( /[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!, ); const anchor = (id: string) => `entry-${id}`; const link = (id: string, label: string) => `${markdown(label, "link-title", { recordId: "" }, "title")}`; const recordLink = (id: string) => `/records/${encodeURIComponent(id)}`; const sessionLink = (session: string, record: string) => `/sessions/${encodeURIComponent(session)}?${new URLSearchParams({ record })}`; export const MERMAID_PATH = "/mermaid.js"; const permalink = (id: string) => ``; const home = homedir(); const tilde = (path: string) => path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path; const projectList = (projects: string[]) => `
Projects
`; const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; // Highlighting is synchronous and blocks Pi, so large files render as plain text. const MAX_HIGHLIGHT_CHARS = 200_000; const SCRIPT = String.raw` // The viewer cookie admits later requests, so the token need not stay in history. const opened = new URL(location.href); if (opened.searchParams.has('token')) { opened.searchParams.delete('token'); history.replaceState(history.state, '', opened); } const search = document.querySelector('#search'); if (search) { const statuses = [...document.querySelectorAll('input[name="status"]')]; const rows = [...document.querySelectorAll('[data-search]')]; const params = new URL(location.href).searchParams; const scopes = [...document.querySelectorAll('[data-param]')].map(list => { const scope = { param: list.dataset.param, values: new Set(params.getAll(list.dataset.param)) }; const input = document.getElementById(scope.param + '-input'); const open = input.form.querySelector('.add-filter'); function render() { list.replaceChildren(...[...scope.values].map(value => { const item = document.createElement('li'); const kind = document.createElement('span'); kind.textContent = scope.param; let label = value; const home = list.dataset.home; if (home && (value === home || value.startsWith(home + '/'))) { label = '~' + value.slice(home.length); } if (scope.param === 'session') { label = document.createElement('a'); label.href = '/sessions/' + encodeURIComponent(value); label.textContent = value; } const remove = document.createElement('button'); remove.type = 'button'; remove.textContent = '\u00d7'; remove.ariaLabel = 'Remove ' + value; remove.addEventListener('click', () => { scope.values.delete(value); render(); filter(); open.focus(); }); item.append(kind, label, remove); return item; })); } function close() { input.value = ''; input.hidden = true; open.hidden = false; } function add() { const value = input.value.trim(); if (value && !scope.values.has(value)) { scope.values.add(value); render(); filter(); } close(); open.focus(); } open.addEventListener('click', () => { open.hidden = true; input.hidden = false; input.focus(); }); input.addEventListener('blur', () => { if (!input.value.trim()) { close(); } }); input.addEventListener('keydown', event => { if (event.key === 'Escape') { close(); open.focus(); } }); input.addEventListener('input', event => { // Datalist choices arrive without typed-text input types. if (!event.inputType || event.inputType === 'insertReplacementText') { add(); } }); // Implicit form submission lets Enter choose an open datalist suggestion first. input.form.addEventListener('submit', event => { event.preventDefault(); add(); }); render(); return scope; }); function filter() { const terms = search.value.toLowerCase().trim().split(/\s+/).filter(Boolean); const selected = statuses.filter(box => box.checked).map(box => box.value); for (const row of rows) { row.hidden = !selected.includes(row.dataset.status) || scopes.some(scope => scope.values.size && !JSON.parse(row.dataset[scope.param]).some(value => scope.values.has(value))) || !terms.every(term => row.dataset.search.includes(term)); } document.querySelector('#no-matches').hidden = rows.some(row => !row.hidden); const url = new URL(location.href); for (const scope of scopes) { url.searchParams.delete(scope.param); for (const value of scope.values) { url.searchParams.append(scope.param, value); } } history.replaceState(history.state, '', url); } search.addEventListener('input', filter); for (const box of statuses) { box.addEventListener('change', filter); } filter(); } function anchorTarget() { try { return document.getElementById(decodeURIComponent(location.hash.slice(1))); } catch { return null; } } function reveal() { const target = anchorTarget(); if (!target) { return; } for (let node = target; node; node = node.parentElement) { if (node.tagName === 'DETAILS') { node.open = true; } } if (target.tabIndex < 0) { target.tabIndex = -1; } target.focus({ preventScroll: true }); target.scrollIntoView(); } addEventListener('hashchange', reveal); reveal(); if (window.mermaid) { mermaid.initialize({ startOnLoad: false, theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default', suppressErrorRendering: true, }); // Rendering without a container measures diagrams in closed details and keeps the source of a failed diagram. document.querySelectorAll('pre.mermaid').forEach(async (block, i) => { try { block.innerHTML = (await mermaid.render('mermaid-' + i, block.textContent)).svg; } catch { // The block shows its source text. } }); } const version = document.body.dataset.version; if (version) { const notice = document.querySelector('#updates'); const timer = setInterval(async () => { if (document.hidden) { return; } try { const response = await fetch(location.pathname, { method: 'HEAD', cache: 'no-store' }); if (!response.ok) { throw new Error(); } if (response.headers.get('etag') !== '"' + version + '"') { notice.hidden = false; notice.textContent = 'Updates available. Reload this page to read them.'; clearInterval(timer); } } catch { notice.hidden = false; notice.textContent = 'Viewer disconnected. Run /work in Pi to reopen it.'; clearInterval(timer); } }, 3000); } `; const STYLE = ` :root { color-scheme: light dark; --bg: #fafafa; --panel: #fff; --text: #252525; --muted: #606060; --line: #d6d6d6; --accent: #1559a6; } @media (prefers-color-scheme: dark) { :root { --bg: #171a20; --panel: #20242c; --text: #e7e9ed; --muted: #b1b7c2; --line: #424955; --accent: #91c5ff; } } * { box-sizing: border-box; } body { background: var(--bg); color: var(--text); font: 16px/1.65 system-ui, sans-serif; margin: auto; max-width: 1000px; padding: 24px; overflow-wrap: anywhere; } a { color: var(--accent); text-underline-offset: 3px; } h1, h2, h3, h4 { line-height: 1.3; } h1 { margin-bottom: 8px; } h2 { font-size: 1.25rem; } h3 { font-size: 1.1rem; } .meta, dt { color: var(--muted); font-size: .9rem; } nav, article, details.section, details.entry { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; margin: 18px 0; padding: 16px 20px; } nav ul { margin: 4px 0; } summary { cursor: pointer; } summary h2, summary h3, summary h4 { display: inline; } summary h3, summary h4 { font-size: 1.1rem; } article { border-radius: 4px; } details.entry:target, article.message:target, article.message:has(span:target), .event:target, .event:has(> span:target) { outline: 2px solid var(--accent); } details.events { margin: -8px 0 0; padding: 0 20px; } details.events > summary { color: var(--muted); font-size: .9rem; } .event { padding: 4px 0; } .event .tools { margin: 0; } .message.user { border-left: 4px solid var(--accent); } .message img { display: block; max-width: 100%; } .tools { margin: 8px 0 0; padding-left: 20px; } .filters { display: grid; gap: 12px; } .filters label { display: inline-flex; align-items: center; gap: 6px; } .filters fieldset { border: 0; padding: 0; margin: 0; min-width: 0; } .scopes { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; } .scopes form { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .scopes input[type=text] { width: min(28rem, 80vw); padding: 6px 10px; } .add-filter { font: inherit; font-size: .9rem; color: var(--accent); background: none; border: 1px dashed var(--line); border-radius: 5px; padding: 4px 10px; cursor: pointer; } .tokens { list-style: none; display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; } .tokens:empty { display: none; } .tokens li { display: inline-flex; align-items: center; border: 1px solid var(--line); border-radius: 5px; padding: 0.5em; font: .85rem ui-monospace, monospace; } .tokens li span { color: var(--muted); margin-right: 6px; } .tokens button { border: 0; background: none; color: inherit; cursor: pointer; font: inherit; padding: 0 8px; } .filters legend { color: var(--muted); font-size: .9rem; margin-bottom: 4px; } .checks { display: flex; flex-wrap: wrap; gap: 8px 16px; } input[type=checkbox] { accent-color: var(--accent); } .badge { display: inline-block; font-size: .8rem; border: 1px solid var(--line); border-radius: 5px; padding: 0 7px; margin-right: 6px; } .provenance { margin-top: 16px; } .projects { margin: 2px 0 8px; padding-left: 20px; } dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 4px 16px; } dd { margin: 0; } pre { overflow-x: auto; background: var(--bg); padding: 16px; border: 1px solid var(--line); border-radius: 4px; } code { font: .9em ui-monospace, monospace; } blockquote { border-left: 3px solid var(--line); margin-left: 0; padding-left: 16px; color: var(--muted); } table { border-collapse: collapse; display: block; overflow-x: auto; } th, td { border: 1px solid var(--line); padding: 6px 12px; text-align: left; } input[type=search], input[type=text] { width: 100%; font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 10px 14px; } #updates { border-left: 3px solid var(--accent); padding: 8px 16px; } .permalink { margin-left: 8px; font-size: .85em; } .file-source { display: grid; grid-template-columns: max-content minmax(0, 1fr); } .file-source pre { margin: 0; border-radius: 0; font: .9em/1.6 ui-monospace, monospace; } .file-source code { font: inherit; } .line-numbers { text-align: right; } .line-numbers a { color: var(--muted); text-decoration: none; } .line-numbers a:target { color: var(--accent); outline: 2px solid var(--accent); } .hljs-keyword, .hljs-selector-tag, .hljs-literal { color: #b13cc5; } .hljs-string, .hljs-regexp, .hljs-attr { color: #2b8651; } .hljs-number, .hljs-built_in, .hljs-type { color: #a96013; } .hljs-title, .hljs-function { color: var(--accent); } .hljs-comment { color: var(--muted); } @media (prefers-color-scheme: dark) { .hljs-keyword, .hljs-selector-tag, .hljs-literal { color: #dfa3f0; } .hljs-string, .hljs-regexp, .hljs-attr { color: #99d6a0; } .hljs-number, .hljs-built_in, .hljs-type { color: #edbe86; } } @media (max-width: 600px) { body { padding: 12px; } nav, article, details.section, details.entry { padding: 12px; } dl { grid-template-columns: 1fr; } } `; export const CONTENT_POLICY = `default-src 'none'; style-src 'unsafe-inline'; script-src 'self' 'sha256-${createHash("sha256").update(SCRIPT).digest("base64")}'; connect-src 'self'; img-src data:; base-uri 'none'; frame-ancestors 'none'; form-action 'none'`; function page(title: string, body: string, version = ""): string { return `${escape(title)}
All work records

${markdown(title, "page-title", { recordId: "" }, "title")}${permalink("top")}

${body}
${body.includes('
') ? `` : ""}`;
}

function codeHtml(text: string, language?: string): string {
    if (language && highlight.getLanguage(language)) {
        try {
            return highlight.highlight(text, { language, ignoreIllegals: true }).value;
        } catch {
            // A grammar failure must not hide the source.
        }
    }
    return escape(text);
}

function htmlLink(href: string, label: string): string {
    return `${label}`;
}

function markdown(
    source: string,
    prefix: string,
    context: ReferenceContext,
    mode: "block" | "inline" | "title" = "block",
    headingOffset = 3,
): string {
    let heading = 0;
    let inLink = mode === "title";
    const marked = new Marked();
    const plain = new marked.Renderer();
    marked.use({
        renderer: {
            html({ text }) {
                return escape(text);
            },
            image({ text }) {
                return escape(text);
            },
            text(token) {
                if (inLink || token.type !== "text" || token.tokens || token.escaped) {
                    return false;
                }
                const parts = referenceParts(token.text, context);
                if (!parts.some((part) => part.href)) {
                    return false;
                }
                return parts
                    .map((part) => {
                        const label = plain.text({ type: "text", raw: part.text, text: part.text });
                        return part.href ? htmlLink(part.href, label) : label;
                    })
                    .join("");
            },
            codespan({ text }) {
                const href = inLink ? undefined : referenceTarget(text, context);
                return href ? `${htmlLink(href, escape(text))}` : false;
            },
            link({ href, tokens }) {
                const previous = inLink;
                let label: string;
                inLink = true;
                try {
                    label = this.parser.parseInline(tokens);
                } finally {
                    inLink = previous;
                }
                if (mode === "title") {
                    return label;
                }
                if (href.startsWith("#")) {
                    return htmlLink(href, label);
                }
                try {
                    const url = new URL(href);
                    return ["http:", "https:", "mailto:"].includes(url.protocol)
                        ? htmlLink(url.href, label)
                        : label;
                } catch {
                    const target = referenceTarget(href, context);
                    return target ? htmlLink(target, label) : label;
                }
            },
            heading({ tokens, depth }) {
                const level = Math.min(6, depth + headingOffset);
                const id = `${prefix}-heading-${heading++}`;
                return `${this.parser.parseInline(tokens)}${permalink(id)}`;
            },
            code({ text, lang }) {
                const language = lang?.split(/\s+/)[0];
                if (language === "mermaid") {
                    return `
${escape(text)}
`; } return `
${codeHtml(text, language)}
`; }, }, }); return mode === "block" ? marked.parse(source, { async: false }) : marked.parseInline(source, { async: false }); } function provenance(entry: Entry, recordId: string): string { const session = sessionLink(entry.author.session, recordId); const code = (value: string, href?: string) => href ? `${escape(value)}` : `${escape(value)}`; const message = (id?: string) => id && code(id, `${session}#${anchor(id)}`); const fields = [ ["Session", code(entry.author.session, session)], ["Message", message(entry.author.entry)], ["Model", entry.author.model && code(entry.author.model)], [ "User message", entry.content.kind === "decision" ? message(entry.content.user_entry) : undefined, ], ]; return `
Provenance
${fields .filter(([, value]) => value) .map(([name, value]) => `
${escape(name!)}
${value}
`) .join("")}
`; } function section(id: string, title: string, body: string, count?: number): string { return `

${escape(title)}${count === undefined ? "" : ` (${count})`}${permalink(id)}

${body}
`; } // Maps each task ID to its subtasks in creation order. function subtaskMap(entries: Entry[]): Map { const tasks = new Set( entries.filter((entry) => entry.content.kind === "task").map((entry) => entry.id), ); const subtasks = new Map(); for (const entry of entries) { const parent = entry.content.kind === "task" ? entry.content.parent : undefined; if (parent && tasks.has(parent)) { subtasks.set(parent, [...(subtasks.get(parent) ?? []), entry]); } } for (const children of subtasks.values()) { children.sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1))); } return subtasks; } function renderEntry(entry: Entry, context: ReferenceContext, subtasks: Entry[] = []): string { const item = entry.content; if (item.kind === "brief") { return ""; } const id = anchor(entry.id); const sources = item.kind === "task" ? item.evidence : item.sources; const supersedes = item.kind === "task" ? undefined : item.supersedes; const level = item.kind === "decision" ? 3 : 4; return `
${escape(entry.id)}: ${markdown(item.title, `${id}-title`, context, "inline")}${permalink(id)}

${escape(item.kind === "decision" ? "decision" : item.status)}${entry.superseded_by ? `Superseded by ${link(anchor(entry.superseded_by), entry.superseded_by)}` : ""}

${escape(entry.id)} · revision ${entry.revision} · ${escape(entry.updated)}

${supersedes ? `

Supersedes ${link(anchor(supersedes), supersedes)}

` : ""} ${item.kind === "task" && item.blocked_on ? `

Blocked on: ${markdown(item.blocked_on, `${id}-blocked-on`, context, "inline")}

` : ""} ${item.kind === "task" && item.owner ? `

Owner: ${escape(item.owner)}

` : ""} ${markdown(item.body ?? "", id, context, "block", level)} ${sources?.length ? `${item.kind === "task" ? "Evidence" : "Sources"}${permalink(`${id}-sources`)}
    ${sources.map((source, i) => `
  • ${markdown(source, `${id}-source-${i}`, context, "block", level + 1)}
  • `).join("")}
` : ""} ${subtasks.map((subtask) => renderEntry(subtask, context)).join("")} ${provenance(entry, context.recordId)}
`; } export function renderCatalogue( records: CatalogueRecord[], matchers: LinkRule[] = [], version = "", ): string { const sessions = new Map(); const projects = new Map(); // Records arrive newest first, so suggestions and their labels start with recent work. for (const record of records) { for (const [values, keys] of [ [sessions, record.sessions.toReversed()], [projects, record.projects], ] as const) { for (const key of keys) { const titles = values.get(key); if (titles) { titles.push(record.title); } else { values.set(key, [record.title]); } } } } const scope = (param: string, placeholder: string, values: Map) => `
    ${[ ...values, ] .map( ([value, titles]) => ``, ) .join("")}
    `; const rows = records .map( (record) => ``, ) .join(""); return page( "Work records", `
    ${scope("session", "Session ID", sessions)}${scope("project", "Project path", projects)}
    Status
    ${(["active", "blocked", "complete", "archived"] as const).map((status) => ``).join("")}

    ${records.length} records

    ${rows}

    No matching records. Check more statuses or remove session and project filters.

    `, version, ); } export function groupRecordEntries(allEntries: Entry[]) { const subtasks = new Set([...subtaskMap(allEntries).values()].flat()); return ( [ ["tasks", "Tasks", "task"], ["findings", "Findings", "finding"], ["decisions", "Decisions", "decision"], ] as const ).map(([id, title, kind]) => { const entries = allEntries.filter((entry) => entry.content.kind === kind); const current = entries.filter((entry) => !entry.superseded_by && !subtasks.has(entry)); const states = kind === "task" ? ["pending", "active", "blocked", "done", "cancelled"] : kind === "finding" ? ["confirmed", "hypothesis", "refuted"] : ["current"]; const groups = states .map((state) => ({ id: `${id}-${state}`, title: state === "current" ? "" : state.charAt(0).toUpperCase() + state.slice(1), entries: current.filter( (entry) => entry.content.kind === "decision" || ((entry.content.kind === "task" || entry.content.kind === "finding") && entry.content.status === state), ), collapsed: false, })) .filter((group) => group.entries.length); const superseded = entries.filter((entry) => entry.superseded_by); if (superseded.length) { groups.push({ id: `${id}-superseded`, title: "Superseded", entries: superseded, collapsed: true, }); } return { id, title, entries, groups }; }); } export function renderRecord(snapshot: WorkSnapshot, matchers: LinkRule[] = []): string { const context = { matchers, recordId: snapshot.id }; const briefEntry = snapshot.entries.find((entry) => entry.id === "brief"); if (briefEntry?.content.kind !== "brief") { throw new Error("Invalid work report brief"); } const brief = briefEntry.content; const sections = groupRecordEntries(snapshot.entries); const subtasks = subtaskMap(snapshot.entries); const contentsItem = (entry: Entry): string => `
  • ${link(anchor(entry.id), `${entry.id}: ${entry.content.title}${entry.superseded_by ? " (superseded)" : ""}`)}${subtasks.has(entry.id) ? `
      ${subtasks.get(entry.id)?.map(contentsItem).join("")}
    ` : ""}
  • `; const contents = ``; const sessions = new Map(); for (const entry of snapshot.entries.toReversed()) { if (!sessions.has(entry.author.session)) { sessions.set(entry.author.session, entry.updated); } } const sessionList = `
    Session transcripts
      ${[...sessions] .map( ([session, updated]) => `
    • ${escape(session)} · ${escape(updated)}
    • `, ) .join("")}
    `; const summary = `

    ${escape(brief.status)}Snapshot revision ${snapshot.revision}

    ${escape(snapshot.id)}

    ${projectList(brief.projects)}${sessionList}`; const fields = [ ["objective", "Objective"], ["scope", "Scope"], ["constraints", "Constraints"], ["approach", "Approach"], ] as const; const overview = fields .filter(([key]) => brief[key]) .map( ([key, title]) => `

    ${title}${permalink(`brief-${key}`)}

    ${markdown(brief[key] ?? "", `brief-${key}`, context)}`, ) .join(""); const related = brief.related?.length ? `
      ${brief.related.map((value, i) => `
    • ${uuid.test(value) ? `${escape(value)}` : markdown(value, `related-${i}`, context, "inline")}
    • `).join("")}
    ` : ""; const body = sections .map(({ id, title, entries, groups }) => section( id, title, groups .map((group) => { const body = group.entries .map((entry) => renderEntry(entry, context, subtasks.get(entry.id))) .join(""); if (!group.title) { return body; } const heading = `

    ${escape(group.title)} (${group.entries.length})${permalink(group.id)}

    `; return group.collapsed ? `
    ${heading}${body}
    ` : `
    ${heading}${body}
    `; }) .join("") || "

    No entries.

    ", entries.length, ), ) .join(""); return page( brief.title, `${summary}${contents}${section("brief", "Brief", `

    Revision ${briefEntry.revision} · ${escape(briefEntry.updated)}

    ` + overview + related + provenance(briefEntry, snapshot.id))}${body}`, String(snapshot.revision), ); } export function renderFile(file: ViewedFile, recordId: string): string { const numbers = file.text .split("\n") .map((_, i) => `${i + 1}`) .join("\n"); return page( basename(file.path), `

    Back to work record

    Current file contents

    ${escape(file.path)}

    ${numbers}
    ${codeHtml(file.text, file.text.length > MAX_HIGHLIGHT_CHARS ? undefined : getLanguageFromPath(file.path))}
    `, ); } export function renderTranscript( transcript: Transcript, matchers: LinkRule[], recordId: string, ): string { const context = { matchers, recordId }; const anchors = (ids: string[]) => ids.map((id) => ``).join(""); const items: string[] = []; let events: string[] = []; let calls = 0; let others = 0; const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; const flush = () => { if (events.length) { const label = [ calls ? `Made ${plural(calls, "tool call")}` : "", others ? plural(others, calls ? "other event" : "event") : "", ]; items.push( `
    ${label.filter(Boolean).join(" and ")}${events.join("")}
    `, ); } events = []; calls = 0; others = 0; }; for (const item of transcript.items) { const id = anchor(item.id); const text = `${item.text ? markdown(item.text, id, context) : ""}${(item.images ?? []).map((src) => ``).join("")}`; const tools = item.tools.length ? `
      ${item.tools.map((tool) => `
    • ${escape(tool)}
    • `).join("")}
    ` : ""; const message = item.kind === "user" || (item.kind === "assistant" && item.text.trim() !== "") || Boolean(item.images?.length); if (message || item.branch) { flush(); } if (item.branch) { items.push(`

    Branch from ${link(anchor(item.branch), item.branch)}

    `); } const meta = `

    ${escape(item.label)} · ${escape(item.timestamp)}${permalink(id)}

    `; if (item.kind === "assistant") { calls += item.tools.length; } else if (!message) { others += 1; } if (message) { items.push( `
    ${meta}${text}${anchors(item.anchors)}
    `, ); if (tools) { events.push(tools); } continue; } events.push( `
    ${meta}${item.kind === "summary" ? `
    Show summary${text}
    ` : text}${tools}${anchors(item.anchors)}
    `, ); } flush(); return page( transcript.name ?? "Session transcript", `${recordId ? `

    Back to work record

    ` : ""}

    ${escape(transcript.id)}${transcript.cwd ? ` · ${escape(tilde(transcript.cwd))}` : ""}

    ${anchors(transcript.anchors)}${items.join("") || "

    No messages.

    "}`, ); } export function renderError(message: string): string { return page("Work viewer", `

    ${escape(message)}

    `); }