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(bots): bots take files too -- attachments ride the job (#231)

tournierjcd1b7894be402
diff --git a/DECISIONS.md b/DECISIONS.md
index c8a28bfe..ce359741 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1,3 +1,4 @@
+
## ADR-022: Operating a fleet — cost, runs, kill switch
- **Context**: ADR-020 and ADR-021 made bot behaviour bounded and legible in the journal, but the owner still had no view of where tokens went, no way to see what a run did without opening JSON files, no single stop, and a dead-letter queue full of pre-ADR-020 misclassified failures with no way to clear it. Onboarding presented the budget as optional.
@@ -308,3 +309,9 @@
- Password login from the app on every launch: no revocation per device, and the password would have to be stored.
- Exposing `/api/health` to unauthenticated remote peers for discovery: rejected; the runtime stays invisible (404) without a credential, and pairing returns the same contract fields.
- **Consequence**: One UI codebase for the web dashboard and the desktop app; the dashboard must keep working in both homes (same-origin cookie, and Bearer from a shell), so no new `window.location` navigation or raw `EventSource` in `ui/` — use `lib/connection.ts` and `lib/sse.ts`. Every API change is judged against the contract rules. The runtime still binds loopback only; remote access means a tunnel, VPN or reverse proxy, which is a later decision with its own ADR. Follow-ups: bundled runtime as a sidecar (install from the app), signed updater artifacts, notifications with actions, the macOS notch capsule, QR pairing over `mercury://`, and the cockpit redesign in `ui/`.
+
+## ADR-031: Bots take files too — attachments ride the job, not the prompt
+
+- **Context**: ADR-028 gave the chat route files (#225) and the profile an avatar, but a bot could still only be *told* about a photo: `POST /api/bots/:id/message` read `message` and the durable job carried `{trigger, prompt, fromBot, source}`. The runtime could already read attachments (`withAttachments`, 8 MB image / 15 MB PDF, vision-gated), so the gap was purely the queue: a bot turn has no request, and the job is the only thing that survives a restart.
+- **Decision**: The job carries **paths**, not bytes — `attachments?: ChannelAttachment[]` on `BotJob` and `DurableBotJob`, stored as a JSON column (`attachments TEXT`, added by an idempotent `ALTER TABLE` like `run_after`), normalized on read. The route validates and writes the bytes with the same helper the chat route uses (`storeInlineAttachments`), then enqueues; files for a job that is refused (`409`) or a message that never arrives are deleted, so `uploads/` cannot accumulate orphans. `idempotencyKeyFor` now includes the attachment paths: the same caption with two different photos is two jobs, while a retried identical request still dedupes. `runBotTurn` names a caption-less turn `(Attached: names)` — a provider rejects an empty text block — and applies `withAttachments` to the last user message, so a vision model gets image parts and a text-only one gets the existing note.
+- **Consequence**: A photo can be handed to a bot exactly like a chat turn, from the phone or a script, and the work survives a restart because the files are on disk and the job references them. Stale paths are harmless: `withAttachments` skips a file that no longer exists rather than failing the turn. Not here: files arriving from *other bots* (bot-to-bot mail carries text), transcription, and any retention sweep for uploads no job references — a disk-hygiene follow-up, not a correctness one.
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 164e0349..549fd333 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';
import { writeFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, rmSync } from 'node:fs';
import type { Tool } from 'ai';
+import type { ChannelAttachment } from '../types/channel.js';
import type { MercuryConfig } from '../utils/config.js';
import type { ProviderRegistry } from '../providers/registry.js';
import type { TokenBudget } from '../utils/tokens.js';
@@ -49,6 +50,8 @@ export interface BotJob {
fromBot?: string;
/** Originating surface for completion delivery. */
source?: { channelType: string; channelId: string };
+ /** Photos/PDFs to hand the turn; `web/api/uploads.ts` already wrote them to disk. */
+ attachments?: ChannelAttachment[];
createdAt: number;
attempts: number;
/** Scheduler task id for cron runs (routine gating + no-outcome streaks). */
@@ -393,7 +396,7 @@ export class BotManager {
return this.journalFor(botId);
}
- enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number; routineId?: string }): { jobId: string; accepted: boolean; reasonCode?: string } {
+ enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number; routineId?: string; attachments?: ChannelAttachment[] }): { jobId: string; accepted: boolean; reasonCode?: string } {
const manifest = this.store.get(botId);
if (!manifest) return { jobId: '', accepted: false, reasonCode: 'target_unknown' };
if (!manifest.enabled || this.disabled.has(botId)) return { jobId: '', accepted: false, reasonCode: 'target_disabled' };
@@ -435,9 +438,10 @@ export class BotManager {
prompt: job.prompt,
fromBot: job.fromBot,
source: job.source,
+ attachments: job.attachments,
attempts: job.attempts ?? 0,
createdAt: Date.now(),
- idempotencyKey: idempotencyKeyFor(botId, job.trigger, job.prompt, job.fromBot),
+ idempotencyKey: idempotencyKeyFor(botId, job.trigger, job.prompt, job.fromBot, job.attachments),
});
if (durable.duplicated) {
return { jobId: durable.job.id, accepted: true };
@@ -1116,6 +1120,7 @@ export class BotManager {
manifest,
trigger: job.trigger,
prompt: job.prompt,
+ attachments: job.attachments,
persona: this.store.readPersona(botId),
mail,
pollMail: () => this.drainMailbox(botId),
diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.ts
index 9a2b92d7..dfa6fd2c 100644
--- a/src/bots/bot-turn.test.ts
+++ b/src/bots/bot-turn.test.ts
@@ -14,7 +14,7 @@ vi.mock('ai', async (importOriginal) => {
});
import { streamText } from 'ai';
-import { runBotTurn, classifyFailure, type BotActivityEvent, type BotTurnInput } from './bot-turn.js';
+import { runBotTurn, classifyFailure, turnCaption, type BotActivityEvent, type BotTurnInput } from './bot-turn.js';
import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';
const mockedStreamText = vi.mocked(streamText);
@@ -429,3 +429,26 @@ describe('shared-folder write budget', () => {
expect(String(r)).toBe('Wrote draft.md');
});
});
+
+describe('turnCaption — files without a caption', () => {
+ const img = { kind: 'image' as const, path: '/tmp/a.png', mime: 'image/png', name: 'a.png' };
+
+ it('keeps a real prompt untouched', () => {
+ expect(turnCaption(' describe this ', [img])).toBe('describe this');
+ });
+
+ it('names the files when there is no text at all', () => {
+ // An empty text block is rejected by providers: the photo says what it is.
+ expect(turnCaption('', [img])).toBe('(Attached: a.png)');
+ expect(turnCaption(' ', [img, { ...img, name: 'b.pdf', kind: 'document' as const }]))
+ .toBe('(Attached: a.png, b.pdf)');
+ });
+
+ it('falls back to "file" when a name is missing, never to an empty string', () => {
+ expect(turnCaption('', [{ kind: 'image', path: '/tmp/x.webp' }])).toBe('(Attached: file)');
+ });
+
+ it('stays empty with neither text nor files', () => {
+ expect(turnCaption('', [])).toBe('');
+ });
+});
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index 5fdd848d..35ce77e5 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -1,4 +1,6 @@
import { streamText, stepCountIs } from 'ai';
+import { withAttachments } from '../core/attachments.js';
+import type { ChannelAttachment } from '../types/channel.js';
import type { ModelMessage, Tool } from 'ai';
import { isAbsolute, relative, resolve } from 'node:path';
import type { CapabilityRegistry } from '../capabilities/registry.js';
@@ -81,6 +83,12 @@ export interface BotTurnInput {
/** Durable job id — correlates activity events with the run. */
jobId?: string;
prompt: string;
+ /**
+ * Photos and PDFs for this turn, already on disk. The runtime reads them here:
+ * a caption-less photo becomes `(Attached: names)` because a provider rejects an
+ * empty text block, and a model without vision gets a note instead of pixels.
+ */
+ attachments?: ChannelAttachment[];
persona: string;
/** Pending mailbox messages at turn start (attributed bot-to-bot handoffs). */
mail: BotTurnMail[];
@@ -187,6 +195,18 @@ const CLAIM_PATTERN = /\b(delivered|filed|shipped|published|executed|committed|p
* only wrote notes gets one nudge to deliver or admit it, and is journaled
* as `none` if it still produced nothing.
*/
+/**
+ * What the turn says. A provider rejects an empty text block, so a photo sent with no
+ * caption names itself instead of arriving as empty text — the same rule the chat route
+ * applies (`web/api/chat.ts`).
+ */
+export function turnCaption(prompt: string, files: ChannelAttachment[]): string {
+ const trimmed = prompt.trim();
+ if (trimmed) return trimmed;
+ if (files.length === 0) return '';
+ return `(Attached: ${files.map(f => f.name ?? 'file').join(', ')})`;
+}
+
export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
const { manifest, provider, capabilities, tokenBudget } = input;
const maxSteps = manifest.autonomy?.maxSteps ?? MAX_STEPS_DEFAULT;
@@ -200,12 +220,29 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
for (const m of input.mail) {
messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });
}
- if (input.prompt) {
- messages.push({ role: 'user', content: input.prompt });
+ const files = input.attachments ?? [];
+ const caption = turnCaption(input.prompt, files);
+ if (caption) {
+ messages.push({ role: 'user', content: caption });
}
if (messages.length === 0) {
messages.push({ role: 'user', content: 'You have no specific task. Check your inbox and report your status.' });
}
+ if (files.length > 0) {
+ // Same transformation channels get: image/file parts for a model that takes them,
+ // a plain note otherwise. Rewrites the last user message in place.
+ const turnMessage = {
+ id: `bot-${manifest.id}-${Date.now()}`,
+ channelId: manifest.id,
+ channelType: 'bot',
+ senderId: manifest.id,
+ content: caption,
+ timestamp: Date.now(),
+ metadata: { attachments: files },
+ } as never;
+ const withFiles = withAttachments(messages, turnMessage, provider.name, provider.getModel());
+ messages.splice(0, messages.length, ...withFiles);
+ }
let tokensIn = 0;
let tokensOut = 0;
diff --git a/src/bots/queue.test.ts b/src/bots/queue.test.ts
index e8238534..d68ec07a 100644
--- a/src/bots/queue.test.ts
+++ b/src/bots/queue.test.ts
@@ -136,6 +136,26 @@ describe('BotQueue backends (JSON-file + SQLite semantics)', () => {
expect(pending.map(j => j.id)).toEqual(['h1', 'backoff']); // backoff included: explicit resume overrides it
});
+ it('keeps a job’s files across a restart, and dedupes on them too', () => {
+ const file = { kind: 'image' as const, path: '/uploads/2026-10/a-dot.png', mime: 'image/png', name: 'dot.png' };
+ const backend = mkBackend(name, root);
+ backend.enqueue(job('a1', { prompt: 'what is this?', attachments: [file] }));
+
+ // Durable: a fresh handle on the same db still sees the file list.
+ const resumed = mkBackend(name, root).rehydratable();
+ expect(resumed[0].attachments).toEqual([file]);
+
+ // Same caption, different photo = different job.
+ const other = mkBackend(name, root).enqueue(job('a2', {
+ prompt: 'what is this?',
+ attachments: [{ ...file, path: '/uploads/2026-10/b-other.png', name: 'other.png' }],
+ idempotencyKey: idempotencyKeyFor('researcher', 'chat', 'what is this?', undefined, [
+ { ...file, path: '/uploads/2026-10/b-other.png', name: 'other.png' },
+ ]),
+ }));
+ expect(other.duplicated).toBe(false);
+ });
+
it('settle dead moves the job to the DLQ with the reason', () => {
const backend = mkBackend(name, root);
backend.enqueue(job('a1'));
diff --git a/src/bots/queue.ts b/src/bots/queue.ts
index dce41f62..70a04594 100644
--- a/src/bots/queue.ts
+++ b/src/bots/queue.ts
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { logger } from '../utils/logger.js';
import { isSqliteAvailable, openSqlite, type SqliteDatabase } from '../utils/sqlite-driver.js';
+import type { ChannelAttachment } from '../types/channel.js';
import type { BotTrigger } from './types.js';
export const QUEUE_DB_FILE = 'queue.db';
@@ -13,6 +14,11 @@ export interface DurableBotJob {
trigger: BotTrigger;
prompt: string;
fromBot?: string;
+ /**
+ * Files on disk for this job (`web/api/uploads.ts` wrote them). Paths, not bytes:
+ * the queue survives a restart and the image is already stored.
+ */
+ attachments?: ChannelAttachment[];
source?: { channelType: string; channelId: string };
state: 'pending' | 'claimed' | 'dead';
attempts: number;
@@ -89,8 +95,19 @@ export interface BotQueueBackend {
export const LEASE_SECONDS = 60;
const DLQ_CAP = 100;
-export function idempotencyKeyFor(botId: string, trigger: BotTrigger, prompt: string, fromBot?: string): string {
- return createHash('sha256').update(`${botId}|${trigger}|${prompt}|${fromBot ?? ''}`).digest('hex').slice(0, 16);
+/**
+ * Two requests that differ only by their files are different jobs: the same caption
+ * ("what is this?") with two different photos must not collapse into one.
+ */
+export function idempotencyKeyFor(
+ botId: string,
+ trigger: BotTrigger,
+ prompt: string,
+ fromBot?: string,
+ attachments?: ChannelAttachment[],
+): string {
+ const files = (attachments ?? []).map(a => a.path).join(',');
+ return createHash('sha256').update(`${botId}|${trigger}|${prompt}|${fromBot ?? ''}|${files}`).digest('hex').slice(0, 16);
}
function normalizeJob(raw: any): DurableBotJob {
@@ -99,12 +116,18 @@ function normalizeJob(raw: any): DurableBotJob {
if (typeof source === 'string') {
try { source = JSON.parse(source); } catch { source = undefined; }
}
+ let attachments = raw.attachments;
+ if (typeof attachments === 'string') {
+ try { attachments = JSON.parse(attachments); } catch { attachments = undefined; }
+ }
+ if (!Array.isArray(attachments) || attachments.length === 0) attachments = undefined;
return {
id: String(raw.id),
botId: String(raw.botId ?? raw.bot_id),
trigger: raw.trigger,
prompt: raw.prompt ?? '',
fromBot: raw.fromBot ?? raw.from_bot ?? undefined,
+ attachments,
source,
state: raw.state ?? 'pending',
attempts: raw.attempts ?? 0,
@@ -266,7 +289,8 @@ export class SqliteQueueBackend implements BotQueueBackend {
lease_expires_at INTEGER,
idempotency_key TEXT NOT NULL,
reason_code TEXT,
- settled_at INTEGER
+ settled_at INTEGER,
+ attachments TEXT
);
CREATE INDEX IF NOT EXISTS idx_bot_jobs_state ON bot_jobs (state, created_at);
CREATE TABLE IF NOT EXISTS bot_mail (
@@ -293,6 +317,7 @@ export class SqliteQueueBackend implements BotQueueBackend {
`);
// Migration for queues created before run_after / bot_mail existed.
try { this.db.exec('ALTER TABLE bot_jobs ADD COLUMN run_after INTEGER'); } catch { /* already present */ }
+ try { this.db.exec('ALTER TABLE bot_jobs ADD COLUMN attachments TEXT'); } catch { /* already present */ }
this.dlqCap = dlqCap;
}
@@ -305,12 +330,13 @@ export class SqliteQueueBackend implements BotQueueBackend {
}
const stored: DurableBotJob = { ...job, state: 'pending' };
this.db.prepare(
- `INSERT INTO bot_jobs (id, bot_id, trigger, prompt, from_bot, source, state, attempts, created_at, lease_expires_at, idempotency_key)
- VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)`,
+ `INSERT INTO bot_jobs (id, bot_id, trigger, prompt, from_bot, source, state, attempts, created_at, lease_expires_at, idempotency_key, attachments)
+ VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?)`,
).run(
stored.id, stored.botId, stored.trigger, stored.prompt,
stored.fromBot ?? null, stored.source ? JSON.stringify(stored.source) : null,
stored.attempts, stored.createdAt, stored.leaseExpiresAt ?? null, stored.idempotencyKey,
+ stored.attachments?.length ? JSON.stringify(stored.attachments) : null,
);
return { job: stored, duplicated: false };
}
diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.ts
index b5feb96f..abfca232 100644
--- a/src/web/api/bots.test.ts
+++ b/src/web/api/bots.test.ts
@@ -348,3 +348,54 @@ describe('web bots API — avatars', () => {
expect(existsSync(join(root, 'bots', 'painter'))).toBe(false);
});
});
+
+describe('web bots API — files on a bot message', () => {
+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
+
+ beforeEach(() => {
+ store.create({ id: 'painter', name: 'Painter' });
+ });
+
+ const send = (body: unknown) =>
+ app.request('/api/bots/painter/message', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ headers: { 'Content-Type': 'application/json' },
+ });
+
+ it('queues a photo with the job and names it in the response', async () => {
+ const res = await send({ message: '', attachments: [{ name: 'dot.png', data: PNG.toString('base64') }] });
+
+ expect(res.status).toBe(202);
+ await expect(jreq(res)).resolves.toMatchObject({
+ accepted: true,
+ status: 'accepted',
+ attachments: [{ name: 'dot.png', kind: 'image' }],
+ });
+ });
+
+ it('still takes a plain message with no files', async () => {
+ const res = await send({ message: 'check the logs' });
+ expect(res.status).toBe(202);
+ const body = await jreq(res);
+ expect(body).toMatchObject({ accepted: true });
+ expect(body.attachments).toBeUndefined();
+ });
+
+ it('refuses a file it cannot read, and writes nothing', async () => {
+ const before = existsSync(join(root, 'uploads'));
+ const res = await send({ message: 'look', attachments: [{ data: Buffer.from('hello').toString('base64') }] });
+
+ expect(res.status).toBe(400);
+ await expect(jreq(res)).resolves.toEqual({
+ error: 'attachment 1 is not a supported image (png, jpeg, webp, gif) or PDF',
+ });
+ expect(existsSync(join(root, 'uploads'))).toBe(before);
+ });
+
+ it('requires something to say when there is nothing attached', async () => {
+ const res = await send({ message: ' ' });
+ expect(res.status).toBe(400);
+ await expect(jreq(res)).resolves.toEqual({ error: 'message is required' });
+ });
+});
diff --git a/src/web/api/bots.ts b/src/web/api/bots.ts
index c637d488..f8126872 100644
--- a/src/web/api/bots.ts
+++ b/src/web/api/bots.ts
@@ -1,12 +1,13 @@
import { Hono } from 'hono';
import { openFolder, tildify } from '../../bots/open-folder.js';
import type { Context } from 'hono';
-import { readFileSync, existsSync, mkdirSync } from 'node:fs';
+import { readFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
import type { BotManager } from '../../bots/bot-manager.js';
import type { BotManifest } from '../../bots/types.js';
import { PERMISSION_TIERS, tierPermissionsFile, isPermissionTier, type PermissionTier } from '../../bots/permission-tiers.js';
import { buildBotBundle, importBotBundle } from '../../bots/bundle.js';
import { decodeAvatarInput, detectImage } from '../../bots/avatar.js';
+import { storeInlineAttachments } from './uploads.js';
const app = new Hono();
@@ -253,13 +254,37 @@ app.patch('/api/bots/:id', async (c: any) => {
app.post('/api/bots/:id/message', async (c: any) => {
if (!botManager) return c.json({ error: 'Bots not available' }, 400);
const id = c.req.param('id');
- const body = await c.req.json().catch(() => null) as { message?: string; from?: string } | null;
- if (!body?.message) return c.json({ error: 'message is required' }, 400);
- const result = botManager.enqueue(id, { trigger: 'api', prompt: body.message, fromBot: body.from });
+ const body = await c.req.json().catch(() => null) as
+ { message?: string; from?: string; attachments?: unknown } | null;
+
+ // Bytes on the wire, written before the job exists: the queue stores paths, and a
+ // bot turn reads them exactly like a channel attachment.
+ const upload = storeInlineAttachments(body?.attachments);
+ if (!upload.ok) return c.json({ error: upload.error }, 400);
+
+ const message = body?.message?.trim() ?? '';
+ if (!message && upload.attachments.length === 0) {
+ for (const a of upload.attachments) rmSync(a.path, { force: true });
+ return c.json({ error: 'message is required' }, 400);
+ }
+
+ const result = botManager.enqueue(id, {
+ trigger: 'api',
+ prompt: message,
+ fromBot: body?.from,
+ attachments: upload.attachments.length > 0 ? upload.attachments : undefined,
+ });
if (!result.accepted) {
+ // The turn will never run: its files must not stay in uploads.
+ for (const a of upload.attachments) rmSync(a.path, { force: true });
return c.json({ accepted: false, reasonCode: result.reasonCode }, 409);
}
- return c.json({ accepted: true, jobId: result.jobId, status: 'accepted' }, 202);
+ return c.json({
+ accepted: true,
+ jobId: result.jobId,
+ status: 'accepted',
+ ...(upload.attachments.length > 0 ? { attachments: upload.attachments.map(a => ({ name: a.name, kind: a.kind })) } : {}),
+ }, 202);
});
// Inbox (pending bot-to-bot mail)