A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Look up Bots, groups and other records by their own keys only
Fei2411192d137d4daa
diff --git a/ds-bot/src/host/agents.js b/ds-bot/src/host/agents.jsindex 2ca06f28..160b80d2 100644--- a/ds-bot/src/host/agents.js+++ b/ds-bot/src/host/agents.js@@ -78,7 +78,7 @@ export function install(rt) {if (readOnly !== undefined) throw new Error(readOnly)}const record = (agentId) => {- const agent = state.agents[agentId]+ const agent = rt.own(state.agents, agentId)if (agent === undefined) throw new Error('Unknown DSH Agent')return agent}diff --git a/ds-bot/src/host/capabilities.js b/ds-bot/src/host/capabilities.jsindex e8f97661..8066cc25 100644--- a/ds-bot/src/host/capabilities.js+++ b/ds-bot/src/host/capabilities.js@@ -1,5 +1,6 @@import { createHash } from 'node:crypto'import { encodeUrlComponent } from './secrets.js'+import { own } from './store.js'const MCP_CLIENT = '@deepseek-ai/dsh-mcp-client'const NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/@@ -17,11 +18,11 @@ export function validateCapabilityName(value) {export function expandCapabilityNames(capabilities, library) {const expanded = new Set()for (const name of capabilities ?? []) {- const item = library[name]+ const item = own(library, name)if (!item) throw new Error(`No capability named ${name}.`)if (item.kind === 'pack') {for (const childName of item.items ?? []) {- const child = library[childName]+ const child = own(library, childName)if (!child || !['mcp', 'skill'].includes(child.kind)) throw new Error(`Pack ${name} refers to an unavailable capability ${childName}.`)expanded.add(childName)}@@ -74,8 +75,10 @@ export function install(rt) {}const allowedToEdit = (item, botId) => rt.isMain(botId) || item.createdBy === botIdconst usedByOthers = (name, botId) => Object.values(state.bots).some(bot => bot.id !== botId- && (bot.capabilities ?? []).some(attached => attached === name- || (library()[attached]?.kind === 'pack' && (library()[attached].items ?? []).includes(name))))+ && (bot.capabilities ?? []).some((attached) => {+ const item = own(library(), attached)+ return attached === name || (item?.kind === 'pack' && (item.items ?? []).includes(name))+ }))// A creator that is not a Main Bot could otherwise rewrite what a Main Bot runs.const editCheck = (item, botId, verb) => {if (!allowedToEdit(item, botId)) throw new Error(`Only ${item.createdBy ? 'its creator or a Main Bot' : 'a Main Bot'} can ${verb} ${item.name}.`)@@ -86,7 +89,7 @@ export function install(rt) {const kind = body.kindif (!['mcp', 'skill', 'pack'].includes(kind)) throw new Error('Choose an MCP server, skill, or pack.')const items = ensureLibrary()- const previous = items[name]+ const previous = own(items, name)if (previous && !ui) editCheck(previous, botId, 'change')if (previous && previous.kind !== kind) throw new Error('A capability cannot change its kind. Delete it and save a new one.')const now = Date.now()@@ -121,7 +124,7 @@ export function install(rt) {} else {const names = [...new Set(strings(body.items))]for (const childName of names) {- const child = items[childName]+ const child = own(items, childName)if (!child || !['mcp', 'skill'].includes(child.kind)) throw new Error(`Packs can include only saved MCP servers and skills. ${childName} is not one.`)}item.items = names@@ -140,7 +143,7 @@ export function install(rt) {await rt.load()writeCheck()const items = ensureLibrary()- const item = items[String(name ?? '')]+ const item = own(items, String(name ?? ''))if (!item) throw new Error(`No capability named ${name}.`)if (!ui) editCheck(item, botId, 'delete')delete items[item.name]@@ -157,7 +160,7 @@ export function install(rt) {const target = targetRef ? rt.findBot(targetRef) : callerif (!target) throw new Error(`No Bot named ${targetRef}.`)if (target.id !== caller.id && !rt.isMain(callerId)) throw new Error('Only a Main Bot can change another Bot’s capabilities.')- const item = ensureLibrary()[String(name ?? '')]+ const item = own(ensureLibrary(), String(name ?? ''))if (!item) throw new Error(`No capability named ${name}.`)await setAttached(target, item.name, endpoint === 'attach')return { bot: target.name, attached: endpoint === 'attach' }@@ -211,7 +214,7 @@ export function install(rt) {for (const bot of Object.values(state.bots)) {const statuses = {}for (const name of bot.capabilities ?? []) {- const item = library()[name]+ const item = own(library(), name)if (!item) continueif (item.kind !== 'pack') {const status = statusFor(bot.id, name)@@ -270,7 +273,7 @@ export function install(rt) {}const mountOne = async (agent, bot, agentMounts, name) => {const sessionId = agent.session.id- const item = library()[name]+ const item = own(library(), name)const drop = async () => {await disposeMount(agentMounts.get(name))agentMounts.delete(name)@@ -456,7 +459,7 @@ export function install(rt) {if (endpoint === 'capability-approve') {await rt.load()writeCheck()- const item = library()[String(body.name ?? '')]+ const item = own(library(), String(body.name ?? ''))if (!item || item.kind !== 'mcp' || item.transport !== 'stdio') throw new Error(`No unapproved stdio MCP named ${body.name}.`)item.approved = trueitem.updatedAt = Date.now()@@ -469,7 +472,7 @@ export function install(rt) {const bot = rt.botOf(String(body.botId ?? ''))if (!bot) throw new Error('Unknown Bot')const name = String(body.name ?? '')- if (!library()[name]) throw new Error(`No capability named ${name}.`)+ if (!own(library(), name)) throw new Error(`No capability named ${name}.`)return setAttached(bot, name, body.attached === true)}throw new Error('Unknown capability operation.')diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.jsindex f5199243..6168b5ee 100644--- a/ds-bot/src/host/channel.js+++ b/ds-bot/src/host/channel.js@@ -247,7 +247,7 @@ export function install(rt) {return ok(await rt.stopMemberWork(String(body.roomId ?? ''), String(body.botId ?? '')))case 'dismiss-question':await rt.load()- if (state.questions[body.sessionId] !== undefined) {+ if (rt.own(state.questions, body.sessionId) !== undefined) {delete state.questions[body.sessionId]await rt.save()}@@ -285,7 +285,7 @@ export function install(rt) {await rt.load()const past = rt.pastOwners.get(body.sessionId)const sessionId = rt.botOf(body.sessionId) ? rt.chatOf(body.sessionId) : past && past.roomId === undefined ? rt.chatOf(past.botId) : body.sessionId- const question = state.questions[sessionId]+ const question = rt.own(state.questions, sessionId)if (question === undefined || question.id !== body.questionId) return fail('This question is no longer open', 'bot/stale')const reply = questionReply(question, body.answer)if (reply === undefined) return fail('Nothing to send', 'bot/invalid')diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.jsindex 57ec0815..6a2625c3 100644--- a/ds-bot/src/host/groups.js+++ b/ds-bot/src/host/groups.js@@ -785,7 +785,7 @@ export function install(rt) {await rt.load()const room = rt.roomOf(roomId)const member = rt.botOf(botId)- const sessionId = room?.sessions?.[botId]+ const sessionId = rt.own(room?.sessions, botId)if (room === undefined || member === undefined || sessionId === undefined || rt.live.get(sessionId)?.turn === undefined) return falseconst agent = await rt.resolveAgent(sessionId)agent.cancel({ kind: 'user' })diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex 1475afeb..8f1ccd1b 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -267,7 +267,7 @@ export function install(rt) {}async function setFlags(id, { pinned, hidden }) {- const entry = rt.botOf(id) ?? rt.roomOf(id) ?? state.agents[id]+ const entry = rt.botOf(id) ?? rt.roomOf(id) ?? rt.own(state.agents, id)if (entry === undefined) throw new Error('Unknown conversation')if (typeof pinned === 'boolean') entry.pinned = pinnedif (typeof hidden === 'boolean') entry.hidden = hiddendiff --git a/ds-bot/src/host/schedules.js b/ds-bot/src/host/schedules.jsindex b5929ffd..469d8134 100644--- a/ds-bot/src/host/schedules.js+++ b/ds-bot/src/host/schedules.js@@ -69,7 +69,7 @@ function selectorOf(when) {}export function install(rt) {- const { ctx, state } = rt+ const { ctx } = rtlet service = nullconst attach = (sub) => {@@ -88,7 +88,7 @@ export function install(rt) {if (rt.roomOf(sessionId) !== undefined) return { roomId: sessionId }return rt.groupOwners.get(sessionId) ?? rt.pastOwners.get(sessionId)}- const known = owner => owner !== undefined && (owner.botId === undefined ? state.rooms[owner.roomId] !== undefined : state.bots[owner.botId] !== undefined)+ const known = owner => owner !== undefined && (owner.botId === undefined ? rt.roomOf(owner.roomId) !== undefined : rt.botOf(owner.botId) !== undefined)async function schedulesView() {if (service === null) return { available: false, tasks: [] }@@ -105,8 +105,8 @@ export function install(rt) {schedules: () => schedulesView(),async 'schedule-create'(body) {if (service === null) throw invalid('Automation tasks are off in DSH')- const bot = state.bots[body.target]- const room = state.rooms[body.target]+ const bot = rt.botOf(body.target)+ const room = rt.roomOf(body.target)if (bot === undefined && room === undefined) throw invalid('No such Bot or group chat')const title = String(body.title ?? '').trim()const prompt = String(body.prompt ?? '').trim()diff --git a/ds-bot/src/host/secrets.js b/ds-bot/src/host/secrets.jsindex 2813a29d..a78ffd02 100644--- a/ds-bot/src/host/secrets.js+++ b/ds-bot/src/host/secrets.js@@ -171,7 +171,14 @@ export function install(rt) {usedTimer.unref?.()}- const requestsOf = botId => ((state.secretRequests ??= {})[botId] ??= [])+ // A Bot's pending secret cards, keyed by its id. A key that is not a real Bot (and+ // never an inherited name like "__proto__", which a plain assignment would not even+ // set as a key) gets a throwaway list instead of a stored one.+ const requestsOf = (botId) => {+ const requests = (state.secretRequests ??= {})+ if (!Object.hasOwn(requests, botId) && rt.botOf(botId) === undefined) return []+ return (requests[botId] ??= [])+ }const findRequest = (id) => {for (const [botId, list] of Object.entries(state.secretRequests ?? {})) {const request = list.find(entry => entry.id === id)diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex 6cd47164..c13c68a5 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -8,6 +8,12 @@ import { LEGACY_THEMES, MAX_EXCHANGES, ROOM_MODES, TEXT_KEPT } from './constantsimport { homeLock } from './home-lock.js'import { currentColor, headOf, normalize, unquote } from './text.js'+// A table read that sees only the keys the table holds itself. Ids that come from+// outside (a request body, a tool argument, a name a model gives) go through this, so+// "__proto__" and other inherited names read as "not there" instead of returning+// Object.prototype.+export const own = (table, key) => (table != null && Object.hasOwn(table, key) ? table[key] : undefined)+export function install(rt) {const { ctx, home, statePath } = rt@@ -314,8 +320,8 @@ export function install(rt) {return writing.finally(() => lock.release())}, 'ds-bot: state lock')- const botOf = id => (id === undefined ? undefined : state.bots[id])- const roomOf = id => (id === undefined ? undefined : state.rooms[id])+ const botOf = id => (id === undefined ? undefined : own(state.bots, id))+ const roomOf = id => (id === undefined ? undefined : own(state.rooms, id))const isMain = id => id !== undefined && state.mainBotIds.includes(id)// Group Sessions. A member speaks in each group from a hidden Session of its own,@@ -381,21 +387,23 @@ export function install(rt) {}const findBot = (ref) => {if (ref === undefined) return undefined- if (state.bots[ref]) return state.bots[ref]+ const byId = own(state.bots, ref)+ if (byId) return byIdconst wanted = normalize(ref).replace(/^@/, '')return Object.values(state.bots).find(bot => normalize(bot.name) === wanted)}// Every group chat whose id or name matches; callers refuse an ambiguous name.const findRooms = (ref) => {if (ref === undefined || ref === null) return []- if (state.rooms[ref]) return [state.rooms[ref]]+ const byId = own(state.rooms, ref)+ if (byId) return [byId]const wanted = normalize(unquote(ref))return Object.values(state.rooms).filter(room => normalize(room.name) === wanted)}const isAdminOf = (room, id) => id !== undefined && room.admin === idObject.assign(rt, {- state, load, save, refresh, readOnly,+ state, load, save, refresh, readOnly, own,botOf, roomOf, isMain, chatOf, selfOf, isBotSession,chatOwners, groupOwners, pastOwners,groupSessionsOf, dropGroupSession, retireGroupSession, findBot, findRooms, isAdminOf,diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.jsindex dcd264ad..9bce15e5 100644--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@ -705,9 +705,9 @@ export function install(rt) {if (!rt.botOf(self)) return `Only Bots on the team can use ${name}.`try {const result = await rt.changeCapabilityAttachment(endpoint, args, self)- const attached = state.capabilities.items[args.name]+ const attached = rt.own(state.capabilities.items, args.name)const members = attached?.kind === 'pack'- ? (attached.items ?? []).map(child => state.capabilities.items[child]).filter(Boolean)+ ? (attached.items ?? []).map(child => rt.own(state.capabilities.items, child)).filter(Boolean): attached ? [attached] : []const approvals = members.filter(item => item.kind === 'mcp' && item.transport === 'stdio' && item.approved !== true)diff --git a/ds-bot/src/host/usage.js b/ds-bot/src/host/usage.jsindex a6033e27..d19c0f8c 100644--- a/ds-bot/src/host/usage.js+++ b/ds-bot/src/host/usage.js@@ -454,7 +454,7 @@ export function install(rt) {}if (key.startsWith('agent:')) {const id = key.slice('agent:'.length)- const agent = state.agents?.[id]+ const agent = rt.own(state.agents, id)return { key, kind: 'agent', id, name: agent?.name ?? name, ...(agent ? {} : { deleted: true }) }}const bot = rt.botOf(key)diff --git a/ds-bot/test/own-keys.test.js b/ds-bot/test/own-keys.test.jsnew file mode 100644index 00000000..1bb19bda--- /dev/null+++ b/ds-bot/test/own-keys.test.js@@ -0,0 +1,164 @@+import assert from 'node:assert/strict'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { apply } from '../index.js'+import { fakeContext } from './fake-ctx.js'++// Ids that name an inherited property: a lookup that misses Object.hasOwn would find+// these on every table and could write onto Object.prototype.+const BAD = ['__proto__', 'constructor', 'prototype', 'toString', 'hasOwnProperty']++const TEAM = {+ version: 1,+ mainBotIds: ['m1'],+ revision: 1,+ whaleStored: true,+ bots: {+ m1: { id: 'm1', sessionId: 'm1', name: 'Chief', role: 'Lead', model: 'deepseek/v4', instructions: '', createdAt: 1, capabilities: [] },+ b2: { id: 'b2', sessionId: 'b2', name: 'Writer', role: 'Write', model: 'deepseek/v4', instructions: '', createdAt: 2, capabilities: [] },+ },+ rooms: {+ r1: { id: 'r1', name: 'Launch', named: true, members: ['m1', 'b2'], admin: 'm1', mode: 'everyone', notice: '', sessions: { b2: 'g2' }, seq: 0, log: [] },+ },+ agents: {},+ capabilities: { items: {} },+ exchanges: [],+ exchangeTurns: {},+ works: {},+ questions: {},+ prefs: {},+}++// An in-memory stand-in for DSH's schedule service, so schedule-create reaches the+// Bot/group lookup it does.+function scheduleService() {+ return {+ tasks: [],+ async create(sessionId, request) { this.tasks.push({ sessionId, request }); return { id: `s${this.tasks.length}` } },+ async list() { return [] },+ async catalog() { return [] },+ async delete() { return { deleted: false } },+ }+}++function start() {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-own-keys-'))+ writeFileSync(join(home, 'state.json'), JSON.stringify(TEAM))+ const ctx = fakeContext({ services: { schedule: scheduleService() } })+ Object.assign(ctx, {+ llm: {+ listProviders: () => [{ id: 'deepseek', name: 'DeepSeek' }],+ listModels: async () => [{ id: 'v4' }],+ resolveModelInfo: async () => ({}),+ },+ sessionController: {+ create: async () => ({ sessionId: 'fresh' }),+ resolveAgent: async sessionId => ({ agent: { session: { id: sessionId, seq: 1 }, followup() {} } }),+ selectModel: async () => {},+ prompt: async () => { throw new Error('no such session') },+ },+ sessionTitle: { rename: async () => {} },+ sessions: { flush: async () => {} },+ workspaceRegistry: { get: () => undefined, resolveByPath: async () => undefined, create: async path => ({ id: 'w1', path }), archiveSession: async () => {} },+ })+ const register = ctx.connection.fetch.register+ ctx.connection.fetch.register = (route) => { ctx.route = route; return register(route) }+ apply(ctx, { home })+ const call = async (endpoint, payload) => (await ctx.route.fetch(new Request('http://localhost/api/bot', {+ method: 'POST', body: JSON.stringify({ endpoint, payload }),+ }))).json()+ const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: { id: sessionId } })+ const state = () => readFileSync(join(home, 'state.json'), 'utf8')+ const stop = async () => {+ await ctx.dispose()+ rmSync(home, { recursive: true, force: true, maxRetries: 5 })+ }+ return { ctx, call, tool, state, stop }+}++// Each endpoint's answer for an inherited name must be the same as for an id that is+// simply not there; in particular never ok and never bot/internal unless an unknown+// id gets that too.+const ENDPOINTS = [+ ['update-bot', id => ({ id, role: 'x' })],+ ['delete-bot', id => ({ id })],+ ['duplicate-bot', id => ({ id })],+ ['set-flags', id => ({ id, pinned: true })],+ ['set-main', id => ({ id, main: false })],+ ['update-room', id => ({ id, name: 'Renamed' })],+ ['delete-room', id => ({ id })],+ ['stop-member-work', id => ({ roomId: id, botId: 'b2' })],+ ['stop-member-work', id => ({ roomId: 'r1', botId: id })],+ ['schedule-create', id => ({ target: id, title: 't', prompt: 'p', when: { kind: 'every', minutes: 5 } })],+ ['dismiss-question', id => ({ sessionId: id })],+ ['answer-question', id => ({ sessionId: id, questionId: 'q1', answer: 'yes' })],+ ['capability-delete', id => ({ name: id })],+ ['capability-approve', id => ({ name: id })],+ ['bot-capability', id => ({ botId: 'b2', name: id, attached: true })],+ ['bot-capability', id => ({ botId: id, name: 'x', attached: true })],+ ['create-room', id => ({ members: [id, 'b2'] })],+ ['chat', id => ({ botId: id })],+ ['earlier', id => ({ sessionId: id })],+ ['run-stats', id => ({ botId: id })],+ ['send', id => ({ sessionId: id, text: 'hi' })],+ ['agent-session', id => ({ agentId: id })],+ ['remove-agent', id => ({ agentId: id })],+]++test('api endpoints answer an inherited name like any unknown id and never write through it', async (t) => {+ const { call, state, stop } = start()+ t.after(stop)+ const prototypeNames = Object.getOwnPropertyNames(Object.prototype)+ const before = state()+ for (const [endpoint, payload] of ENDPOINTS) {+ const control = await call(endpoint, payload('id-that-is-not-there'))+ for (const id of BAD) {+ const result = await call(endpoint, payload(id))+ assert.equal(result.ok, control.ok, `${endpoint} ${id}: ${JSON.stringify(result)}`)+ assert.equal(result.error?.code, control.error?.code, `${endpoint} ${id}: ${JSON.stringify(result)}`)+ assert.notEqual(result.error?.code, 'bot/internal', `${endpoint} ${id}: ${JSON.stringify(result)}`)+ }+ }+ assert.deepEqual(Object.getOwnPropertyNames(Object.prototype), prototypeNames)+ assert.equal({}.role, undefined)+ assert.equal({}.hidden, undefined)+ assert.equal({}.name, undefined)+ assert.equal(state(), before)+})++test('tools answer an inherited Bot name like any unknown name', async (t) => {+ const { tool, state, stop } = start()+ t.after(stop)+ const prototypeNames = Object.getOwnPropertyNames(Object.prototype)+ const before = state()+ for (const id of BAD) {+ assert.equal(await tool('message_bot', { to: id, message: 'hi' }, 'm1'), `No Bot named ${id}. Team: Chief, Writer`)+ assert.equal(await tool('update_bot', { bot: id, role: 'x' }, 'm1'), `No Bot named ${id}.`)+ assert.match(await tool('create_group', { members: [id, 'Writer'] }, 'm1'), new RegExp(`^No Bot named ${id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`))+ // Asking as a Bot named like this finds no caller either.+ assert.equal(await tool('update_bot', { name: 'King' }, id), 'Only Bots on the team can use update_bot.')+ }+ assert.deepEqual(Object.getOwnPropertyNames(Object.prototype), prototypeNames)+ assert.equal(state(), before)+})++test('a capability may be called constructor, and inherited names read as missing', async (t) => {+ const { call, stop } = start()+ t.after(stop)+ const prototypeNames = Object.getOwnPropertyNames(Object.prototype)+ const saved = await call('capability-save', { name: 'constructor', kind: 'skill', content: 'first' })+ assert.equal(saved.ok, true, JSON.stringify(saved))+ const updated = await call('capability-save', { name: 'constructor', kind: 'skill', content: 'second' })+ assert.equal(updated.ok, true, JSON.stringify(updated))+ assert.equal(updated.value.content, 'second')+ assert.equal((await call('capability-delete', { name: 'constructor' })).ok, true)+ for (const id of BAD) {+ const gone = await call('capability-delete', { name: id })+ assert.equal(gone.ok, false)+ assert.match(gone.error.message, /No capability named/)+ assert.notEqual(gone.error.code, 'bot/internal')+ }+ assert.deepEqual(Object.getOwnPropertyNames(Object.prototype), prototypeNames)+})