A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Name the Session in DS Bot's own model requests
Fei24115bd60b7ca191
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex be0739b5..6a154551 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change## [Unreleased]+### Fixed++- On model providers that need every request to name its conversation, such as OpenCode Go, the memory panel, automatic memory updates, the context check of long chats and image reading for text-only models failed. They now work there too.+## [0.1.4] - 2026-10-13### Addeddiff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 16d1c877..07ddc7c7 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -651,9 +651,10 @@ export function install(rt) {// A group chat's own Session never consults the model: models drift from "only call// group_relay" (they message one member directly when the user names it), so the- // relay step is synthesized here. Auxiliary calls such as titles still reach the model.+ // relay step is synthesized here. Auxiliary calls such as titles, and DS Bot's own+ // calls for the room such as image readings, still reach the model.ctx.on('llm/stream', (options, next) => {- if (options.sessionId === undefined || options.purpose !== undefined) return next()+ if (options.sessionId === undefined || options.purpose !== undefined || rt.ownRequest(options)) return next()return (async function* relayOrPass() {await rt.load()if (rt.roomOf(options.sessionId) === undefined) {diff --git a/ds-bot/src/host/images.js b/ds-bot/src/host/images.jsindex c522db0a..6f9833c8 100644--- a/ds-bot/src/host/images.js+++ b/ds-bot/src/host/images.js@@ -91,10 +91,10 @@ export function install(rt) {const route = await ocrRoute()if (route === undefined) throw new Error('no vision model is available')const assembler = new BlockAssembler()- // No sessionId: this call is not a Session request, so the hook below lets it through.for await (const chunk of ctx.llm.stream({provider: route.provider,model: route.model,+ sessionId,messages: rt.tagUsage([{ role: 'user', content: [{ type: 'image', attachment }, { type: 'text', text: OCR_PROMPT }] }], { sessionId, kind: 'image' }),maxTokens: 8192,signal: AbortSignal.timeout(OCR_TIMEOUT_MS),@@ -176,7 +176,7 @@ export function install(rt) {}ctx.on('llm/stream', (options, next) => {- if (options.sessionId === undefined || !(options.messages ?? []).some(liveImages)) return next()+ if (options.sessionId === undefined || rt.ownRequest(options) || !(options.messages ?? []).some(liveImages)) return next()return (async function* imagesAsTextOrPass() {await rt.load()if (rt.roomOf(options.sessionId) !== undefined || await readsImages(options.provider, options.model)) {diff --git a/ds-bot/src/host/memory.js b/ds-bot/src/host/memory.jsindex aee6322d..b33689e0 100644--- a/ds-bot/src/host/memory.js+++ b/ds-bot/src/host/memory.js@@ -919,6 +919,7 @@ export function install(rt) {for await (const chunk of ctx.llm.stream({provider: route.provider,model: route.model,+ ...(tag?.sessionId === undefined ? {} : { sessionId: tag.sessionId }),...(effort === undefined ? {} : { reasoningEffort: effort }),system,messages,diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex de23473c..f66025d1 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -489,6 +489,7 @@ export function install(rt) {system: STEWARD_SYSTEM,messages: rt.tagUsage([{ role: 'user', content: [{ type: 'text', text: stewardRequest({ lines, midTurn, checkpoints: checkpointCount(session.deriveMessages()), group }) }] }], { sessionId: agent.id, kind: 'compaction' }),maxTokens: STEWARD_MAX_TOKENS,+ sessionId: session.id,purpose: 'compaction',signal: AbortSignal.timeout(STEWARD_TIMEOUT_MS),})) assembler.push(chunk)@@ -902,7 +903,7 @@ export function install(rt) {// in the part's history. When nothing is left to do, that turn's reply is a fixed// line instead of a model call.ctx.on('llm/stream', (options, next) => {- if (options.sessionId === undefined || options.purpose !== undefined) return next()+ if (options.sessionId === undefined || options.purpose !== undefined || rt.ownRequest(options)) return next()const messages = options.messages ?? []const since = messages.findLastIndex(message => message.role === 'assistant' || message.role === 'tool') + 1const opened = messages.slice(since).filter(message => message.role === 'user' && (message.source?.kind === 'user' || message.source?.kind === SOURCE_KIND))diff --git a/ds-bot/src/host/usage.js b/ds-bot/src/host/usage.jsindex 3ff63955..1c021e3d 100644--- a/ds-bot/src/host/usage.js+++ b/ds-bot/src/host/usage.js@@ -523,6 +523,9 @@ export function install(rt) {const tag = from !== null && typeof from === 'object' ? tags.get(from) : undefinedif (tag !== undefined) tagUsage(to, tag)}+ // DS Bot's own requests name the Session they serve, as some routes require, so+ // `sessionId` alone does not make a request that Session's own round; the tag does.+ const ownRequest = options => tags.has(options?.messages)// Owner and group use are journaled with the call itself: a Bot or room that// is deleted before the first scan still leaves its calls under its own name.const journaled = new Map()@@ -590,5 +593,5 @@ export function install(rt) {})()})- Object.assign(rt, { usageView, tagUsage, carryUsageTag })+ Object.assign(rt, { usageView, tagUsage, carryUsageTag, ownRequest })}diff --git a/ds-bot/test/memory.test.js b/ds-bot/test/memory.test.jsindex d49c01b6..297a2a30 100644--- a/ds-bot/test/memory.test.js+++ b/ds-bot/test/memory.test.js@@ -119,8 +119,9 @@ const ownChat = [// The model answers each call with the next of `replies`. `history` holds the events// of a Session, oldest first; each own chat has one user message, at seq 10, unless-// it says otherwise.-function start({ home = mkdtempSync(join(tmpdir(), 'ds-bot-memory-')), replies = [], config = {}, history = {}, reasoning = { efforts: [{ id: 'off' }, { id: 'high' }] } } = {}) {+// it says otherwise. `requireSession` turns down a request without a Session, as+// some routes do.+function start({ home = mkdtempSync(join(tmpdir(), 'ds-bot-memory-')), replies = [], config = {}, history = {}, reasoning = { efforts: [{ id: 'off' }, { id: 'high' }] }, requireSession = false } = {}) {if (!existsSync(join(home, 'state.json'))) writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))const ctx = fakeContext()const requests = []@@ -131,6 +132,7 @@ function start({ home = mkdtempSync(join(tmpdir(), 'ds-bot-memory-')), replies =resolveModelInfo: async () => ({ reasoning }),async* stream(request) {requests.push(request)+ if (requireSession && request.sessionId === undefined) throw new Error('400: {"type":"MissingSessionID","message":"Request is missing x-opencode-session"}')const reply = await replies.shift()if (reply instanceof Error) throw replyconst out = typeof reply === 'object' && reply !== null ? reply : { text: reply ?? '' }@@ -147,6 +149,7 @@ function start({ home = mkdtempSync(join(tmpdir(), 'ds-bot-memory-')), replies =return { records, hasMore: records.length < all.length }},},+ sessions: { messageProjections: [] },workspaceRegistry: { archiveSession: async () => {} },})let route@@ -949,3 +952,67 @@ test('config.memory false leaves the tools, the section, and the panel out', asy// The first state call applies the Bots' models and saves; let that finish first.await settle()})++// Routes such as OpenCode Go turn down a request that names no Session. Each memory+// call names the Bot's own current chat.+const idleSession = { requestHeader: () => undefined }+test('a memory summary names the Bot chat on both of its tries', async (t) => {+ const { tool, call, requests, stop } = start({ requireSession: true, replies: [{ text: 'Half', finish: 'max-tokens' }, 'You like tea.'] })+ t.after(() => stop())+ await tool('remember', { text: 'Likes tea' }, 'b2')+ await call('memory-view', { botId: 'b2', summarize: true })+ await settle()+ const view = (await call('memory-view', { botId: 'b2' })).value+ assert.equal(view.error, null)+ assert.equal(view.summary?.text, 'You like tea.')+ assert.deepEqual(requests.map(request => [request.sessionId, request.maxTokens, request.purpose]), [['b2', 2048, undefined], ['b2', 8192, undefined]])+})++test('a memory panel question names the Bot chat', async (t) => {+ const { call, requests, stop } = start({ requireSession: true, replies: [JSON.stringify({ reply: 'You have no entries yet.', changes: [] })] })+ t.after(() => stop())+ const answer = await call('memory-ask', { botId: 'b2', text: 'What do you remember?' })+ assert.equal(answer.ok, true)+ assert.equal(answer.value.reply, 'You have no entries yet.')+ assert.equal(requests[0].sessionId, 'b2')+})++test('a memory review of a Bot chat names that chat and saves its changes', async (t) => {+ const { ctx, call, read, requests, stop } = start({+ requireSession: true, config: { memoryReviewDelayMs: 0 },+ replies: [JSON.stringify({ changes: [{ op: 'add', text: 'The user wants this remembered' }] })],+ })+ t.after(() => stop())+ await call('state', {})+ ctx.emit('agent/status', { agent: { id: 'b2', session: idleSession }, status: 'idle' })+ await reviewed(call)+ assert.equal(requests.length, 1)+ assert.equal(requests[0].sessionId, 'b2')+ assert.match(read('bots', 'b2', 'MEMORY.md'), /The user wants this remembered/)+})++test('a memory review of a group names the member Bot chat', async (t) => {+ const { ctx, call, read, requests, stop } = start({+ requireSession: true, config: { memoryReviewDelayMs: 0 },+ replies: [JSON.stringify({ changes: [{ op: 'add', text: 'Keep replies under one page', team: true }] })],+ })+ t.after(() => stop())+ await call('state', {})+ ctx.emit('agent/status', { agent: { id: 'g3', session: idleSession }, status: 'idle' })+ await reviewed(call)+ assert.equal(requests.length, 1)+ assert.equal(requests[0].sessionId, 'b3')+ assert.match(read('team', 'MEMORY.md'), /Keep replies under one page/)+})++test('a memory call names the current part of the Bot chat', async (t) => {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-memory-'))+ const team = structuredClone(TEAM)+ team.bots.b2.sessionId = 'b2-part2'+ writeFileSync(join(home, 'state.json'), JSON.stringify(team))+ const { call, requests, stop } = start({ home, requireSession: true, replies: [JSON.stringify({ reply: 'This part.', changes: [] })] })+ t.after(() => stop())+ const answer = await call('memory-ask', { botId: 'b2', text: 'Which part?' })+ assert.equal(answer.ok, true)+ assert.equal(requests[0].sessionId, 'b2-part2')+})diff --git a/ds-bot/test/session-identity.test.js b/ds-bot/test/session-identity.test.jsnew file mode 100644index 00000000..4ac088fe--- /dev/null+++ b/ds-bot/test/session-identity.test.js@@ -0,0 +1,174 @@+import assert from 'node:assert/strict'+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { createRuntime } from '../index.js'+import { fakeContext } from './fake-ctx.js'++// Some routes (OpenCode Go among them) turn down every model request that names no+// Session. DS Bot's own requests name the Session they serve, and the hooks that act+// on a Session's own rounds still leave them alone.++const TEAM = {+ version: 1,+ mainBotIds: ['m1'],+ revision: 1,+ whaleStored: true,+ bots: {+ m1: { id: 'm1', sessionId: 'm1', name: 'Chief', role: 'Chief of Staff', model: 'deepseek/v4', instructions: '', createdAt: 1 },+ b2: { id: 'b2', sessionId: 'b2', name: 'Writer', role: 'Writing', model: 'deepseek/v4', instructions: '', createdAt: 2 },+ b3: { id: 'b3', sessionId: 'b3', name: 'Coder', role: 'Code', model: 'deepseek/v4', instructions: '', createdAt: 3 },+ },+ rooms: {+ r1: { id: 'r1', name: 'Launch', named: true, members: ['b2', 'b3'], admin: 'b3', mode: 'everyone', notice: '', sessions: { b3: 'g3' }, seq: 0, log: [] },+ },+ exchanges: [],+ exchangeTurns: {},+ questions: {},+}++const MISSING = '400: {"type":"MissingSessionID","message":"Request is missing x-opencode-session"}'+const attachment = { attachmentId: `sha256:${'a'.repeat(64)}`, name: 'triangle.png' }+const userText = text => ({ role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text }] })++async function drain(stream) {+ const chunks = []+ for await (const chunk of stream) chunks.push(chunk)+ return chunks+}++// `ctx.llm.stream` runs the plugin's `llm/stream` listeners in order, as DSH does,+// and then a route that turns down a request without a Session. `respond` gives the+// text of each answer the route lets through.+function start() {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-session-identity-'))+ writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))+ const bench = { tokens: 0, compacted: 0, respond: () => '', requests: [] }+ const compaction = {+ summarize() {},+ async compactIfNeeded() {+ bench.compacted += 1+ bench.tokens = 100+ return {}+ },+ async compactNow() {},+ async compactRegion() {},+ }+ const ctx = fakeContext({ services: { compaction, tokenMeter: { measure: () => ({ totalTokens: bench.tokens }) } } })+ async function* route(options) {+ bench.requests.push(options)+ if (options.sessionId === undefined) {+ yield { type: 'finish', reason: { kind: 'error', failure: { message: MISSING } } }+ return+ }+ yield { type: 'text-delta', index: 0, text: bench.respond(options) }+ yield { type: 'finish', reason: { kind: 'stop' } }+ }+ Object.assign(ctx, {+ llm: {+ listProviders: () => [{ id: 'deepseek', name: 'DeepSeek' }],+ listModels: async () => [{ id: 'v4' }, { id: 'vision', inputModalities: ['text', 'image'] }],+ resolveModelInfo: async (_provider, model) => ({+ inputModalities: model === 'vision' ? ['text', 'image'] : ['text'],+ context: { contextWindow: 100_000 },+ defaultMaxTokens: 8_000,+ reasoning: { efforts: [{ id: 'off' }, { id: 'high' }] },+ }),+ stream(options) {+ const chain = ctx.listeners.get('llm/stream') ?? []+ const run = index => (index < chain.length ? chain[index](options, () => run(index + 1)) : route(options))+ return run(0)+ },+ },+ sessionController: {+ resolveAgent: async sessionId => ({ agent: { id: sessionId, session: { id: sessionId, seq: 2 } } }),+ selectModel: async () => {},+ page: async () => ({+ records: [+ { event: { seq: 0, time: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'Keep working on the report' }] } } },+ { event: { seq: 1, time: 2, type: 'assistant/message', data: { message: { content: [{ type: 'text', text: 'Working on it.' }] } } } },+ ],+ hasMore: false,+ }),+ },+ sessions: { messageProjections: [] },+ workspaceRegistry: { archiveSession: async () => {} },+ })+ const rt = createRuntime(ctx, { home })+ const hook = pattern => ctx.listeners.get('llm/stream').find(listener => pattern.test(String(listener)))+ const stop = async () => {+ await ctx.dispose()+ // A reading is cached on disk in the background.+ if (bench.requests.some(request => request.model === 'vision' && request.sessionId !== undefined)) {+ for (let tries = 0; tries < 100 && !existsSync(join(home, 'ocr.json')); tries += 1) await new Promise(resolve => setTimeout(resolve, 10))+ }+ rmSync(home, { recursive: true, force: true, maxRetries: 5 })+ }+ return { ctx, rt, bench, hook, stop }+}++for (const sessionId of ['b2', 'g3']) {+ test(`the context steward names the Session it decides for (${sessionId}), and the part is condensed in place`, async (t) => {+ const { ctx, bench, stop } = start()+ t.after(stop)+ bench.tokens = 95_000+ bench.respond = () => '{"action":"compact"}'+ const session = { id: sessionId, seq: 2, requestHeader: () => ({ config: { provider: 'deepseek', model: 'v4' } }), deriveMessages: () => [], toolHistory: () => [] }+ const preStep = ctx.listeners.get('agent/pre-step').find(listener => /adoptCompaction/.test(String(listener)))+ const next = { kind: 'continue' }+ const result = await preStep({ agent: { id: sessionId, session }, messages: [], step: 2, signal: new AbortController().signal }, () => next)+ assert.equal(result, next)+ assert.equal(bench.compacted, 1)+ assert.deepEqual(bench.requests.map(request => [request.sessionId, request.purpose]), [[sessionId, 'compaction']])+ })+}++test('an image in a Bot chat is read for that chat, and the chat gets the reading', async (t) => {+ const { ctx, bench, stop } = start()+ t.after(stop)+ bench.respond = options => (options.model === 'vision' ? 'A red triangle.' : 'It is a triangle.')+ const message = { role: 'user', source: { kind: 'user' }, content: [{ type: 'image', attachment }, { type: 'text', text: 'What is this?' }] }+ const chunks = await drain(ctx.llm.stream({ provider: 'deepseek', model: 'v4', sessionId: 'b2', messages: [message] }))+ assert.equal(chunks.at(-1).reason.kind, 'stop')+ assert.deepEqual(bench.requests.map(request => [request.model, request.sessionId]), [['vision', 'b2'], ['v4', 'b2']])+ assert.equal(bench.requests[0].messages[0].content[0].type, 'image')+ assert.match(bench.requests[1].messages[0].content[0].text, /A red triangle\./)+})++test('an image in a group is read for the group, and the group still relays its own rounds', async (t) => {+ const { ctx, rt, bench, stop } = start()+ t.after(stop)+ bench.respond = () => 'A red triangle.'+ const [reading] = await rt.imagesForGroup([attachment], 'r1')+ assert.match(reading, /read by vision:\]\nA red triangle\./)+ assert.deepEqual(bench.requests.map(request => [request.model, request.sessionId]), [['vision', 'r1']])++ const chunks = await drain(ctx.llm.stream({ provider: 'deepseek', model: 'v4', sessionId: 'r1', messages: [userText('Discuss the picture')] }))+ assert.ok(chunks.some(chunk => chunk.type === 'tool-call-delta' && chunk.name === 'group_relay'))+ assert.equal(bench.requests.length, 1)+})++test('the Session hooks pass DS Bot\'s own requests through, and still act on a Session\'s own rounds', async (t) => {+ const { rt, hook, stop } = start()+ t.after(stop)+ await rt.load()+ const own = (sessionId, messages) => ({ provider: 'deepseek', model: 'v4', sessionId, messages: rt.tagUsage([...messages], { sessionId, kind: 'memory' }) })+ const round = (sessionId, messages) => ({ provider: 'deepseek', model: 'v4', sessionId, messages })+ const passed = (async function* () {})()+ const pass = () => passed++ const relay = hook(/relayOrPass/)+ assert.equal(relay(own('r1', [userText('Read this')]), pass), passed)+ assert.ok((await drain(relay(round('r1', [userText('Read this')]), pass))).some(chunk => chunk.name === 'group_relay'))++ const handoff = [{ role: 'user', source: { kind: 'bot', handoff: true }, content: [{ type: 'text', text: 'Handoff note' }] }]+ const acknowledge = hook(/acknowledge/)+ assert.equal(acknowledge(own('b2', handoff), pass), passed)+ assert.ok((await drain(acknowledge(round('b2', handoff), pass))).some(chunk => chunk.type === 'text-delta'))++ const picture = [{ role: 'user', source: { kind: 'user' }, content: [{ type: 'image', attachment }] }]+ const images = hook(/imagesAsTextOrPass/)+ assert.equal(images(own('b2', picture), pass), passed)+ assert.notEqual(images(round('b2', picture), pass), passed)+})