Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(artifacts): keep what Mercury makes, linked to its conversation

Salman Qureshib65bd291a1f7
diff --git a/src/artifacts/artifacts.test.ts b/src/artifacts/artifacts.test.ts
new file mode 100644
index 00000000..96bba33b
--- /dev/null
+++ b/src/artifacts/artifacts.test.ts
@@ -0,0 +1,115 @@
+import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, it } from 'vitest';
+import { classifyArtifact, type ClassifyContext } from './classify.js';
+import { ArtifactCollector, pathsIn } from './collector.js';
+import { ArtifactStore } from './store.js';
+
+const HOME = '/Users/me/.mercury';
+const chat = (over: Partial<ClassifyContext> = {}): ClassifyContext => ({ surface: 'chat', cwd: '/Users/me', mercuryHome: HOME, how: 'written', isNew: true, size: 5000, ...over });
+const code = (over: Partial<ClassifyContext> = {}): ClassifyContext => chat({ surface: 'code', cwd: '/Users/me/proj', ...over });
+
+describe('what counts as an artifact', () => {
+ it('chat: new media, PDFs, documents and real notes count', () => {
+ expect(classifyArtifact('/Users/me/Desktop/chart.png', chat())).toBe('image');
+ expect(classifyArtifact('/Users/me/Movies/teaser.mp4', chat())).toBe('video');
+ expect(classifyArtifact('/Users/me/Documents/report.pdf', chat())).toBe('pdf');
+ expect(classifyArtifact('/Users/me/Documents/deck.pptx', chat())).toBe('document');
+ expect(classifyArtifact('/Users/me/notes/research.md', chat())).toBe('text');
+ });
+
+ it('never: code, config, edits of old files, tiny notes, hidden files, build or dependency folders, Mercury\'s own state', () => {
+ expect(classifyArtifact('/Users/me/script.py', chat())).toBeNull();
+ expect(classifyArtifact('/Users/me/config.json', chat())).toBeNull();
+ expect(classifyArtifact('/Users/me/Documents/report.pdf', chat({ isNew: false }))).toBeNull();
+ expect(classifyArtifact('/Users/me/todo.txt', chat({ size: 40 }))).toBeNull();
+ expect(classifyArtifact('/Users/me/.hidden.png', chat())).toBeNull();
+ expect(classifyArtifact('/Users/me/app/node_modules/x/logo.png', chat())).toBeNull();
+ expect(classifyArtifact('/Users/me/app/dist/out.pdf', chat())).toBeNull();
+ expect(classifyArtifact(`${HOME}/plugins/optimus/data/shot.png`, chat())).toBeNull();
+ expect(classifyArtifact(`${HOME}/workspace/chart.png`, chat())).toBe('image');
+ expect(classifyArtifact('/Users/me/icon.svg', chat({ size: 900 }))).toBeNull();
+ });
+
+ it('the system temp folder: generated media counts, scratch text and a project tmp/ don\'t', () => {
+ expect(classifyArtifact('/tmp/generated-cat.png', chat())).toBe('image');
+ expect(classifyArtifact(join(tmpdir(), 'mercury-gen', 'clip.mp4'), chat())).toBe('video');
+ expect(classifyArtifact('/private/tmp/x/tea-research.md', chat())).toBe('text');
+ expect(classifyArtifact('/tmp/page-dump.txt', chat())).toBeNull();
+ expect(classifyArtifact('/tmp/build/out.png', chat())).toBeNull();
+ expect(classifyArtifact('/Users/me/app/tmp/render.png', chat())).toBeNull();
+ });
+
+ it('code: project files never count, written-for-you reports do', () => {
+ expect(classifyArtifact('/Users/me/proj/src/index.ts', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/proj/public/logo.png', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/proj/README.md', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/proj/docs/api.md', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/proj/notes.md', code())).toBe('text');
+ expect(classifyArtifact('/Users/me/proj/CHANGELOG.md', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/proj/research/perf-analysis.md', code())).toBe('text');
+ expect(classifyArtifact('/Users/me/proj/security-report.pdf', code())).toBe('pdf');
+ expect(classifyArtifact('/Users/me/proj/screenshot.png', code())).toBeNull();
+ expect(classifyArtifact('/Users/me/Desktop/benchmark-chart.png', code())).toBe('image');
+ });
+
+ it('sent to the owner always counts; seen in output, loose text doesn\'t', () => {
+ expect(classifyArtifact('/Users/me/proj/src/index.ts', code({ how: 'sent', isNew: false }))).toBe('file');
+ expect(classifyArtifact('/Users/me/Documents/old.pdf', chat({ how: 'sent', isNew: false }))).toBe('pdf');
+ expect(classifyArtifact('/Users/me/out/log.txt', chat({ how: 'mentioned' }))).toBeNull();
+ expect(classifyArtifact('/Users/me/Movies/clip.mp4', chat({ how: 'mentioned' }))).toBe('video');
+ expect(classifyArtifact('/Users/me/app/out/clip.mp4', chat({ how: 'mentioned' }))).toBeNull(); // build output
+ });
+
+ it('finds paths in commands and output, quoted, escaped or relative', () => {
+ const found = pathsIn('ffmpeg -i in.mov -vf scale=1280:-1 "/Users/me/Movies/My Clip.mp4" && echo saved ./out/chart.png; cat x.ts', '/Users/me', { relative: true });
+ expect(found).toContain('/Users/me/Movies/My Clip.mp4');
+ expect(found).toContain('/Users/me/out/chart.png');
+ expect(found.some((p) => p.endsWith('x.ts'))).toBe(false);
+ expect(found).not.toContain('/out/chart.png');
+ });
+});
+
+describe('collecting a turn\'s artifacts', () => {
+ it('keeps what the turn made, skips old files and code, and deletes with the thread', () => {
+ const root = mkdtempSync(join(tmpdir(), 'mercury-art-'));
+ const work = join(root, 'work');
+ mkdirSync(work);
+ const old = join(work, 'old-report.pdf');
+ writeFileSync(old, 'x'.repeat(2000));
+ const past = (Date.now() - 3_600_000) / 1000;
+ utimesSync(old, past, past);
+ const store = new ArtifactStore(join(root, 'mercury', 'artifacts'));
+ const c = new ArtifactCollector({ startedAt: Date.now() - 1000, cwd: work, surface: 'chat', mercuryHome: join(root, 'mercury') });
+ writeFileSync(join(work, 'chart.png'), Buffer.alloc(4000, 1));
+ writeFileSync(join(work, 'research-notes.md'), '# Notes\n' + 'finding '.repeat(80));
+ writeFileSync(join(work, 'helper.py'), 'print(1)\n'.repeat(50));
+ c.observe('create_file', { path: 'research-notes.md' }, 'Created research-notes.md');
+ c.observe('write_file', { path: 'helper.py' }, 'ok');
+ c.observe('run_command', { command: 'python helper.py' }, `Saved chart to ${join(work, 'chart.png')}\nAlso see ${old}`);
+ const kept = c.finalize('thread-1', store);
+ expect(kept.map((a) => a.name).sort()).toEqual(['chart.png', 'research-notes.md']);
+ const list = store.list({ threadId: 'thread-1' });
+ expect(list.counts).toMatchObject({ all: 2, image: 1, text: 1 });
+ expect(store.list({ kind: 'image' }).items[0].name).toBe('chart.png');
+ expect(store.removeThread('thread-1')).toBe(2);
+ expect(store.list().items).toHaveLength(0);
+ });
+
+ it('pages newest first and sweeps threads that no longer exist', () => {
+ const root = mkdtempSync(join(tmpdir(), 'mercury-art-'));
+ const store = new ArtifactStore(join(root, 'artifacts'));
+ for (let i = 0; i < 5; i++) {
+ const f = join(root, `img-${i}.png`);
+ writeFileSync(f, Buffer.alloc(100 + i, 1));
+ store.add({ threadId: i < 3 ? 'keep' : 'gone', path: f, kind: 'image' }, 1000 + i);
+ }
+ const p1 = store.list({ limit: 2 });
+ expect(p1.items.map((a) => a.name)).toEqual(['img-4.png', 'img-3.png']);
+ const p2 = store.list({ limit: 2, cursor: p1.nextCursor! });
+ expect(p2.items.map((a) => a.name)).toEqual(['img-2.png', 'img-1.png']);
+ expect(store.reconcile((id) => id === 'keep')).toBe(2);
+ expect(store.list().counts.all).toBe(3);
+ });
+});
diff --git a/src/artifacts/classify.ts b/src/artifacts/classify.ts
new file mode 100644
index 00000000..a6ac2033
--- /dev/null
+++ b/src/artifacts/classify.ts
@@ -0,0 +1,118 @@
+import { tmpdir } from 'node:os';
+import { basename, extname, isAbsolute, relative, sep } from 'node:path';
+
+/**
+ * What counts as an artifact: a deliverable Mercury made for the owner,
+ * worth keeping and showing (an image, a video, a PDF, a report), never a
+ * by-product (code, config, caches, build output, a project's own assets).
+ * Strict on purpose: a false artifact is noise in every chat.
+ */
+
+export type ArtifactKind = 'image' | 'video' | 'audio' | 'pdf' | 'document' | 'text' | 'file';
+
+const EXT: Record<string, Exclude<ArtifactKind, 'file'>> = {
+ png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', webp: 'image', heic: 'image', avif: 'image', bmp: 'image', tiff: 'image', svg: 'image',
+ mp4: 'video', mov: 'video', webm: 'video', mkv: 'video', m4v: 'video', avi: 'video',
+ mp3: 'audio', wav: 'audio', m4a: 'audio', ogg: 'audio', flac: 'audio', aac: 'audio', opus: 'audio',
+ pdf: 'pdf',
+ docx: 'document', doc: 'document', pptx: 'document', ppt: 'document', xlsx: 'document', xls: 'document', odt: 'document', ods: 'document', odp: 'document', key: 'document', pages: 'document', numbers: 'document', epub: 'document', csv: 'document',
+ md: 'text', markdown: 'text', txt: 'text',
+};
+
+export const MIME: Record<string, string> = {
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', heic: 'image/heic', avif: 'image/avif', bmp: 'image/bmp', tiff: 'image/tiff', svg: 'image/svg+xml',
+ mp4: 'video/mp4', mov: 'video/quicktime', webm: 'video/webm', mkv: 'video/x-matroska', m4v: 'video/mp4', avi: 'video/x-msvideo',
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac', aac: 'audio/aac', opus: 'audio/opus',
+ pdf: 'application/pdf',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', doc: 'application/msword',
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', ppt: 'application/vnd.ms-powerpoint',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', xls: 'application/vnd.ms-excel',
+ odt: 'application/vnd.oasis.opendocument.text', ods: 'application/vnd.oasis.opendocument.spreadsheet', odp: 'application/vnd.oasis.opendocument.presentation',
+ epub: 'application/epub+zip', csv: 'text/csv', md: 'text/markdown', markdown: 'text/markdown', txt: 'text/plain',
+};
+
+export function extOf(path: string): string {
+ return extname(path).slice(1).toLowerCase();
+}
+
+export function mimeOf(path: string): string {
+ return MIME[extOf(path)] ?? 'application/octet-stream';
+}
+
+/** Folders whose contents are never artifacts: dependencies, build output, caches, VCS, Mercury's own state. */
+const NEVER_UNDER = new Set(['node_modules', '.git', '.hg', '.svn', 'dist', 'build', 'out', 'target', '.next', '.nuxt', '.turbo', '.cache', 'cache', '__pycache__', '.venv', 'venv', 'coverage', '.idea', '.vscode', 'tmp', '.tmp', 'Library', 'DerivedData', 'Pods', '.gradle', 'vendor']);
+/** Inside a project, these hold the project's own assets (a favicon, a logo), not deliverables. */
+const PROJECT_ASSET_DIRS = new Set(['public', 'assets', 'static', 'src', 'app', 'lib', 'components', 'images', 'img', 'icons', 'fonts', 'res', 'resources', 'test', 'tests', '__tests__', 'fixtures', 'docs', 'packages', 'apps', 'examples', 'scripts', 'bin']);
+/** Project files that are never deliverables even when written. */
+const PROJECT_DOCS = /^(readme|changelog|changes|license|licence|contributing|code_of_conduct|security|authors|notice|todo|agents|claude|gemini|copilot-instructions|history|roadmap|decisions|architecture)(\.[a-z]+)?$/i;
+/** Names that read like a deliverable written for the owner. */
+const DELIVERABLE_NAME = /(report|research|summary|summar|notes|analysis|findings|brief|overview|comparison|compare|review|study|digest|proposal|outline|memo|article|guide|plan)/i;
+
+export interface ClassifyContext {
+ /** 'code' when the turn ran in Mercury Code (a project), else 'chat'. */
+ surface: 'chat' | 'code';
+ /** The project folder for Code turns (and the working folder otherwise). */
+ cwd: string;
+ /** Mercury's home (~/.mercury): its own files are never artifacts, except its artifact store. */
+ mercuryHome: string;
+ /** How the file reached the owner: 'sent' (send_file: always a deliverable), 'written' (a file tool), 'mentioned' (seen in a command's output). */
+ how: 'sent' | 'written' | 'mentioned';
+ /** The file is new in this turn (created, not an edit of an older file). */
+ isNew: boolean;
+ size: number;
+}
+
+function inside(child: string, parent: string): boolean {
+ const rel = relative(parent, child);
+ return !!rel && !rel.startsWith('..') && !isAbsolute(rel);
+}
+
+/** System temp folders: where generated media often lands before it's sent. */
+const TEMP_ROOTS = [...new Set([tmpdir(), '/tmp', '/private/tmp', '/var/tmp', '/private/var/tmp'])];
+
+function tempRoot(path: string): string | null {
+ return TEMP_ROOTS.find((root) => inside(path, root)) ?? null;
+}
+
+/** The kind of artifact this file is, or null when it isn't one. */
+export function classifyArtifact(path: string, ctx: ClassifyContext): ArtifactKind | null {
+ const name = basename(path);
+ const ext = extOf(path);
+ const kind = EXT[ext];
+ if (ctx.size <= 0 || ctx.size > 2 * 1024 ** 3) return null;
+ if (name.startsWith('.') || name.startsWith('~$')) return null;
+ // Folder rules apply below the system temp folder, not to it ("tmp" means a project's tmp/).
+ const temp = tempRoot(path);
+ const parts = (temp ? relative(temp, path) : path).split(sep);
+ if (parts.some((p) => NEVER_UNDER.has(p))) return null;
+ if (inside(path, ctx.mercuryHome) && !inside(path, `${ctx.mercuryHome}${sep}artifacts`) && !inside(path, `${ctx.mercuryHome}${sep}workspace`) && !inside(path, `${ctx.mercuryHome}${sep}outputs`)) return null;
+
+ // Sent to the owner on purpose: a deliverable, whatever its type (code files sent stay plain files).
+ if (ctx.how === 'sent') return kind ?? 'file';
+ if (!kind) return null;
+ // An old file Mercury touched isn't something it made.
+ if (!ctx.isNew) return null;
+ if (kind === 'text') {
+ if (ctx.size < 300) return null;
+ if (PROJECT_DOCS.test(name)) return null;
+ }
+ // Seen only in a command's output: media and documents count, loose text doesn't.
+ if (ctx.how === 'mentioned' && kind === 'text') return null;
+ // Text in a temp folder is usually scratch (a scrape, a draft) unless it's named like a deliverable.
+ if (temp && kind === 'text' && !DELIVERABLE_NAME.test(name)) return null;
+
+ if (ctx.surface === 'code' && inside(path, ctx.cwd)) {
+ // In a project, only a written-for-you report counts: a PDF, Markdown or text
+ // deliverable at the root or in a reports/research folder, named like one.
+ const rel = relative(ctx.cwd, path).split(sep);
+ const top = rel.length > 1 ? rel[0].toLowerCase() : '';
+ if (rel.some((p, i) => i < rel.length - 1 && PROJECT_ASSET_DIRS.has(p.toLowerCase()))) return null;
+ const deliverableDir = top === '' || /^(reports?|research|notes|output|outputs|artifacts|deliverables)$/.test(top);
+ if (!deliverableDir) return null;
+ if (kind === 'pdf' || kind === 'text' || kind === 'document') return DELIVERABLE_NAME.test(name) ? kind : null;
+ // Media at a project's root or reports folder is a project file unless it's clearly output.
+ return top === '' ? null : kind;
+ }
+ if (kind === 'image' && ext === 'svg' && ctx.size < 2048) return null; // icons
+ return kind;
+}
diff --git a/src/artifacts/collector.ts b/src/artifacts/collector.ts
new file mode 100644
index 00000000..db90feaa
--- /dev/null
+++ b/src/artifacts/collector.ts
@@ -0,0 +1,106 @@
+import { existsSync, realpathSync, statSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { isAbsolute, join, resolve } from 'node:path';
+import { classifyArtifact, extOf } from './classify.js';
+import type { Artifact, ArtifactStore } from './store.js';
+
+/**
+ * Watches one turn for files that might be artifacts, then keeps the ones
+ * that are. Candidates come from:
+ * send_file sent to the owner: always a deliverable
+ * write_file / create_file written by Mercury
+ * run_command, other tools paths in the command or its output that were
+ * made during this turn (ffmpeg, a chart script,
+ * an image plugin)
+ * Nothing is decided until the turn ends: a file written then deleted, or
+ * overwritten by a later step, is judged by what's on disk at the end.
+ */
+
+const ARTIFACT_EXT = 'png|jpe?g|gif|webp|heic|avif|bmp|tiff|svg|mp4|mov|webm|mkv|m4v|avi|mp3|wav|m4a|ogg|flac|aac|opus|pdf|docx?|pptx?|xlsx?|odt|ods|odp|key|pages|numbers|epub|csv|md|markdown|txt';
+// An absolute path starts a token (after a space, quote, = or bracket), never mid-word ("./out/x.png" isn't "/out/x.png").
+const ABS_PATH = new RegExp(`(?<=^|[\\s'"=(:\\[])(?:~|/)(?:[^\\s'"\`<>|;,()\\[\\]{}]|\\\\ )+\\.(?:${ARTIFACT_EXT})(?=$|[\\s'"\`<>|;,()\\]\\[.:!?])`, 'gi');
+/** Quoted paths may contain spaces: "/Users/me/Movies/My Clip.mp4". */
+const QUOTED_PATH = new RegExp(`(["'])((?:~|/)[^"'\\n]+?\\.(?:${ARTIFACT_EXT}))\\1`, 'gi');
+const REL_PATH = new RegExp(`(?:^|[\\s'"=])((?:\\./)?[\\w@][\\w.@/-]*\\.(?:${ARTIFACT_EXT}))(?=$|[\\s'"\`;,)])`, 'gi');
+
+type How = 'sent' | 'written' | 'mentioned';
+const RANK: Record<How, number> = { sent: 3, written: 2, mentioned: 1 };
+
+export interface TurnContext {
+ startedAt: number;
+ cwd: string;
+ surface: 'chat' | 'code';
+ mercuryHome: string;
+}
+
+function expand(p: string, cwd: string): string {
+ const unescaped = p.replace(/\\ /g, ' ');
+ if (unescaped.startsWith('~/')) return join(homedir(), unescaped.slice(2));
+ return isAbsolute(unescaped) ? resolve(unescaped) : resolve(cwd, unescaped);
+}
+
+/** Paths with artifact extensions in free text (a command line or a tool's output). */
+export function pathsIn(text: string, cwd: string, opts: { relative: boolean }): string[] {
+ const out = new Set<string>();
+ for (const m of text.matchAll(QUOTED_PATH)) out.add(expand(m[2], cwd));
+ for (const m of text.matchAll(ABS_PATH)) out.add(expand(m[0], cwd));
+ if (opts.relative) for (const m of text.matchAll(REL_PATH)) out.add(expand(m[1], cwd));
+ return [...out].slice(0, 40);
+}
+
+export class ArtifactCollector {
+ private candidates = new Map<string, { how: How; tool: string }>();
+ constructor(private readonly ctx: TurnContext) {}
+
+ private add(path: string, how: How, tool: string): void {
+ if (!path || !extOf(path) && how !== 'sent') return;
+ const prev = this.candidates.get(path);
+ if (!prev || RANK[how] > RANK[prev.how]) this.candidates.set(path, { how, tool });
+ }
+
+ observe(tool: string, input: unknown, result: unknown, cwd = this.ctx.cwd): void {
+ try {
+ const args = (input ?? {}) as Record<string, unknown>;
+ const text = typeof result === 'string' ? result : JSON.stringify(result ?? '');
+ if (tool === 'send_file' && typeof args.path === 'string') this.add(expand(args.path, cwd), 'sent', tool);
+ else if ((tool === 'write_file' || tool === 'create_file') && typeof args.path === 'string') {
+ if (!/^(Error|⚠)/.test(text.trim())) this.add(expand(args.path, cwd), 'written', tool);
+ } else if (tool === 'run_command') {
+ const cmd = typeof args.command === 'string' ? args.command : '';
+ for (const p of pathsIn(`${cmd}\n${text.slice(0, 20_000)}`, cwd, { relative: true })) this.add(p, 'mentioned', tool);
+ } else if (!/^(read_file|list_dir|edit_file|delete_file|git_|web_search|fetch_url|search_memory|save_memory)/.test(tool)) {
+ // Plugins and MCP servers (an image generator, a screen recorder): absolute paths in what they return.
+ for (const p of pathsIn(text.slice(0, 20_000), cwd, { relative: false })) this.add(p, 'mentioned', tool);
+ }
+ } catch { /* watching must never break a turn */ }
+ }
+
+ get size(): number {
+ return this.candidates.size;
+ }
+
+ /** Judge every candidate as it is now, keep the artifacts in the store, and return them. */
+ finalize(threadId: string, store: ArtifactStore): Artifact[] {
+ const kept: Artifact[] = [];
+ const seen = new Set<string>();
+ const since = this.ctx.startedAt - 2000;
+ for (const [path, { how, tool }] of this.candidates) {
+ try {
+ if (!existsSync(path)) continue;
+ const real = realpathSync(path);
+ if (seen.has(real)) continue;
+ seen.add(real);
+ const st = statSync(real);
+ if (!st.isFile()) continue;
+ // "New in this turn": created now (birth time where the disk keeps it), else changed now.
+ const born = st.birthtimeMs > 0 ? st.birthtimeMs : st.mtimeMs;
+ const isNew = born >= since;
+ if (how === 'mentioned' && st.mtimeMs < since) continue;
+ const kind = classifyArtifact(real, { surface: this.ctx.surface, cwd: this.ctx.cwd, mercuryHome: this.ctx.mercuryHome, how, isNew, size: st.size });
+ if (!kind) continue;
+ kept.push(store.add({ threadId, path: real, kind, tool, surface: this.ctx.surface }));
+ } catch { /* one bad candidate never loses the others */ }
+ }
+ return kept;
+ }
+}
diff --git a/src/artifacts/ref.ts b/src/artifacts/ref.ts
new file mode 100644
index 00000000..2c887231
--- /dev/null
+++ b/src/artifacts/ref.ts
@@ -0,0 +1,21 @@
+import type { ArtifactKind } from './classify.js';
+import type { Artifact } from './store.js';
+
+/** What a message or an event carries about an artifact (never the stored path). */
+export interface ArtifactRef { id: string; name: string; kind: ArtifactKind; mime: string; size: number; path: string }
+
+export function artifactRef(a: Artifact): ArtifactRef {
+ return { id: a.id, name: a.name, kind: a.kind, mime: a.mime, size: a.size, path: a.originalPath };
+}
+
+const LABEL: Record<ArtifactKind, string> = { image: 'image', video: 'video', audio: 'audio', pdf: 'PDF', document: 'document', text: 'notes', file: 'file' };
+export function artifactKindLabel(kind: ArtifactKind): string {
+ return LABEL[kind];
+}
+
+export function formatBytes(n: number): string {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 ** 2) return `${Math.round(n / 1024)} KB`;
+ if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`;
+ return `${(n / 1024 ** 3).toFixed(2)} GB`;
+}
diff --git a/src/artifacts/store.ts b/src/artifacts/store.ts
new file mode 100644
index 00000000..f3f62552
--- /dev/null
+++ b/src/artifacts/store.ts
@@ -0,0 +1,146 @@
+import { randomUUID } from 'node:crypto';
+import { copyFileSync, existsSync, linkSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+import { type ArtifactKind, mimeOf } from './classify.js';
+
+/**
+ * Artifacts: deliverables Mercury made, kept with the conversation they came
+ * from. Each is Mercury's own copy (a hard link when the disk allows, so a
+ * big video isn't stored twice) under ~/.mercury/artifacts/<thread>/, so
+ * deleting the thread deletes them, and the owner's original file is never
+ * touched. One small index lists them all, newest first.
+ */
+
+export interface Artifact {
+ id: string;
+ threadId: string;
+ name: string;
+ kind: ArtifactKind;
+ mime: string;
+ size: number;
+ /** Where Mercury wrote it (may have moved or been deleted since). */
+ originalPath: string;
+ /** Mercury's copy, which the apps show and download. */
+ storedPath: string;
+ createdAt: number;
+ /** The tool that made or sent it. */
+ tool?: string;
+ /** "code" when it came from Mercury Code. */
+ surface?: 'chat' | 'code';
+}
+
+export interface ArtifactQuery { kind?: ArtifactKind | 'all'; q?: string; threadId?: string; cursor?: string; limit?: number }
+
+export class ArtifactStore {
+ private items: Artifact[] | null = null;
+ constructor(readonly root = join(getMercuryHome(), 'artifacts')) {}
+
+ private get indexPath(): string { return join(this.root, 'index.json'); }
+
+ private load(): Artifact[] {
+ if (this.items) return this.items;
+ try {
+ this.items = existsSync(this.indexPath) ? (JSON.parse(readFileSync(this.indexPath, 'utf-8')) as Artifact[]).filter((a) => a && a.id && a.threadId) : [];
+ } catch (err) {
+ logger.warn({ err: err instanceof Error ? err.message : String(err) }, 'Artifact index unreadable; starting a new one');
+ this.items = [];
+ }
+ return this.items;
+ }
+
+ private save(): void {
+ mkdirSync(this.root, { recursive: true });
+ const tmp = `${this.indexPath}.tmp`;
+ writeFileSync(tmp, JSON.stringify(this.load()), { encoding: 'utf-8', mode: 0o600 });
+ renameSync(tmp, this.indexPath);
+ }
+
+ /** Keep a copy of a file as an artifact of a thread. The same file twice in a thread is one artifact. */
+ add(input: { threadId: string; path: string; kind: ArtifactKind; tool?: string; surface?: 'chat' | 'code' }, now = Date.now()): Artifact {
+ const items = this.load();
+ const existing = items.find((a) => a.threadId === input.threadId && a.originalPath === input.path);
+ const st = statSync(input.path);
+ const id = existing?.id ?? randomUUID();
+ const dir = join(this.root, safe(input.threadId));
+ mkdirSync(dir, { recursive: true });
+ const storedPath = join(dir, `${id.slice(0, 8)}-${safe(basename(input.path))}`);
+ rmSync(storedPath, { force: true });
+ try { linkSync(input.path, storedPath); } catch { copyFileSync(input.path, storedPath); }
+ const record: Artifact = {
+ id, threadId: input.threadId, name: basename(input.path), kind: input.kind, mime: mimeOf(input.path), size: st.size,
+ originalPath: input.path, storedPath, createdAt: existing?.createdAt ?? now, tool: input.tool, surface: input.surface,
+ };
+ if (existing) items.splice(items.indexOf(existing), 1);
+ items.unshift(record);
+ this.save();
+ return record;
+ }
+
+ get(id: string): Artifact | null {
+ return this.load().find((a) => a.id === id) ?? null;
+ }
+
+ /** Newest first, filtered, a page at a time (cursor = the last id seen). */
+ list(query: ArtifactQuery = {}): { items: Artifact[]; nextCursor: string | null; counts: Record<string, number> } {
+ const q = (query.q ?? '').trim().toLowerCase();
+ const all = this.load().filter((a) => (!query.threadId || a.threadId === query.threadId) && (!q || a.name.toLowerCase().includes(q) || a.originalPath.toLowerCase().includes(q)));
+ const counts: Record<string, number> = { all: all.length };
+ for (const a of all) counts[a.kind] = (counts[a.kind] ?? 0) + 1;
+ const filtered = !query.kind || query.kind === 'all' ? all : all.filter((a) => a.kind === query.kind);
+ const start = query.cursor ? filtered.findIndex((a) => a.id === query.cursor) + 1 : 0;
+ const limit = Math.min(Math.max(query.limit ?? 40, 1), 200);
+ const items = filtered.slice(Math.max(0, start), Math.max(0, start) + limit);
+ const more = Math.max(0, start) + limit < filtered.length;
+ return { items, nextCursor: more ? items[items.length - 1]?.id ?? null : null, counts };
+ }
+
+ remove(id: string): boolean {
+ const items = this.load();
+ const a = items.find((x) => x.id === id);
+ if (!a) return false;
+ rmSync(a.storedPath, { force: true });
+ items.splice(items.indexOf(a), 1);
+ this.save();
+ return true;
+ }
+
+ /** The thread was deleted: its artifacts go too (Mercury's copies; the owner's originals stay). */
+ removeThread(threadId: string): number {
+ const items = this.load();
+ const gone = items.filter((a) => a.threadId === threadId);
+ if (!gone.length) return 0;
+ this.items = items.filter((a) => a.threadId !== threadId);
+ rmSync(join(this.root, safe(threadId)), { recursive: true, force: true });
+ this.save();
+ return gone.length;
+ }
+
+ /** Drop artifacts of threads that no longer exist, and records whose copy is missing. */
+ reconcile(threadExists: (id: string) => boolean): number {
+ const items = this.load();
+ let removed = 0;
+ for (const thread of new Set(items.map((a) => a.threadId))) {
+ if (!threadExists(thread)) removed += this.removeThread(thread);
+ }
+ const left = this.load();
+ const missing = left.filter((a) => !existsSync(a.storedPath));
+ if (missing.length) {
+ this.items = left.filter((a) => existsSync(a.storedPath));
+ this.save();
+ removed += missing.length;
+ }
+ return removed;
+ }
+}
+
+function safe(s: string): string {
+ return s.replace(/[^\w.-]+/g, '_').slice(0, 120) || 'file';
+}
+
+let shared: ArtifactStore | null = null;
+export function artifactStore(): ArtifactStore {
+ shared ??= new ArtifactStore();
+ return shared;
+}
diff --git a/src/channels/web.ts b/src/channels/web.ts
index cded1bf8..b10c1202 100644
--- a/src/channels/web.ts
+++ b/src/channels/web.ts
@@ -18,7 +18,7 @@ interface PendingInteraction {
}
export interface ChatEvent {
- type: 'thinking' | 'reasoning' | 'plan' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';
+ type: 'thinking' | 'reasoning' | 'plan' | 'artifacts' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';
data?: Record<string, unknown>;
}
@@ -339,6 +339,12 @@ export class WebChannel extends BaseChannel {
this.broadcast({ type: 'plan', data: { steps: plan.steps, updatedAt: plan.updatedAt, targetId } });
}
+ /** Artifacts this turn made (images, PDFs, reports…), for the conversation's live view. */
+ sendArtifacts(items: unknown[], targetId?: string): void {
+ if (!items.length) return;
+ this.broadcast({ type: 'artifacts', data: { items, targetId } });
+ }
+
sendStepDone(toolName: string, result: unknown, targetId?: string): void {
const summary = typeof result === 'string'
? result.slice(0, 200)
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 36c75719..cf01487c 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -14,6 +14,10 @@ import type { TokenBudget } from '../utils/tokens.js';
import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { ScheduledTaskManifest } from './scheduler.js';
import { DeepSeekProvider } from '../providers/deepseek.js';
+import { ArtifactCollector } from '../artifacts/collector.js';
+import { artifactStore, type Artifact } from '../artifacts/store.js';
+import { artifactKindLabel, artifactRef, formatBytes } from '../artifacts/ref.js';
+import { getMercuryHome } from '../utils/config.js';
import { createProvider } from '../providers/registry.js';
import type { BaseProvider } from '../providers/base.js';
import { Lifecycle } from './lifecycle.js';
@@ -1992,6 +1996,20 @@ export class Agent {
* Record the model's plan checklist (update_plan tool) into the TUI so the
* user sees which step is being implemented. Never throws.
*/
+ /** Tell the owner about this turn's artifacts: a card in the apps, a line in the terminal (it can't show them). */
+ private announceArtifacts(channel: any, items: Artifact[], targetId?: string): void {
+ try {
+ if (channel instanceof CLIChannel) {
+ const list = items.slice(0, 6).map((a) => `${a.name} (${artifactKindLabel(a.kind)}, ${formatBytes(a.size)})`).join(', ');
+ const more = items.length > 6 ? ` and ${items.length - 6} more` : '';
+ const where = items.length === 1 ? `\n ${items[0].originalPath}` : '';
+ channel.sendSystemNotice(`◆ ${items.length === 1 ? 'Artifact' : `${items.length} artifacts`}: ${list}${more}${where}\n Open them in Mercury Desktop → Artifacts.`);
+ } else if (typeof channel?.sendArtifacts === 'function') {
+ channel.sendArtifacts(items.map(artifactRef), targetId);
+ }
+ } catch { /* telling about artifacts must never break a turn */ }
+ }
+
private maybeRecordPlanProgress(channel: any, toolName: string, input: unknown, targetId?: string): void {
try {
if (toolName !== 'update_plan') return;
@@ -2922,6 +2940,13 @@ export class Agent {
// Compact per-turn tool trace, written to the session at turn end so
// the next turn's history carries what was read and written.
const turnToolTrace: string[] = [];
+ // Files this turn makes that are worth keeping (images, PDFs, reports…): artifacts of the conversation.
+ const artifactCollector = new ArtifactCollector({
+ startedAt: Date.now(),
+ cwd: this.capabilities.getCwd(),
+ surface: this.programmingMode.isActive() ? 'code' : 'chat',
+ mercuryHome: getMercuryHome(),
+ });
const noteToolSteps = (toolCalls: readonly any[] | undefined, toolResults: readonly any[] | undefined): void => {
if (!toolCalls || !toolResults) return;
for (let i = 0; i < toolCalls.length; i++) {
@@ -3059,6 +3084,7 @@ export class Agent {
recordExecuteToolResult(tc.toolName, trValue);
this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, trValue);
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
+ artifactCollector.observe(tc.toolName, tc.input, trValue, this.capabilities.getCwd());
const resultStr = typeof trValue === 'string' ? trValue : JSON.stringify(trValue ?? '');
const failed = resultStr.length < 5000 && (
resultStr.startsWith('Error:') ||
@@ -3313,6 +3339,7 @@ export class Agent {
recordExecuteToolResult(tc.toolName, toolResultValue(toolResults[i]));
this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, toolResultValue(toolResults[i]));
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
+ artifactCollector.observe(tc.toolName, tc.input, toolResultValue(toolResults[i]), this.capabilities.getCwd());
loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);
}
}
@@ -3917,6 +3944,7 @@ export class Agent {
}
this.maybeShowFileChange(channel, msg, tc.toolName, tc.input, guardToolResult);
this.maybeRecordPlanProgress(channel, tc.toolName, tc.input, msg.channelId);
+ artifactCollector.observe(tc.toolName, tc.input, guardToolResult, this.capabilities.getCwd());
loopDetector.record(tc.toolName, tc.input as Record<string, any>, false);
}
}
@@ -4229,6 +4257,11 @@ export class Agent {
}
}
+ // Keep this turn's artifacts with the conversation (Mercury's copies, deleted with the thread).
+ let turnArtifacts: Artifact[] = [];
+ if (canonicalSessionId && artifactCollector.size > 0) {
+ try { turnArtifacts = artifactCollector.finalize(canonicalSessionId, artifactStore()); } catch (err) { logger.warn({ err }, 'Keeping artifacts failed'); }
+ }
if (canonicalSessionId) {
if (turnToolTrace.length > 0) {
this.sessions.appendMessage(canonicalSessionId, {
@@ -4262,8 +4295,10 @@ export class Agent {
cachedInputTokens: result.usage?.cachedInputTokens ?? 0,
outputTokens: result.usage?.outputTokens ?? 0,
...(lastVerificationNote ? { verification: lastVerificationNote } : {}),
+ ...(turnArtifacts.length ? { artifacts: turnArtifacts.map(artifactRef) } : {}),
},
});
+ if (turnArtifacts.length && channel) this.announceArtifacts(channel, turnArtifacts, msg.channelId);
if (msg.channelType !== 'internal' && msg.senderId !== 'system' && usedProvider) {
this.scheduleSessionTitleGeneration(canonicalSessionId, usedProvider.name);
}
diff --git a/src/index.ts b/src/index.ts
index 21b9715b..16be05e9 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -103,6 +103,8 @@ import { spawnDetachedRestart } from './cli/daemon.js';
import { recordVoiceCalls } from './plugins/voice-calls.js';
import { setChannelRuntime } from './web/api/channels.js';
import { setSkillBuilder } from './web/api/system.js';
+import { setArtifactSessions } from './web/api/artifacts.js';
+import { artifactStore } from './artifacts/store.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken, initWebAuth } from './web/auth.js';
import { startLoopLagMonitor } from './utils/loop-lag.js';
import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';
@@ -2507,6 +2509,16 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
migrateLegacyMemory();
const shortTerm = new ShortTermMemory(config);
const sessions = new SessionRepository();
+ // Artifacts follow their thread: drop those whose thread is gone (deleted anywhere), now and every hour.
+ setArtifactSessions(sessions);
+ const sweepArtifacts = () => {
+ try {
+ const removed = artifactStore().reconcile((id) => { try { return sessions.get(id).status !== 'deleted'; } catch { return false; } });
+ if (removed) logger.info({ removed }, 'Removed artifacts of deleted threads');
+ } catch (err) { logger.warn({ err }, 'Artifact sweep failed'); }
+ };
+ sweepArtifacts();
+ setInterval(sweepArtifacts, 60 * 60_000).unref();
// Desktop voice calls are saved as chat threads, live.
recordVoiceCalls(sessions);
setWebSessions(sessions);
diff --git a/src/web/api-contract.ts b/src/web/api-contract.ts
index 8c13a61d..9f5603b9 100644
--- a/src/web/api-contract.ts
+++ b/src/web/api-contract.ts
@@ -40,6 +40,7 @@ export const API_FEATURES: readonly string[] = Object.freeze([
'chat.stop', // POST /api/chat/stop — interrupt the running turn (same as /stop)
'providers.manage', // GET /api/providers/settings, POST /api/providers/:id/check (live, unsaved), PUT /api/providers/roles; saves apply live; health.setupRequired
'voice.check',
+ 'artifacts', // GET /api/artifacts (paged), /:id, /:id/file (Range), POST /:id/export, DELETE /:id; SSE 'artifacts'; message.artifacts
'chat.plan', // SSE 'plan' { steps, updatedAt } + GET /api/chat/plan?sessionId= (the plan checklist)
'channels', // GET /api/channels, POST :type/check, PUT :type, POST :type/access, POST/GET signal/link
'transcribe', // GET/POST /api/transcribe — dictation: raw audio in, text out
diff --git a/src/web/api/artifacts-route.test.ts b/src/web/api/artifacts-route.test.ts
new file mode 100644
index 00000000..7740b9d5
--- /dev/null
+++ b/src/web/api/artifacts-route.test.ts
@@ -0,0 +1,46 @@
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, it, vi } from 'vitest';
+
+const home = await vi.hoisted(async () => {
+ const fs = await import('node:fs');
+ const os = await import('node:os');
+ const path = await import('node:path');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-artifacts-route-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+import artifacts from './artifacts.js';
+import { artifactStore } from '../../artifacts/store.js';
+
+describe('artifacts API', () => {
+ it('lists, serves (with ranges), exports and deletes; never exposes the stored path', async () => {
+ const f = join(home, 'clip.mp4');
+ writeFileSync(f, Buffer.from('0123456789abcdef'));
+ const a = artifactStore().add({ threadId: 't1', path: f, kind: 'video' });
+ const list = (await (await artifacts.request('http://127.0.0.1/api/artifacts?kind=video')).json()) as any;
+ expect(list.items[0]).toMatchObject({ id: a.id, name: 'clip.mp4', kind: 'video', threadExists: false });
+ expect(JSON.stringify(list)).not.toContain('storedPath');
+ expect(list.counts).toMatchObject({ all: 1, video: 1 });
+
+ const full = await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}/file`);
+ expect(full.headers.get('content-type')).toBe('video/mp4');
+ expect(await full.text()).toBe('0123456789abcdef');
+ const part = await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}/file`, { headers: { Range: 'bytes=4-7' } });
+ expect(part.status).toBe(206);
+ expect(await part.text()).toBe('4567');
+
+ const dest = join(home, 'saved-copy.mp4');
+ const req = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ dest }) };
+ const remote = await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}/export`, req, { incoming: { socket: { remoteAddress: '10.0.0.7' } } });
+ expect(remote.status).toBe(403);
+ const exp = await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}/export`, req, { incoming: { socket: { remoteAddress: '127.0.0.1' } } });
+ expect(exp.status).toBe(200);
+ expect(readFileSync(dest, 'utf-8')).toBe('0123456789abcdef');
+
+ expect((await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}`, { method: 'DELETE' })).status).toBe(200);
+ expect(existsSync(f)).toBe(true); // the original stays
+ expect((await artifacts.request(`http://127.0.0.1/api/artifacts/${a.id}/file`)).status).toBe(404);
+ });
+});
diff --git a/src/web/api/artifacts.ts b/src/web/api/artifacts.ts
new file mode 100644
index 00000000..b93c41e2
--- /dev/null
+++ b/src/web/api/artifacts.ts
@@ -0,0 +1,94 @@
+import { copyFileSync, createReadStream, existsSync, statSync } from 'node:fs';
+import { dirname, isAbsolute } from 'node:path';
+import { Readable } from 'node:stream';
+import { Hono } from 'hono';
+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';
+
+/**
+ * Artifacts: what Mercury made, by conversation.
+ *
+ * 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)
+ * DELETE /api/artifacts/:id forget one (Mercury's copy only)
+ */
+
+let sessions: SessionRepository | null = null;
+export function setArtifactSessions(repo: SessionRepository | null): void { sessions = repo; }
+
+const KINDS: Array<ArtifactKind | 'all'> = ['all', 'image', 'video', 'audio', 'pdf', 'document', 'text', 'file'];
+
+function withThread(a: Artifact) {
+ let threadTitle: string | null = null;
+ let threadExists = false;
+ try {
+ const s = sessions?.get(a.threadId);
+ if (s && s.status !== 'deleted') { threadTitle = s.title; threadExists = true; }
+ } catch { /* gone */ }
+ const { storedPath: _stored, ...rest } = a;
+ return { ...rest, threadTitle, threadExists, originalExists: existsSync(a.originalPath) };
+}
+
+const artifacts = new Hono();
+
+artifacts.get('/api/artifacts', (c) => {
+ const kind = c.req.query('kind') as ArtifactKind | 'all' | undefined;
+ const r = artifactStore().list({
+ kind: kind && KINDS.includes(kind) ? kind : 'all',
+ q: c.req.query('q') ?? undefined,
+ threadId: c.req.query('threadId') ?? undefined,
+ cursor: c.req.query('cursor') ?? undefined,
+ limit: Number(c.req.query('limit') ?? 40) || 40,
+ });
+ return c.json({ items: r.items.map(withThread), nextCursor: r.nextCursor, counts: r.counts });
+});
+
+artifacts.get('/api/artifacts/:id', (c) => {
+ const a = artifactStore().get(c.req.param('id'));
+ return a ? c.json({ artifact: withThread(a) }) : c.json({ error: 'Not found' }, 404);
+});
+
+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 size = statSync(a.storedPath).size;
+ const headers: Record<string, string> = {
+ 'Content-Type': a.mime,
+ 'Accept-Ranges': 'bytes',
+ 'Cache-Control': 'private, max-age=3600',
+ 'Content-Disposition': `${c.req.query('download') === '1' ? 'attachment' : 'inline'}; filename*=UTF-8''${encodeURIComponent(a.name)}`,
+ // SVG and HTML-ish content can't run anything when opened directly.
+ 'Content-Security-Policy': "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; media-src 'self'",
+ 'X-Content-Type-Options': 'nosniff',
+ };
+ const range = c.req.header('range');
+ const m = range ? /^bytes=(\d*)-(\d*)$/.exec(range) : null;
+ if (m && (m[1] || m[2])) {
+ const start = m[1] ? Number(m[1]) : Math.max(0, size - Number(m[2]));
+ const end = m[1] && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1;
+ if (start > end || start >= size) return new Response(null, { status: 416, headers: { 'Content-Range': `bytes */${size}` } });
+ const body = Readable.toWeb(createReadStream(a.storedPath, { start, end })) as unknown as ReadableStream;
+ return new Response(body, { status: 206, headers: { ...headers, 'Content-Range': `bytes ${start}-${end}/${size}`, 'Content-Length': String(end - start + 1) } });
+ }
+ const body = Readable.toWeb(createReadStream(a.storedPath)) as unknown as ReadableStream;
+ return new Response(body, { status: 200, headers: { ...headers, 'Content-Length': String(size) } });
+});
+
+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 dest = typeof body.dest === 'string' ? body.dest : '';
+ if (!dest || !isAbsolute(dest) || !existsSync(dirname(dest))) return c.json({ error: 'Choose a folder that exists.' }, 400);
+ copyFileSync(a.storedPath, dest);
+ return c.json({ ok: true, path: dest });
+});
+
+artifacts.delete('/api/artifacts/:id', (c) => (artifactStore().remove(c.req.param('id')) ? c.json({ ok: true }) : c.json({ error: 'Not found' }, 404)));
+
+export default artifacts;
diff --git a/src/web/api/chat.ts b/src/web/api/chat.ts
index 9f25de89..36f9a33b 100644
--- a/src/web/api/chat.ts
+++ b/src/web/api/chat.ts
@@ -1,4 +1,5 @@
import { Hono } from 'hono';
+import { artifactStore } from '../../artifacts/store.js';
import { scopedProgrammingState } from '../../core/programming-mode.js';
import { isInsideWorkspace } from './workspace-ide.js';
import { storeInlineAttachments, attachmentRefs, resolveUploadRef, uploadMime } from './uploads.js';
@@ -48,6 +49,7 @@ function toThread(session: ReturnType<SessionRepository['get']>, includeMessages
kind: message.kind,
sequence: message.sequence,
...(typeof message.metadata?.voiceRole === 'string' ? { voice: message.metadata.voiceRole } : {}),
+ ...(Array.isArray(message.metadata?.artifacts) && message.metadata.artifacts.length ? { artifacts: message.metadata.artifacts } : {}),
...(Array.isArray(message.metadata?.attachments) && message.metadata.attachments.length > 0
? { attachments: (message.metadata.attachments as Array<{ name: string; kind: string; mime?: string; ref: string }>).map((a) => ({ name: a.name, kind: a.kind, mime: a.mime, url: `/api/chat/uploads/${a.ref}` })) }
: {}),
@@ -684,7 +686,10 @@ chat.post('/api/chat/threads/:id/delete', async (c) => {
if (target.id !== id) return c.json({ error: 'Confirmation must use the exact session ID' }, 400);
const syncPending = sessionSyncEnabledFn?.() === true;
const deleted = syncPending ? sessions.markDeleted(target.id) : sessions.deletePermanently(target.id);
- return c.json({ deleted: true, sessionId: deleted.id, syncPending });
+ // Its artifacts go with it (Mercury's copies; the owner's original files stay).
+ let artifactsRemoved = 0;
+ try { artifactsRemoved = artifactStore().removeThread(target.id); } catch { /* the hourly sweep catches it */ }
+ return c.json({ deleted: true, sessionId: deleted.id, syncPending, artifactsRemoved });
} catch {
return c.json({ deleted: false, error: 'Thread not found' }, 404);
}
diff --git a/src/web/server.ts b/src/web/server.ts
index e6a59d7a..d64d157a 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -15,6 +15,7 @@ import providerRoutes from './api/providers.js';
import cloudRoutes from './api/cloud.js';
import transcribeRoutes from './api/transcribe.js';
import channelRoutes from './api/channels.js';
+import artifactRoutes from './api/artifacts.js';
import configRoutes from './api/config.js';
import systemRoutes, { setScheduler } from './api/system.js';
import brainRoutes, { setUserMemory } from './api/brain.js';
@@ -97,6 +98,7 @@ app.route('/', providerRoutes);
app.route('/', cloudRoutes);
app.route('/', transcribeRoutes);
app.route('/', channelRoutes);
+app.route('/', artifactRoutes);
app.route('/', configRoutes);
app.route('/', systemRoutes);
app.route('/', brainRoutes);