Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Let create_bot and update_bot set a Bot's photo

chimneya9b872178b3b
diff --git a/ds-bot/README.md b/ds-bot/README.md
index 03d6011c..87fadfca 100644
--- a/ds-bot/README.md
+++ b/ds-bot/README.md
@@ -11,7 +11,7 @@ Tested with dsh `0.2.1-rc.2` (Web) and `0.2.0-rc.2` (Web and Desktop).
- **Long-lived Bots**: each Bot is a dsh Session in the "DS Bot" workspace, with its own name, role, instructions and model.
- **Working folders**: a Bot can work in a folder you choose instead of the team workspace, and a group chat can set one folder for all its members there. Pick it in the Bot's settings or details panel or in the group's settings, or ask a Bot (`update_bot`, `update_group`). After a change, the chat goes on in a fresh part that starts in the new folder. When a Bot sets a folder outside the team workspace, or adds a Bot to a group that works in one, it asks for your approval if those Bots can only write in their folder. Folders that hold dsh data (`$DSH_HOME`, the team's data) are refused.
- **Permission presets**: each Bot runs with its own dsh permission preset (Read only, Workspace or Full access), set in its details panel. A group chat can run all its members with one preset there, in place of their own: turn on **Same for every member** under Permissions in the group's settings. Only you set permissions; Bots cannot change them.
-- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots, and `ask_user` asks you a question without blocking the other Bots.
+- **Bots work together**: `message_bot` sends a message to another Bot, `create_bot` and `update_bot` add and set up Bots (including a profile photo from a local file, an http(s) link, or a data URL), and `ask_user` asks you a question without blocking the other Bots.
- **Group chats**: members speak one at a time, and each one reads the latest messages first. A message can `@Name` a member to pass the turn on; type `@` to pick one from a list. **+ → Reference a chat** adds another Bot's chat to a message as context, and in a group the members who answer get it. A member with nothing new to add stays quiet (`[PASS]`). Each member has its own hidden Session per group, so a group never reads a Bot's private chat.
- **Roles and permissions**:
diff --git a/ds-bot/src/host/avatar.js b/ds-bot/src/host/avatar.js
new file mode 100644
index 00000000..06f949a9
--- /dev/null
+++ b/ds-bot/src/host/avatar.js
@@ -0,0 +1,140 @@
+// Avatar input for create_bot and update_bot: a local image path, a data URL, or an
+// http(s) link, read into the data URL a Bot keeps in avatar.image. There is no image
+// library in the host, so images are not resized; a small square image is asked for,
+// and every kind of input is capped at what the stored format holds.
+import { readFile, stat } from 'node:fs/promises'
+import { homedir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { MAX_AVATAR_IMAGE } from './constants.js'
+
+const TIMEOUT_MS = 15_000
+// Base64 is four characters for every three bytes, and the data URL adds a mime
+// prefix, so a raw image must stay under this to fit MAX_AVATAR_IMAGE once stored.
+const LONGEST_PREFIX = 'data:image/jpeg;base64,'
+const MAX_BYTES = Math.floor((MAX_AVATAR_IMAGE - LONGEST_PREFIX.length) / 4) * 3
+const HINT = 'Use a square image; 256x256 is recommended.'
+const MIMES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
+
+const ascii = (bytes, start, end) => Buffer.from(bytes.subarray(start, end)).toString('latin1')
+
+// The real format, from the bytes themselves: an extension, a Content-Type header, or
+// the mime in a data URL can all be wrong.
+function mimeOf(bytes) {
+ if (bytes.length >= 8 && ascii(bytes, 0, 8) === '\x89PNG\r\n\x1a\n') 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(ascii(bytes, 0, 6))) return 'image/gif'
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === 'RIFF' && ascii(bytes, 8, 12) === 'WEBP') return 'image/webp'
+ return undefined
+}
+
+const tooLarge = size => `The avatar image is too large: ${size} bytes, and the limit is ${MAX_BYTES} bytes (about 120 KB). ${HINT}`
+const NOT_IMAGE = `The avatar must be a PNG, JPEG, WebP, or GIF image. ${HINT}`
+const CHECK_LINK = 'Check the link, or download the image and pass its path.'
+
+function toDataUrl(bytes) {
+ if (bytes.length > MAX_BYTES) throw new Error(tooLarge(bytes.length))
+ const mime = mimeOf(bytes)
+ if (mime === undefined) throw new Error(NOT_IMAGE)
+ const url = `data:${mime};base64,${bytes.toString('base64')}`
+ if (url.length > MAX_AVATAR_IMAGE) throw new Error(tooLarge(bytes.length))
+ return url
+}
+
+const expandHome = (text) => {
+ if (text === '~') return homedir()
+ if (/^~[\\/]/.test(text)) return join(homedir(), text.slice(2))
+ return text
+}
+
+async function readLocal(path, baseDir) {
+ const full = resolve(baseDir ?? process.cwd(), expandHome(path))
+ let info
+ try {
+ info = await stat(full)
+ } catch (error) {
+ if (error?.code === 'ENOENT') throw new Error(`There is no image file at ${full}. Pass the path of an existing image file.`)
+ throw new Error(`Cannot read the image at ${full}: ${error?.code === 'EACCES' ? 'permission denied' : error.message}`)
+ }
+ if (!info.isFile()) throw new Error(`${full} is not an image file. Pass the path of an image file.`)
+ if (info.size > MAX_BYTES) throw new Error(tooLarge(info.size))
+ let bytes
+ try {
+ bytes = await readFile(full)
+ } catch (error) {
+ throw new Error(`Cannot read the image at ${full}: ${error?.code === 'EACCES' ? 'permission denied' : error.message}`)
+ }
+ if (bytes.length > MAX_BYTES) throw new Error(tooLarge(bytes.length))
+ return toDataUrl(bytes)
+}
+
+function readDataUrl(value) {
+ const comma = value.indexOf(',')
+ if (comma === -1) throw new Error(`The avatar data URL has no comma before its image data. ${HINT}`)
+ const header = value.slice('data:'.length, comma)
+ const [mime = '', ...params] = header.split(';').map(part => part.trim().toLowerCase())
+ if (!MIMES.has(mime)) throw new Error(`The avatar data URL must hold a PNG, JPEG, WebP, or GIF image. ${HINT}`)
+ if (!params.includes('base64')) throw new Error('The avatar data URL must be base64 encoded, as in data:image/png;base64,...')
+ const payload = value.slice(comma + 1).replace(/\s/g, '')
+ if (payload === '' || payload.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(payload)) {
+ throw new Error('The avatar data URL does not hold valid base64 image data.')
+ }
+ return toDataUrl(Buffer.from(payload, 'base64'))
+}
+
+const secondsOf = timeoutMs => {
+ const seconds = Math.max(1, Math.round(timeoutMs / 1000))
+ return `${seconds} second${seconds === 1 ? '' : 's'}`
+}
+const timedOut = timeoutMs => `The image link did not answer within ${secondsOf(timeoutMs)}. ${CHECK_LINK}`
+const isTimeout = error => error?.name === 'TimeoutError' || error?.name === 'AbortError' || error?.cause?.name === 'TimeoutError'
+const discard = async (response) => { try { await response.body?.cancel() } catch {} }
+
+async function readUrl(url, timeoutMs) {
+ let response
+ try {
+ response = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
+ } catch (error) {
+ if (isTimeout(error)) throw new Error(timedOut(timeoutMs))
+ throw new Error(`Could not download the image: ${error?.cause?.message ?? error?.message ?? 'network error'}. ${CHECK_LINK}`)
+ }
+ if (!response.ok) {
+ await discard(response)
+ throw new Error(`The image link answered ${response.status}${response.statusText ? ` ${response.statusText}` : ''}. ${CHECK_LINK}`)
+ }
+ const length = Number(response.headers.get('content-length'))
+ if (Number.isFinite(length) && length > MAX_BYTES) {
+ await discard(response)
+ throw new Error(tooLarge(length))
+ }
+ const reader = response.body?.getReader()
+ if (reader === undefined) return toDataUrl(Buffer.alloc(0))
+ const chunks = []
+ let size = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ size += value.length
+ if (size > MAX_BYTES) {
+ await reader.cancel().catch(() => {})
+ throw new Error(tooLarge(size))
+ }
+ chunks.push(Buffer.from(value))
+ }
+ } catch (error) {
+ if (error?.name === 'AbortError' || error?.name === 'TimeoutError') throw new Error(timedOut(timeoutMs))
+ throw error
+ }
+ return toDataUrl(Buffer.concat(chunks))
+}
+
+// Returns the data URL for avatar.image, or throws with a line the user can read.
+// `baseDir` is where a relative local path starts, `timeoutMs` covers a whole download.
+export async function readAvatar(input, { baseDir, timeoutMs = TIMEOUT_MS } = {}) {
+ const value = typeof input === 'string' ? input.trim() : ''
+ if (value === '') throw new Error(`Give an image path, an http(s) link, or a data URL. ${HINT}`)
+ if (/^data:/i.test(value)) return readDataUrl(value)
+ if (/^https?:\/\//i.test(value)) return readUrl(value, timeoutMs)
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) throw new Error(`The avatar must be a local image path, an http(s) link, or a data URL. ${HINT}`)
+ return readLocal(value, baseDir)
+}
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index e5cfb73f..933bbf6c 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -2,6 +2,7 @@
// question card. Group rounds and reading chats are in groups.js.
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
+import { readAvatar } from './avatar.js'
import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'
import { absoluteLinks } from './links.js'
import { unquote } from './text.js'
@@ -20,6 +21,10 @@ const MODE_PARAM = {
description: '"everyone": every member answers a plain message in turn, admin first. "admin" (the default): a plain message goes to the admin, who calls others with @Name. @mentions always choose who answers.',
}
const WORK_DIR_PARAM = { type: 'string', description: 'Full path of the folder to work in, where commands and file tools start. Only when the user asks for it' }
+const AVATAR_PARAM = {
+ type: 'string',
+ description: 'Profile picture: a local image path (a relative path starts in your working folder), an http(s) link, or a data URL. PNG, JPEG, WebP, or GIF; square, 256x256 recommended, up to 120 KB. Images are not resized.',
+}
export function install(rt) {
const { ctx, state } = rt
@@ -250,12 +255,14 @@ export function install(rt) {
model: { type: 'string', description: 'Model the Bot runs on, as provider/model or a model id. Only when the user names one; otherwise the model you run on.' },
effort: { type: 'string', description: 'Thinking level for the model, as list_models shows it. Only when the user names one.' },
work_dir: WORK_DIR_PARAM,
+ avatar: AVATAR_PARAM,
},
output,
async execute(args, exec) {
await rt.load()
if (!rt.isMain(rt.selfOf(exec.agent?.id))) return 'Only the Main Bot can create Bots. Ask the Main Bot instead.'
try {
+ const avatar = args.avatar ? await readAvatar(String(args.avatar), { baseDir: rt.sessionFolder?.(exec.agent?.session ?? exec.agent) }) : undefined
const workDir = args.work_dir ? await rt.cleanWorkDir(args.work_dir) : undefined
const name = String(args.name ?? '').trim()
await rt.approveFolder(exec, { path: workDir, who: { en: `the new Bot ${name}`, zh: `新 Bot ${name} ` } })
@@ -264,7 +271,7 @@ export function install(rt) {
const creator = callerBot(exec)
const served = creator?.model && (await rt.catalog()).some(entry => entry.ref === creator.model)
const model = args.model || (served ? creator.model : undefined)
- const bot = await rt.createBot({ ...args, model, workDir, effort: args.effort, createdBy: creator?.id })
+ const bot = await rt.createBot({ ...args, avatar: avatar === undefined ? undefined : { image: avatar }, model, workDir, effort: args.effort, createdBy: creator?.id })
return `Created ${bot.name}${workDir ? `, working in ${workDir}` : ''}. It is greeting the user now.`
} catch (error) {
return `Could not create the Bot: ${error.message}`
@@ -274,13 +281,14 @@ export function install(rt) {
ctx.tools.register(defineTool({
name: 'update_bot',
- description: 'Change a Bot\'s name, role, color, model, thinking level, working folder, or instructions. Every Bot may change itself; only a Main Bot may change another Bot.',
+ description: 'Change a Bot\'s name, role, color, profile picture, model, thinking level, working folder, or instructions. Every Bot may change itself; only a Main Bot may change another Bot.',
parameters: {
bot: { type: 'string', description: 'Current name of the Bot to change; leave out to change yourself' },
name: { type: 'string', description: 'New name' },
role: { type: 'string', description: 'New role label' },
instructions: { type: 'string', description: 'Replacement instructions' },
color: { type: 'string', description: `One of ${[...COLORS, ...EXTRA_COLORS].join(', ')}` },
+ avatar: { ...AVATAR_PARAM, description: `${AVATAR_PARAM.description} An empty string removes the photo and shows the Bot's character again.` },
model: { type: 'string', description: 'Move the Bot to another model, as provider/model or a model id' },
effort: { type: 'string', description: 'Thinking level for the Bot\'s model, as list_models shows; an empty string returns to the model\'s default' },
work_dir: { ...WORK_DIR_PARAM, description: `${WORK_DIR_PARAM.description}; an empty string returns it to the team workspace` },
@@ -296,10 +304,17 @@ export function install(rt) {
if (bot.id !== caller.id && !rt.isMain(self)) return 'Only a Main Bot can change another Bot. Leave out bot to change yourself, or ask a Main Bot with message_bot.'
try {
const { name: newName, role, instructions, color, model, effort } = args
+ let avatar
+ if (args.avatar !== undefined) {
+ const input = typeof args.avatar === 'string' ? args.avatar.trim() : args.avatar
+ avatar = input === null || input === ''
+ ? null
+ : { image: await readAvatar(String(input), { baseDir: rt.sessionFolder?.(exec.agent?.session ?? exec.agent) }) }
+ }
const moving = typeof args.work_dir === 'string'
const workDir = moving ? await rt.cleanWorkDir(args.work_dir) : undefined
if (moving && workDir !== bot.workDir) await rt.approveFolder(exec, { path: workDir, sessions: rt.sessionsOfBot(bot.id), who: { en: bot.name, zh: ` ${bot.name} ` } })
- const next = await rt.updateBot(bot.id, { name: newName, role, instructions, color, ...(model ? { model } : {}), ...(effort === undefined ? {} : { effort }), ...(moving ? { workDir: workDir ?? '' } : {}) })
+ const next = await rt.updateBot(bot.id, { name: newName, role, instructions, color, ...(avatar !== undefined ? { avatar } : {}), ...(model ? { model } : {}), ...(effort === undefined ? {} : { effort }), ...(moving ? { workDir: workDir ?? '' } : {}) })
if (!moving) return `Updated ${next.name}.`
const folder = workDir ?? 'the team workspace'
return bot.id === caller.id ? `Updated ${next.name}. From your next step on, you work in ${folder}.` : `Updated ${next.name}. It now works in ${folder}.`
diff --git a/ds-bot/test/avatar.test.js b/ds-bot/test/avatar.test.js
new file mode 100644
index 00000000..75ae54f1
--- /dev/null
+++ b/ds-bot/test/avatar.test.js
@@ -0,0 +1,158 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:http'
+import { homedir, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { readAvatar } from '../src/host/avatar.js'
+import { MAX_AVATAR_IMAGE } from '../src/host/constants.js'
+
+// Only the magic bytes matter to the reader; the rest of a fixture need not decode.
+const file = (magic, size = 32) => Buffer.concat([magic, Buffer.alloc(size, 7)])
+const PNG = file(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
+const JPEG = file(Buffer.from([0xff, 0xd8, 0xff, 0xe0]))
+const GIF = file(Buffer.from('GIF89a', 'latin1'))
+const WEBP = file(Buffer.concat([Buffer.from('RIFF'), Buffer.from([0x20, 0, 0, 0]), Buffer.from('WEBP')]))
+const asDataUrl = (mime, bytes) => `data:${mime};base64,${bytes.toString('base64')}`
+const pngUrl = asDataUrl('image/png', PNG)
+const jpegUrl = asDataUrl('image/jpeg', JPEG)
+
+const tempDir = (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'ds-bot-avatar-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ return dir
+}
+
+async function serve(handler) {
+ const server = createServer(handler)
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ const { port } = server.address()
+ return {
+ url: `http://127.0.0.1:${port}`,
+ close: () => new Promise((resolve) => {
+ server.closeAllConnections()
+ server.close(resolve)
+ }),
+ }
+}
+
+test('a data URL is stored under the type its bytes really are', async () => {
+ assert.equal(await readAvatar(pngUrl), pngUrl)
+ assert.equal(await readAvatar(jpegUrl), jpegUrl)
+ // The mime in the data URL is not trusted: the bytes decide, and the base64 is
+ // rewritten in its canonical form.
+ assert.equal(await readAvatar(asDataUrl('image/png', JPEG)), jpegUrl)
+ assert.equal(await readAvatar(asDataUrl('image/gif', WEBP)), asDataUrl('image/webp', WEBP))
+ assert.equal(await readAvatar(asDataUrl('image/jpeg', GIF)), asDataUrl('image/gif', GIF))
+ assert.equal(await readAvatar(`data:IMAGE/PNG;base64,${PNG.toString('base64')}`), pngUrl)
+ assert.equal(await readAvatar(`data:image/png;base64, ${PNG.toString('base64')}\n`), pngUrl)
+})
+
+test('a local image file is read, and a relative path starts in baseDir', async (t) => {
+ const dir = tempDir(t)
+ writeFileSync(join(dir, 'photo.png'), PNG)
+ assert.equal(await readAvatar(join(dir, 'photo.png')), pngUrl)
+ assert.equal(await readAvatar('photo.png', { baseDir: dir }), pngUrl)
+ // The extension does not decide the type either.
+ writeFileSync(join(dir, 'photo.jpg'), PNG)
+ assert.equal(await readAvatar(join(dir, 'photo.jpg')), pngUrl)
+})
+
+test('a path starting with ~ expands to the home folder', async () => {
+ await assert.rejects(readAvatar('~'), (error) => {
+ assert.match(error.message, /is not an image file/)
+ assert.ok(error.message.includes(homedir()), 'the expanded home path is shown')
+ return true
+ })
+ const missing = 'ds-bot-avatar-does-not-exist.png'
+ await assert.rejects(readAvatar(`~/${missing}`), (error) => {
+ assert.ok(error.message.includes(join(homedir(), missing)))
+ return true
+ })
+})
+
+test('a missing file, a folder, and a non-image file are refused', async (t) => {
+ const dir = tempDir(t)
+ await assert.rejects(readAvatar(join(dir, 'missing.png')), /There is no image file at .*missing\.png/)
+ await assert.rejects(readAvatar(dir), /is not an image file/)
+ writeFileSync(join(dir, 'notes.png'), 'this is not an image')
+ await assert.rejects(readAvatar(join(dir, 'notes.png')), /The avatar must be a PNG, JPEG, WebP, or GIF image\. Use a square image; 256x256 is recommended/)
+})
+
+test('an image over the limit is refused with the limit in the message', async (t) => {
+ const huge = Buffer.concat([PNG.subarray(0, 8), Buffer.alloc(200_000)])
+ const dir = tempDir(t)
+ writeFileSync(join(dir, 'huge.png'), huge)
+ const expected = (error) => {
+ assert.match(error.message, /too large: 200008 bytes/)
+ assert.match(error.message, /119982 bytes/)
+ assert.match(error.message, /256x256/)
+ return true
+ }
+ await assert.rejects(readAvatar(join(dir, 'huge.png')), expected)
+ await assert.rejects(readAvatar(asDataUrl('image/png', huge)), expected)
+})
+
+test('an image just under the limit still fits the stored format', async () => {
+ const fits = Buffer.concat([PNG.subarray(0, 8), Buffer.alloc(119_000 - 8, 1)])
+ const url = await readAvatar(asDataUrl('image/png', fits))
+ assert.ok(url.length <= MAX_AVATAR_IMAGE)
+ assert.ok(url.startsWith('data:image/png;base64,'))
+})
+
+test('a malformed data URL is refused', async () => {
+ await assert.rejects(readAvatar('data:image/png;base64'), /no comma/)
+ await assert.rejects(readAvatar('data:image/svg+xml;base64,PHN2Zz4='), /must hold a PNG, JPEG, WebP, or GIF image/)
+ await assert.rejects(readAvatar('data:text/plain;base64,aGVsbG8='), /must hold a PNG, JPEG, WebP, or GIF image/)
+ await assert.rejects(readAvatar('data:image/png,aGVsbG8='), /must be base64 encoded/)
+ await assert.rejects(readAvatar('data:image/png;base64,not base64!'), /does not hold valid base64/)
+ await assert.rejects(readAvatar('data:image/png;base64,aGVsbG8='), /must be a PNG, JPEG, WebP, or GIF image/)
+ await assert.rejects(readAvatar('data:image/png;base64,abcd'), /must be a PNG, JPEG, WebP, or GIF image/)
+})
+
+test('an empty value or a link that is not http(s) is refused', async () => {
+ await assert.rejects(readAvatar(''), /Give an image path, an http\(s\) link, or a data URL/)
+ await assert.rejects(readAvatar(' '), /Give an image path/)
+ await assert.rejects(readAvatar('ftp://example.com/photo.png'), /must be a local image path, an http\(s\) link, or a data URL/)
+ await assert.rejects(readAvatar('file:///tmp/photo.png'), /must be a local image path, an http\(s\) link, or a data URL/)
+})
+
+test('an http link is downloaded, and its content type is not trusted', async (t) => {
+ const server = await serve((request, response) => {
+ if (request.url === '/photo') {
+ response.writeHead(200, { 'content-type': 'text/plain' })
+ response.end(JPEG)
+ return
+ }
+ response.writeHead(404, { 'content-type': 'text/plain' })
+ response.end('no such image')
+ })
+ t.after(server.close)
+ assert.equal(await readAvatar(`${server.url}/photo`), jpegUrl)
+ await assert.rejects(readAvatar(`${server.url}/missing`), /answered 404/)
+})
+
+test('an oversized or slow download is refused', async (t) => {
+ const huge = Buffer.concat([PNG.subarray(0, 8), Buffer.alloc(200_000)])
+ const server = await serve((request, response) => {
+ if (request.url === '/length') {
+ response.writeHead(200, { 'content-length': String(huge.length) })
+ response.end(huge)
+ return
+ }
+ if (request.url === '/chunks') {
+ response.writeHead(200, { 'content-type': 'image/png' })
+ for (let at = 0; at < huge.length; at += 25_000) response.write(huge.subarray(at, at + 25_000))
+ response.end()
+ return
+ }
+ // /slow: keep the request open until the caller's timeout fires.
+ })
+ t.after(server.close)
+ await assert.rejects(readAvatar(`${server.url}/length`), /too large: 200008 bytes/)
+ await assert.rejects(readAvatar(`${server.url}/chunks`), /The avatar image is too large/)
+ await assert.rejects(readAvatar(`${server.url}/slow`, { timeoutMs: 200 }), /did not answer within 0\.2 seconds|did not answer within 1 second/)
+})
diff --git a/ds-bot/test/roster.test.js b/ds-bot/test/roster.test.js
index 6dc8cde5..38842dbe 100644
--- a/ds-bot/test/roster.test.js
+++ b/ds-bot/test/roster.test.js
@@ -763,3 +763,75 @@ test('list_models names the thinking levels of the models a Bot runs on', async
assert.match(result, /deepseek\/deepseek-v4-flash.*thinking: low, high \(default: high\)/)
assert.doesNotMatch(result.split('\n').find(line => line.includes('deepseek/plain')), /thinking/)
})
+
+// #320: create_bot and update_bot take a photo from a local path, a data URL, or an
+// http(s) link, and store it in the same data URL the settings page writes.
+const PNG_BYTES = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(24, 1)])
+const PNG_DATA_URL = `data:image/png;base64,${PNG_BYTES.toString('base64')}`
+const tempAvatarDir = (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'ds-bot-avatar-'))
+ t.after(() => rmSync(dir, { recursive: true, force: true }))
+ return dir
+}
+
+test('create_bot and update_bot advertise an optional photo', async (t) => {
+ const { ctx, stop } = start(undefined, { models: ['deepseek-v4-flash'] })
+ t.after(stop)
+ for (const name of ['create_bot', 'update_bot']) {
+ const schema = ctx.registeredTools.get(name).parameters
+ assert.equal(schema.properties.avatar?.type, 'string')
+ assert.equal(schema.required?.includes('avatar') ?? false, false)
+ assert.match(schema.properties.avatar.description, /local image path.*http\(s\) link.*data URL/)
+ assert.match(schema.properties.avatar.description, /256x256/)
+ }
+})
+
+test('create_bot stores a photo, and update_bot changes and clears it', async (t) => {
+ const { ctx, call, stop, sent } = start(undefined, { models: ['deepseek-v4-flash'] })
+ t.after(stop)
+ const chief = (await call('state', {})).value.mainBotId
+ const dir = tempAvatarDir(t)
+ const photo = join(dir, 'photo.png')
+ writeFileSync(photo, PNG_BYTES)
+ const exec = { agent: { id: chief } }
+ assert.match(await ctx.registeredTools.get('create_bot').execute({ name: 'Writer', role: 'Write', instructions: 'Write', avatar: photo }, exec), /^Created Writer/)
+ const writer = async () => (await call('state', {})).value.bots.find(bot => bot.name === 'Writer')
+ assert.equal((await writer()).avatar.image, PNG_DATA_URL)
+ const writerId = (await writer()).id
+ await until(() => sent.some(entry => entry.sessionId === writerId))
+
+ const tool = args => ctx.registeredTools.get('update_bot').execute({ bot: 'Writer', ...args }, exec)
+ // A mime that does not match the bytes is corrected, not stored as given.
+ assert.equal(await tool({ avatar: `data:image/jpeg;base64,${PNG_BYTES.toString('base64')}` }), 'Updated Writer.')
+ assert.equal((await writer()).avatar.image, PNG_DATA_URL)
+ // An empty string removes the photo, so the Bot shows its character again.
+ assert.equal(await tool({ avatar: '' }), 'Updated Writer.')
+ assert.equal((await writer()).avatar, undefined)
+ // The photo can be set again after it was cleared.
+ assert.equal(await tool({ avatar: PNG_DATA_URL }), 'Updated Writer.')
+ assert.equal((await writer()).avatar.image, PNG_DATA_URL)
+})
+
+test('a photo that cannot be read changes nothing, and a non-Main Bot cannot set another Bot\'s', async (t) => {
+ const { ctx, call, stop, sent } = start(undefined, { models: ['deepseek-v4-flash'] })
+ t.after(stop)
+ const chief = (await call('state', {})).value.mainBotId
+ const dir = tempAvatarDir(t)
+ const notes = join(dir, 'notes.png')
+ writeFileSync(notes, 'this is not an image')
+ const exec = { agent: { id: chief } }
+ assert.match(await ctx.registeredTools.get('create_bot').execute({ name: 'Phantom', role: 'Write', instructions: 'Write', avatar: notes }, exec), /^Could not create the Bot: The avatar must be a PNG, JPEG, WebP, or GIF image/)
+ assert.equal((await call('state', {})).value.bots.some(bot => bot.name === 'Phantom'), false)
+
+ const writer = (await call('create-bot', { name: 'Writer' })).value
+ await until(() => sent.some(entry => entry.sessionId === writer.id))
+ const mine = { agent: { id: writer.id } }
+ // Another Bot's photo is a Main Bot's to change, as its other settings are.
+ assert.match(await ctx.registeredTools.get('update_bot').execute({ bot: 'Chief', avatar: PNG_DATA_URL }, mine), /^Only a Main Bot can change another Bot/)
+ assert.equal((await call('state', {})).value.bots.find(bot => bot.id === chief).avatar?.image, undefined)
+ // Its own it may set; a later bad photo leaves the good one alone.
+ assert.equal(await ctx.registeredTools.get('update_bot').execute({ avatar: PNG_DATA_URL }, mine), 'Updated Writer.')
+ assert.equal((await call('state', {})).value.bots.find(bot => bot.id === writer.id).avatar.image, PNG_DATA_URL)
+ assert.match(await ctx.registeredTools.get('update_bot').execute({ avatar: notes }, mine), /^Could not update the Bot: The avatar must be a PNG/)
+ assert.equal((await call('state', {})).value.bots.find(bot => bot.id === writer.id).avatar.image, PNG_DATA_URL)
+})