Skip to content

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

Apply the scoped tools once a new Bot Session has an owner

Fei2411efe4cef65656
diff --git a/ds-bot/src/host/groups.js b/ds-bot/src/host/groups.js
index edfaf059..9bb922e2 100644
--- a/ds-bot/src/host/groups.js
+++ b/ds-bot/src/host/groups.js
@@ -223,6 +223,8 @@ export function install(rt) {
await rt.applyPermission(member, id, room)
.catch(error => rt.warn('ds-bot: permission for %s in %s not applied: %s', member.name, room.name, error))
await rt.save()
+ // The Session was resolved before the group owned it, so its scoped tools land now.
+ await rt.resolveAgent(id)
await rt.ensureCapabilities(id)
return { id, brief: await rt.ownChatBrief(member) }
}
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js
index 3ff2b491..3bf5c281 100644
--- a/ds-bot/src/host/roster.js
+++ b/ds-bot/src/host/roster.js
@@ -188,9 +188,12 @@ export function install(rt) {
if (modelRef === undefined) {
bot.kickoff = { text, from: createdBy ?? null, ...(main ? { main: true } : {}) }
await rt.save()
+ // The Session was resolved before the Bot existed, so its scoped tools land now.
+ await rt.resolveAgent(id)
return bot
}
await rt.save()
+ await rt.resolveAgent(id)
// 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)))
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index 36a19b81..d0b5ffc7 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -736,8 +736,9 @@ export function install(rt) {
}
}
// A new Bot, part, or group Session gets its Agent before ds-bot records it, so the
- // list is only trimmed once ds-bot resolves that Agent again; meanwhile the guard
- // refuses the question tool in any Bot Session, and a goal made there is blocked.
+ // recording path resolves it again once the session is known as a Bot's; meanwhile
+ // the guard refuses the question tool in any Bot Session, and a goal made there is
+ // blocked.
ctx.tools.guard(exec => (exec.name === BLOCKING_QUESTION_TOOL && rt.isBotSession(exec.agent?.id)
? `Bots cannot use ${BLOCKING_QUESTION_TOOL}. Ask with ask_user in your own chat, or ask in your reply.`
: undefined))
diff --git a/ds-bot/test/scoped-tools-creation.test.js b/ds-bot/test/scoped-tools-creation.test.js
new file mode 100644
index 00000000..c07d7fee
--- /dev/null
+++ b/ds-bot/test/scoped-tools-creation.test.js
@@ -0,0 +1,192 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, 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'
+
+// A Bot-owned Session gets its Agent before ds-bot records the owner, so the
+// scoped show_view and the hidden-tool restrict used to wait for a later
+// resolveAgent that a held kickoff never ran. These tests drive each creation
+// path with another plugin's global show_view already in place and check the
+// Agent's own tool list before its first step.
+const TEAM = {
+ version: 1,
+ mainBotIds: ['a'],
+ workspaceId: 'w1',
+ bots: {
+ a: { id: 'a', name: 'Chief', role: 'Boss', sessionId: 'a', createdAt: 1 },
+ b: { id: 'b', name: 'Writer', role: 'Write', sessionId: 'b', createdAt: 2 },
+ },
+ rooms: {
+ r1: { id: 'r1', name: 'Ops', members: ['a', 'b'], mode: 'admin', admin: 'a', named: true, sessions: {}, log: [], seq: 0, seen: {} },
+ },
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ prefs: {},
+ revision: 0,
+}
+
+const start = (team = TEAM, services = {}) => {
+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-scoped-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(team))
+ const ctx = fakeContext({ services })
+ // Another plugin's global show_view, in place before ds-bot loads.
+ ctx.tools.register({ name: 'show_view', description: 'global', execute: async () => 'global' })
+ const scoped = []
+ const restricted = []
+ let sessions = 0
+ const agentOf = (sessionId) => {
+ const nextStep = []
+ const nextTurn = []
+ return {
+ id: sessionId,
+ session: { id: sessionId, header: { cwd: '/team' }, requestHeader: () => undefined, deriveMessages: () => [] },
+ ctx: {
+ tools: {
+ register: (tool) => { scoped.push({ sessionId, name: tool.name }); return () => {} },
+ restrict: (filter) => { restricted.push({ sessionId, deny: filter.deny ?? [] }); return () => {} },
+ },
+ effect: execute => (typeof execute === 'function' ? execute() : undefined),
+ on: () => () => {},
+ },
+ status: 'idle',
+ followup() {},
+ steer() {},
+ inject() {},
+ send(message, target) {
+ ;(target === 'next-turn' ? nextTurn : nextStep).push(message)
+ },
+ cancel() {},
+ async whenIdle() {},
+ async runMaintenance(fn) { return fn(AbortSignal.timeout(60_000)) },
+ inbox: {
+ nextStep,
+ nextTurn,
+ prepend(target, message) { ;(target === 'next-turn' ? nextTurn : nextStep).unshift(message) },
+ append(target, message) { ;(target === 'next-turn' ? nextTurn : nextStep).push(message) },
+ remove(id) {
+ for (const list of [nextStep, nextTurn]) {
+ const at = list.findIndex(message => message.id === id)
+ if (at !== -1) { list.splice(at, 1); return true }
+ }
+ return false
+ },
+ },
+ }
+ }
+ // ask_user_question is served, so the deny list is not empty in a Bot scope.
+ ctx.tools.schemas = () => [{ name: 'ask_user_question' }, { name: 'show_view' }]
+ Object.assign(ctx, {
+ llm: { listProviders: () => [], listModels: async () => [], resolveModelInfo: async () => ({}) },
+ workspaceRegistry: {
+ get: id => (id === 'w1' ? { id: 'w1', path: '/team' } : undefined),
+ list: () => [{ id: 'w1', path: '/team' }],
+ resolveByPath: async () => undefined,
+ create: async path => ({ id: 'w1', path }),
+ archiveSession: async () => {},
+ },
+ sessionController: {
+ create: async () => ({ sessionId: `s${++sessions}` }),
+ resolveAgent: async sessionId => ({ agent: agentOf(sessionId) }),
+ selectModel: async () => {},
+ page: async () => ({ records: [], hasMore: false }),
+ },
+ sessionTitle: { rename: async () => {} },
+ sessions: { flush: async () => {} },
+ })
+ let route
+ const register = ctx.connection.fetch.register
+ ctx.connection.fetch.register = (options) => { route = options; return register(options) }
+ apply(ctx, { home })
+ const call = async (endpoint, payload) => (await route.fetch(new Request('http://localhost/api/bot', {
+ method: 'POST', body: JSON.stringify({ endpoint, payload }),
+ }))).json()
+ const emit = (id, type, data) => {
+ for (const listener of ctx.listeners.get('session/event') ?? []) {
+ if (listener.length >= 2) listener({ id }, { type, data })
+ }
+ }
+ const agentCreated = async (sessionId) => {
+ for (const listener of ctx.listeners.get('agent/created') ?? []) await listener({ agent: agentOf(sessionId) })
+ }
+ const tool = (name, args, sessionId, exec = {}) =>
+ ctx.registeredTools.get(name).execute(args, { agent: agentOf(sessionId), name, callId: 'c1', ...exec })
+ const stop = async () => {
+ await ctx.dispose()
+ rmSync(home, { recursive: true, force: true, maxRetries: 5 })
+ }
+ return { ctx, call, tool, emit, agentCreated, agentOf, scoped, restricted, stop }
+}
+
+const until = async (check, ms = 3000) => {
+ const end = Date.now() + ms
+ while (!check()) {
+ if (Date.now() > end) throw new Error('until: the condition did not hold')
+ await new Promise(resolve => setTimeout(resolve, 20))
+ }
+}
+
+const hasShowView = (host, id) => host.scoped.some(entry => entry.sessionId === id && entry.name === 'show_view')
+const denied = (host, id) => host.restricted.some(entry => entry.sessionId === id && entry.deny.includes('ask_user_question'))
+
+test('a Bot made without a model has the scoped tools before its first step', async (t) => {
+ const host = start({ ...TEAM, rooms: {} })
+ t.after(host.stop)
+ const created = await host.call('create-bot', { name: 'Solo' })
+ assert.equal(created.ok, true)
+ const id = created.value.id
+ assert.ok(hasShowView(host, id), 'the Bot scope has ds-bot\'s show_view over the global one')
+ assert.ok(denied(host, id), 'the blocking question tool is denied')
+})
+
+test('a group Session made for a member has the scoped tools before its first step', async (t) => {
+ const host = start()
+ t.after(host.stop)
+ await host.call('state', {})
+ const stop = new AbortController()
+ t.after(() => stop.abort())
+ // The user's post starts a round; Writer has no group Session yet, so the round
+ // makes one — which used to keep whatever tools a global registration left.
+ host.emit('r1', 'user/message', { content: [{ type: 'text', text: 'launch moved' }], source: { kind: 'user' } })
+ void host.tool('group_relay', {}, 'r1', { callId: 'r1', signal: stop.signal }).catch(() => {})
+ await until(() => hasShowView(host, 's1'), 5000)
+ assert.ok(denied(host, 's1'), 'the blocking question tool is denied in the group scope')
+})
+
+test('a fresh part Session has the scoped tools before its first step', async (t) => {
+ const project = mkdtempSync(join(tmpdir(), 'ds-bot-scoped-proj-'))
+ const host = start({ ...TEAM, rooms: {} }, {
+ sandboxPolicy: { resolve: () => ({ mode: 'workspace-write' }) },
+ approval: { request: async () => 'allowed-once' },
+ })
+ t.after(async () => {
+ await host.stop()
+ rmSync(project, { recursive: true, force: true, maxRetries: 5 })
+ })
+ await host.call('state', {})
+ host.agentOf('b').status = 'running'
+ const moved = await host.tool('update_bot', { work_dir: project }, 'b')
+ assert.equal(String(moved).includes('From your next step on'), true)
+ // The next step sees the folder change and switches to a fresh part.
+ const preStep = host.ctx.listeners.get('agent/pre-step').at(-1)
+ const answer = await preStep(
+ { agent: host.agentOf('b'), messages: [{ role: 'user', content: [{ type: 'text', text: 'go on' }], source: { kind: 'user' } }], step: 2, signal: AbortSignal.timeout(60_000) },
+ async () => 'next',
+ )
+ assert.deepEqual(answer, { kind: 'reject' })
+ await until(() => hasShowView(host, 's1'), 5000)
+ assert.ok(denied(host, 's1'), 'the blocking question tool is denied in the fresh part')
+})
+
+test('a Session ds-bot does not own keeps only the global show_view', async (t) => {
+ const host = start()
+ t.after(host.stop)
+ await host.call('state', {})
+ await host.agentCreated('plain1')
+ assert.ok(!hasShowView(host, 'plain1'), 'no scoped show_view shadows the global one')
+ assert.ok(!host.restricted.some(entry => entry.sessionId === 'plain1'), 'no restrict applies outside the team')
+})