Skip to content

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

Make a Bot's working_directory change outside its folder its new working folder

Fei2411e62abcb36375
diff --git a/ds-bot/src/host/folders.js b/ds-bot/src/host/folders.js
index 239e3d5c..b0e97841 100644
--- a/ds-bot/src/host/folders.js
+++ b/ds-bot/src/host/folders.js
@@ -24,6 +24,9 @@ export function install(rt) {
const workDirOf = ({ botId, roomId } = {}) => rt.roomOf(roomId)?.workDir ?? rt.botOf(botId)?.workDir
const isFolder = path => stat(path).then(info => info.isDirectory(), () => false)
const real = path => realpath(path).catch(() => resolve(path))
+ // Where `input` leads from `base`, as a real path, the way DSH's working_directory resolves
+ // a change; undefined when nothing is there.
+ const folderAt = (base, input) => realpath(resolve(base, input)).catch(() => undefined)
// Where a Session works: the folder DSH has for it, else the one DS Bot made it for.
const sessionFolder = (session) => {
const reported = session?.header === undefined ? undefined : ctx.get?.('workingDirectory')?.get?.(session) ?? session.header.cwd
@@ -138,5 +141,5 @@ export function install(rt) {
}
}
- Object.assign(rt, { teamFolder, workDirOf, sessionFolder, isFolder, cleanWorkDir, sessionsOfBot, approveFolder, folderEndpoint })
+ Object.assign(rt, { teamFolder, workDirOf, sessionFolder, isFolder, real, folderAt, cleanWorkDir, sessionsOfBot, approveFolder, folderEndpoint })
}
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index e5cfb73f..d5e495d4 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -3,6 +3,7 @@
import { randomUUID } from 'node:crypto'
import { defineTool } from '@deepseek-ai/dsh-tools'
import { COLORS, EXTRA_COLORS, MESSAGE_INLINE_MAX, ROOM_MODES, SOURCE_KIND } from './constants.js'
+import { within } from './folders.js'
import { absoluteLinks } from './links.js'
import { unquote } from './text.js'
import { mentionSpans } from '../shared/mentions.js'
@@ -20,6 +21,7 @@ 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 WORKING_DIRECTORY_TOOL = 'working_directory'
export function install(rt) {
const { ctx, state } = rt
@@ -309,6 +311,29 @@ export function install(rt) {
},
}))
+ // DSH's working_directory changes a Session's folder in place, and the next part starts in
+ // the Bot's working folder again. A Bot that changes to a folder outside its working folder
+ // sets its working folder instead, with update_bot's checks, and goes on in a fresh part
+ // there; a folder inside it only moves this Session there.
+ ctx.on('tools/execute', async (exec, next) => {
+ const cd = exec.name === WORKING_DIRECTORY_TOOL && typeof exec.arguments?.cd === 'string' ? exec.arguments.cd.trim() : ''
+ const session = exec.agent?.session
+ if (cd === '' || session === undefined || rt.readOnly() !== undefined) return next()
+ await rt.load()
+ const bot = callerBot(exec)
+ if (bot === undefined) return next()
+ const room = rt.roomOf(rt.groupOwners.get(exec.agent.id)?.roomId)
+ const home = rt.workDirOf({ botId: bot.id, roomId: room?.id }) ?? rt.teamFolder()
+ const target = await rt.folderAt(rt.sessionFolder(session), cd)
+ if (target === undefined || home === undefined || within(target, await rt.real(home))) return next()
+ if (room?.workDir) throw new Error(`Every member of "${room.name}" works in ${room.workDir} here, so you stay inside it. The user or a Main Bot can change the group's folder.`)
+ const workDir = await rt.cleanWorkDir(target)
+ await rt.approveFolder(exec, { path: workDir, sessions: rt.sessionsOfBot(bot.id), who: { en: bot.name, zh: ` ${bot.name} ` } })
+ const result = await next()
+ if (result?.isError !== true) await rt.updateBot(bot.id, { workDir: workDir ?? '' })
+ return result
+ })
+
ctx.tools.register(defineTool({
name: 'list_models',
description: 'List the models a Bot can run on, as provider/model refs for create_bot and update_bot. A model in use also lists the thinking levels it serves.',
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index ca96813f..6b715972 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -50,6 +50,7 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'tool stop_bot',
'tool create_bot',
'tool update_bot',
+ 'on tools/execute',
'tool list_models',
'tool create_group',
'tool update_group',
diff --git a/ds-bot/test/secrets.test.js b/ds-bot/test/secrets.test.js
index 5a3a334f..a4e844e0 100644
--- a/ds-bot/test/secrets.test.js
+++ b/ds-bot/test/secrets.test.js
@@ -281,7 +281,8 @@ test('tool results and model requests lose the values', async (t) => {
t.after(bench.stop)
const value = fresh()
await bench.call('secret-set', { name: 'DEMO_TOKEN', value })
- const [execute] = bench.listeners['tools/execute']
+ // The team tools' listener (working_directory) registers first.
+ const execute = bench.listeners['tools/execute'].at(-1)
const ok = await execute({}, async () => ({ isError: false, value: { kind: 'foreground', stdout: { text: `${value}\n`, truncated: false } }, content: [{ type: 'text', text: value }], meta: { stdout: value } }))
assert.deepEqual(ok, { isError: false, value: { kind: 'foreground', stdout: { text: '[secret:DEMO_TOKEN]\n', truncated: false } } })
const failed = await execute({}, async () => ({ isError: true, error: { message: `bad ${value}` }, content: [{ type: 'text', text: `bad ${value}` }] }))
diff --git a/ds-bot/test/work-dir.test.js b/ds-bot/test/work-dir.test.js
index 116dc97c..0d8c4f25 100644
--- a/ds-bot/test/work-dir.test.js
+++ b/ds-bot/test/work-dir.test.js
@@ -608,3 +608,100 @@ test('a Bot deleted while its chat moves to a new folder leaves no fresh part be
assert.equal(state().bots.b, undefined)
assert.equal(handoffOf(agentOf(fresh)), undefined)
})
+
+// DSH 0.2.1's working_directory, run through ds-bot's tools/execute listeners as DSH runs
+// them; the last step is the tool, which changes the Session's folder in place.
+async function changeDirectory(ctx, service, agent, cd) {
+ let ran = false
+ const tool = async () => {
+ ran = true
+ const cwd = resolve(service.get(agent.session), cd)
+ await service.set(agent, cwd)
+ return { isError: false, value: { cwd } }
+ }
+ const exec = { name: 'working_directory', arguments: { cd }, agent, callId: 'c1', signal: AbortSignal.timeout(60_000) }
+ const run = ctx.listeners.get('tools/execute').reduceRight((next, listener) => () => listener(exec, next), tool)
+ try {
+ return { result: await run(), ran }
+ } catch (error) {
+ return { error: error.message, ran }
+ }
+}
+
+test('a Bot that changes to a folder inside its working folder only moves that Session there', async (t) => {
+ const { service } = folderService()
+ const { requests, services } = approvalServices('rejected')
+ const { ctx, agentOf, team, created, state, preStep, stop } = await start({ services: { ...services, workingDirectory: service } })
+ t.after(stop)
+ mkdirSync(join(team, 'site'))
+ agentOf('b').status = 'running'
+ const moved = await changeDirectory(ctx, service, agentOf('b'), 'site')
+ assert.deepEqual(moved, { result: { isError: false, value: { cwd: join(team, 'site') } }, ran: true })
+ assert.equal(state().bots.b.workDir, undefined)
+ assert.equal(requests.length, 0)
+ assert.equal(await preStep('b'), 'next')
+ assert.deepEqual(created, [])
+})
+
+test('a Bot that changes to a folder outside its working folder makes it its working folder and goes on in a fresh part there', async (t) => {
+ const { service } = folderService()
+ const { requests, services } = approvalServices('allowed-once')
+ const { ctx, agentOf, project, created, state, preStep, stop } = await start({ services: { ...services, workingDirectory: service } })
+ t.after(stop)
+ agentOf('b').status = 'running'
+ const moved = await changeDirectory(ctx, service, agentOf('b'), project)
+ assert.deepEqual(moved, { result: { isError: false, value: { cwd: project } }, ran: true })
+ assert.equal(requests.length, 1)
+ assert.equal(requests[0].toolName, 'working_directory')
+ assert.equal(requests[0].reason, `Let Writer work in ${project}? Files there can then be changed.`)
+ assert.equal(state().bots.b.workDir, project)
+
+ const input = { id: 'm1', role: 'user', content: [{ type: 'text', text: 'Now build it' }], source: { kind: 'user' } }
+ assert.deepEqual(await preStep('b', [input]), { kind: 'reject' })
+ await until(() => state().bots.b.sessionId === 's1')
+ assert.deepEqual(created, [{ cwd: project }])
+ await until(() => handoffOf(agentOf('s1')) !== undefined)
+ assert.match(handoffOf(agentOf('s1')), new RegExp(`because your working folder changed to ${escapeRegExp(project)}\\.`))
+})
+
+test('a change out of the working folder that is not allowed changes nothing', async (t) => {
+ const { service } = folderService()
+ const { services } = approvalServices('rejected')
+ const { ctx, agentOf, dsh, project, state, stop } = await start({ services: { ...services, workingDirectory: service } })
+ t.after(stop)
+ assert.deepEqual(await changeDirectory(ctx, service, agentOf('b'), project), { error: notAllowed(project), ran: false })
+ const guarded = await changeDirectory(ctx, service, agentOf('b'), dsh)
+ assert.match(guarded.error, /holds DeepSeek Harness data, so Bots cannot work there/)
+ assert.equal(guarded.ran, false)
+ assert.equal(state().bots.b.workDir, undefined)
+})
+
+test('in a group with a folder of its own a member stays inside it; without one the member\'s own folder changes', async (t) => {
+ const { service } = folderService()
+ const { services } = approvalServices('allowed-once')
+ const { ctx, call, agentOf, team, project, state, stop } = await start({ services: { ...services, workingDirectory: service } })
+ t.after(stop)
+ assert.equal((await call('update-room', { id: 'r1', workDir: project })).ok, true)
+ mkdirSync(join(project, 'src'))
+ const inside = await changeDirectory(ctx, service, agentOf('gb'), join(project, 'src'))
+ assert.equal(inside.ran, true)
+ const out = await changeDirectory(ctx, service, agentOf('gb'), team)
+ assert.deepEqual(out, { error: `Every member of "Ops" works in ${project} here, so you stay inside it. The user or a Main Bot can change the group's folder.`, ran: false })
+ assert.equal(state().bots.b.workDir, undefined)
+
+ assert.equal((await call('update-room', { id: 'r1', workDir: '' })).ok, true)
+ const own = await changeDirectory(ctx, service, agentOf('gb'), project)
+ assert.equal(own.ran, true)
+ assert.equal(state().bots.b.workDir, project)
+ assert.equal(state().rooms.r1.workDir, undefined)
+})
+
+test('Sessions that are not a Bot\'s keep DSH\'s own working_directory', async (t) => {
+ const { service } = folderService()
+ const { requests, services } = approvalServices('rejected')
+ const { ctx, agentOf, project, state, stop } = await start({ services: { ...services, workingDirectory: service } })
+ t.after(stop)
+ assert.deepEqual(await changeDirectory(ctx, service, agentOf('x'), project), { result: { isError: false, value: { cwd: project } }, ran: true })
+ assert.equal(requests.length, 0)
+ assert.deepEqual(Object.values(state().bots).map(bot => bot.workDir), [undefined, undefined])
+})