Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(research): export reports as PDF and Word, and show site icons in sources
Salman Qureshi12dee583734b
diff --git a/DECISIONS.md b/DECISIONS.mdindex 41181db3..14f0c9e0 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -337,4 +337,5 @@- **Cut short is still a report**: "write the report now", the step budget, every provider failing, and an empty answer all write the report from the page excerpts (default model, then the others), with "Coverage & gaps": why it stopped, plan questions not marked done, sources that failed and why, searches that found nothing. Stop (plain) ends the run as `stopped`. `/research continue` and `/research retry` start a new run in the same chat that builds on the last one.- **Tool results pair by call id**: parallel calls' results don't always come back in call order; pairing by position showed a search's results on a `fetch_url` row. `resultFor()` matches `toolCallId`, and every step handler uses it.- **Desktop**: a research bar above the composer (on for the next message, or the live phase · questions done · read · failed · searches · time · step N/225, with Details and "Write report now"); Details is Sources (read / cited / failed + reason, filterable) and Activity (questions, searches); the plan card to edit and Start; a report card under the answer (Open report, Copy, Sources & activity, Continue research / Go deeper, Retry N failed); a Research toggle in the composer (normal, deep research, plan first); a research notification ("Research ready: … · 41 sources read · 23 cited") instead of the plain "Done".-- **Consequence**: The owner can see what research is doing, why sources failed, and always gets what was gathered. Not here: steering a run mid-way with new instructions (a follow-up waits in the queue), resuming a run after a restart (runs live in memory; the report file and the thread's metadata persist), export to PDF/DOCX (the artifact viewer saves the `.md`), and favicons (no third-party image requests from the app).+- **Consequence**: The owner can see what research is doing, why sources failed, and always gets what was gathered. Not here: steering a run mid-way with new instructions (a follow-up waits in the queue), resuming a run after a restart (runs live in memory; the report file and the thread's metadata persist).+ - **Export and site icons (follow-up)**: any Markdown or text artifact can be saved as a PDF or a Word document (`GET /api/artifacts/:id/file?as=pdf|docx`, `POST …/export { dest, as }`; flag `artifacts.convert`), from the report card's Export menu and the artifact viewer's "Export as". Both are written by the runtime with no library or browser (`src/artifacts/convert/`: Markdown → blocks via `marked`, a small zip writer for the `.docx`, a PDF writer on the PDF core fonts with real glyph widths, page numbers and clickable links). The PDF's core fonts cover Western European text (other scripts show as "?"; the Word file keeps every character). Site icons in the source list come from `GET /api/chat/favicon?domain=` (flag `chat.favicon`): the runtime fetches the site's `/favicon.ico` through the SSRF guard, then DuckDuckGo's icon service, keeps only real images (≤ 100 KB), and caches them in `~/.mercury/cache/favicons` (30 days; "no icon" 7 days). The app still loads nothing from third parties.diff --git a/apps/desktop/src/api/artifacts.ts b/apps/desktop/src/api/artifacts.tsindex f43e3b18..1722d9d4 100644--- a/apps/desktop/src/api/artifacts.ts+++ b/apps/desktop/src/api/artifacts.ts@@ -37,7 +37,8 @@ export const artifactsApi = {get: (id: string) => http.get<{ artifact: ArtifactItem }>(`/api/artifacts/${encodeURIComponent(id)}`).then((r) => r.artifact),remove: (id: string) => http.delete<{ ok: boolean }>(`/api/artifacts/${encodeURIComponent(id)}`),/** Save a copy to a folder on the computer Mercury runs on. */- exportTo: (id: string, dest: string) => http.post<{ ok: boolean; path: string }>(`/api/artifacts/${encodeURIComponent(id)}/export`, { dest }),+ /** Save a copy on this computer; `as` makes a Markdown/text artifact a PDF or Word document. */+ exportTo: (id: string, dest: string, as?: "pdf" | "docx") => http.post<{ ok: boolean; path: string }>(`/api/artifacts/${encodeURIComponent(id)}/export`, { dest, ...(as ? { as } : {}) }),};/**@@ -76,3 +77,70 @@ export function formatBytes(n: number): string {}export const KIND_LABEL: Record<ArtifactKind, string> = { image: "Image", video: "Video", audio: "Audio", pdf: "PDF", document: "Document", text: "Notes", file: "File" };++/** Markdown and text can also be saved as a PDF or a Word document. */+export function canExportAsDocument(a: { name: string; mime: string }): boolean {+ return /^text\/(markdown|plain)$/.test(a.mime) || /\.(md|markdown|txt)$/i.test(a.name);+}++export type ExportFormat = "original" | "pdf" | "docx";++const FORMAT_LABEL: Record<Exclude<ExportFormat, "original">, string> = { pdf: "PDF", docx: "Word document" };++export function exportName(name: string, format: ExportFormat): string {+ return format === "original" ? name : `${name.replace(/\.(md|markdown|txt)$/i, "")}.${format}`;+}++/**+ * Save an artifact as itself, a PDF or a Word document: a Save dialog when+ * Mercury runs on this computer (the runtime writes the file), a download+ * otherwise. Resolves where it went ("" for a download), or null when the+ * dialog was cancelled.+ */+export async function exportArtifact(a: { id: string; name: string }, format: ExportFormat, local: boolean, tauri: boolean): Promise<string | null> {+ const as = format === "original" ? undefined : format;+ const name = exportName(a.name, format);+ if (tauri && local) {+ const { save } = await import("@tauri-apps/plugin-dialog");+ const ext = name.split(".").pop() ?? "";+ const dest = await save({ defaultPath: name, title: `Save ${as ? FORMAT_LABEL[as] : name}`, filters: ext ? [{ name: as ? FORMAT_LABEL[as] : ext.toUpperCase(), extensions: [ext] }] : undefined });+ if (!dest) return null;+ await artifactsApi.exportTo(a.id, dest, as);+ return dest;+ }+ const r = await fetch(apiUrl(`/api/artifacts/${encodeURIComponent(a.id)}/file${as ? `?as=${as}` : "?download=1"}`), { headers: authHeaders() });+ if (!r.ok) {+ let message = `Couldn't make the file (${r.status})`;+ try { message = ((await r.json()) as { error?: string }).error ?? message; } catch { /* not JSON */ }+ throw new Error(message);+ }+ const url = URL.createObjectURL(await r.blob());+ const link = document.createElement("a");+ link.href = url;+ link.download = name;+ link.click();+ setTimeout(() => URL.revokeObjectURL(url), 30_000);+ return "";+}++/**+ * A site's icon as a blob URL, through the runtime (GET /api/chat/favicon):+ * the app itself never loads anything from a third party. null = no icon.+ */+const icons = new Map<string, Promise<string | null>>();+export function faviconUrl(domain: string): Promise<string | null> {+ const key = domain.toLowerCase();+ let hit = icons.get(key);+ if (!hit) {+ hit = fetch(apiUrl(`/api/chat/favicon?domain=${encodeURIComponent(key)}`), { headers: authHeaders() })+ .then(async (r) => (r.status === 200 ? URL.createObjectURL(await r.blob()) : null))+ .catch(() => null);+ icons.set(key, hit);+ if (icons.size > 300) {+ const [oldest, url] = icons.entries().next().value as [string, Promise<string | null>];+ icons.delete(oldest);+ void url.then((u) => { if (u) URL.revokeObjectURL(u); });+ }+ }+ return hit;+}diff --git a/apps/desktop/src/components/artifacts/ArtifactViewer.tsx b/apps/desktop/src/components/artifacts/ArtifactViewer.tsxindex 82768f83..78c4090b 100644--- a/apps/desktop/src/components/artifacts/ArtifactViewer.tsx+++ b/apps/desktop/src/components/artifacts/ArtifactViewer.tsx@@ -1,6 +1,7 @@-import { Copy, Download, FileText, FolderOpen, MessageSquareText, Trash2 } from "lucide-react";+import { ChevronDown, Copy, Download, FileText, FolderOpen, MessageSquareText, Trash2 } from "lucide-react";import { useEffect, useState } from "react";-import { artifactBlobUrl, artifactText, artifactsApi, formatBytes, KIND_LABEL, type ArtifactItem, type ArtifactKind } from "~/api/artifacts";+import { artifactBlobUrl, artifactText, artifactsApi, canExportAsDocument, exportArtifact, formatBytes, KIND_LABEL, type ArtifactItem, type ArtifactKind, type ExportFormat } from "~/api/artifacts";+import { Menu, MenuItem } from "~/components/ui/Menu";import { Markdown } from "~/components/Markdown";import { Button } from "~/components/ui/Button";import { Badge, Spinner } from "~/components/ui/bits";@@ -36,24 +37,23 @@ export function ArtifactViewer({ id, onOpenThread, onDeleted }: { id: string; onreturn () => { live = false; };}, [id]);- async function saveAs() {+ async function saveAs(format: ExportFormat = "original") {if (!a) return;setNote(null);try {- if (isTauri && local) {- const { save } = await import("@tauri-apps/plugin-dialog");- const dest = await save({ defaultPath: a.name, title: `Save ${a.name}` });- if (!dest) return;- await artifactsApi.exportTo(a.id, dest);- setNote({ text: `Saved to ${dest}`, ok: true });- } else {+ if (format === "original" && !(isTauri && local)) {const url = await artifactBlobUrl(a.id);if (!url) throw new Error("Couldn't load the file.");const link = document.createElement("a");link.href = url;link.download = a.name;link.click();+ return;}+ if (format !== "original") setNote({ text: `Making the ${format === "pdf" ? "PDF" : "Word document"}…`, ok: true });+ const dest = await exportArtifact(a, format, !!local, isTauri);+ if (dest === null) { setNote(null); return; }+ setNote({ text: dest ? `Saved to ${dest}` : "Downloaded.", ok: true });} catch (e) { setNote({ text: errorText(e), ok: false }); }}@@ -81,6 +81,12 @@ export function ArtifactViewer({ id, onOpenThread, onDeleted }: { id: string; on<div className="flex flex-wrap items-center gap-1.5 border-b border-line px-5 py-2"><Button size="sm" variant="primary" onClick={() => void saveAs()}><Download size={13} /> {isTauri && local ? "Save as…" : "Download"}</Button>+ {canExportAsDocument(a) && (+ <Menu trigger={<Button size="sm" variant="secondary" aria-label="Export as"><FileText size={13} /> Export as <ChevronDown size={12} /></Button>}>+ <MenuItem onSelect={() => void saveAs("pdf")} hint="links stay clickable">PDF</MenuItem>+ <MenuItem onSelect={() => void saveAs("docx")} hint="opens in Word, Pages, Google Docs">Word (.docx)</MenuItem>+ </Menu>+ )}{isTauri && local && a.originalExists && <Button size="sm" variant="ghost" onClick={() => void reveal()}><FolderOpen size={13} /> Show in Finder</Button>}<Button size="sm" variant="ghost" onClick={() => { void navigator.clipboard.writeText(a.originalPath); setNote({ text: "Path copied.", ok: true }); }}><Copy size={13} /> Copy path</Button>{onOpenThread && a.threadExists && <Button size="sm" variant="ghost" onClick={() => onOpenThread(a.threadId)}><MessageSquareText size={13} /> Open conversation</Button>}diff --git a/apps/desktop/src/views/chat/Research.tsx b/apps/desktop/src/views/chat/Research.tsxindex 44c1362f..caf7931a 100644--- a/apps/desktop/src/views/chat/Research.tsx+++ b/apps/desktop/src/views/chat/Research.tsx@@ -1,5 +1,9 @@-import { AlertTriangle, BookOpen, Check, ChevronRight, CircleSlash, Copy, FileText, Globe, ListChecks, Plus, RotateCw, Search, Telescope, Trash2, X } from "lucide-react";+import { AlertTriangle, BookOpen, Check, ChevronDown, ChevronRight, CircleSlash, Copy, Download, FileText, Globe, ListChecks, Plus, RotateCw, Search, Telescope, Trash2, X } from "lucide-react";import { useEffect, useState } from "react";+import { exportArtifact, faviconUrl, type ExportFormat } from "~/api/artifacts";+import { Menu, MenuItem } from "~/components/ui/Menu";+import { useConnections } from "~/shell/connections";+import { isTauri } from "~/shell/tauri";import * as api from "~/api/mercury";import type { ResearchSnapshot, ResearchSource } from "~/api/types";import { useConversation, useConversationStore } from "~/app/conversation";@@ -219,7 +223,20 @@ export function ResearchReport({ run, content }: { run: ResearchSnapshot; contenconst [details, setDetails] = useState(false);const [reportOpen, setReportOpen] = useState(false);const [copied, setCopied] = useState(false);+ const [exported, setExported] = useState<{ text: string; ok: boolean } | null>(null);+ const local = useConnections((s) => s.connections.find((c) => c.id === s.activeId)?.kind === "local");const { title, tone } = outcomeLine(run);++ async function exportAs(format: ExportFormat) {+ if (!run.report) return;+ setExported({ text: format === "original" ? "Saving…" : `Making the ${format === "pdf" ? "PDF" : "Word document"}…`, ok: true });+ try {+ const dest = await exportArtifact(run.report, format, !!local, isTauri);+ setExported(dest === null ? null : { text: dest ? `Saved to ${dest}` : "Downloaded.", ok: true });+ } catch (e) {+ setExported({ text: e instanceof Error ? e.message : String(e), ok: false });+ }+ }const took = run.endedAt ? elapsed(run.endedAt - run.startedAt) : null;const shortOf = run.state !== "done";@@ -242,6 +259,13 @@ export function ResearchReport({ run, content }: { run: ResearchSnapshot; conten</div><div className="flex flex-wrap items-center gap-1.5 pl-[25px]">{run.report && <Button size="sm" variant="secondary" onClick={() => setReportOpen(true)}><FileText size={13} /> Open report</Button>}+ {run.report && (+ <Menu trigger={<Button size="sm" variant="ghost" aria-label="Export the report"><Download size={13} /> Export <ChevronDown size={12} /></Button>}>+ <MenuItem onSelect={() => void exportAs("pdf")} hint="links stay clickable">PDF</MenuItem>+ <MenuItem onSelect={() => void exportAs("docx")} hint="Word, Pages, Google Docs">Word (.docx)</MenuItem>+ <MenuItem onSelect={() => void exportAs("original")} hint="with every source">Markdown (.md)</MenuItem>+ </Menu>+ )}{content.trim() && (<Button size="sm" variant="ghost" onClick={() => { void navigator.clipboard.writeText(content).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }); }}>{copied ? <Check size={13} /> : <Copy size={13} />} {copied ? "Copied" : "Copy"}@@ -257,6 +281,7 @@ export function ResearchReport({ run, content }: { run: ResearchSnapshot; conten</>)}</div>+ {exported && <p className={cx("pl-[25px] text-xs", exported.ok ? "text-ink3" : "text-red")} data-selectable>{exported.text}</p>}<ResearchDetails run={run} open={details} onOpenChange={setDetails} />{run.report && (<Dialog open={reportOpen} onOpenChange={setReportOpen} title="Research report" width={900}>@@ -330,13 +355,30 @@ export function ResearchDetails({ run, open, onOpenChange }: { run: ResearchSnap);}+/** A site's icon (fetched by the runtime), or its first letters while there's none. */+export function SiteIcon({ domain, failed, cited }: { domain: string; failed?: boolean; cited?: boolean }) {+ const [url, setUrl] = useState<string | null>(null);+ useEffect(() => {+ let live = true;+ setUrl(null);+ void faviconUrl(domain).then((u) => { if (live) setUrl(u); });+ return () => { live = false; };+ }, [domain]);+ return (+ <span className="relative mt-0.5 flex h-6 w-6 shrink-0" aria-hidden="true">+ {url+ ? <img src={url} alt="" className={cx("h-6 w-6 rounded-md bg-white object-contain p-0.5 ring-1 ring-line", failed && "opacity-50 grayscale")} draggable={false} />+ : <span className={cx("flex h-6 w-6 items-center justify-center rounded-md font-mono text-2xs uppercase", failed ? "bg-red/10 text-red" : cited ? "bg-accent/15 text-accent" : "bg-ink/[0.06] text-ink3")}>{domain.slice(0, 2)}</span>}+ {failed && <span className="absolute -bottom-1 -right-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-red text-white ring-2 ring-surface"><X size={9} strokeWidth={3} /></span>}+ {cited && !failed && <span className="absolute -bottom-1 -right-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-accent text-on-accent ring-2 ring-surface"><Check size={9} strokeWidth={3} /></span>}+ </span>+ );+}+function SourceRow({ source: s }: { source: ResearchSource }) {return (<li className="flex items-start gap-3 px-3 py-2">- <span className={cx("mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-md font-mono text-2xs uppercase",- s.status === "failed" ? "bg-red/10 text-red" : s.cited ? "bg-accent/15 text-accent" : "bg-ink/[0.06] text-ink3")} aria-hidden="true">- {s.status === "failed" ? <X size={12} /> : s.domain.slice(0, 2)}- </span>+ <SiteIcon domain={s.domain} failed={s.status === "failed"} cited={s.cited} /><span className="min-w-0 flex-1"><a href={s.url} target="_blank" rel="noreferrer" className="block truncate text-sm text-ink hover:underline" title={s.url}>{s.title || s.domain}</a><span className="block truncate text-xs text-ink4">{s.domain}</span>diff --git a/src/artifacts/convert/blocks.ts b/src/artifacts/convert/blocks.tsnew file mode 100644index 00000000..7d269246--- /dev/null+++ b/src/artifacts/convert/blocks.ts@@ -0,0 +1,112 @@+import { Marked, type Token, type Tokens } from 'marked';++/**+ * Markdown as a few plain blocks, the shape both document writers (Word and+ * PDF) lay out: headings, paragraphs, list items (with depth and number),+ * quotes, code, rules, tables. Inline text is runs with bold / italic / code+ * and a link target. Images become a linked "[Image: alt]" line: the+ * writers don't fetch from the web.+ */++export interface Run {+ text: string;+ bold?: boolean;+ italic?: boolean;+ code?: boolean;+ href?: string;+}++export type Block =+ | { type: 'heading'; level: number; runs: Run[] }+ | { type: 'para'; runs: Run[] }+ | { type: 'item'; depth: number; marker: string; runs: Run[] }+ | { type: 'quote'; runs: Run[] }+ | { type: 'code'; text: string }+ | { type: 'rule' }+ | { type: 'table'; header: Run[][]; rows: Run[][][] };++const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", apos: "'", nbsp: ' ' };+const decode = (s: string): string => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (_, e: string) => ENTITIES[e] ?? _);++type Style = Omit<Run, 'text'>;++function inline(tokens: Token[] | undefined, style: Style = {}): Run[] {+ const out: Run[] = [];+ for (const t of tokens ?? []) {+ switch (t.type) {+ case 'strong': out.push(...inline((t as Tokens.Strong).tokens, { ...style, bold: true })); break;+ case 'em': out.push(...inline((t as Tokens.Em).tokens, { ...style, italic: true })); break;+ case 'del': out.push(...inline((t as Tokens.Del).tokens, style)); break;+ case 'codespan': out.push({ ...style, code: true, text: decode((t as Tokens.Codespan).text) }); break;+ case 'link': {+ const l = t as Tokens.Link;+ const runs = inline(l.tokens, { ...style, href: l.href });+ out.push(...(runs.length ? runs : [{ ...style, href: l.href, text: l.href }]));+ break;+ }+ case 'image': {+ const i = t as Tokens.Image;+ out.push({ ...style, italic: true, href: i.href, text: `[Image: ${decode(i.text || 'image')}]` });+ break;+ }+ case 'br': out.push({ ...style, text: '\n' }); break;+ case 'html': break;+ case 'text': {+ const x = t as Tokens.Text;+ if (x.tokens?.length) out.push(...inline(x.tokens, style));+ else out.push({ ...style, text: decode(x.text) });+ break;+ }+ default: {+ const raw = (t as { text?: string }).text;+ if (raw) out.push({ ...style, text: decode(raw) });+ }+ }+ }+ return out;+}++function blocks(tokens: Token[], out: Block[], depth = 0, inQuote = false): void {+ for (const t of tokens) {+ switch (t.type) {+ case 'heading': out.push({ type: 'heading', level: Math.min(6, (t as Tokens.Heading).depth), runs: inline((t as Tokens.Heading).tokens) }); break;+ case 'paragraph': out.push({ type: inQuote ? 'quote' : 'para', runs: inline((t as Tokens.Paragraph).tokens) }); break;+ case 'text': out.push({ type: inQuote ? 'quote' : 'para', runs: inline([t]) }); break;+ case 'blockquote': blocks((t as Tokens.Blockquote).tokens, out, depth, true); break;+ case 'code': out.push({ type: 'code', text: (t as Tokens.Code).text }); break;+ case 'hr': out.push({ type: 'rule' }); break;+ case 'list': {+ const l = t as Tokens.List;+ const start = typeof l.start === 'number' ? l.start : 1;+ l.items.forEach((item, i) => {+ const marker = item.task ? (item.checked ? '☑' : '☐') : l.ordered ? `${start + i}.` : '•';+ // The item's own text first; nested lists and later paragraphs after it.+ const [first, ...rest] = item.tokens;+ const lead = first && (first.type === 'text' || first.type === 'paragraph') ? inline((first as Tokens.Text).tokens ?? [first]) : [];+ out.push({ type: 'item', depth, marker, runs: lead });+ blocks(first && lead.length ? rest : item.tokens, out, depth + 1, inQuote);+ });+ break;+ }+ case 'table': {+ const tb = t as Tokens.Table;+ out.push({ type: 'table', header: tb.header.map((h) => inline(h.tokens)), rows: tb.rows.map((r) => r.map((cell) => inline(cell.tokens))) });+ break;+ }+ default: break;+ }+ }+}++export function markdownBlocks(markdown: string): Block[] {+ const out: Block[] = [];+ blocks(new Marked({ gfm: true }).lexer(markdown), out);+ // Nested paragraphs inside list items read as items' continuation lines.+ return out.filter((b) => b.type !== 'para' || b.runs.some((r) => r.text.trim()));+}++/** The document's title: its first heading, else the fallback. */+export function titleOf(blocks: Block[], fallback: string): string {+ const h = blocks.find((b) => b.type === 'heading');+ return h && h.type === 'heading' ? h.runs.map((r) => r.text).join('').trim() || fallback : fallback;+}diff --git a/src/artifacts/convert/convert.test.ts b/src/artifacts/convert/convert.test.tsnew file mode 100644index 00000000..041317cc--- /dev/null+++ b/src/artifacts/convert/convert.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';+import { writeFileSync } from 'node:fs';+import { inflateRawSync, inflateSync } from 'node:zlib';+import { markdownBlocks, titleOf } from './blocks.js';+import { canConvert, convertedName, convertMarkdown } from './index.js';+import { measure, winAnsi, wrap } from './pdf.js';+import { crc32 } from './zip.js';++const REPORT = `# Solid-state batteries in 2026++**TL;DR:** pilot lines now, *cars* in 2027–28. See [Toyota](https://global.toyota/en/newsroom/).++## Who++- **Toyota**: sulfide → cars 2027+ - nested detail+1. Cost: $370/kWh+- [x] checked task++| Company | First cars |+|---|---|+| Toyota | 2027 |++> A quote.++\`\`\`+code line+\`\`\`++---+++`;++/** The files inside a zip, by name (a tiny reader for the test). */+function unzip(buf: Buffer): Record<string, string> {+ const out: Record<string, string> = {};+ let p = 0;+ while (buf.readUInt32LE(p) === 0x04034b50) {+ const size = buf.readUInt32LE(p + 18);+ const nameLen = buf.readUInt16LE(p + 26);+ const extra = buf.readUInt16LE(p + 28);+ const name = buf.subarray(p + 30, p + 30 + nameLen).toString('utf-8');+ const data = buf.subarray(p + 30 + nameLen + extra, p + 30 + nameLen + extra + size);+ out[name] = inflateRawSync(data).toString('utf-8');+ p += 30 + nameLen + extra + size;+ }+ return out;+}++describe('markdown blocks', () => {+ it('reads a report into headings, items, tables, quotes, code and links', () => {+ const b = markdownBlocks(REPORT);+ expect(titleOf(b, 'x')).toBe('Solid-state batteries in 2026');+ expect(b.map((x) => x.type)).toEqual(['heading', 'para', 'heading', 'item', 'item', 'item', 'item', 'table', 'quote', 'code', 'rule', 'para']);+ const items = b.filter((x) => x.type === 'item') as Array<{ depth: number; marker: string }>;+ expect(items.map((i) => [i.depth, i.marker])).toEqual([[0, '•'], [1, '•'], [0, '1.'], [0, '☑']]);+ const para = b[1] as { runs: Array<{ text: string; bold?: boolean; italic?: boolean; href?: string }> };+ expect(para.runs.find((r) => r.bold)?.text).toBe('TL;DR:');+ expect(para.runs.find((r) => r.href)?.href).toBe('https://global.toyota/en/newsroom/');+ expect((b[11] as { runs: Array<{ text: string }> }).runs[0].text).toBe('[Image: a chart]');+ });+});++describe('Word', () => {+ it('is a valid zip with headings, a table and working links', () => {+ const buf = convertMarkdown(REPORT, 'docx', 'x');+ const files = unzip(buf);+ expect(Object.keys(files).sort()).toEqual(['[Content_Types].xml', '_rels/.rels', 'docProps/core.xml', 'word/_rels/document.xml.rels', 'word/document.xml', 'word/styles.xml']);+ const doc = files['word/document.xml'];+ expect(doc).toContain('<w:pStyle w:val="Heading1"/>');+ expect(doc).toContain('<w:tbl>');+ expect(doc).toMatch(/<w:hyperlink r:id="rLink1"/);+ expect(files['word/_rels/document.xml.rels']).toContain('Target="https://global.toyota/en/newsroom/" TargetMode="External"');+ expect(files['docProps/core.xml']).toContain('<dc:title>Solid-state batteries in 2026</dc:title>');+ // Text is escaped, never raw markup.+ expect(convertMarkdown('a < b & "c"', 'docx', 'x').length).toBeGreaterThan(0);+ expect(unzip(convertMarkdown('a < b & "c"', 'docx', 'x'))['word/document.xml']).toContain('a < b & "c"');+ expect(unzip(convertMarkdown('bell\u0007 here', 'docx', 'x'))['word/document.xml']).toContain('bell here');+ });++ it('checksums the way zip readers expect', () => {+ expect(crc32(Buffer.from('123456789'))).toBe(0xcbf43926);+ });+});++describe('PDF', () => {+ it('is a well-formed PDF with its title, pages, text and link annotations', () => {+ const long = `${REPORT}\n\n${Array.from({ length: 60 }, (_, i) => `Paragraph ${i} with enough words to wrap a line or two in the layout.`).join('\n\n')}`;+ const buf = convertMarkdown(long, 'pdf', 'x');+ const s = buf.toString('latin1');+ expect(s.startsWith('%PDF-1.4')).toBe(true);+ expect(s.trimEnd().endsWith('%%EOF')).toBe(true);+ expect(s).toContain('/Title (Solid-state batteries in 2026)');+ const count = Number(/\/Type \/Pages \/Kids \[[^\]]*\] \/Count (\d+)/.exec(s)?.[1]);+ expect(count).toBeGreaterThan(1);+ expect(s).toContain('/URI (https://global.toyota/en/newsroom/)');+ // The xref points at each object.+ const start = Number(/startxref\n(\d+)/.exec(s)?.[1]);+ expect(s.slice(start, start + 4)).toBe('xref');+ const offsets = [...s.slice(start).matchAll(/^(\d{10}) 00000 n $/gm)].map((m) => Number(m[1]));+ offsets.forEach((o, i) => expect(s.slice(o, o + `${i + 1} 0 obj`.length)).toBe(`${i + 1} 0 obj`));+ // Page text is in the streams.+ const streams = [...s.matchAll(/stream\n([\s\S]*?)\nendstream/g)].map((m) => inflateSync(Buffer.from(m[1], 'latin1')).toString('latin1'));+ expect(streams.join('\n')).toContain('(Solid-state batteries in 2026) Tj');+ expect(streams.join('\n')).toContain(`(1 / ${count}) Tj`);+ if (process.env.MERCURY_CONVERT_OUT) {+ writeFileSync(`${process.env.MERCURY_CONVERT_OUT}/test.pdf`, buf);+ writeFileSync(`${process.env.MERCURY_CONVERT_OUT}/test.docx`, convertMarkdown(long, 'docx', 'x'));+ }+ });++ it('spells what the core fonts lack and wraps by real widths', () => {+ expect(winAnsi('a → b ≥ c “q” – é')).toBe('a -> b >= c \x93q\x94 \x96 \xe9');+ expect(winAnsi('東京')).toBe('??');+ expect(winAnsi('Łódź')).toBe('Lódz');+ expect(measure('Hello', 'R', 10)).toBeCloseTo((722 + 556 + 222 + 222 + 556) / 100, 5);+ const lines = wrap([{ text: 'word '.repeat(60) }], 200, 10);+ expect(lines.length).toBeGreaterThan(5);+ for (const l of lines) expect(l.w).toBeLessThanOrEqual(200);+ // A word wider than the line is cut, not overflowed.+ for (const l of wrap([{ text: 'x'.repeat(300) }], 100, 10)) expect(l.w).toBeLessThanOrEqual(100.01);+ });++ it('only text converts, and names follow the format', () => {+ expect(canConvert({ name: 'r.md', mime: 'text/markdown' })).toBe(true);+ expect(canConvert({ name: 'a.png', mime: 'image/png' })).toBe(false);+ expect(convertedName('2026-report.md', 'pdf')).toBe('2026-report.pdf');+ });+});diff --git a/src/artifacts/convert/docx.ts b/src/artifacts/convert/docx.tsnew file mode 100644index 00000000..c949c25a--- /dev/null+++ b/src/artifacts/convert/docx.ts@@ -0,0 +1,119 @@+import type { Block, Run } from './blocks.js';+import { zip } from './zip.js';++/**+ * Blocks → a Word document (.docx): real heading styles (so Word's+ * navigation pane and table of contents work), lists, quotes, code, tables,+ * and links that open. Opens in Word, Pages, Google Docs and LibreOffice.+ */++/** XML 1.0 can't hold control characters other than tab, newline and return. */+const printable = (s: string): string => [...s].filter((ch) => { const c = ch.charCodeAt(0); return c >= 32 || c === 9 || c === 10 || c === 13; }).join('');++const esc = (s: string): string => printable(s)+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');++class Links {+ readonly list: string[] = [];+ id(href: string): string {+ let i = this.list.indexOf(href);+ if (i < 0) { this.list.push(href); i = this.list.length - 1; }+ return `rLink${i + 1}`;+ }+}++function run(r: Run, extra = ''): string {+ const props = [+ r.bold ? '<w:b/>' : '',+ r.italic ? '<w:i/>' : '',+ r.code ? '<w:rFonts w:ascii="Menlo" w:hAnsi="Menlo" w:cs="Menlo"/><w:sz w:val="19"/>' : '',+ r.href ? '<w:rStyle w:val="Hyperlink"/>' : '',+ extra,+ ].join('');+ const parts = r.text.split('\n').map((t) => `<w:t xml:space="preserve">${esc(t)}</w:t>`);+ return `<w:r>${props ? `<w:rPr>${props}</w:rPr>` : ''}${parts.join('<w:br/>')}</w:r>`;+}++function runs(list: Run[], links: Links, extra = ''): string {+ let out = '';+ for (let i = 0; i < list.length; i++) {+ const r = list[i];+ if (!r.href) { out += run(r, extra); continue; }+ // Consecutive runs with the same target are one hyperlink.+ let j = i;+ let inner = '';+ while (j < list.length && list[j].href === r.href) inner += run(list[j++], extra);+ out += `<w:hyperlink r:id="${links.id(r.href)}" w:history="1">${inner}</w:hyperlink>`;+ i = j - 1;+ }+ return out;+}++// On the table itself too: not every viewer applies a table style's borders.+const BORDERS = '<w:tblBorders>' + ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map((side) => `<w:${side} w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>`).join('') + '</w:tblBorders>';++const para = (style: string | null, body: string, pPr = ''): string =>+ `<w:p>${style || pPr ? `<w:pPr>${style ? `<w:pStyle w:val="${style}"/>` : ''}${pPr}</w:pPr>` : ''}${body}</w:p>`;++function body(blocks: Block[], links: Links): string {+ const out: string[] = [];+ for (const b of blocks) {+ switch (b.type) {+ case 'heading': out.push(para(`Heading${b.level}`, runs(b.runs, links))); break;+ case 'para': out.push(para(null, runs(b.runs, links))); break;+ case 'quote': out.push(para('Quote', runs(b.runs, links))); break;+ case 'item': {+ const left = 360 + b.depth * 360;+ out.push(para('ListParagraph', `${run({ text: `${b.marker}\t` })}${runs(b.runs, links)}`, `<w:tabs><w:tab w:val="left" w:pos="${left}"/></w:tabs><w:ind w:left="${left}" w:hanging="300"/>`));+ break;+ }+ case 'code':+ for (const line of b.text.split('\n')) out.push(para('Code', run({ text: line || ' ', code: true })));+ break;+ case 'rule': out.push(para(null, '', '<w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="BBBBBB"/></w:pBdr>')); break;+ case 'table': {+ const cols = Math.max(b.header.length, ...b.rows.map((r) => r.length), 1);+ const cell = (rs: Run[], head: boolean): string =>+ `<w:tc><w:tcPr><w:tcW w:w="${Math.floor(9000 / cols)}" w:type="dxa"/>${head ? '<w:shd w:val="clear" w:color="auto" w:fill="F2F2F2"/>' : ''}</w:tcPr>${para(null, runs(rs, links, head ? '<w:b/>' : ''))}</w:tc>`;+ const row = (cells: Run[][], head: boolean): string => `<w:tr>${Array.from({ length: cols }, (_, i) => cell(cells[i] ?? [], head)).join('')}</w:tr>`;+ out.push(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="0" w:type="auto"/>${BORDERS}</w:tblPr>${row(b.header, true)}${b.rows.map((r) => row(r, false)).join('')}</w:tbl>`);+ out.push(para(null, ''));+ break;+ }+ }+ }+ return out.join('');+}++const STYLES = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">+<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="140" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>+<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style>+${[1, 2, 3, 4, 5, 6].map((n) => `<w:style w:type="paragraph" w:styleId="Heading${n}"><w:name w:val="heading ${n}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="${n === 1 ? 240 : 200}" w:after="100"/><w:outlineLvl w:val="${n - 1}"/></w:pPr><w:rPr><w:b/><w:sz w:val="${[40, 32, 27, 24, 22, 22][n - 1]}"/></w:rPr></w:style>`).join('\n')}+<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:pPr><w:ind w:left="400"/><w:pBdr><w:left w:val="single" w:sz="12" w:space="8" w:color="CCCCCC"/></w:pBdr></w:pPr><w:rPr><w:i/><w:color w:val="555555"/></w:rPr></w:style>+<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="60"/></w:pPr></w:style>+<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/><w:shd w:val="clear" w:color="auto" w:fill="F5F5F5"/></w:pPr><w:rPr><w:rFonts w:ascii="Menlo" w:hAnsi="Menlo" w:cs="Menlo"/><w:sz w:val="19"/></w:rPr></w:style>+<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="1F5FBF"/><w:u w:val="single"/></w:rPr></w:style>+<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:tblPr><w:tblBorders><w:top w:val="single" w:sz="4" w:color="BFBFBF"/><w:left w:val="single" w:sz="4" w:color="BFBFBF"/><w:bottom w:val="single" w:sz="4" w:color="BFBFBF"/><w:right w:val="single" w:sz="4" w:color="BFBFBF"/><w:insideH w:val="single" w:sz="4" w:color="BFBFBF"/><w:insideV w:val="single" w:sz="4" w:color="BFBFBF"/></w:tblBorders><w:tblCellMar><w:left w:w="100" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>+</w:styles>`;++export function toDocx(blocks: Block[], title: string, now = new Date()): Buffer {+ const links = new Links();+ const content = body(blocks, links);+ const document = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>${content}<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1300" w:right="1300" w:bottom="1300" w:left="1300" w:header="700" w:footer="700" w:gutter="0"/></w:sectPr></w:body></w:document>`;+ const rels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>${links.list.map((href, i) => `<Relationship Id="rLink${i + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="${esc(href)}" TargetMode="External"/>`).join('')}</Relationships>`;+ const iso = now.toISOString().replace(/\.\d+Z$/, 'Z');+ return zip([+ { name: '[Content_Types].xml', data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>` },+ { name: '_rels/.rels', data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>` },+ { name: 'docProps/core.xml', data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:title>${esc(title)}</dc:title><dc:creator>Mercury</dc:creator><dcterms:created xsi:type="dcterms:W3CDTF">${iso}</dcterms:created></cp:coreProperties>` },+ { name: 'word/document.xml', data: document },+ { name: 'word/styles.xml', data: STYLES },+ { name: 'word/_rels/document.xml.rels', data: rels },+ ], now);+}diff --git a/src/artifacts/convert/index.ts b/src/artifacts/convert/index.tsnew file mode 100644index 00000000..4d496e1f--- /dev/null+++ b/src/artifacts/convert/index.ts@@ -0,0 +1,38 @@+import { readFileSync } from 'node:fs';+import { markdownBlocks, titleOf } from './blocks.js';+import { toDocx } from './docx.js';+import { toPdf } from './pdf.js';++/**+ * A Markdown or text artifact (a research report, notes) as a PDF or a Word+ * document, made on request. Nothing is stored: the .md stays the source.+ */++export type ConvertFormat = 'pdf' | 'docx';++export const CONVERT_MIME: Record<ConvertFormat, string> = {+ pdf: 'application/pdf',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+};++/** Only text can be turned into a document. */+export function canConvert(a: { name: string; mime: string }): boolean {+ return /^text\/(markdown|plain)$/.test(a.mime) || /\.(md|markdown|txt)$/i.test(a.name);+}++export function convertedName(name: string, format: ConvertFormat): string {+ return `${name.replace(/\.(md|markdown|txt)$/i, '')}.${format}`;+}++export function convertMarkdown(markdown: string, format: ConvertFormat, fallbackTitle: string): Buffer {+ const blocks = markdownBlocks(markdown);+ const title = titleOf(blocks, fallbackTitle);+ return format === 'pdf' ? toPdf(blocks, title) : toDocx(blocks, title);+}++export function convertFile(path: string, name: string, format: ConvertFormat): Buffer {+ const text = readFileSync(path, 'utf-8');+ // Plain text: each line its own paragraph, not one Markdown blob.+ const markdown = /\.txt$/i.test(name) ? text.split('\n').map((l) => l.replace(/^([#>*\-+]|\d+\.)/, '\\$1')).join('\n\n') : text;+ return convertMarkdown(markdown, format, name.replace(/\.[^.]+$/, ''));+}diff --git a/src/artifacts/convert/pdf.ts b/src/artifacts/convert/pdf.tsnew file mode 100644index 00000000..5f35d081--- /dev/null+++ b/src/artifacts/convert/pdf.ts@@ -0,0 +1,330 @@+import { deflateSync } from 'node:zlib';+import type { Block, Run } from './blocks.js';++/**+ * Blocks → a PDF: real, selectable text in the PDF's built-in Helvetica and+ * Courier (no font files, no browser), A4, wrapped by the fonts' own+ * widths, page numbers, and links you can click (sources stay sources).+ * The built-in fonts cover Western European text; anything outside it is+ * spelled out where there's a common equivalent (→ "->") or shown as "?".+ */++type Font = 'R' | 'B' | 'I' | 'BI' | 'M';+type Rgb = [number, number, number];++const PAGE_W = 595.28;+const PAGE_H = 841.89;+const MARGIN_X = 62;+const MARGIN_TOP = 64;+const MARGIN_BOTTOM = 70;+const TEXT_W = PAGE_W - MARGIN_X * 2;++const INK: Rgb = [0.11, 0.11, 0.12];+const MUTED: Rgb = [0.4, 0.4, 0.43];+const LINK: Rgb = [0.12, 0.37, 0.75];+const RULE: Rgb = [0.78, 0.78, 0.8];+const SOFT: Rgb = [0.955, 0.955, 0.96];++// Glyph widths (1/1000 em) for ASCII 32–126: Helvetica, then Helvetica-Bold (the Adobe core-font metrics).+const HELV = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];+const HELV_B = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];++/** WinAnsi codes 0x80–0x9F, by character. */+const WIN_HIGH: Record<string, number> = {+ '€': 0x80, '‚': 0x82, 'ƒ': 0x83, '„': 0x84, '…': 0x85, '†': 0x86, '‡': 0x87, 'ˆ': 0x88, '‰': 0x89, 'Š': 0x8a, '‹': 0x8b, 'Œ': 0x8c, 'Ž': 0x8e,+ '‘': 0x91, '’': 0x92, '“': 0x93, '”': 0x94, '•': 0x95, '–': 0x96, '—': 0x97, '˜': 0x98, '™': 0x99, 'š': 0x9a, '›': 0x9b, 'œ': 0x9c, 'ž': 0x9e, 'Ÿ': 0x9f,+};+/** Widths (regular, bold) for the non-ASCII WinAnsi glyphs that aren't a plain letter. */+const HIGH_W: Record<number, [number, number]> = {+ 0x80: [556, 556], 0x82: [222, 278], 0x84: [333, 500], 0x85: [1000, 1000], 0x86: [556, 556], 0x87: [556, 556], 0x89: [1000, 1000], 0x8b: [333, 333], 0x9b: [333, 333],+ 0x91: [222, 278], 0x92: [222, 278], 0x93: [333, 500], 0x94: [333, 500], 0x95: [350, 350], 0x96: [556, 556], 0x97: [1000, 1000], 0x99: [1000, 1000],+ 0xa0: [278, 278], 0xa9: [737, 737], 0xae: [737, 737], 0xb0: [400, 400], 0xb1: [584, 584], 0xb7: [278, 278], 0xd7: [584, 584], 0xf7: [584, 584], 0xa7: [556, 556], 0xb6: [537, 556],+};+/** Common characters the core fonts don't have, spelled with ones they do. */+const SPELL: Record<string, string> = {+ '→': '->', '←': '<-', '↔': '<->', '⇒': '=>', '≥': '>=', '≤': '<=', '≠': '!=', '≈': '~', '∼': '~', '−': '-', '‑': '-', '‐': '-', '′': "'", '″': '"',+ 'Ł': 'L', 'ł': 'l', 'Đ': 'D', 'đ': 'd', 'ı': 'i', 'Ħ': 'H', 'ħ': 'h', 'Ŧ': 'T', 'ŧ': 't', 'fi': 'fi', 'fl': 'fl',+ '✓': 'v', '✔': 'v', '✗': 'x', '✘': 'x', '☑': '[x]', '☐': '[ ]', '★': '*', '☆': '*', '▪': '•', '◦': '•', '‣': '•', '·': '·', '': '', '': '', '\t': ' ',+};++/** A string as WinAnsi bytes (in a latin1 string), and what couldn't be shown became "?". */+export function winAnsi(text: string): string {+ let out = '';+ for (const ch of text.normalize('NFC')) {+ const spelled = SPELL[ch];+ if (spelled !== undefined) { out += spelled === '·' ? '·' : spelled === '•' ? '\u0095' : spelled; continue; }+ const code = ch.codePointAt(0)!;+ if (code >= 32 && code <= 126) out += ch;+ else if (code >= 0xa0 && code <= 0xff) out += ch;+ else if (WIN_HIGH[ch] !== undefined) out += String.fromCharCode(WIN_HIGH[ch]);+ else if (code === 10) out += ' ';+ else {+ // An accented letter outside Latin-1: its plain letter. Anything else: "?".+ const base = ch.normalize('NFD').replace(/[̀-ͯ]/g, '');+ out += base && base.charCodeAt(0) < 127 ? base : '?';+ }+ }+ return out;+}++function glyphWidth(code: number, bold: boolean): number {+ if (code >= 32 && code <= 126) return (bold ? HELV_B : HELV)[code - 32];+ const w = HIGH_W[code];+ if (w) return bold ? w[1] : w[0];+ if (code >= 0xc0) {+ // Latin-1 letters: their plain letter's width.+ const base = String.fromCharCode(code).normalize('NFD').charCodeAt(0);+ if (base >= 32 && base <= 126) return (bold ? HELV_B : HELV)[base - 32];+ }+ return 556;+}++export function measure(win: string, font: Font, size: number): number {+ if (font === 'M') return win.length * 600 * size / 1000;+ const bold = font === 'B' || font === 'BI';+ let w = 0;+ for (let i = 0; i < win.length; i++) w += glyphWidth(win.charCodeAt(i), bold);+ return w * size / 1000;+}++const pdfString = (win: string): string => {+ let s = '(';+ for (let i = 0; i < win.length; i++) {+ const c = win.charCodeAt(i);+ if (c === 0x28 || c === 0x29 || c === 0x5c) s += `\\${win[i]}`;+ else if (c < 32 || c > 126) s += `\\${c.toString(8).padStart(3, '0')}`;+ else s += win[i];+ }+ return `${s})`;+};++const num = (n: number): string => (Math.round(n * 100) / 100).toString();+const rgb = (c: Rgb, stroke = false): string => `${c.map(num).join(' ')} ${stroke ? 'RG' : 'rg'}`;++interface Piece { text: string; font: Font; size: number; color: Rgb; href?: string; w: number }+interface Line { pieces: Piece[]; w: number }++function fontOf(r: Run, base: Font): Font {+ if (r.code) return 'M';+ const bold = r.bold || base === 'B' || base === 'BI';+ const italic = r.italic || base === 'I' || base === 'BI';+ return bold && italic ? 'BI' : bold ? 'B' : italic ? 'I' : 'R';+}++/** Runs → lines no wider than `width`, wrapped at spaces (a word longer than a line is cut). */+export function wrap(runs: Run[], width: number, size: number, base: Font = 'R', color: Rgb = INK): Line[] {+ const lines: Line[] = [];+ let line: Line = { pieces: [], w: 0 };+ const push = () => { lines.push(line); line = { pieces: [], w: 0 }; };+ for (const r of runs) {+ const font = fontOf(r, base);+ const fsize = r.code ? size * 0.9 : size;+ const col = r.href ? LINK : color;+ for (const part of r.text.split(/(\n|\s+)/)) {+ if (!part) continue;+ if (part === '\n') { push(); continue; }+ const isSpace = /^\s+$/.test(part);+ if (isSpace && line.pieces.length === 0) continue;+ let win = winAnsi(isSpace ? ' ' : part);+ let w = measure(win, font, fsize);+ if (!isSpace && line.w + w > width && line.pieces.length) {+ // Drop the trailing space before breaking.+ const last = line.pieces[line.pieces.length - 1];+ if (last && last.text === ' ') { line.pieces.pop(); line.w -= last.w; }+ push();+ }+ // A word wider than the whole line: cut it.+ while (!isSpace && w > width) {+ let cut = win.length;+ while (cut > 1 && measure(win.slice(0, cut), font, fsize) > width - line.w) cut--;+ const head = win.slice(0, cut);+ line.pieces.push({ text: head, font, size: fsize, color: col, href: r.href, w: measure(head, font, fsize) });+ push();+ win = win.slice(cut);+ w = measure(win, font, fsize);+ }+ if (!win) continue;+ line.pieces.push({ text: win, font, size: fsize, color: col, href: r.href, w });+ line.w += w;+ }+ }+ if (line.pieces.length) push();+ return lines.length ? lines : [{ pieces: [], w: 0 }];+}++class Doc {+ pages: Array<{ ops: string[]; links: Array<{ rect: [number, number, number, number]; href: string }> }> = [];+ y = 0;+ constructor() { this.newPage(); }+ get page() { return this.pages[this.pages.length - 1]; }+ newPage(): void { this.pages.push({ ops: [], links: [] }); this.y = MARGIN_TOP; }+ /** Room for `h` more points on this page, or a new page. */+ room(h: number): void { if (this.y + h > PAGE_H - MARGIN_BOTTOM && this.y > MARGIN_TOP) this.newPage(); }+ space(h: number): void { if (this.y > MARGIN_TOP) this.y += h; }+ rect(x: number, top: number, w: number, h: number, fill: Rgb): void {+ this.page.ops.push(`${rgb(fill)} ${num(x)} ${num(PAGE_H - top - h)} ${num(w)} ${num(h)} re f`);+ }+ line(x1: number, y1: number, x2: number, y2: number, color: Rgb, width = 0.6): void {+ this.page.ops.push(`${rgb(color, true)} ${num(width)} w ${num(x1)} ${num(PAGE_H - y1)} m ${num(x2)} ${num(PAGE_H - y2)} l S`);+ }+ /** One line of text with its baseline at `baseline` (from the top). */+ text(line: Line, x: number, baseline: number): void {+ let cx = x;+ // Words of one style are one string: smaller files, and copied text reads as text.+ const merged: Piece[] = [];+ for (const p of line.pieces) {+ const last = merged[merged.length - 1];+ if (last && last.font === p.font && last.size === p.size && last.href === p.href && last.color === p.color) merged[merged.length - 1] = { ...last, text: last.text + p.text, w: last.w + p.w };+ else merged.push({ ...p });+ }+ for (const p of merged) {+ if (p.text !== ' ') {+ this.page.ops.push(`BT /F${p.font} ${num(p.size)} Tf ${rgb(p.color)} ${num(cx)} ${num(PAGE_H - baseline)} Td ${pdfString(p.text)} Tj ET`);+ if (p.href) this.page.links.push({ rect: [cx, PAGE_H - baseline - p.size * 0.25, cx + p.w, PAGE_H - baseline + p.size * 0.85], href: p.href });+ }+ cx += p.w;+ }+ }+ /** Wrapped lines, flowing onto new pages; `decorate` draws behind each line (code shading, a quote bar). */+ flow(lines: Line[], x: number, size: number, leading: number, decorate?: (top: number, h: number) => void): void {+ const h = size * leading;+ for (const l of lines) {+ this.room(h);+ decorate?.(this.y, h);+ this.text(l, x, this.y + size * 0.95);+ this.y += h;+ }+ }+}++const HEADING_SIZE = [20, 15.5, 13, 11.5, 10.5, 10.5];+const BODY = 10.5;++function table(doc: Doc, header: Run[][], rows: Run[][][]): void {+ const cols = Math.max(header.length, ...rows.map((r) => r.length), 1);+ const colW = TEXT_W / cols;+ const size = 9;+ const pad = 4;+ const lh = size * 1.35;+ const drawRow = (cells: Run[][], head: boolean) => {+ const wrapped = Array.from({ length: cols }, (_, i) => wrap(cells[i] ?? [], colW - pad * 2, size, head ? 'B' : 'R'));+ const h = Math.max(...wrapped.map((w) => w.length)) * lh + pad * 2;+ doc.room(Math.min(h, PAGE_H - MARGIN_TOP - MARGIN_BOTTOM));+ const top = doc.y;+ if (head) doc.rect(MARGIN_X, top, TEXT_W, h, SOFT);+ wrapped.forEach((lines, i) => lines.forEach((l, j) => doc.text(l, MARGIN_X + i * colW + pad, top + pad + j * lh + size * 0.95)));+ for (let i = 0; i <= cols; i++) doc.line(MARGIN_X + i * colW, top, MARGIN_X + i * colW, top + h, RULE, 0.5);+ doc.line(MARGIN_X, top, MARGIN_X + TEXT_W, top, RULE, 0.5);+ doc.line(MARGIN_X, top + h, MARGIN_X + TEXT_W, top + h, RULE, 0.5);+ doc.y = top + h;+ };+ if (header.length) drawRow(header, true);+ for (const r of rows) drawRow(r, false);+}++function layout(blocks: Block[]): Doc {+ const doc = new Doc();+ let prev: Block['type'] | null = null;+ for (const b of blocks) {+ // A list ends with a little room before what follows it.+ if (prev === 'item' && b.type !== 'item') doc.y += BODY * 0.5;+ switch (b.type) {+ case 'heading': {+ const size = HEADING_SIZE[b.level - 1];+ doc.space(b.level <= 2 ? size * 0.9 : size * 0.7);+ const lines = wrap(b.runs, TEXT_W, size, 'B');+ // Keep a heading with the line after it.+ doc.room(lines.length * size * 1.25 + BODY * 2.5);+ doc.flow(lines, MARGIN_X, size, 1.25);+ if (b.level === 1) { doc.line(MARGIN_X, doc.y + 3, MARGIN_X + TEXT_W, doc.y + 3, RULE); doc.y += 6; }+ doc.y += size * 0.35;+ break;+ }+ case 'para':+ doc.flow(wrap(b.runs, TEXT_W, BODY), MARGIN_X, BODY, 1.5);+ doc.y += BODY * 0.6;+ break;+ case 'item': {+ const indent = 14 + b.depth * 16;+ const marker = winAnsi(b.marker);+ const lines = wrap(b.runs, TEXT_W - indent - 4, BODY);+ doc.room(BODY * 1.45);+ doc.text({ pieces: [{ text: marker, font: 'R', size: BODY, color: MUTED, w: measure(marker, 'R', BODY) }], w: 0 }, MARGIN_X + indent - measure(marker, 'R', BODY) - 6, doc.y + BODY * 0.95);+ doc.flow(lines, MARGIN_X + indent, BODY, 1.45);+ doc.y += BODY * 0.2;+ break;+ }+ case 'quote':+ doc.flow(wrap(b.runs, TEXT_W - 16, BODY, 'I', MUTED), MARGIN_X + 14, BODY, 1.5, (top, h) => doc.rect(MARGIN_X, top, 2.2, h, RULE));+ doc.y += BODY * 0.6;+ break;+ case 'code': {+ const size = 8.6;+ const lines = b.text.split('\n').flatMap((l) => wrap([{ text: l || ' ', code: true }], TEXT_W - 16, size / 0.9));+ doc.y += 2;+ doc.flow(lines, MARGIN_X + 8, size, 1.45, (top, h) => doc.rect(MARGIN_X, top, TEXT_W, h, SOFT));+ doc.y += BODY * 0.8;+ break;+ }+ case 'rule':+ doc.space(6);+ doc.room(12);+ doc.line(MARGIN_X, doc.y, MARGIN_X + TEXT_W, doc.y, RULE);+ doc.y += 12;+ break;+ case 'table':+ doc.space(4);+ table(doc, b.header, b.rows);+ doc.y += BODY;+ break;+ }+ prev = b.type;+ }+ return doc;+}++const FONTS: Record<Font, string> = { R: 'Helvetica', B: 'Helvetica-Bold', I: 'Helvetica-Oblique', BI: 'Helvetica-BoldOblique', M: 'Courier' };++const asciiUri = (href: string): string => href.replace(/[^\x21-\x7e]/g, (c) => encodeURIComponent(c)).replace(/([()\\])/g, '\\$1');++export function toPdf(blocks: Block[], title: string, now = new Date()): Buffer {+ const doc = layout(blocks);+ const total = doc.pages.length;+ doc.pages.forEach((p, i) => {+ const label = winAnsi(`${i + 1} / ${total}`);+ const w = measure(label, 'R', 8);+ p.ops.push(`BT /FR 8 Tf ${rgb(MUTED)} ${num((PAGE_W - w) / 2)} ${num(MARGIN_BOTTOM / 2)} Td ${pdfString(label)} Tj ET`);+ });++ const objects: Array<string | Buffer> = [];+ const add = (o: string | Buffer): number => { objects.push(o); return objects.length; };+ const catalog = add('');+ const pagesObj = add('');+ const fontIds = Object.fromEntries((Object.keys(FONTS) as Font[]).map((f) => [f, add(`<< /Type /Font /Subtype /Type1 /BaseFont /${FONTS[f]} /Encoding /WinAnsiEncoding >>`)])) as Record<Font, number>;+ const fontRes = (Object.keys(FONTS) as Font[]).map((f) => `/F${f} ${fontIds[f]} 0 R`).join(' ');+ const pageIds: number[] = [];+ for (const p of doc.pages) {+ const stream = deflateSync(Buffer.from(p.ops.join('\n'), 'latin1'));+ const content = add(Buffer.concat([Buffer.from(`<< /Length ${stream.length} /Filter /FlateDecode >>\nstream\n`, 'latin1'), stream, Buffer.from('\nendstream', 'latin1')]));+ const annots = p.links.map((l) => add(`<< /Type /Annot /Subtype /Link /Rect [${l.rect.map(num).join(' ')}] /Border [0 0 0] /A << /S /URI /URI (${asciiUri(l.href)}) >> >>`));+ pageIds.push(add(`<< /Type /Page /Parent ${pagesObj} 0 R /MediaBox [0 0 ${num(PAGE_W)} ${num(PAGE_H)}] /Resources << /Font << ${fontRes} >> >> /Contents ${content} 0 R${annots.length ? ` /Annots [${annots.map((a) => `${a} 0 R`).join(' ')}]` : ''} >>`));+ }+ objects[catalog - 1] = `<< /Type /Catalog /Pages ${pagesObj} 0 R >>`;+ objects[pagesObj - 1] = `<< /Type /Pages /Kids [${pageIds.map((id) => `${id} 0 R`).join(' ')}] /Count ${pageIds.length} >>`;+ const d = now.toISOString().replace(/[-:T]/g, '').slice(0, 14);+ const info = add(`<< /Title ${pdfString(winAnsi(title))} /Producer (Mercury) /CreationDate (D:${d}Z) >>`);++ const parts: Buffer[] = [Buffer.from('%PDF-1.4\n%\xe2\xe3\xcf\xd3\n', 'latin1')];+ const offsets: number[] = [];+ let pos = parts[0].length;+ objects.forEach((o, i) => {+ const body = typeof o === 'string' ? Buffer.from(o, 'latin1') : o;+ const chunk = Buffer.concat([Buffer.from(`${i + 1} 0 obj\n`, 'latin1'), body, Buffer.from('\nendobj\n', 'latin1')]);+ offsets.push(pos);+ parts.push(chunk);+ pos += chunk.length;+ });+ const xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('')}`;+ parts.push(Buffer.from(`${xref}trailer\n<< /Size ${objects.length + 1} /Root ${catalog} 0 R /Info ${info} 0 R >>\nstartxref\n${pos}\n%%EOF\n`, 'latin1'));+ return Buffer.concat(parts);+}diff --git a/src/artifacts/convert/zip.ts b/src/artifacts/convert/zip.tsnew file mode 100644index 00000000..b061439e--- /dev/null+++ b/src/artifacts/convert/zip.ts@@ -0,0 +1,73 @@+import { deflateRawSync } from 'node:zlib';++/**+ * A minimal zip writer (deflate, no zip64): enough for an Office document,+ * which is a zip of a few small XML files. No library, so standalone+ * binaries don't carry one.+ */++const CRC_TABLE = (() => {+ const t = new Uint32Array(256);+ for (let n = 0; n < 256; n++) {+ let c = n;+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ t[n] = c >>> 0;+ }+ return t;+})();++export function crc32(buf: Buffer): number {+ let c = 0xffffffff;+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++export function zip(files: Array<{ name: string; data: Buffer | string }>, now = new Date()): Buffer {+ const time = ((now.getHours() << 11) | (now.getMinutes() << 5) | Math.floor(now.getSeconds() / 2)) & 0xffff;+ const date = (((now.getFullYear() - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate()) & 0xffff;+ const locals: Buffer[] = [];+ const centrals: Buffer[] = [];+ let offset = 0;+ for (const f of files) {+ const name = Buffer.from(f.name, 'utf-8');+ const raw = typeof f.data === 'string' ? Buffer.from(f.data, 'utf-8') : f.data;+ const packed = deflateRawSync(raw);+ const crc = crc32(raw);+ const local = Buffer.alloc(30);+ local.writeUInt32LE(0x04034b50, 0);+ local.writeUInt16LE(20, 4);+ local.writeUInt16LE(0x0800, 6); // UTF-8 names+ local.writeUInt16LE(8, 8); // deflate+ local.writeUInt16LE(time, 10);+ local.writeUInt16LE(date, 12);+ local.writeUInt32LE(crc, 14);+ local.writeUInt32LE(packed.length, 18);+ local.writeUInt32LE(raw.length, 22);+ local.writeUInt16LE(name.length, 26);+ local.writeUInt16LE(0, 28);+ locals.push(local, name, packed);+ const central = Buffer.alloc(46);+ central.writeUInt32LE(0x02014b50, 0);+ central.writeUInt16LE(20, 4);+ central.writeUInt16LE(20, 6);+ central.writeUInt16LE(0x0800, 8);+ central.writeUInt16LE(8, 10);+ central.writeUInt16LE(time, 12);+ central.writeUInt16LE(date, 14);+ central.writeUInt32LE(crc, 16);+ central.writeUInt32LE(packed.length, 20);+ central.writeUInt32LE(raw.length, 24);+ central.writeUInt16LE(name.length, 28);+ central.writeUInt32LE(offset, 42);+ centrals.push(central, name);+ offset += local.length + name.length + packed.length;+ }+ const dir = Buffer.concat(centrals);+ const end = Buffer.alloc(22);+ end.writeUInt32LE(0x06054b50, 0);+ end.writeUInt16LE(files.length, 8);+ end.writeUInt16LE(files.length, 10);+ end.writeUInt32LE(dir.length, 12);+ end.writeUInt32LE(offset, 16);+ return Buffer.concat([...locals, dir, end]);+}diff --git a/src/web/api-contract.ts b/src/web/api-contract.tsindex 1695dff6..913e8662 100644--- a/src/web/api-contract.ts+++ b/src/web/api-contract.ts@@ -51,6 +51,8 @@ export const API_FEATURES: readonly string[] = Object.freeze(['threads.save', // POST /api/chat/threads/:id/save { saved } — thread.savedAt'cloud.signin', // GET /api/cloud/status, POST/GET/DELETE /api/cloud/signin (browser pairing from any client) // POST /api/voice/check { vendor, key?, endpoint? }'brain.map', // GET /api/brain/map[?archive=1] — themes, sub-themes, notes, related links+ 'artifacts.convert', // GET /api/artifacts/:id/file?as=pdf|docx, POST /api/artifacts/:id/export { dest, as } — Markdown/text as PDF or Word+ 'chat.favicon', // GET /api/chat/favicon?domain= — a site's icon (204 when it has none), fetched and cached by the runtime'chat.research', // SSE 'research' / 'research_plan' / 'research_plan_resolved' / 'notice'; GET /api/chat/threads/:id/research, POST …/research/finish, …/research/off, POST /api/chat/research/plan/:id; message.research; step_done { failed, reason }]);diff --git a/src/web/api/artifacts.ts b/src/web/api/artifacts.tsindex b93c41e2..c0345b7f 100644--- a/src/web/api/artifacts.ts+++ b/src/web/api/artifacts.ts@@ -1,4 +1,4 @@-import { copyFileSync, createReadStream, existsSync, statSync } from 'node:fs';+import { copyFileSync, createReadStream, existsSync, statSync, writeFileSync } from 'node:fs';import { dirname, isAbsolute } from 'node:path';import { Readable } from 'node:stream';import { Hono } from 'hono';@@ -6,6 +6,10 @@ import { artifactStore, type Artifact } from '../../artifacts/store.js';import type { ArtifactKind } from '../../artifacts/classify.js';import type { SessionRepository } from '../../sessions/index.js';import { isLoopbackRequest } from '../middleware.js';+import { canConvert, CONVERT_MIME, convertedName, convertFile, type ConvertFormat } from '../../artifacts/convert/index.js';+import { logger } from '../../utils/logger.js';++const asFormat = (v: unknown): ConvertFormat | null => (v === 'pdf' || v === 'docx' ? v : null);/*** Artifacts: what Mercury made, by conversation.@@ -13,7 +17,8 @@ import { isLoopbackRequest } from '../middleware.js';* GET /api/artifacts?kind=&q=&threadId=&cursor=&limit= newest first, a page at a time, with counts per kind* GET /api/artifacts/:id one, with its thread* GET /api/artifacts/:id/file the file itself (Range for video and audio)- * POST /api/artifacts/:id/export { dest } Save as… (this computer only)+ * GET /api/artifacts/:id/file?as=pdf|docx a Markdown/text artifact as a PDF or Word document+ * POST /api/artifacts/:id/export { dest, as? } Save as… (this computer only), converted when `as` is given* DELETE /api/artifacts/:id forget one (Mercury's copy only)*/@@ -55,6 +60,23 @@ artifacts.get('/api/artifacts/:id', (c) => {artifacts.get('/api/artifacts/:id/file', (c) => {const a = artifactStore().get(c.req.param('id'));if (!a || !existsSync(a.storedPath)) return c.json({ error: 'Not found' }, 404);+ const as = asFormat(c.req.query('as'));+ if (c.req.query('as') !== undefined && !as) return c.json({ error: 'as must be pdf or docx' }, 400);+ if (as) {+ if (!canConvert(a)) return c.json({ error: 'Only Markdown and text can be exported as a document.' }, 415);+ let bytes: Buffer;+ try { bytes = convertFile(a.storedPath, a.name, as); } catch (err) {+ logger.warn({ err: err instanceof Error ? err.message : String(err), id: a.id, as }, 'Artifact conversion failed');+ return c.json({ error: `Couldn't make the ${as === 'pdf' ? 'PDF' : 'Word document'}.` }, 500);+ }+ return new Response(new Uint8Array(bytes), { status: 200, headers: {+ 'Content-Type': CONVERT_MIME[as],+ 'Content-Length': String(bytes.length),+ 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(convertedName(a.name, as))}`,+ 'X-Content-Type-Options': 'nosniff',+ 'Cache-Control': 'no-store',+ } });+ }const size = statSync(a.storedPath).size;const headers: Record<string, string> = {'Content-Type': a.mime,@@ -82,9 +104,18 @@ artifacts.post('/api/artifacts/:id/export', async (c) => {if (!isLoopbackRequest(c)) return c.json({ error: 'Saving to a folder only works on the computer Mercury runs on. Use Download instead.' }, 403);const a = artifactStore().get(c.req.param('id'));if (!a || !existsSync(a.storedPath)) return c.json({ error: 'Not found' }, 404);- const body = (await c.req.json().catch(() => ({}))) as { dest?: unknown };+ const body = (await c.req.json().catch(() => ({}))) as { dest?: unknown; as?: unknown };const dest = typeof body.dest === 'string' ? body.dest : '';if (!dest || !isAbsolute(dest) || !existsSync(dirname(dest))) return c.json({ error: 'Choose a folder that exists.' }, 400);+ const as = asFormat(body.as);+ if (body.as !== undefined && !as) return c.json({ error: 'as must be pdf or docx' }, 400);+ if (as) {+ if (!canConvert(a)) return c.json({ error: 'Only Markdown and text can be exported as a document.' }, 415);+ try { writeFileSync(dest, convertFile(a.storedPath, a.name, as)); } catch (err) {+ return c.json({ error: `Couldn't make the ${as === 'pdf' ? 'PDF' : 'Word document'}: ${err instanceof Error ? err.message : String(err)}` }, 500);+ }+ return c.json({ ok: true, path: dest });+ }copyFileSync(a.storedPath, dest);return c.json({ ok: true, path: dest });});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex d4cfae79..2ee30ffa 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -2,6 +2,7 @@ import { Hono } from 'hono';import { commandCatalog } from '../../core/commands/catalog.js';import { getPluginManager } from '../../plugins/manager.js';import { artifactStore } from '../../artifacts/store.js';+import { favicons } from '../favicons.js';import { scopedProgrammingState } from '../../core/programming-mode.js';import { isInsideWorkspace } from './workspace-ide.js';import { storeInlineAttachments, attachmentRefs, resolveUploadRef, uploadMime } from './uploads.js';@@ -796,6 +797,19 @@ chat.post('/api/chat/threads/:id/research/off', (c) => {return c.json({ ok: true });});+// A site's icon for the source lists (fetched and cached by the runtime; the apps load nothing from third parties).+chat.get('/api/chat/favicon', async (c) => {+ const icon = await favicons().get(c.req.query('domain') ?? '');+ if (!icon) return c.body(null, 204, { 'Cache-Control': 'private, max-age=86400' });+ return new Response(new Uint8Array(icon.bytes), { status: 200, headers: {+ 'Content-Type': icon.mime,+ 'Cache-Control': 'private, max-age=604800',+ // An SVG opened on its own can't run anything.+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'",+ 'X-Content-Type-Options': 'nosniff',+ } });+});+// The owner's answer to a research plan: { action: 'start' | 'cancel', questions?: string[] }.chat.post('/api/chat/research/plan/:id', async (c) => {if (!webChannel) return c.json({ error: 'Web channel not initialized' }, 503);diff --git a/src/web/favicons.test.ts b/src/web/favicons.test.tsnew file mode 100644index 00000000..4091c09b--- /dev/null+++ b/src/web/favicons.test.ts@@ -0,0 +1,62 @@+import { mkdtempSync, rmSync, writeFileSync, utimesSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';+import { FaviconCache, iconDomain, imageMime } from './favicons.js';++const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(200)]);+const dirs: string[] = [];+const dir = () => { const d = mkdtempSync(join(tmpdir(), 'fav-')); dirs.push(d); return d; };+afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); });++describe('site icons', () => {+ it('only public domain names are asked for', () => {+ expect(iconDomain('WWW.BBC.co.uk.')).toBe('www.bbc.co.uk');+ for (const bad of ['localhost', '127.0.0.1', '10.0.0.1', 'a.b/../etc', 'evil.com/x', 'x', '', '::1', 'http://a.com']) expect(iconDomain(bad)).toBeNull();+ });++ it('keeps only real images', () => {+ expect(imageMime(PNG)).toBe('image/png');+ expect(imageMime(Buffer.from([0, 0, 1, 0, 1, 0]))).toBe('image/x-icon');+ expect(imageMime(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>'))).toBe('image/svg+xml');+ expect(imageMime(Buffer.from('<!doctype html><html>'))).toBeNull();+ });++ it("tries the site, then the icon service, and caches the answer either way", async () => {+ const asked: string[] = [];+ const cache = new FaviconCache(dir(), async (url) => { asked.push(url); return url.includes('duckduckgo') ? PNG : null; });+ expect(await cache.get('example.org')).toMatchObject({ mime: 'image/png' });+ expect(asked).toEqual(['https://example.org/favicon.ico', 'https://icons.duckduckgo.com/ip3/example.org.ico']);+ await cache.get('example.org');+ expect(asked).toHaveLength(2);+ });++ it('remembers "no icon" for a while, then asks again', async () => {+ const d = dir();+ let calls = 0;+ const cache = new FaviconCache(d, async () => { calls++; return null; });+ expect(await cache.get('none.example')).toBeNull();+ expect(await cache.get('none.example')).toBeNull();+ expect(calls).toBe(2); // site + service, once+ const old = (Date.now() - 8 * 24 * 3600_000) / 1000;+ utimesSync(join(d, 'none.example.none'), old, old);+ await cache.get('none.example');+ expect(calls).toBe(4);+ });++ it('one fetch for many screens asking at once; bad domains never fetch', async () => {+ let calls = 0;+ const cache = new FaviconCache(dir(), async () => { calls++; await new Promise((r) => setTimeout(r, 10)); return PNG; });+ await Promise.all([cache.get('a.example'), cache.get('a.example'), cache.get('a.example')]);+ expect(calls).toBe(1);+ expect(await cache.get('127.0.0.1')).toBeNull();+ expect(calls).toBe(1);+ });++ it('a cached file that is not an image is fetched again', async () => {+ const d = dir();+ writeFileSync(join(d, 'x.example.icon'), '<html>');+ const cache = new FaviconCache(d, async () => PNG);+ expect(await cache.get('x.example')).toMatchObject({ mime: 'image/png' });+ });+});diff --git a/src/web/favicons.ts b/src/web/favicons.tsnew file mode 100644index 00000000..44076b2a--- /dev/null+++ b/src/web/favicons.ts@@ -0,0 +1,102 @@+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { getMercuryHome } from '../utils/config.js';+import { guardedFetch } from '../utils/ssrf.js';++/**+ * Site icons for the apps' source lists, fetched by the runtime so the apps+ * themselves never load anything from a third party. Asked for by domain;+ * the site's own /favicon.ico first (the site was already visited by the+ * research), then DuckDuckGo's icon service for sites that only declare an+ * icon in their HTML. Cached on disk: an icon for 30 days, "no icon" for 7.+ * Only real images are kept and served; anything else is "no icon".+ */++const ICON_TTL_MS = 30 * 24 * 3600_000;+const MISS_TTL_MS = 7 * 24 * 3600_000;+const MAX_BYTES = 100_000;+const TIMEOUT_MS = 5_000;++const DOMAIN = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;++/** A plain public host name ("www.bbc.co.uk"), lowercased, or null. IP addresses and "localhost" are not domains here. */+export function iconDomain(raw: string): string | null {+ const d = raw.trim().toLowerCase().replace(/\.$/, '');+ return DOMAIN.test(d) ? d : null;+}++/** What kind of image the bytes are, or null when they aren't one. */+export function imageMime(buf: Buffer): string | null {+ if (buf.length < 4) return null;+ if (buf[0] === 0x89 && buf.subarray(1, 4).toString('latin1') === 'PNG') return 'image/png';+ if (buf[0] === 0 && buf[1] === 0 && buf[2] === 1 && buf[3] === 0) return 'image/x-icon';+ if (buf.subarray(0, 3).toString('latin1') === 'GIF') return 'image/gif';+ if (buf[0] === 0xff && buf[1] === 0xd8) return 'image/jpeg';+ if (buf.subarray(0, 4).toString('latin1') === 'RIFF' && buf.subarray(8, 12).toString('latin1') === 'WEBP') return 'image/webp';+ const head = buf.subarray(0, 300).toString('utf-8').trimStart().toLowerCase();+ if (head.startsWith('<svg') || (head.startsWith('<?xml') && head.includes('<svg'))) return 'image/svg+xml';+ return null;+}++async function fetchIcon(url: string): Promise<Buffer | null> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);+ try {+ const resp = await guardedFetch(url, controller.signal, { 'User-Agent': 'Mercury', Accept: 'image/*' });+ if (!resp.ok) { void resp.body?.cancel(); return null; }+ const declared = Number(resp.headers.get('content-length') ?? 0);+ if (declared > MAX_BYTES) { void resp.body?.cancel(); return null; }+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length === 0 || buf.length > MAX_BYTES || !imageMime(buf)) return null;+ // DuckDuckGo's placeholder for "no icon" is a tiny generic image: count it as none.+ if (url.includes('icons.duckduckgo.com') && buf.length < 120) return null;+ return buf;+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}++const inFlight = new Map<string, Promise<{ bytes: Buffer; mime: string } | null>>();++export class FaviconCache {+ constructor(private readonly dir = join(getMercuryHome(), 'cache', 'favicons'), private readonly fetcher: (url: string) => Promise<Buffer | null> = fetchIcon) {}++ /** The icon for a domain, or null when it has none (or isn't a public domain). */+ get(rawDomain: string, now = Date.now()): Promise<{ bytes: Buffer; mime: string } | null> {+ const domain = iconDomain(rawDomain);+ if (!domain) return Promise.resolve(null);+ const icon = join(this.dir, `${domain}.icon`);+ const miss = join(this.dir, `${domain}.none`);+ try {+ if (existsSync(icon) && now - statSync(icon).mtimeMs < ICON_TTL_MS) {+ const bytes = readFileSync(icon);+ const mime = imageMime(bytes);+ if (mime) return Promise.resolve({ bytes, mime });+ }+ if (existsSync(miss) && now - statSync(miss).mtimeMs < MISS_TTL_MS) return Promise.resolve(null);+ } catch { /* fetch again */ }+ const key = `${this.dir}:${domain}`;+ let pending = inFlight.get(key);+ if (!pending) {+ pending = (async () => {+ const bytes = (await this.fetcher(`https://${domain}/favicon.ico`)) ?? (await this.fetcher(`https://icons.duckduckgo.com/ip3/${domain}.ico`));+ try {+ mkdirSync(this.dir, { recursive: true });+ writeFileSync(bytes ? icon : miss, bytes ?? '');+ } catch { /* serve it anyway */ }+ const mime = bytes ? imageMime(bytes) : null;+ return bytes && mime ? { bytes, mime } : null;+ })().finally(() => inFlight.delete(key));+ inFlight.set(key, pending);+ }+ return pending;+ }+}++let shared: FaviconCache | null = null;+export function favicons(): FaviconCache {+ shared ??= new FaviconCache();+ return shared;+}