A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Check working folder approvals against every Session that moves
Fei24114fe7017b3508
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 129b73d9..aae8260a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,11 @@ All notable changes to DS Bot are listed here. The format follows [Keep a Change### Added-- **Working folder**: a Bot can work directly in a folder you choose instead of the team workspace. Set it in the Bot's settings or details panel: type a path, pick one of your DSH projects, or browse. A group chat can set one folder for all its members there. You can also ask a Bot to change its own folder, or a Main Bot to change any Bot's or group's folder. A Bot that sets a folder outside the team workspace for Bots that can only write in their folder asks for your approval first. After a change, the Bot's chat goes on in a fresh part that starts in the new folder.+- **Working folder**: a Bot can work directly in a folder you choose instead of the team workspace. Set it in the Bot's settings or details panel: type a path, pick one of your DSH projects, or browse. A group chat can set one folder for all its members there. You can also ask a Bot to change its own folder, or a Main Bot to change any Bot's or group's folder. A Bot that sets a folder outside the team workspace, or adds a Bot to a group that works in one, asks for your approval first when those Bots can only write in their folder. After a change, the Bot's chat goes on in a fresh part that starts in the new folder.++### Fixed++- With `DSH_HOME` empty or starting with `~`, DS Bot now keeps its data in `bot/` inside the folder dsh uses. Before, it used a folder relative to the one dsh was started in; to keep a team made that way, close dsh and move that `bot/` folder into dsh's folder.## [0.1.4] - 2026-10-13diff --git a/ds-bot/README.md b/ds-bot/README.mdindex 19316d26..f04b118d 100644--- a/ds-bot/README.md+++ b/ds-bot/README.md@@ -9,7 +9,7 @@ Tested with dsh `0.2.1-alpha.1` (Web and Desktop) on Linux.## Features- **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 for Bots that can only write in their folder, it asks for your approval. Folders that hold dsh data (`$DSH_HOME`, the team's data) are refused.+- **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.- **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.- **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/index.js b/ds-bot/index.jsindex 9e15aa4f..9cdb56ac 100644--- a/ds-bot/index.js+++ b/ds-bot/index.js@@ -1,7 +1,6 @@// DS Bot: a team of long-lived Bots on top of ordinary dsh root Sessions.// Every Bot is one root Session; the roster, rooms, and the bot-to-bot exchange log live// in one JSON file under DSH_HOME so they survive restarts without new Session event types.-import { homedir } from 'node:os'import { join } from 'node:path'import * as diagnostics from './src/host/diagnostics.js'import * as store from './src/host/store.js'@@ -48,7 +47,7 @@ export function apply(ctx, config = {}) {}export function createRuntime(ctx, config = {}) {- const dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh')+ const dshHome = folders.dshHomeOf(process.env.DSH_HOME)const home = config.home ?? join(dshHome, 'bot')const rt = {ctx,diff --git a/ds-bot/src/host/folders.js b/ds-bot/src/host/folders.jsindex 035f7c46..4261da74 100644--- a/ds-bot/src/host/folders.js+++ b/ds-bot/src/host/folders.js@@ -11,6 +11,12 @@ const PICK_TIMEOUT_MS = 10 * 60_000export const within = (inner, outer) => inner === outer || inner.startsWith(outer.endsWith(sep) ? outer : outer + sep)+const expandHome = text => (text === '~' ? homedir() : /^~[\\/]/.test(text) ? join(homedir(), text.slice(2)) : text)++// Read as DSH reads it, so the team's data and the guarded folder are where DSH keeps+// its own: a blank value counts as unset.+export const dshHomeOf = value => resolve(expandHome(value?.trim() ? value : join(homedir(), '.dsh')))+export function install(rt) {const { ctx, state } = rt@@ -36,7 +42,7 @@ export function install(rt) {async function cleanWorkDir(input) {const text = unquote(input)if (text === '') return undefined- const expanded = text === '~' ? homedir() : /^~[\\/]/.test(text) ? join(homedir(), text.slice(2)) : text+ const expanded = expandHome(text)if (!isAbsolute(expanded)) throw new Error(`Give the full path of the folder, not ${text}`)let pathtry {@@ -49,21 +55,24 @@ export function install(rt) {return path === teamFolder() ? undefined : path}+ // Every Session of a Bot: its own chat and its conversation in each of its groups.+ const sessionsOfBot = botId => [rt.chatOf(botId), ...Object.values(state.rooms)+ .filter(room => room.members.includes(botId)).map(room => room.sessions?.[botId])].filter(Boolean)+// A folder outside the team workspace widens where a Bot may write, so a Bot that// sets one for Bots whose writes are bounded by their folder asks the user first.- // `sessions` are the Sessions that would move; undefined stands for a Bot not made yet.- // Throws when the user does not allow it.- async function approveFolder(exec, { path, sessions, who }) {+ // `sessions` are the Sessions that would work there; the default policy counts too,+ // since the Sessions made there later start under it. Throws when it is not allowed.+ async function approveFolder(exec, { path, sessions = [], who }) {const team = teamFolder()const policy = ctx.get?.('sandboxPolicy')if (path === undefined || (team !== undefined && within(path, team)) || policy === undefined) return- const modes = sessions === undefined ? [policy.resolve().mode]- : await Promise.all(sessions.map(async id => policy.resolve({ session: (await rt.resolveAgent(id)).session }).mode))+ const agents = await Promise.all(sessions.map(id => rt.resolveAgent(id)))+ const modes = [policy.resolve(), ...agents.map(agent => policy.resolve({ session: agent.session }))].map(entry => entry.mode)if (!modes.includes('workspace-write')) returnconst approval = ctx.get?.('approval')const agent = exec.agent- if (approval === undefined || agent?.session === undefined) throw new Error('Setting this folder needs the user\'s approval, and there is no way to ask for it here. The user can set the folder in the settings.')- if (approval.effectivePolicy?.(agent.session) === 'never') throw new Error('Your approval settings do not let you ask the user, so you cannot set this folder. The user can set it in the settings.')+ if (approval === undefined || agent?.session === undefined) throw new Error(`Working in ${path} needs the user's approval, and there is no way to ask for it here, so nothing changed. The user can make this change in the settings.`)const outcome = await approval.request({agent,toolName: exec.name,@@ -73,9 +82,10 @@ export function install(rt) {...(exec.signal ? { signal: exec.signal } : {}),})if (outcome === 'allowed-once') return- throw new Error(outcome === 'rejected' ? 'The user did not allow this folder. Leave the folder as it is.'- : outcome === 'cancelled' ? 'The approval was cancelled, so the folder stays as it is.'- : 'Setting this folder needs the user\'s approval, and no one could answer. The user can set the folder in the settings.')+ // An approval policy that never asks answers 'rejected' as well.+ throw new Error(outcome === 'rejected' ? `Working in ${path} was not allowed, so nothing changed. The user can make this change in the settings.`+ : outcome === 'cancelled' ? 'The approval was cancelled, so nothing changed.'+ : `Working in ${path} needs the user's approval, and no one could answer, so nothing changed. The user can make this change in the settings.`)}const picker = () => {@@ -121,5 +131,5 @@ export function install(rt) {}}- Object.assign(rt, { teamFolder, workDirOf, isFolder, cleanWorkDir, approveFolder, folderEndpoint })+ Object.assign(rt, { teamFolder, workDirOf, isFolder, cleanWorkDir, sessionsOfBot, approveFolder, folderEndpoint })}diff --git a/ds-bot/src/host/parts.js b/ds-bot/src/host/parts.jsindex f66e32f2..f9ef6762 100644--- a/ds-bot/src/host/parts.js+++ b/ds-bot/src/host/parts.js@@ -838,7 +838,7 @@ export function install(rt) {freshParts.delete(agent.id)partBase.set(agent.id, (tokensOf(agent.session) ?? 0) + fresh)}- if (!readOnly() && await folderMove(agent) !== undefined) return switchBeforeStep(agent, payload, { folder: true })+ if (!readOnly() && await folderMove(agent, { midTurn: payload.step > 1 }) !== undefined) return switchBeforeStep(agent, payload, { folder: true })const lines = await contextLines(agent.session).catch(() => undefined)const tokens = tokensOf(agent.session)if (lines === undefined || tokens === undefined || tokens < lines.hard || !grown(agent.id, tokens, lines) || readOnly()) return next()@@ -863,11 +863,12 @@ export function install(rt) {// The folder a part should move to, when it is not the one the part was made in. A// working folder that is gone counts as the team workspace, where a fresh part would- // start.- async function folderMove(agent) {+ // start. A group reply ends where it began; the group conversation moves at its next+ // turn there.+ async function folderMove(agent, { midTurn = false } = {}) {const place = placeOf(agent.id)const cwd = agent.session.header?.cwd- if (place === undefined || cwd === undefined || Date.now() < (folderRetry.get(agent.id) ?? 0)) return undefined+ if (place === undefined || cwd === undefined || (midTurn && place.roomId !== undefined) || Date.now() < (folderRetry.get(agent.id) ?? 0)) return undefinedconst wanted = rt.workDirOf(place)const target = wanted !== undefined && await rt.isFolder(wanted) ? wanted : rt.teamFolder()return target === undefined || target === cwd ? undefined : targetdiff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.jsindex f9fc22df..20809096 100644--- a/ds-bot/src/host/tools.js+++ b/ds-bot/src/host/tools.js@@ -205,7 +205,7 @@ export function install(rt) {const { name: newName, role, instructions, color, model } = argsconst 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.chatOf(bot.id)], who: { en: bot.name, zh: ` ${bot.name} ` } })+ 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 } : {}), ...(moving ? { workDir: workDir ?? '' } : {}) })if (!moving) return `Updated ${next.name}.`const folder = workDir ?? 'the team workspace'@@ -317,9 +317,14 @@ export function install(rt) {}try {const workDir = moving ? await rt.cleanWorkDir(args.work_dir) : undefined+ // A Bot that joins a group with a folder works there from its first turn.+ const joining = add.bots.filter(bot => !room.members.includes(bot.id))if (moving && workDir !== room.workDir) {- const members = [...new Set([...room.members, ...add.bots.map(bot => bot.id)])]- await rt.approveFolder(exec, { path: workDir, sessions: members.map(id => rt.chatOf(id)), who: { en: `every member of "${room.name}"`, zh: `群聊「${room.name}」的成员` } })+ const members = [...room.members, ...joining.map(bot => bot.id)]+ await rt.approveFolder(exec, { path: workDir, sessions: members.map(id => room.sessions?.[id]).filter(Boolean), who: { en: `every member of "${room.name}"`, zh: `群聊「${room.name}」的成员` } })+ } else if (joining.length > 0) {+ const names = joining.map(bot => bot.name)+ await rt.approveFolder(exec, { path: room.workDir, sessions: joining.map(bot => room.sessions?.[bot.id]).filter(Boolean), who: { en: names.join(', '), zh: ` ${names.join('、')} ` } })}const { room: next, changes } = await rt.updateRoom(room.id, {name: args.name,diff --git a/ds-bot/test/work-dir.test.js b/ds-bot/test/work-dir.test.jsindex 5d0453cf..37903dc8 100644--- a/ds-bot/test/work-dir.test.js+++ b/ds-bot/test/work-dir.test.js@@ -1,9 +1,10 @@import assert from 'node:assert/strict'import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { homedir, tmpdir } from 'node:os'+import { join, resolve } from 'node:path'import { test } from 'node:test'import { apply } from '../index.js'+import { dshHomeOf } from '../src/host/folders.js'import { escapeRegExp } from '../src/host/text.js'import { fakeContext } from './fake-ctx.js'@@ -99,8 +100,8 @@ async function start({ services = {}, workspaces = [] } = {}) {}))).json()const tool = (name, args, sessionId) => ctx.registeredTools.get(name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1' })// Runs the parts check, registered last; 'next' means the step goes on.- const preStep = (sessionId, messages = []) => ctx.listeners.get('agent/pre-step').at(-1)(- { agent: agentOf(sessionId), messages, step: 1, signal: AbortSignal.timeout(60_000) }, async () => 'next')+ const preStep = (sessionId, messages = [], step = 1) => ctx.listeners.get('agent/pre-step').at(-1)(+ { agent: agentOf(sessionId), messages, step, signal: AbortSignal.timeout(60_000) }, async () => 'next')const state = () => JSON.parse(readFileSync(join(home, 'state.json'), 'utf8'))// Waits until the Bot's own chat runs in `dir` and its move has finished.const workingIn = async (botId, dir) => {@@ -129,24 +130,35 @@ const until = async (check) => {const textOf = message => message.content.map(block => block.text ?? '').join('\n')const handoffOf = agent => agent.calls.filter(([kind, message]) => kind === 'followup' && message.source?.role === 'handoff').map(([, message]) => textOf(message)).at(-1)-// Approvals that answer `outcome` and keep every request; Sessions write inside their-// folder only.-const approvalServices = (outcome, { policy = 'on-request' } = {}) => {+// Approvals that answer `outcome` and keep every request. Sessions run in `mode`, the+// default, unless `modes` names another for them; 'workspace-write' writes inside the+// Session's folder only. Under the 'never' policy DSH answers 'rejected' without asking.+const approvalServices = (outcome, { policy = 'on-request', mode = 'workspace-write', modes = {} } = {}) => {const requests = []return {requests,services: {- sandboxPolicy: { resolve: () => ({ mode: 'workspace-write' }) },+ sandboxPolicy: { resolve: ({ session } = {}) => ({ mode: modes[session?.id] ?? mode }) },approval: {- effectivePolicy: () => policy,request: async (request) => {requests.push(request)- return outcome+ return policy === 'never' ? 'rejected' : outcome},},},}}+const notAllowed = path => `Working in ${path} was not allowed, so nothing changed. The user can make this change in the settings.`++test('DSH_HOME is read as DSH reads it', () => {+ const dsh = join(homedir(), '.dsh')+ assert.equal(dshHomeOf(undefined), dsh)+ assert.equal(dshHomeOf(' '), dsh)+ assert.equal(dshHomeOf('~'), homedir())+ assert.equal(dshHomeOf('~/dsh-x'), join(homedir(), 'dsh-x'))+ assert.equal(dshHomeOf('~\\dsh-x'), join(homedir(), 'dsh-x'))+ assert.equal(dshHomeOf('dsh-x'), resolve('dsh-x'))+})test('a working folder is a full path to a folder outside the DeepSeek Harness data', async (t) => {const { call, state, workingIn, dsh, home, team, root, project, stop } = await start()@@ -229,9 +241,9 @@ test('a folder outside the team workspace needs the user\'s approval', async (t)const rejected = approvalServices('rejected')const first = await start({ services: rejected.services })t.after(first.stop)- assert.equal(await first.tool('update_bot', { work_dir: first.project }, 'b'), 'Could not update the Bot: The user did not allow this folder. Leave the folder as it is.')+ assert.equal(await first.tool('update_bot', { work_dir: first.project }, 'b'), `Could not update the Bot: ${notAllowed(first.project)}`)assert.equal(first.state().bots.b.workDir, undefined)- assert.match(await first.tool('create_bot', { name: 'Builder', role: 'Build', instructions: 'Build', work_dir: first.project }, 'a'), /^Could not create the Bot: The user did not allow this folder/)+ assert.equal(await first.tool('create_bot', { name: 'Builder', role: 'Build', instructions: 'Build', work_dir: first.project }, 'a'), `Could not create the Bot: ${notAllowed(first.project)}`)assert.deepEqual(first.created, [])// A folder inside the team workspace widens nothing, so nobody is asked.mkdirSync(join(first.team, 'site'))@@ -242,7 +254,8 @@ test('a folder outside the team workspace needs the user\'s approval', async (t)const never = await start(approvalServices('allowed-once', { policy: 'never' }))t.after(never.stop)- assert.equal(await never.tool('update_bot', { work_dir: never.project }, 'b'), 'Could not update the Bot: Your approval settings do not let you ask the user, so you cannot set this folder. The user can set it in the settings.')+ assert.equal(await never.tool('update_bot', { work_dir: never.project }, 'b'), `Could not update the Bot: ${notAllowed(never.project)}`)+ assert.equal(never.state().bots.b.workDir, undefined)const allowed = approvalServices('allowed-once')const third = await start({ services: allowed.services })@@ -263,8 +276,11 @@ test('a group\'s folder holds for every member there; only the user or a Main Boassert.equal(requests.length, 0)assert.match(await tool('list_bots', {}, 'a'), new RegExp(`"Ops" — .*; members work in ${escapeRegExp(project)} here`))- // The member's group Session moves at its next turn there; its own chat stays.+ // The member's group Session moves at its next turn there, not within a reply; its+ // own chat stays.assert.equal(await preStep('b'), 'next')+ assert.equal(await preStep('gb', [], 2), 'next')+ assert.deepEqual(created, [])assert.deepEqual(await preStep('gb'), { kind: 'reject' })await until(() => state().rooms.r1.sessions.b === 's1')assert.deepEqual(created, [{ cwd: project }])@@ -278,6 +294,48 @@ test('a group\'s folder holds for every member there; only the user or a Main Boassert.equal(requests[0].displayReason.zh, `允许群聊「Ops」的成员在 ${project} 中工作吗?之后可以修改这个文件夹里的文件。`)})+test('the approval counts every Session that would work in the folder', async (t) => {+ // Writer's own chat and new Sessions only read; its conversation in Ops may write.+ const group = approvalServices('allowed-once', { mode: 'read-only', modes: { gb: 'workspace-write' } })+ const first = await start({ services: group.services })+ t.after(first.stop)+ assert.equal(await first.tool('update_bot', { bot: 'Writer', work_dir: first.project }, 'a'), `Updated Writer. It now works in ${first.project}.`)+ assert.equal(group.requests.length, 1)+ await first.workingIn('b', first.project)+ assert.match(await first.tool('update_group', { group: 'Ops', work_dir: first.project }, 'a'), /^Updated "Ops": every member now works in /)+ assert.equal(group.requests.length, 2)++ // Nothing that would work there may write, so nobody is asked.+ const reading = approvalServices('rejected', { mode: 'read-only' })+ const second = await start({ services: reading.services })+ t.after(second.stop)+ assert.equal(await second.tool('update_bot', { bot: 'Writer', work_dir: second.project }, 'a'), `Updated Writer. It now works in ${second.project}.`)+ assert.equal(reading.requests.length, 0)+ await second.workingIn('b', second.project)++ // Sessions made there later start under the default, so a default that writes asks.+ const later = approvalServices('rejected', { modes: { a: 'read-only', b: 'read-only', gb: 'read-only' } })+ const third = await start({ services: later.services })+ t.after(third.stop)+ assert.equal(await third.tool('update_bot', { bot: 'Writer', work_dir: third.project }, 'a'), `Could not update the Bot: ${notAllowed(third.project)}`)+ assert.equal(later.requests.length, 1)+})++test('a Bot that joins a group with a folder needs the user\'s approval to work there', async (t) => {+ const { requests, services } = approvalServices('rejected')+ const { call, tool, project, state, stop } = await start({ services })+ t.after(stop)+ assert.equal((await call('update-room', { id: 'r1', workDir: project })).ok, true)+ assert.equal((await call('create-bot', { name: 'Coder' })).ok, true)+ assert.equal(await tool('update_group', { group: 'Ops', add_members: ['Coder'] }, 'a'), `Could not update "Ops": ${notAllowed(project)}`)+ assert.deepEqual(state().rooms.r1.members, ['a', 'b'])+ assert.equal(requests.length, 1)+ assert.equal(requests[0].reason, `Let Coder work in ${project}? Files there can then be changed.`)+ // Members already there are not asked again.+ assert.equal(await tool('update_group', { group: 'Ops', add_members: ['Writer'], notice: 'Ship it' }, 'a'), 'Updated "Ops": updated the notice.')+ assert.equal(requests.length, 1)+})+test('the folder menu lists DSH projects and the folders Bots use, but not the team workspace', async (t) => {const { call, workingIn, root, project, team, stop } = await start({ workspaces: [{ id: 'w2', path: join(rootless(), 'gone'), title: 'Gone' }] })t.after(stop)