Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): give a bot a face — avatar bytes in the profile dir (#226)
tournierjc912097f76c69
diff --git a/DECISIONS.md b/DECISIONS.mdindex 05509bb4..9fe6e8ba 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -1,3 +1,9 @@+## ADR-024: A bot has a face — avatars live in the profile dir++- **Context**: Every surface identified a bot by its id and a two-letter monogram derived from it — dashboard, Android client, TUI — because there was nowhere to put a picture: a profile is `bot.yaml` (identity), `persona.md` (character), `permissions.yaml` (what it may do), and nothing else. A fleet of eight bots is a wall of near-identical monograms, and the phone is where a fleet is actually run (ADR-023).+- **Decision**: An avatar is profile data, not settings. One extension-less file `avatar` in the bot's own profile dir — written through a temp file and renamed so a half-written face never serves, `0600`, replacing any previous one. `GET`/`PUT`/`DELETE /api/bots/:id/avatar`: bytes in as `{ data }` (base64, ≤ 2 MB, png/jpeg/webp/gif decided by the signature, never by the client's label), bytes out with the detected type, an `ETag` for cache validation, and `hasAvatar` on `getStatusSummaries()` so a client needs no probe per bot. A write or a delete rebroadcasts the roster frame, so every open dashboard learns the change at once. Nothing is added to `bot.yaml`: an absent file *is* "no custom avatar", which keeps an exported profile without a face byte-identical, and deleting a bot deletes its face along with the directory.+- **Consequence**: Clients stop inventing identity, and the monogram becomes a fallback rather than the only option. The extension-less name is the point: the format is decided by the bytes, so a webp re-upload can never be served as png because a stale filename said so. Not in this ADR: an avatar for the owner (there is one), generated faces, cropping or thumbnail derivatives — the client scales, and a 2 MB cap keeps that honest.+## 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.diff --git a/src/bots/avatar.ts b/src/bots/avatar.tsnew file mode 100644index 00000000..ddb7dc4e--- /dev/null+++ b/src/bots/avatar.ts@@ -0,0 +1,49 @@+/**+ * A bot's face, arriving from a client.+ *+ * Same rule as chat attachments: only bytes, never a path, and the bytes decide+ * the format. An avatar is a picture and nothing else — a PDF or a text file in+ * this slot would be served back to a dashboard that expects an image.+ */+/**+ * Image formats the roster can serve, recognised by signature. Kept local to the+ * avatar slot rather than shared with chat attachments so this change stands on+ * its own; the two will want one detector once both land.+ */+export function detectImage(bytes: Buffer): string | null {+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';+ if (bytes.length >= 6 && /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString('latin1'))) return 'image/gif';+ if (+ bytes.length >= 12 &&+ bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&+ bytes.subarray(8, 12).toString('latin1') === 'WEBP'+ ) {+ return 'image/webp';+ }+ return null;+}++/** Small on purpose: it is a face in a roster, not a photo library. */+export const MAX_AVATAR_BYTES = 2 * 1024 * 1024;++export type AvatarInput =+ | { ok: true; bytes: Buffer; mime: string }+ | { ok: false; error: string };++/** Reads `{ data: <base64> }`, tolerating a `data:` URL prefix. */+export function decodeAvatarInput(body: unknown): AvatarInput {+ const data = (body as { data?: unknown } | null)?.data;+ if (typeof data !== 'string' || data.length === 0) {+ return { ok: false, error: 'avatar needs base64 "data"' };+ }+ const payload = data.startsWith('data:') ? data.slice(data.indexOf(',') + 1) : data;+ const bytes = Buffer.from(payload, 'base64');+ if (bytes.length === 0) return { ok: false, error: 'avatar is not valid base64' };+ if (bytes.length > MAX_AVATAR_BYTES) {+ return { ok: false, error: `avatar is ${Math.round(bytes.length / 1048576)} MB; the limit is 2 MB` };+ }+ const mime = detectImage(bytes);+ if (!mime) return { ok: false, error: 'avatar must be a png, jpeg, webp or gif image' };+ return { ok: true, bytes, mime };+}diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 63e69997..2ccd5c13 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1743,6 +1743,7 @@ export class BotManager {lastRunAt: last?.at,lastRunState: last?.state,needsYou: this.needsYou.has(m.id),+ hasAvatar: this.store.hasAvatar(m.id),fleetRole: m.fleetRole,parent: m.parent,crewWorking: m.fleetRole === 'lead'diff --git a/src/bots/store.ts b/src/bots/store.tsindex 1cad00d4..86663d19 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -11,6 +11,8 @@ import type {export const BOT_MANIFEST_FILENAME = 'bot.yaml';export const BOT_PERSONA_FILENAME = 'persona.md';+/** A bot's face. Extension-less on purpose: the format is sniffed from the bytes. */+export const BOT_AVATAR_FILENAME = 'avatar';export const BOT_PERMISSIONS_FILENAME = 'permissions.yaml';/** Fleet-shared sandbox folder (every bot gets read/write/execute). The* underscore prefix keeps store.list() from ever treating it as a bot. */@@ -309,6 +311,62 @@ export class BotStore {}}+ /**+ * The bot's avatar, kept next to the persona so deleting a bot takes its face+ * with it and an exported/imported profile stays whole. No extension: the+ * bytes decide the format (see `core/media-type.ts`), so a re-uploaded webp+ * cannot end up labelled png by a stale filename.+ */+ avatarPath(id: string): string {+ return join(this.botDir(id), BOT_AVATAR_FILENAME);+ }++ hasAvatar(id: string): boolean {+ try {+ return existsSync(this.avatarPath(id));+ } catch {+ return false;+ }+ }++ /** Last write time of the avatar, for cache validators. 0 when there is none. */+ avatarMtimeMs(id: string): number {+ try {+ return statSync(this.avatarPath(id)).mtimeMs;+ } catch {+ return 0;+ }+ }++ readAvatar(id: string): Buffer | null {+ try {+ return readFileSync(this.avatarPath(id));+ } catch {+ return null;+ }+ }++ /** Replaces any previous avatar; the write is atomic so a half-written face never serves. */+ writeAvatar(id: string, bytes: Buffer): void {+ const file = this.avatarPath(id);+ mkdirSync(join(file, '..'), { recursive: true });+ const tmp = `${file}.tmp-${process.pid}`;+ writeFileSync(tmp, bytes, { mode: 0o600 });+ renameSync(tmp, file);+ this.locationCache.delete(id);+ }++ removeAvatar(id: string): boolean {+ try {+ const file = this.avatarPath(id);+ if (!existsSync(file)) return false;+ rmSync(file, { force: true });+ return true;+ } catch {+ return false;+ }+ }+/** Bot directory for an id, with traversal guard. Throws on invalid ids. */botDir(id: string): string {assertValidBotId(id);diff --git a/src/bots/types.ts b/src/bots/types.tsindex e63c6f84..070ca0a9 100644--- a/src/bots/types.ts+++ b/src/bots/types.ts@@ -246,4 +246,6 @@ export interface BotStatusSummary {crewWorking?: number;/** Earliest automatic resume time of a paused routine, when any is paused. */routinePausedUntil?: number;+ /** The bot has a custom avatar (`GET /api/bots/:id/avatar`); clients draw a monogram otherwise. */+ hasAvatar?: boolean;}\ No newline at end of filediff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex 5cea5660..ce22b519 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -206,3 +206,100 @@ describe('web bots API — deliverables folder (where results land)', () => {expect((await app.request('/api/bots/ghost/folder')).status).toBe(404);});});++describe('web bots API — avatars', () => {+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');+ const put = (id: string, body: unknown) =>+ app.request(`/api/bots/${id}/avatar`, { method: 'PUT', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } });++ beforeEach(() => {+ store.create({ id: 'painter', name: 'Painter' });+ });++ it('stores a face and serves it back with the type the bytes have', async () => {+ expect((await put('painter', { data: PNG.toString('base64') })).status).toBe(200);++ const res = await app.request('/api/bots/painter/avatar');+ expect(res.status).toBe(200);+ expect(res.headers.get('Content-Type')).toBe('image/png');+ expect(res.headers.get('Cache-Control')).toContain('private');+ const served = Buffer.from(await res.arrayBuffer());+ expect(served.equals(PNG)).toBe(true);+ });++ it('advertises the avatar in the roster so a client need not probe', async () => {+ const before = await jreq(await app.request('/api/bots'));+ expect(before.bots.find((b: any) => b.id === 'painter').hasAvatar).toBe(false);++ await put('painter', { data: PNG.toString('base64') });++ const after = await jreq(await app.request('/api/bots'));+ expect(after.bots.find((b: any) => b.id === 'painter').hasAvatar).toBe(true);+ });++ it('answers 404 when there is no avatar yet', async () => {+ const res = await app.request('/api/bots/painter/avatar');+ expect(res.status).toBe(404);+ await expect(jreq(res)).resolves.toEqual({ error: 'Bot has no avatar' });+ });++ it('replaces the previous face in place', async () => {+ await put('painter', { data: PNG.toString('base64') });+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00]);+ const res = await put('painter', { data: jpeg.toString('base64') });+ expect(res.status).toBe(200);+ await expect(jreq(res)).resolves.toMatchObject({ ok: true, mime: 'image/jpeg' });++ const served = await app.request('/api/bots/painter/avatar');+ expect(served.headers.get('Content-Type')).toBe('image/jpeg');+ expect(existsSync(store.avatarPath('painter'))).toBe(true);+ // one face, never two: the file name carries no extension to accumulate+ expect(readFileSync(store.avatarPath('painter')).length).toBe(jpeg.length);+ });++ it('refuses a document, a text file, and an oversized image', async () => {+ await expect(jreq(await put('painter', { data: Buffer.from('%PDF-1.4\n').toString('base64') })))+ .resolves.toEqual({ error: 'avatar must be a png, jpeg, webp or gif image' });+ await expect(jreq(await put('painter', { data: Buffer.from('hello').toString('base64') })))+ .resolves.toEqual({ error: 'avatar must be a png, jpeg, webp or gif image' });+ await expect(jreq(await put('painter', {}))).resolves.toEqual({ error: 'avatar needs base64 "data"' });++ const huge = Buffer.concat([PNG, Buffer.alloc(2 * 1024 * 1024)]);+ const res = await put('painter', { data: huge.toString('base64') });+ expect(res.status).toBe(400);+ expect((await jreq(res)).error).toContain('the limit is 2 MB');+ expect(store.hasAvatar('painter')).toBe(false);+ });++ it('validates the cache with an ETag instead of resending the face', async () => {+ await put('painter', { data: PNG.toString('base64') });+ const first = await app.request('/api/bots/painter/avatar');+ const etag = first.headers.get('ETag');+ expect(etag).toBeTruthy();++ const again = await app.request('/api/bots/painter/avatar', { headers: { 'If-None-Match': etag! } });+ expect(again.status).toBe(304);+ });++ it('deletes the face and says whether there was one', async () => {+ await put('painter', { data: PNG.toString('base64') });++ await expect(jreq(await app.request('/api/bots/painter/avatar', { method: 'DELETE' }))).resolves.toEqual({ ok: true, removed: true });+ expect(store.hasAvatar('painter')).toBe(false);+ await expect(jreq(await app.request('/api/bots/painter/avatar', { method: 'DELETE' }))).resolves.toEqual({ ok: true, removed: false });+ });++ it('answers 404 for a bot that does not exist', async () => {+ expect((await app.request('/api/bots/ghost/avatar')).status).toBe(404);+ expect((await put('ghost', { data: PNG.toString('base64') })).status).toBe(404);+ expect((await app.request('/api/bots/ghost/avatar', { method: 'DELETE' })).status).toBe(404);+ });++ it('keeps the avatar inside the bot profile dir, so deleting the bot takes it', async () => {+ await put('painter', { data: PNG.toString('base64') });+ expect(store.avatarPath('painter')).toBe(join(root, 'bots', 'painter', 'avatar'));++ manager.store.delete('painter');+ expect(existsSync(join(root, 'bots', 'painter'))).toBe(false);+ });+});diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex a368a4ba..ba8bd760 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -6,6 +6,7 @@ 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';const app = new Hono();@@ -396,6 +397,60 @@ app.put('/api/bots/:id/persona', async (c: any) => {}});+// Avatar (a bot's face) — bytes in, bytes out. Stored as one extension-less+// file in the bot's profile dir, so the format is always the real one and+// deleting the bot deletes its face. Clients that get no avatar draw a+// monogram from the id; `hasAvatar` in the roster tells them which without a+// probe per bot.+app.get('/api/bots/:id/avatar', (c: any) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const id = c.req.param('id');+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);+ const bytes = botManager.store.readAvatar(id);+ if (!bytes) return c.json({ error: 'Bot has no avatar' }, 404);++ const mime = detectImage(bytes);+ if (!mime) {+ // On disk but unreadable as an image: say so rather than serve a broken face.+ return c.json({ error: 'Stored avatar is not a readable image' }, 500);+ }+ const etag = `W/"${bytes.length}-${Math.round(botManager.store.avatarMtimeMs(id))}"`;+ if (c.req.header('If-None-Match') === etag) return c.body(null, 304);+ return c.body(new Uint8Array(bytes), 200, {+ 'Content-Type': mime,+ 'Content-Length': String(bytes.length),+ 'Cache-Control': 'private, max-age=0, must-revalidate',+ ETag: etag,+ });+});++app.put('/api/bots/:id/avatar', async (c: any) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const id = c.req.param('id');+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);+ const body = await c.req.json().catch(() => null);+ const avatar = decodeAvatarInput(body);+ if (!avatar.ok) return c.json({ error: avatar.error }, 400);+ try {+ botManager.store.writeAvatar(id, avatar.bytes);+ // The roster carries `hasAvatar`, so every open dashboard learns the face+ // changed without another request.+ broadcastRoster();+ return c.json({ ok: true, mime: avatar.mime, bytes: avatar.bytes.length });+ } catch (err: any) {+ return c.json({ error: err?.message ?? 'Could not store the avatar' }, 400);+ }+});++app.delete('/api/bots/:id/avatar', (c: any) => {+ if (!botManager) return c.json({ error: 'Bots not available' }, 400);+ const id = c.req.param('id');+ if (!botManager.store.exists(id)) return c.json({ error: 'Bot not found' }, 404);+ const removed = botManager.store.removeAvatar(id);+ if (removed) broadcastRoster();+ return c.json({ ok: true, removed });+});+// Permissions.yaml — the single source of truth (tool gate, path scopes,// shell lists). PUT with a tier applies the tier wholesale; PUT with a// full document is the "custom" path. Fleet inheritance: a crew bot shows