A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Refuse writes from a host that lost the state lock
lulu feizhu7018a8becec0
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.jsindex 07cd7474..9df0fc43 100644--- a/ds-bot/src/host/roster.js+++ b/ds-bot/src/host/roster.js@@ -63,45 +63,54 @@ export function install(rt) {const modelRef = model ? await rt.resolveModel(model) : pickModel ? undefined : await rt.defaultModel()const effortId = modelRef !== undefined && effort !== undefined ? await rt.resolveEffort(modelRef, effort) : undefinedconst id = await createSession(cleanName)- state.bots[id] = {- id,- name: cleanName,- role: String(role).trim().slice(0, 24),- // A color is only stored when the user picks one; otherwise the id picks it.- ...(isColor(currentColor(color)) ? { color: currentColor(color) } : {}),- ...(cleanAvatarValue ? { avatar: cleanAvatarValue } : {}),- ...(modelRef ? { model: modelRef } : {}),- ...(effortId ? { effort: effortId } : {}),- instructions: String(instructions).trim(),- createdAt: Date.now(),- createdBy: createdBy ?? null,- }- if (main) state.mainBotIds.push(id)- const creator = rt.botOf(createdBy)- const original = rt.botOf(copyOf)- const language = rt.uiLanguage?.()- const kickoff = main- ? `You were just set up as the user's Main Bot. Greet the user in one or two short messages: say you will run their Bot team and that they can come to you for anything that needs a decision. Then use ask_user to ask what they want the team to help with first (3-4 short options). Write in ${language ?? 'the user\'s language if known; otherwise Chinese'}.`- : original- ? `The user just made you as a copy of ${original.name}: same job, fresh memory. Greet the user in one short message, then use ask_user to ask what this copy should focus on (3-4 short options).`- : creator- ? `${creator.name} just created you for the user.${brief ? ` Why you exist: ${brief}` : ''}\nGreet the user in one short message, then use ask_user to ask where to start (3-4 short options relevant to your role, with allowCustom). Keep it brief.`- : brief- ? `The user just created you and sent this first message:\n\n${brief}\n\nIntroduce yourself in one short line, then help with it.`- : 'The user just created you. Greet the user in one short message, then use ask_user to ask what you should focus on (3-4 short options, with allowCustom).'- const text = !main && language ? `${kickoff}\nWrite in ${language}.` : kickoff- const bot = state.bots[id]- if (modelRef === undefined) {- bot.kickoff = { text, from: createdBy ?? null, ...(main ? { main: true } : {}) }+ try {+ state.bots[id] = {+ id,+ name: cleanName,+ role: String(role).trim().slice(0, 24),+ // A color is only stored when the user picks one; otherwise the id picks it.+ ...(isColor(currentColor(color)) ? { color: currentColor(color) } : {}),+ ...(cleanAvatarValue ? { avatar: cleanAvatarValue } : {}),+ ...(modelRef ? { model: modelRef } : {}),+ ...(effortId ? { effort: effortId } : {}),+ instructions: String(instructions).trim(),+ createdAt: Date.now(),+ createdBy: createdBy ?? null,+ }+ if (main) state.mainBotIds.push(id)+ const creator = rt.botOf(createdBy)+ const original = rt.botOf(copyOf)+ const language = rt.uiLanguage?.()+ const kickoff = main+ ? `You were just set up as the user's Main Bot. Greet the user in one or two short messages: say you will run their Bot team and that they can come to you for anything that needs a decision. Then use ask_user to ask what they want the team to help with first (3-4 short options). Write in ${language ?? 'the user\'s language if known; otherwise Chinese'}.`+ : original+ ? `The user just made you as a copy of ${original.name}: same job, fresh memory. Greet the user in one short message, then use ask_user to ask what this copy should focus on (3-4 short options).`+ : creator+ ? `${creator.name} just created you for the user.${brief ? ` Why you exist: ${brief}` : ''}\nGreet the user in one short message, then use ask_user to ask where to start (3-4 short options relevant to your role, with allowCustom). Keep it brief.`+ : brief+ ? `The user just created you and sent this first message:\n\n${brief}\n\nIntroduce yourself in one short line, then help with it.`+ : 'The user just created you. Greet the user in one short message, then use ask_user to ask what you should focus on (3-4 short options, with allowCustom).'+ const text = !main && language ? `${kickoff}\nWrite in ${language}.` : kickoff+ const bot = state.bots[id]+ if (modelRef === undefined) {+ bot.kickoff = { text, from: createdBy ?? null, ...(main ? { main: true } : {}) }+ await rt.save()+ return bot+ }await rt.save()+ // The greeting runs on the Bot's own model, once its provider is registered.+ void rt.waitForModel(bot)+ .then(() => rt.applyModel(bot).catch(error => rt.warn('ds-bot: model for %s not applied: %s', cleanName, error)))+ .then(() => sendKickoff(bot, { text, from: createdBy }))return bot+ } catch (error) {+ // The Bot's Session was already made: archive it instead of leaving an orphan.+ delete state.bots[id]+ state.mainBotIds = state.mainBotIds.filter(other => other !== id)+ rt.chatOwners.delete(id)+ await ctx.workspaceRegistry.archiveSession(id).catch(() => {})+ throw error}- await rt.save()- // The greeting runs on the Bot's own model, once its provider is registered.- void rt.waitForModel(bot)- .then(() => rt.applyModel(bot).catch(error => rt.warn('ds-bot: model for %s not applied: %s', cleanName, error)))- .then(() => sendKickoff(bot, { text, from: createdBy }))- return bot}function sendKickoff(bot, { text, from }) {@@ -242,19 +251,26 @@ export function install(rt) {if (mode !== undefined && !ROOM_MODES.includes(mode)) throw new Error(`Reply mode must be one of ${ROOM_MODES.join(', ')}`)const title = custom || autoRoomName(members)const id = await createSession(title)- state.rooms[id] = {- id,- name: title,- ...(custom ? { named: true } : {}),- members,- admin: adminId,- mode: mode ?? 'admin',- notice: cleanNotice(notice),- createdAt: Date.now(),- createdBy: createdBy ?? null,+ try {+ state.rooms[id] = {+ id,+ name: title,+ ...(custom ? { named: true } : {}),+ members,+ admin: adminId,+ mode: mode ?? 'admin',+ notice: cleanNotice(notice),+ createdAt: Date.now(),+ createdBy: createdBy ?? null,+ }+ await rt.save()+ return state.rooms[id]+ } catch (error) {+ // The group's Session was already made: archive it instead of leaving an orphan.+ delete state.rooms[id]+ await ctx.workspaceRegistry.archiveSession(id).catch(() => {})+ throw error}- await rt.save()- return state.rooms[id]}// `actorId` is the Bot asking, or undefined for the user. Returns what changed, in words.diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.jsindex 8e528a9d..77d07b2f 100644--- a/ds-bot/src/host/store.js+++ b/ds-bot/src/host/store.js@@ -161,7 +161,7 @@ export function install(rt) {if (holder !== undefined) warn('ds-bot: %s', readOnly())const { migrated, stale } = adopt(await readFileState())if (holder !== undefined) return- if (migrated && stuck === undefined) await save()+ if (migrated && stuck === undefined && lockError === undefined) await save()// Not awaited: renaming a session must not hold up the first roster read.for (const room of stale) void rt.retitleRoom(room)})()@@ -178,6 +178,20 @@ export function install(rt) {adopt(await readFileState())return}+ } else if (!lock.owns()) {+ // A cached "writer" is stale once the lock file no longer names this host:+ // another dsh may have taken it over, or the file may just be gone. Re-claim+ // and re-check instead of trusting the flag.+ claimLock()+ if (lockError !== undefined) return+ if (holder === undefined) {+ // The lock was free: still the writer, but the file may carry changes+ // written while no host held it.+ warnedReadOnly = false+ adopt(await readFileState())+ return+ }+ warn('ds-bot: %s', readOnly())}if ((stuck !== undefined || holder !== undefined) && stamp() !== seen) adopt(await readFileState())}@@ -208,7 +222,11 @@ export function install(rt) {if (stopped) return writingindexSessions()// A reading host keeps the file's revision, so its window does not skip the next change.- if (!writable()) return writing+ if (!writable()) {+ const error = new Error(readOnly())+ error.code = 'bot/read-only'+ return Promise.reject(error)+ }state.revision += 1state.exchanges = state.exchanges.slice(-MAX_EXCHANGES)const snapshot = JSON.stringify(state, null, 2)diff --git a/ds-bot/test/roster.test.js b/ds-bot/test/roster.test.jsindex 89cd9d88..8d6d4f68 100644--- a/ds-bot/test/roster.test.js+++ b/ds-bot/test/roster.test.js@@ -1,6 +1,6 @@import assert from 'node:assert/strict'import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'+import { hostname, tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'import { apply } from '../index.js'@@ -281,3 +281,55 @@ test('a hidden Bot made Main Bot shows again, and a replaced Chief drops its helawait settle()assert.equal(sent.length, greeted)})++const takeover = (home, team) => {+ writeFileSync(join(home, 'state.lock'), JSON.stringify({ pid: process.ppid, host: hostname(), token: 'new-owner' }))+ if (team !== undefined) writeFileSync(join(home, 'state.json'), JSON.stringify(team))+}++test('a host that loses its lock to another dsh refuses changes instead of making a phantom Bot', async (t) => {+ const { call, stop, home, ctx } = start({ version: 1, mainBotIds: ['chief'], bots: { chief: { id: 'chief', name: 'Chief' } } })+ t.after(stop)+ assert.equal((await call('state', {})).value.readOnly, null)+ let created = 0+ const create = ctx.sessionController.create+ ctx.sessionController.create = async (...args) => { created += 1; return create(...args) }+ // Another live dsh takes the lock and writes its own team.+ takeover(home, { version: 1, revision: 9, mainBotIds: ['chief'], bots: { chief: { id: 'chief', name: 'Chief' }, other: { id: 'other', name: 'FromB' } } })+ const answer = await call('create-bot', { name: 'Phantom' })+ assert.equal(answer.ok, false)+ assert.equal(answer.error.code, 'bot/read-only')+ assert.equal(created, 0)+ // The file keeps the new owner's team, and this host now follows it.+ const team = (await call('state', {})).value+ assert.match(team.readOnly, /another dsh/)+ assert.ok(team.bots.some(bot => bot.name === 'FromB'))+ assert.equal(team.bots.some(bot => bot.name === 'Phantom'), false)+})++test('a write refused at save time archives the Session it made', async (t) => {+ const { call, stop, home, ctx } = start({ version: 1, mainBotIds: ['chief'], bots: { chief: { id: 'chief', name: 'Chief' } } })+ t.after(stop)+ await call('state', {})+ const created = []+ const create = ctx.sessionController.create+ ctx.sessionController.create = async (...args) => {+ const made = await create(...args)+ created.push(made.sessionId)+ // The lock goes to another live dsh after this request's refresh, before its save.+ takeover(home)+ return made+ }+ const archived = []+ const archive = ctx.workspaceRegistry.archiveSession+ ctx.workspaceRegistry.archiveSession = async (id) => { archived.push(id); return archive(id) }+ const answer = await call('create-bot', { name: 'Phantom' })+ assert.equal(answer.ok, false)+ assert.equal(answer.error.code, 'bot/read-only')+ assert.deepEqual(archived, created)+ const team = (await call('state', {})).value+ assert.match(team.readOnly, /another dsh/)+ assert.equal(team.bots.some(bot => bot.name === 'Phantom'), false)+ const saved = JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))+ assert.equal(Object.values(saved.bots).some(bot => bot.name === 'Phantom'), false)+})diff --git a/ds-bot/test/store.test.js b/ds-bot/test/store.test.jsindex ede3abd4..3c0a8a2b 100644--- a/ds-bot/test/store.test.js+++ b/ds-bot/test/store.test.js@@ -112,7 +112,7 @@ test('malformed state stays read-only when its backup cannot be copied', async (await rt.load()assert.match(rt.readOnly(), /could not be read/)rt.state.prefs.marker = 'not saved'- await rt.save()+ await assert.rejects(rt.save(), { code: 'bot/read-only' })assert.equal(fs.readFileSync(statePath, 'utf8'), original)assert.deepEqual(fs.readdirSync(rt.home).filter(name => name.startsWith('state.json.broken-')), [])} finally {@@ -126,7 +126,7 @@ test('a state from a newer version remains untouched', async (t) => {await rt.load()assert.match(rt.readOnly(), /saved by a newer DS Bot; update DS Bot/)rt.state.prefs.marker = 'not saved'- await rt.save()+ await assert.rejects(rt.save(), { code: 'bot/read-only' })assert.equal(fs.readFileSync(statePath, 'utf8'), original)})@@ -143,7 +143,7 @@ test('a read error keeps the existing state read-only', async (t) => {restore()}assert.match(rt.readOnly(), /could not be read \(EACCES\)/)- await rt.save()+ await assert.rejects(rt.save(), { code: 'bot/read-only' })assert.equal(fs.readFileSync(statePath, 'utf8'), original)})@@ -172,7 +172,7 @@ test('an unusable state lock fails closed', async (t) => {await rt.load()assert.match(rt.readOnly(), /cannot lock the Bot team.*EACCES/)rt.state.prefs.marker = 'not saved'- await rt.save()+ await assert.rejects(rt.save(), { code: 'bot/read-only' })assert.equal(fs.existsSync(statePath), false)} finally {restore()