Skip to content

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

Add shared Bot capability management

lulu feizhu69ccaa5f083f
diff --git a/ds-bot/index.js b/ds-bot/index.js
index 4379acdd..a45fbe89 100644
--- a/ds-bot/index.js
+++ b/ds-bot/index.js
@@ -22,6 +22,7 @@ import * as images from './src/host/images.js'
import * as browser from './src/host/browser.js'
import * as secrets from './src/host/secrets.js'
import * as connectors from './src/host/connectors.js'
+import * as capabilities from './src/host/capabilities.js'
import * as schedules from './src/host/schedules.js'
import * as usage from './src/host/usage.js'
import * as update from './src/host/update.js'
@@ -37,9 +38,13 @@ export const inject = ['llm', 'tools', 'systemPrompt', 'sessionController', 'ses
// the functions other modules call; they call them through `rt` at run time, never during
// install. Listeners run and tools are listed in registration order, so this order holds:
// usage meters model requests after every listener that rewrites them.
-const MODULES = [diagnostics, store, models, permissions, turns, delivery, roster, agents, prompt, timeContext, tools, chatIndex, groups, memory, parts, images, secrets, connectors, schedules, browser, usage, update, dshUpdate, channel]
+const MODULES = [diagnostics, store, models, permissions, turns, delivery, roster, agents, prompt, timeContext, tools, chatIndex, groups, memory, parts, images, secrets, connectors, capabilities, schedules, browser, usage, update, dshUpdate, channel]
export function apply(ctx, config = {}) {
+ createRuntime(ctx, config)
+}
+
+export function createRuntime(ctx, config = {}) {
const home = config.home ?? join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), 'bot')
const rt = {
ctx,
@@ -52,4 +57,5 @@ export function apply(ctx, config = {}) {
},
}
for (const module of MODULES) module.install(rt)
+ return rt
}
diff --git a/ds-bot/src/host/capabilities.js b/ds-bot/src/host/capabilities.js
new file mode 100644
index 00000000..ba03a667
--- /dev/null
+++ b/ds-bot/src/host/capabilities.js
@@ -0,0 +1,447 @@
+import { createHash } from 'node:crypto'
+
+const MCP_CLIENT = '@deepseek-ai/dsh-mcp-client'
+const NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
+const SECRET_REFERENCE = /\$DSH_SECRET_([A-Z][A-Z0-9_]*)/g
+
+export function validateCapabilityName(value) {
+ const name = String(value ?? '').trim()
+ if (name.length > 32 || !NAME.test(name) || name === 'github') {
+ throw new Error('Use a capability name with lowercase letters, digits, and single hyphens; "github" is reserved.')
+ }
+ return name
+}
+
+export function expandCapabilityNames(capabilities, library) {
+ const expanded = new Set()
+ for (const name of capabilities ?? []) {
+ const item = 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]
+ if (!child || !['mcp', 'skill'].includes(child.kind)) throw new Error(`Pack ${name} refers to an unavailable capability ${childName}.`)
+ expanded.add(childName)
+ }
+ } else if (item.kind === 'mcp' || item.kind === 'skill') {
+ expanded.add(name)
+ } else {
+ throw new Error(`Capability ${name} has an unknown kind.`)
+ }
+ }
+ return expanded
+}
+
+const same = (a, b) => JSON.stringify(a) === JSON.stringify(b)
+const strings = value => {
+ if (value === undefined) return []
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) throw new Error('Arguments must be a list of text values.')
+ return [...value]
+}
+const stringMap = (value, label) => {
+ if (value === undefined) return {}
+ if (value === null || typeof value !== 'object' || Array.isArray(value)
+ || Object.values(value).some(item => typeof item !== 'string')) throw new Error(`${label} must contain text values.`)
+ return Object.fromEntries(Object.entries(value))
+}
+
+export function install(rt) {
+ const { ctx, state } = rt
+ const agents = new Map()
+ const mounts = new WeakMap()
+ const sessionStatuses = new Map()
+ let pluginPromise
+ let queue = Promise.resolve()
+ let scheduled = null
+ let loadingSecrets = false
+
+ const library = () => state.capabilities.items
+ const ensureLibrary = () => {
+ state.capabilities ??= { items: {} }
+ state.capabilities.items ??= {}
+ return library()
+ }
+ const writeCheck = () => {
+ const readOnly = rt.readOnly()
+ if (readOnly !== undefined) throw new Error(readOnly)
+ }
+ const allowedToEdit = (item, botId) => rt.isMain(botId) || item.createdBy === botId
+ const itemInput = (body, { botId, ui }) => {
+ const name = validateCapabilityName(body.name)
+ const kind = body.kind
+ if (!['mcp', 'skill', 'pack'].includes(kind)) throw new Error('Choose an MCP server, skill, or pack.')
+ const items = ensureLibrary()
+ const previous = items[name]
+ if (previous && !ui && !allowedToEdit(previous, botId)) throw new Error(`Only ${previous.createdBy ? 'its creator or a Main Bot' : 'a Main Bot'} can change ${name}.`)
+ 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()
+ const item = {
+ name,
+ kind,
+ description: String(body.description ?? '').trim().slice(0, 2000),
+ createdBy: previous?.createdBy ?? (ui ? null : botId),
+ createdAt: previous?.createdAt ?? now,
+ updatedAt: now,
+ }
+ if (kind === 'mcp') {
+ const transport = body.transport === 'streamable-http' ? 'streamable-http' : 'stdio'
+ if (transport === 'stdio') {
+ const command = String(body.command ?? '').trim()
+ if (command === '') throw new Error('Enter a command for the MCP server.')
+ const args = strings(body.args)
+ const env = stringMap(body.env, 'Environment variables')
+ const changed = !previous || previous.kind !== 'mcp' || previous.transport !== 'stdio'
+ || previous.command !== command || !same(previous.args ?? [], args) || !same(previous.env ?? {}, env)
+ Object.assign(item, { transport, command, args, env, approved: ui ? true : changed ? false : previous.approved === true })
+ } else {
+ const url = String(body.url ?? '').trim()
+ try {
+ const parsed = new URL(url)
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') throw new Error()
+ } catch { throw new Error('Enter a valid HTTP or HTTPS URL.') }
+ Object.assign(item, { transport, url, headers: stringMap(body.headers, 'Headers'), approved: true })
+ }
+ } else if (kind === 'skill') {
+ item.content = String(body.content ?? '').trim()
+ } else {
+ const names = [...new Set(strings(body.items))]
+ for (const childName of names) {
+ const child = 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
+ }
+ items[name] = item
+ return item
+ }
+ const capabilitySave = async (body, options = {}) => {
+ await rt.load()
+ writeCheck()
+ const item = itemInput(body ?? {}, options)
+ await rt.save()
+ return item
+ }
+ const capabilityDelete = async (name, { botId, ui } = {}) => {
+ await rt.load()
+ writeCheck()
+ const items = ensureLibrary()
+ const item = items[String(name ?? '')]
+ if (!item) throw new Error(`No capability named ${name}.`)
+ if (!ui && !allowedToEdit(item, botId)) throw new Error(`Only its creator or a Main Bot can delete ${name}.`)
+ delete items[item.name]
+ for (const pack of Object.values(items)) if (pack.kind === 'pack') pack.items = (pack.items ?? []).filter(child => child !== item.name)
+ for (const bot of Object.values(state.bots)) bot.capabilities = (bot.capabilities ?? []).filter(attached => attached !== item.name)
+ await rt.save()
+ return true
+ }
+ const changeAttachment = async (endpoint, { name, bot: targetRef }, callerId) => {
+ await rt.load()
+ writeCheck()
+ const caller = rt.botOf(callerId)
+ if (!caller) throw new Error('Only Bots on the team can change capabilities.')
+ const target = targetRef ? rt.findBot(targetRef) : caller
+ if (!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 ?? '')]
+ if (!item) throw new Error(`No capability named ${name}.`)
+ target.capabilities ??= []
+ const wasEmpty = target.capabilities.length === 0
+ if (endpoint === 'attach') {
+ if (!target.capabilities.includes(item.name)) target.capabilities.push(item.name)
+ } else {
+ target.capabilities = target.capabilities.filter(attached => attached !== item.name)
+ }
+ await rt.save()
+ if (endpoint === 'attach' && wasEmpty && target.capabilities.length > 0) {
+ await trackBotAgents(target)
+ void scheduleReconcile()
+ }
+ return { bot: target.name, attached: endpoint === 'attach' }
+ }
+
+ const statusSet = (botId, itemName, sessionId, status) => {
+ let byItem = sessionStatuses.get(botId)
+ if (!byItem) sessionStatuses.set(botId, byItem = new Map())
+ let bySession = byItem.get(itemName)
+ if (!bySession) byItem.set(itemName, bySession = new Map())
+ bySession.set(sessionId, status)
+ }
+ const clearStatus = (botId, itemName, sessionId) => {
+ const byItem = sessionStatuses.get(botId)
+ const bySession = byItem?.get(itemName)
+ bySession?.delete(sessionId)
+ if (bySession?.size === 0) byItem.delete(itemName)
+ if (byItem?.size === 0) sessionStatuses.delete(botId)
+ }
+ const clearSession = sessionId => {
+ for (const [botId, byItem] of sessionStatuses) {
+ for (const [name, bySession] of byItem) {
+ bySession.delete(sessionId)
+ if (bySession.size === 0) byItem.delete(name)
+ }
+ if (byItem.size === 0) sessionStatuses.delete(botId)
+ }
+ }
+ const statusFor = (botId, name) => {
+ const values = [...(sessionStatuses.get(botId)?.get(name)?.values() ?? [])]
+ if (values.some(status => status.state === 'error')) return values.find(status => status.state === 'error')
+ if (values.some(status => status.state === 'needs-approval')) return { state: 'needs-approval' }
+ if (values.some(status => status.state === 'connecting')) return { state: 'connecting' }
+ return values.length > 0 ? { state: 'ready' } : undefined
+ }
+ const capabilityStatusesView = () => {
+ const result = {}
+ for (const bot of Object.values(state.bots)) {
+ const statuses = {}
+ for (const name of bot.capabilities ?? []) {
+ const item = library()[name]
+ if (!item) continue
+ if (item.kind !== 'pack') {
+ const status = statusFor(bot.id, name)
+ if (status) statuses[name] = status
+ continue
+ }
+ const children = (item.items ?? []).map(child => statusFor(bot.id, child)).filter(Boolean)
+ const status = children.find(status => status.state === 'error')
+ ?? children.find(status => status.state === 'needs-approval')
+ ?? children.find(status => status.state === 'connecting')
+ ?? children[0]
+ if (status) statuses[name] = status
+ }
+ result[bot.id] = statuses
+ }
+ return result
+ }
+ const libraryView = () => Object.values(library()).map(item => ({
+ ...item,
+ ...(item.env ? { env: { ...item.env } } : {}),
+ ...(item.headers ? { headers: { ...item.headers } } : {}),
+ ...(item.items ? { items: [...item.items] } : {}),
+ }))
+
+ async function loadMcpPlugin() {
+ if (!pluginPromise) {
+ pluginPromise = (async () => {
+ const loader = ctx.get?.('loader')
+ if (typeof loader?.import !== 'function') throw new Error('This DSH cannot load MCP servers.')
+ const exports = await loader.import(MCP_CLIENT)
+ return loader.unwrapExports?.(exports) ?? exports?.default ?? exports
+ })()
+ }
+ return pluginPromise
+ }
+ function resolveValues(values, botId) {
+ const resolved = {}
+ for (const [key, raw] of Object.entries(values ?? {})) {
+ resolved[key] = String(raw).replace(SECRET_REFERENCE, (_match, name) => {
+ if (!rt.canUseSecret(name, botId)) throw new Error(`Secret ${name} is missing or unavailable for this Bot.`)
+ const value = rt.secretValue(name)
+ if (value === undefined) throw new Error(`Secret ${name} is missing or unavailable for this Bot.`)
+ return value
+ })
+ }
+ return resolved
+ }
+ const configFor = (item, botId) => {
+ if (item.kind === 'skill') return { name: item.name, description: item.description, content: item.content }
+ if (item.transport === 'stdio') return { transport: 'stdio', serverName: item.name, command: item.command, args: item.args ?? [], env: resolveValues(item.env, botId), failOnStartupError: true }
+ return { transport: 'streamable-http', serverName: item.name, url: item.url, headers: resolveValues(item.headers, botId), failOnStartupError: true }
+ }
+ const disposeMount = async mount => {
+ if (mount?.fiber) await Promise.resolve().then(() => mount.fiber.dispose()).catch(() => {})
+ }
+ const reconcileAgent = async (agent, bot) => {
+ const sessionId = agent.session.id
+ const agentMounts = mounts.get(agent) ?? new Map()
+ mounts.set(agent, agentMounts)
+ const desired = expandCapabilityNames(bot.capabilities, library())
+ for (const name of sessionStatuses.get(bot.id)?.keys() ?? []) {
+ if (!desired.has(name)) clearStatus(bot.id, name, sessionId)
+ }
+ for (const [name, mount] of agentMounts) {
+ if (desired.has(name)) continue
+ await disposeMount(mount)
+ agentMounts.delete(name)
+ }
+ for (const name of desired) {
+ const item = library()[name]
+ if (item.kind === 'mcp' && item.transport === 'stdio' && item.approved !== true) {
+ await disposeMount(agentMounts.get(name))
+ agentMounts.delete(name)
+ statusSet(bot.id, name, sessionId, { state: 'needs-approval' })
+ continue
+ }
+ let config
+ try {
+ config = configFor(item, bot.id)
+ } catch (error) {
+ await disposeMount(agentMounts.get(name))
+ agentMounts.delete(name)
+ statusSet(bot.id, name, sessionId, { state: 'error', error: rt.redactSecrets(error.message).slice(0, 300) })
+ continue
+ }
+ const key = `${name}:${createHash('sha256').update(JSON.stringify(config)).digest('hex')}`
+ const current = agentMounts.get(name)
+ if (current?.key === key) continue
+ await disposeMount(current)
+ statusSet(bot.id, name, sessionId, { state: 'connecting' })
+ try {
+ const fiber = item.kind === 'skill'
+ ? agent.ctx.plugin({
+ name: `ds-bot-capability-skill-${name}`,
+ inject: ['skills'],
+ apply(c) {
+ c.effect(() => c.skills.register({ name: config.name, description: config.description, source: 'runtime', content: config.content }))
+ },
+ })
+ : agent.ctx.plugin(await loadMcpPlugin(), config)
+ agentMounts.set(name, { key, fiber })
+ await fiber.await()
+ if (agents.get(sessionId)?.deref() !== agent) continue
+ statusSet(bot.id, name, sessionId, { state: 'ready' })
+ } catch (error) {
+ await disposeMount(agentMounts.get(name))
+ agentMounts.delete(name)
+ const message = rt.redactSecrets([error, error?.cause].filter(Boolean).map(part => String(part?.message ?? part)).join(': ') || 'Connection failed').slice(0, 300)
+ statusSet(bot.id, name, sessionId, { state: 'error', error: message })
+ }
+ }
+ }
+ async function reconcile() {
+ await rt.load()
+ loadingSecrets = true
+ try {
+ await rt.loadSecrets()
+ } finally {
+ loadingSecrets = false
+ }
+ for (const [sessionId, reference] of agents) {
+ const agent = reference.deref()
+ if (!agent) {
+ agents.delete(sessionId)
+ clearSession(sessionId)
+ continue
+ }
+ if (!rt.isBotSession(sessionId)) {
+ clearSession(sessionId)
+ continue
+ }
+ const bot = rt.botOf(rt.selfOf(sessionId))
+ if (!bot) {
+ clearSession(sessionId)
+ continue
+ }
+ try {
+ await reconcileAgent(agent, bot)
+ } catch (error) {
+ rt.warn('ds-bot: capability reconcile for %s failed: %s', sessionId, error)
+ }
+ }
+ }
+ const scheduleReconcile = () => {
+ if (!scheduled) {
+ scheduled = new Promise(resolve => queueMicrotask(() => {
+ const current = queue = queue.then(reconcile).catch(error => rt.warn('ds-bot: capability reconcile failed: %s', error))
+ scheduled = null
+ resolve(current)
+ }))
+ }
+ return scheduled
+ }
+ const trackAgent = agent => {
+ const sessionId = agent?.session?.id
+ if (typeof sessionId !== 'string' || !agent.ctx) return
+ if (agents.get(sessionId)?.deref() === agent) return
+ agents.set(sessionId, new WeakRef(agent))
+ agent.ctx.effect(() => () => {
+ if (agents.get(sessionId)?.deref() === agent) agents.delete(sessionId)
+ clearSession(sessionId)
+ for (const mount of mounts.get(agent)?.values() ?? []) void disposeMount(mount)
+ mounts.delete(agent)
+ }, `ds-bot: capabilities ${sessionId}`)
+ }
+ const trackBotAgents = async bot => {
+ const sessionIds = new Set()
+ try {
+ const sessionId = rt.chatOf(bot.id)
+ if (typeof sessionId === 'string') sessionIds.add(sessionId)
+ } catch (error) {
+ rt.warn('ds-bot: capability chat session for %s could not be read: %s', bot.id, error)
+ }
+ try {
+ for (const sessionId of rt.groupSessionsOf(bot.id) ?? []) {
+ if (typeof sessionId === 'string') sessionIds.add(sessionId)
+ }
+ } catch (error) {
+ rt.warn('ds-bot: capability group sessions for %s could not be read: %s', bot.id, error)
+ }
+ for (const sessionId of sessionIds) {
+ try {
+ trackAgent(await rt.resolveAgent(sessionId))
+ } catch (error) {
+ rt.warn('ds-bot: capability Agent for %s could not be resolved: %s', sessionId, error)
+ }
+ }
+ }
+
+ async function capabilityEndpoint(endpoint, body = {}) {
+ if (endpoint === 'capability-save') return capabilitySave(body, { ui: true })
+ if (endpoint === 'capability-delete') return capabilityDelete(body.name, { ui: true })
+ if (endpoint === 'capability-approve') {
+ await rt.load()
+ writeCheck()
+ const item = library()[String(body.name ?? '')]
+ if (!item || item.kind !== 'mcp' || item.transport !== 'stdio') throw new Error(`No unapproved stdio MCP named ${body.name}.`)
+ item.approved = true
+ item.updatedAt = Date.now()
+ await rt.save()
+ return item
+ }
+ if (endpoint === 'bot-capabilities') {
+ await rt.load()
+ writeCheck()
+ const bot = rt.botOf(String(body.botId ?? ''))
+ if (!bot) throw new Error('Unknown Bot')
+ if (!Array.isArray(body.capabilities) || body.capabilities.some(name => typeof name !== 'string' || !library()[name])) throw new Error('Choose saved capabilities.')
+ const wasEmpty = (bot.capabilities ?? []).length === 0
+ bot.capabilities = [...new Set(body.capabilities)]
+ await rt.save()
+ if (wasEmpty && bot.capabilities.length > 0) {
+ await trackBotAgents(bot)
+ void scheduleReconcile()
+ }
+ return bot.capabilities
+ }
+ throw new Error('Unknown capability operation.')
+ }
+ const secretsChanged = rt.secretsChanged
+ rt.secretsChanged = () => {
+ secretsChanged?.()
+ if (!loadingSecrets) void scheduleReconcile()
+ }
+ rt.capabilitiesStateSaved = () => { void scheduleReconcile() }
+ ctx.on('agent/created', ({ agent }) => {
+ trackAgent(agent)
+ void rt.load().then(scheduleReconcile).catch(error => rt.warn('ds-bot: capability load failed: %s', error))
+ })
+ ctx.effect(() => {
+ void rt.load().then(async () => {
+ for (const bot of Object.values(state.bots)) {
+ if ((bot.capabilities ?? []).length > 0) await trackBotAgents(bot)
+ }
+ await scheduleReconcile()
+ }).catch(error => rt.warn('ds-bot: capability startup failed: %s', error))
+ return () => { agents.clear() }
+ }, 'ds-bot: capabilities')
+ Object.assign(rt, {
+ capabilitySave,
+ capabilityDelete,
+ capabilityEndpoint,
+ capabilityLibraryView: libraryView,
+ capabilityStatusesView,
+ reconcileCapabilities: reconcile,
+ scheduleCapabilitiesReconcile: scheduleReconcile,
+ expandCapabilities: names => expandCapabilityNames(names, library()),
+ changeCapabilityAttachment: changeAttachment,
+ })
+}
diff --git a/ds-bot/src/host/channel.js b/ds-bot/src/host/channel.js
index 60f59690..34ea5a9f 100644
--- a/ds-bot/src/host/channel.js
+++ b/ds-bot/src/host/channel.js
@@ -51,6 +51,7 @@ export function install(rt) {
agents: Object.values(state.agents),
// Key names and who may use them; values never leave the host.
secrets: rt.secretsView(),
+ capabilities: rt.capabilityLibraryView(),
secretRequests: state.secretRequests ?? {},
colors: [...COLORS, ...EXTRA_COLORS],
models: rt.cachedCatalog(),
@@ -68,7 +69,13 @@ export function install(rt) {
// What changes without a new revision, sent with every state answer. `memoryNews`:
// per Bot, its latest memory change; `memoryReviews`: memory reviews waiting or
// running.
- const live = () => ({ activity: rt.activityView(), memoryNews: rt.memoryNews(), memoryReviews: rt.memoryReviews(), connectors: rt.connectorsView() })
+ const live = () => ({
+ activity: rt.activityView(),
+ memoryNews: rt.memoryNews(),
+ memoryReviews: rt.memoryReviews(),
+ connectors: rt.connectorsView(),
+ capabilityStatuses: rt.capabilityStatusesView(),
+ })
// What a host that only reads the team may still answer.
// Updates change the dsh profile, not the team, so a reading host may run them too.
const READS = new Set(['state', 'models', 'efforts', 'earlier', 'room-progress', 'exchange', 'usage', 'schedules', 'memory-view', 'browser-wait', 'browser-result', 'diagnostics', 'diagnostics-log', 'diagnostics-clear', 'update-check', 'update-install', 'dsh-update-install', 'repo-stars'])
@@ -215,6 +222,12 @@ export function install(rt) {
case 'connector-retry':
await rt.load()
return ok(await rt.connectorEndpoint(endpoint, body))
+ case 'capability-save':
+ case 'capability-delete':
+ case 'capability-approve':
+ case 'bot-capabilities':
+ await rt.load()
+ return ok(await rt.capabilityEndpoint(endpoint, body))
case 'schedules':
case 'schedule-create':
case 'schedule-delete':
diff --git a/ds-bot/src/host/constants.js b/ds-bot/src/host/constants.js
index 0810dcf6..71396431 100644
--- a/ds-bot/src/host/constants.js
+++ b/ds-bot/src/host/constants.js
@@ -49,6 +49,8 @@ export const TEAM_TOOLS = [
'create_group', 'update_group', 'delete_group', 'post_to_group', 'ask_user',
'request_secret', 'list_secrets', 'group_relay', 'read_own_chat',
'read_group_chat', 'remember', 'forget', 'recall', 'read_browser',
+ 'list_capabilities', 'save_capability', 'delete_capability',
+ 'attach_capability', 'detach_capability',
]
// Rounds Bots may start in one group by posting, before the user speaks there again.
export const ROOM_BOT_ROUNDS = 3
diff --git a/ds-bot/src/host/roster.js b/ds-bot/src/host/roster.js
index 8e4a5da8..28cfd8da 100644
--- a/ds-bot/src/host/roster.js
+++ b/ds-bot/src/host/roster.js
@@ -76,6 +76,7 @@ export function install(rt) {
instructions: String(instructions).trim(),
createdAt: Date.now(),
createdBy: createdBy ?? null,
+ capabilities: [],
}
if (main) state.mainBotIds.push(id)
const creator = rt.botOf(createdBy)
diff --git a/ds-bot/src/host/secrets.js b/ds-bot/src/host/secrets.js
index 15583698..54f8683d 100644
--- a/ds-bot/src/host/secrets.js
+++ b/ds-bot/src/host/secrets.js
@@ -526,5 +526,13 @@ export function install(rt) {
return () => { if (usedTimer !== null) clearTimeout(usedTimer) }
}, 'ds-bot: load secrets')
- Object.assign(rt, { secretsView, secretValue: name => secrets.get(name)?.value, secretEndpoint, forgetBotSecrets, loadSecrets, redactSecrets: text => redact(text) })
+ Object.assign(rt, {
+ secretsView,
+ secretValue: name => secrets.get(name)?.value,
+ canUseSecret: (name, botId) => canUse(secrets.get(name), botId),
+ secretEndpoint,
+ forgetBotSecrets,
+ loadSecrets,
+ redactSecrets: text => redact(text),
+ })
}
diff --git a/ds-bot/src/host/store.js b/ds-bot/src/host/store.js
index d29df440..2769537f 100644
--- a/ds-bot/src/host/store.js
+++ b/ds-bot/src/host/store.js
@@ -11,8 +11,8 @@ import { currentColor, normalize, unquote } from './text.js'
export function install(rt) {
const { ctx, home, statePath } = rt
- /** @type {{version:1, workspaceId?:string, mainBotIds:string[], bots:Record<string,any>, rooms:Record<string,any>, agents:Record<string,any>, exchanges:any[], exchangeTurns:Record<string,number[]>, revision:number}} */
- const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, exchanges: [], exchangeTurns: {}, questions: {}, prefs: {}, revision: 0 }
+ /** @type {{version:1, workspaceId?:string, mainBotIds:string[], bots:Record<string,any>, rooms:Record<string,any>, agents:Record<string,any>, capabilities:{items:Record<string,any>}, exchanges:any[], exchangeTurns:Record<string,number[]>, revision:number}} */
+ const state = { version: 1, mainBotIds: [], bots: {}, rooms: {}, agents: {}, capabilities: { items: {} }, exchanges: [], exchangeTurns: {}, questions: {}, prefs: {}, revision: 0 }
let loaded = null
let writing = Promise.resolve()
const { warn } = rt
@@ -97,13 +97,25 @@ export function install(rt) {
// Fill `state` from the saved file and bring an older team up to date. Returns the
// groups whose Session titles still need the new name.
const adopt = (parsed) => {
+ const hadCapabilities = parsed !== null && parsed !== undefined && Object.hasOwn(parsed, 'capabilities')
for (const key of Object.keys(state)) delete state[key]
Object.assign(state, JSON.parse(EMPTY), parsed ?? {})
state.prefs ??= {}
// Teams saved before the DSH Agent existed carry no `agents`; corrupt values reset.
if (state.agents === null || typeof state.agents !== 'object' || Array.isArray(state.agents)) state.agents = {}
- let migrated = false
+ let migrated = !hadCapabilities
+ if (state.capabilities === null || typeof state.capabilities !== 'object' || Array.isArray(state.capabilities)) {
+ state.capabilities = { items: {} }
+ migrated = true
+ } else if (state.capabilities.items === null || typeof state.capabilities.items !== 'object' || Array.isArray(state.capabilities.items)) {
+ state.capabilities.items = {}
+ migrated = true
+ }
for (const bot of Object.values(state.bots)) {
+ if (!Array.isArray(bot.capabilities)) {
+ bot.capabilities = []
+ migrated = true
+ }
if (bot.color !== currentColor(bot.color)) {
bot.color = currentColor(bot.color)
migrated = true
@@ -248,6 +260,7 @@ export function install(rt) {
ensureLock()
await rename(temp, statePath)
seen = stamp()
+ rt.capabilitiesStateSaved?.()
} catch (error) {
await unlink(temp).catch(() => {})
throw error
diff --git a/ds-bot/src/host/tools.js b/ds-bot/src/host/tools.js
index ade3c930..e8b656b0 100644
--- a/ds-bot/src/host/tools.js
+++ b/ds-bot/src/host/tools.js
@@ -437,5 +437,103 @@ export function install(rt) {
},
}))
+ ctx.tools.register(defineTool({
+ name: 'list_capabilities',
+ description: 'List shared MCP servers, skills, and packs, plus the capabilities attached to you.',
+ parameters: {},
+ output,
+ async execute(_args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ const bot = rt.botOf(self)
+ if (!bot) return 'Only Bots on the team can use list_capabilities.'
+ const items = Object.values(state.capabilities?.items ?? {})
+ if (items.length === 0) return 'No shared capabilities are saved yet.'
+ const statuses = rt.capabilityStatusesView()[bot.id] ?? {}
+ const lines = items.map(item => {
+ const extra = item.kind === 'pack' ? `; includes ${(item.items ?? []).join(', ') || 'nothing'}`
+ : item.kind === 'mcp' && item.transport === 'stdio' ? `; ${item.approved ? 'allowed' : 'needs user approval'}` : ''
+ const itemStatus = statuses[item.name]
+ const state = itemStatus ? ` (${itemStatus.state}${itemStatus.error ? `: ${itemStatus.error}` : ''})` : ''
+ const status = bot.capabilities?.includes(item.name) ? `; attached to you${state}` : ''
+ return `- ${item.name} (${item.kind})${item.description ? ` — ${item.description}` : ''}${extra}${status}`
+ })
+ return ['Shared capabilities:', ...lines].join('\n')
+ },
+ }))
+ ctx.tools.register(defineTool({
+ name: 'save_capability',
+ description: 'Create or update a shared MCP server, skill, or pack. Changes apply from your next message.',
+ parameters: {
+ name: { type: 'string', required: true, description: 'Lowercase letters, digits, and single hyphens, up to 32 characters; "github" is reserved' },
+ kind: { type: 'string', required: true, enum: ['mcp', 'skill', 'pack'] },
+ description: { type: 'string', description: 'What this capability provides' },
+ transport: { type: 'string', enum: ['stdio', 'streamable-http'], description: 'How to reach an MCP server: a local command or an HTTP URL' },
+ command: { type: 'string', description: 'Program that starts a local MCP server' },
+ args: { type: 'array', items: { type: 'string' }, description: 'Arguments for command' },
+ env: { type: 'object', additionalProperties: true, description: 'Environment variables for command; write $DSH_SECRET_<NAME> to insert a saved secret instead of the value' },
+ url: { type: 'string', description: 'MCP server URL' },
+ headers: { type: 'object', additionalProperties: true, description: 'HTTP headers; write $DSH_SECRET_<NAME> to insert a saved secret instead of the value' },
+ content: { type: 'string', description: 'Skill instructions' },
+ items: { type: 'array', items: { type: 'string' }, description: 'MCP server and skill names in the pack' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ if (!rt.botOf(self)) return 'Only Bots on the team can use save_capability.'
+ try {
+ const item = await rt.capabilitySave(args, { botId: self })
+ const approval = item.kind === 'mcp' && item.transport === 'stdio' && !item.approved
+ ? ' The user must allow this MCP server in DS Bot settings before it can work.'
+ : ''
+ return `Saved ${item.name}. Bots with it attached use the change from their next message.${approval}`
+ } catch (error) { return error.message }
+ },
+ }))
+ ctx.tools.register(defineTool({
+ name: 'delete_capability',
+ description: 'Remove a shared capability and detach it from every Bot and pack.',
+ parameters: { name: { type: 'string', required: true } },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ if (!rt.botOf(self)) return 'Only Bots on the team can use delete_capability.'
+ try {
+ await rt.capabilityDelete(args.name, { botId: self })
+ return `Deleted ${args.name}; it was removed from every Bot and pack. The change applies from their next message.`
+ } catch (error) { return error.message }
+ },
+ }))
+ for (const [name, endpoint, verb] of [['attach_capability', 'attach', 'Attached'], ['detach_capability', 'detach', 'Detached']]) {
+ ctx.tools.register(defineTool({
+ name,
+ description: `${verb} a shared capability to yourself, or to another Bot if you are a Main Bot.`,
+ parameters: {
+ name: { type: 'string', required: true, description: 'Capability name from list_capabilities' },
+ bot: { type: 'string', description: 'Optional Bot name; only a Main Bot may change another Bot' },
+ },
+ output,
+ async execute(args, exec) {
+ await rt.load()
+ const self = rt.selfOf(exec.agent?.id)
+ 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 members = attached?.kind === 'pack'
+ ? (attached.items ?? []).map(child => state.capabilities.items[child]).filter(Boolean)
+ : attached ? [attached] : []
+ const approvals = members
+ .filter(item => item.kind === 'mcp' && item.transport === 'stdio' && item.approved !== true)
+ .map(item => ` The user must allow ${item.name} in DS Bot settings before it can work.`)
+ .join('')
+ return `${verb} ${args.name} ${args.bot ? `to ${result.bot}` : 'to yourself'}. Changes apply from ${result.bot}'s next message.${endpoint === 'attach' ? approvals : ''}`
+ } catch (error) { return error.message }
+ },
+ }))
+ }
+
Object.assign(rt, { pickRoom })
}
diff --git a/ds-bot/test/agents.test.js b/ds-bot/test/agents.test.js
index c1623609..ee5ce746 100644
--- a/ds-bot/test/agents.test.js
+++ b/ds-bot/test/agents.test.js
@@ -45,7 +45,10 @@ function start(team, { config = {} } = {}) {
resolveAgent: async (sessionId) => {
const agent = {
session: { id: sessionId },
- ctx: { tools: { restrict: (filter) => { restricted.push({ sessionId, filter }); return () => {} } } },
+ ctx: {
+ tools: { restrict: (filter) => { restricted.push({ sessionId, filter }); return () => {} } },
+ effect: execute => execute(),
+ },
followup() {},
}
return { agent }
@@ -241,7 +244,15 @@ test('team tools are restricted on DSH Agent Sessions but not on Bot Sessions',
t.after(stop)
await call('state', {})
// A Bot resolving its agent triggers agent/created but owns no team tools mask.
- createdAgents({ agent: { session: { id: 'm1' }, ctx: { tools: { restrict: filter => { restricted.push({ sessionId: 'm1', filter }) } } } } })
+ createdAgents({
+ agent: {
+ session: { id: 'm1' },
+ ctx: {
+ tools: { restrict: filter => { restricted.push({ sessionId: 'm1', filter }) } },
+ effect: execute => execute(),
+ },
+ },
+ })
await flush()
assert.equal(restricted.length, 0)
// Creating the agent records the session, then restrict fires on its own agent.
@@ -250,7 +261,13 @@ test('team tools are restricted on DSH Agent Sessions but not on Bot Sessions',
assert.equal(restricted[0].sessionId, agent.sessions[0])
assert.deepEqual([...restricted[0].filter.deny].sort(), [...TEAM_TOOLS].sort())
// A later agent/created for that session does not restrict a second time.
- const listener = { session: { id: agent.sessions[0] }, ctx: { tools: { restrict: filter => { restricted.push({ sessionId: agent.sessions[0], filter }) } } } }
+ const listener = {
+ session: { id: agent.sessions[0] },
+ ctx: {
+ tools: { restrict: filter => { restricted.push({ sessionId: agent.sessions[0], filter }) } },
+ effect: execute => execute(),
+ },
+ }
createdAgents({ agent: listener })
await flush()
// The listener path resolves through rt.load() + the session index; because the
diff --git a/ds-bot/test/capabilities.test.js b/ds-bot/test/capabilities.test.js
new file mode 100644
index 00000000..957f36ab
--- /dev/null
+++ b/ds-bot/test/capabilities.test.js
@@ -0,0 +1,276 @@
+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 { createRuntime } from '../index.js'
+import { expandCapabilityNames, validateCapabilityName } from '../src/host/capabilities.js'
+import { fakeContext } from './fake-ctx.js'
+
+const makeHome = state => {
+ const home = mkdtempSync(join(tmpdir(), 'dsb-capabilities-'))
+ writeFileSync(join(home, 'state.json'), JSON.stringify(state))
+ return home
+}
+const team = () => ({
+ version: 1,
+ mainBotIds: ['chief'],
+ bots: {
+ chief: { id: 'chief', sessionId: 'chief', name: 'Chief', capabilities: [], createdAt: 1 },
+ worker: { id: 'worker', sessionId: 'worker', name: 'Worker', capabilities: [], createdAt: 2 },
+ helper: { id: 'helper', sessionId: 'helper', name: 'Helper', capabilities: [], createdAt: 3 },
+ },
+ rooms: { room: { id: 'room', members: ['chief'], sessions: { chief: 'room-chief' }, admin: 'chief', mode: 'everyone' } },
+ agents: {},
+ exchanges: [],
+ exchangeTurns: {},
+ questions: {},
+ revision: 1,
+})
+const mcp = (name, command = 'node') => ({ name, kind: 'mcp', description: 'Echo service', transport: 'stdio', command, args: [], env: {} })
+
+function testAgent(id, mounts, skillsBySession) {
+ const disposers = []
+ const skills = new Map()
+ skillsBySession.set(id, skills)
+ const agentCtx = {
+ effect(execute) {
+ const dispose = execute()
+ if (typeof dispose === 'function') disposers.push(dispose)
+ },
+ plugin(plugin, config) {
+ const record = { plugin, config, sessionId: id, disposed: false }
+ mounts.push(record)
+ if (plugin.inject?.includes('skills')) {
+ const c = {
+ skills: { register(skill) { skills.set(skill.name, skill); return () => skills.delete(skill.name) } },
+ effect: execute => { record.cleanup = execute() },
+ }
+ plugin.apply(c)
+ }
+ return {
+ await: async () => {},
+ dispose: () => { record.disposed = true; record.cleanup?.() },
+ }
+ },
+ dispose() { for (const dispose of disposers.reverse()) dispose() },
+ }
+ return { session: { id }, ctx: agentCtx }
+}
+
+async function setup({ state = team(), secret, beforeLoad } = {}) {
+ const home = makeHome(state)
+ if (secret) writeFileSync(join(home, 'secrets.json'), JSON.stringify({ secrets: [secret] }))
+ const mounts = []
+ const skills = new Map()
+ const mcpPlugin = { name: 'mcp-client', apply() {} }
+ const loader = { import: async () => ({ default: mcpPlugin }), unwrapExports: exports => exports.default }
+ const ctx = fakeContext({ services: { loader } })
+ const rt = createRuntime(ctx, { home, github: false })
+ beforeLoad?.({ ctx, rt, mounts, skills, mcpPlugin })
+ await rt.load()
+ return { home, ctx, rt, mounts, skills, mcpPlugin, dispose() { ctx.dispose(); rmSync(home, { recursive: true, force: true }) } }
+}
+
+test('capability names use the MCP and skill validator intersection', () => {
+ assert.equal(validateCapabilityName('a'), 'a')
+ assert.equal(validateCapabilityName('web-search-1'), 'web-search-1')
+ for (const name of ['github', 'with_underscore', 'with--dash', '1tool', 'A', 'a'.repeat(33)]) assert.throws(() => validateCapabilityName(name))
+})
+
+test('packs expand only to MCP and skill items', () => {
+ const items = { server: { kind: 'mcp' }, guide: { kind: 'skill' }, team: { kind: 'pack', items: ['server', 'guide'] } }
+ assert.deepEqual(expandCapabilityNames(['team', 'server'], items), new Set(['server', 'guide']))
+ assert.throws(() => expandCapabilityNames(['missing'], items), /No capability/)
+ assert.throws(() => expandCapabilityNames(['bad'], { ...items, bad: { kind: 'pack', items: ['team'] } }), /unavailable capability/)
+})
+
+test('state migration adds an empty library and Bot attachment lists', async t => {
+ const old = team()
+ delete old.capabilities
+ for (const bot of Object.values(old.bots)) delete bot.capabilities
+ const env = await setup({ state: old })
+ t.after(() => env.dispose())
+ await env.rt.load()
+ assert.deepEqual(env.rt.state.capabilities, { items: {} })
+ assert.deepEqual(env.rt.state.bots.chief.capabilities, [])
+ const saved = JSON.parse(await (await import('node:fs/promises')).readFile(join(env.home, 'state.json'), 'utf8'))
+ assert.deepEqual(saved.capabilities, { items: {} })
+ assert.deepEqual(saved.bots.chief.capabilities, [])
+})
+
+test('Bot saves enforce approval and ownership, and deletion cascades', async t => {
+ const env = await setup()
+ t.after(() => env.dispose())
+ const { rt } = env
+ const { state } = rt
+ const created = await rt.capabilitySave(mcp('echo'), { botId: 'worker' })
+ assert.equal(created.approved, false)
+ const description = await rt.capabilitySave({ ...mcp('echo'), description: 'Updated' }, { botId: 'worker' })
+ assert.equal(description.approved, false)
+ await rt.capabilityEndpoint('capability-approve', { name: 'echo' })
+ const approved = await rt.capabilitySave({ ...mcp('echo'), description: 'Another description' }, { botId: 'worker' })
+ assert.equal(approved.approved, true)
+ const changed = await rt.capabilitySave(mcp('echo', 'node-new'), { botId: 'worker' })
+ assert.equal(changed.approved, false)
+ await assert.rejects(
+ rt.capabilitySave({ name: 'echo', kind: 'skill', description: 'Other kind', content: 'Instructions' }, { botId: 'worker' }),
+ error => error.message === 'A capability cannot change its kind. Delete it and save a new one.',
+ )
+ await assert.rejects(rt.capabilitySave(mcp('echo'), { botId: 'helper' }), /creator or a Main Bot/)
+ await assert.rejects(rt.capabilityDelete('echo', { botId: 'helper' }), /creator or a Main Bot/)
+ await rt.capabilitySave({ name: 'guide', kind: 'skill', description: 'Guide', content: 'Do the work.' }, { botId: 'worker' })
+ await rt.capabilitySave({ name: 'team', kind: 'pack', items: ['echo', 'guide'] }, { botId: 'worker' })
+ state.bots.worker.capabilities = ['echo', 'team']
+ await rt.capabilityDelete('echo', { botId: 'worker' })
+ assert.equal(state.capabilities.items.echo, undefined)
+ assert.deepEqual(state.capabilities.items.team.items, ['guide'])
+ assert.deepEqual(state.bots.worker.capabilities, ['team'])
+})
+
+test('capability Bot tools refuse DSH Agent sessions', async t => {
+ const env = await setup()
+ t.after(() => env.dispose())
+ const list = env.ctx.registeredTools.get('list_capabilities')
+ assert.ok(list)
+ assert.match(await list.execute({}, { agent: { id: 'outside' } }), /Only Bots on the team/)
+})
+
+test('capability tool descriptions and attach results explain approval', async t => {
+ const env = await setup()
+ t.after(() => env.dispose())
+ const parameters = env.ctx.registeredTools.get('save_capability').parameters.properties
+ assert.deepEqual(
+ Object.fromEntries(['transport', 'command', 'args', 'env', 'url', 'headers', 'content'].map(name => [name, parameters[name].description])),
+ {
+ transport: 'How to reach an MCP server: a local command or an HTTP URL',
+ command: 'Program that starts a local MCP server',
+ args: 'Arguments for command',
+ env: 'Environment variables for command; write $DSH_SECRET_<NAME> to insert a saved secret instead of the value',
+ url: 'MCP server URL',
+ headers: 'HTTP headers; write $DSH_SECRET_<NAME> to insert a saved secret instead of the value',
+ content: 'Skill instructions',
+ },
+ )
+ await env.rt.capabilitySave(mcp('blocked'), { botId: 'worker' })
+ const attached = await env.ctx.registeredTools.get('attach_capability').execute(
+ { name: 'blocked' },
+ { agent: { id: 'worker' } },
+ )
+ assert.ok(attached.endsWith(' The user must allow blocked in DS Bot settings before it can work.'))
+})
+
+test('read-only secret reload does not requeue capability reconciliation', async t => {
+ const env = await setup()
+ t.after(() => env.dispose())
+ await env.rt.loadSecrets()
+ await env.rt.scheduleCapabilitiesReconcile()
+ env.rt.readOnly = () => 'The Bot team is open in another dsh.'
+ let loads = 0
+ const loadSecrets = env.rt.loadSecrets
+ env.rt.loadSecrets = async () => {
+ loads += 1
+ return loadSecrets()
+ }
+ await env.rt.reconcileCapabilities()
+ assert.equal(loads, 1)
+})
+
+test('startup and empty-to-nonempty attachments track existing Bot Agents', async t => {
+ const state = team()
+ state.capabilities = { items: { echo: { ...mcp('echo'), approved: true, createdBy: 'chief', createdAt: 1, updatedAt: 1 } } }
+ state.bots.chief.capabilities = ['echo']
+ const resolved = []
+ const env = await setup({
+ state,
+ beforeLoad: ({ rt, mounts, skills }) => {
+ const existing = Object.fromEntries(['chief', 'room-chief', 'worker', 'helper'].map(id => [id, testAgent(id, mounts, skills)]))
+ rt.chatOf = botId => botId
+ rt.groupSessionsOf = botId => botId === 'chief' ? ['room-chief', 'room-chief'] : []
+ rt.resolveAgent = async sessionId => {
+ if (Object.hasOwn(existing, sessionId)) resolved.push(sessionId)
+ return existing[sessionId]
+ }
+ },
+ })
+ t.after(() => env.dispose())
+ await new Promise(resolve => setImmediate(resolve))
+ await env.rt.scheduleCapabilitiesReconcile()
+ assert.deepEqual(resolved, ['chief', 'room-chief'])
+ assert.deepEqual(env.mounts.map(mount => mount.sessionId), ['chief', 'room-chief'])
+
+ await env.rt.changeCapabilityAttachment('attach', { name: 'echo' }, 'worker')
+ await env.rt.capabilityEndpoint('bot-capabilities', { botId: 'helper', capabilities: ['echo'] })
+ await env.rt.scheduleCapabilitiesReconcile()
+ assert.deepEqual(resolved, ['chief', 'room-chief', 'worker', 'helper'])
+ assert.deepEqual(env.mounts.filter(mount => !mount.disposed).map(mount => mount.sessionId), ['chief', 'room-chief', 'worker', 'helper'])
+})
+
+test('unset capability statuses are omitted from the view and tool listing', async t => {
+ const env = await setup()
+ t.after(() => env.dispose())
+ const { rt, ctx } = env
+ await rt.capabilitySave({ ...mcp('echo'), approved: true }, { botId: 'chief' })
+ await rt.capabilitySave({ name: 'guide', kind: 'skill', description: 'Guide', content: 'Instructions' }, { botId: 'chief' })
+ await rt.capabilitySave({ name: 'team', kind: 'pack', items: ['echo', 'guide'] }, { botId: 'chief' })
+ rt.state.bots.chief.capabilities = ['echo', 'team']
+ await rt.save()
+ assert.deepEqual(rt.capabilityStatusesView().chief, {})
+ const listed = await ctx.registeredTools.get('list_capabilities').execute({}, { agent: { id: 'chief' } })
+ assert.match(listed, /echo \(mcp\).*; attached to you(?:\n|$)/)
+ assert.doesNotMatch(listed, /attached to you \(connecting\)/)
+})
+
+test('mounts agent-only MCP and skills, remounts changed config, resolves scoped secrets and reports missing secrets', async t => {
+ const env = await setup({ secret: { name: 'TOKEN', value: 'fake-secret-value', purpose: '', scope: ['chief'], requestedBy: null, createdAt: 1, updatedAt: 1 } })
+ t.after(() => env.dispose())
+ const { ctx, rt, mounts, skills, mcpPlugin } = env
+ await rt.capabilitySave({ ...mcp('echo'), transport: 'streamable-http', url: 'https://example.test/mcp', headers: { Authorization: 'Bearer $DSH_SECRET_TOKEN' } }, { botId: 'chief' })
+ await rt.capabilitySave({ name: 'guide', kind: 'skill', description: 'How to work', content: 'Capability marker.' }, { botId: 'chief' })
+ await rt.capabilitySave({ name: 'team', kind: 'pack', items: ['echo', 'guide'] }, { botId: 'chief' })
+ await rt.changeCapabilityAttachment('attach', { name: 'team' }, 'chief')
+ await rt.changeCapabilityAttachment('attach', { name: 'team', bot: 'Worker' }, 'chief')
+ await assert.rejects(rt.changeCapabilityAttachment('attach', { name: 'team', bot: 'Chief' }, 'worker'), /Main Bot/)
+ await assert.rejects(rt.changeCapabilityAttachment('detach', { name: 'team', bot: 'Chief' }, 'worker'), /Main Bot/)
+ await rt.capabilitySave(mcp('blocked'), { botId: 'worker' })
+ await rt.changeCapabilityAttachment('attach', { name: 'blocked' }, 'worker')
+ const chief = testAgent('chief', mounts, skills)
+ const room = testAgent('room-chief', mounts, skills)
+ const worker = testAgent('worker', mounts, skills)
+ const dsh = testAgent('outside', mounts, skills)
+ for (const agent of [chief, room, worker, dsh]) ctx.emit('agent/created', { agent })
+ await rt.scheduleCapabilitiesReconcile()
+ assert.equal(mounts.filter(mount => mount.plugin === mcpPlugin).length, 2)
+ assert.equal(mounts.find(mount => mount.config.serverName === 'echo').config.headers.Authorization, 'Bearer fake-secret-value')
+ assert.equal(skills.get('chief').has('guide'), true)
+ assert.deepEqual(mounts.filter(mount => mount.plugin === mcpPlugin).map(mount => mount.sessionId), ['chief', 'room-chief'])
+ assert.equal(JSON.stringify(rt.state.capabilities).includes('fake-secret-value'), false)
+ assert.equal(JSON.stringify(rt.capabilityLibraryView()).includes('fake-secret-value'), false)
+ assert.equal(rt.capabilityStatusesView().chief.team.state, 'ready')
+ assert.equal(rt.capabilityStatusesView().worker.team.state, 'error')
+ assert.equal(rt.capabilityStatusesView().worker.blocked.state, 'needs-approval')
+ assert.equal(mounts.some(mount => mount.config?.serverName === 'blocked'), false)
+ await rt.capabilityEndpoint('capability-approve', { name: 'blocked' })
+ await rt.scheduleCapabilitiesReconcile()
+ assert.equal(mounts.some(mount => mount.config?.serverName === 'blocked' && mount.sessionId === 'worker'), true)
+ const first = mounts.find(mount => mount.config.serverName === 'echo')
+ const firstSkill = mounts.find(mount => mount.sessionId === 'chief' && mount.plugin.inject?.includes('skills'))
+ await rt.capabilitySave({ ...mcp('echo'), transport: 'streamable-http', url: 'https://example.test/mcp', headers: { Authorization: 'Bearer changed' } }, { botId: 'chief' })
+ await rt.capabilitySave({ name: 'guide', kind: 'skill', description: 'How to work', content: 'Changed capability marker.' }, { botId: 'chief' })
+ await rt.scheduleCapabilitiesReconcile()
+ assert.equal(first.disposed, true)
+ assert.equal(firstSkill.disposed, true)
+ assert.equal(skills.get('chief').get('guide').content, 'Changed capability marker.')
+ assert.equal(mounts.filter(mount => mount.plugin === mcpPlugin && mount.config.serverName === 'echo').length, 5)
+ assert.equal(rt.capabilityStatusesView().worker.team.state, 'ready')
+ await rt.capabilitySave({ ...mcp('missing-secret'), transport: 'streamable-http', url: 'https://example.test/mcp', headers: { Authorization: '$DSH_SECRET_TOKEN' } }, { botId: 'worker' })
+ await rt.changeCapabilityAttachment('attach', { name: 'missing-secret' }, 'worker')
+ await rt.scheduleCapabilitiesReconcile()
+ assert.equal(rt.capabilityStatusesView().worker['missing-secret'].state, 'error')
+ assert.match(rt.capabilityStatusesView().worker['missing-secret'].error, /TOKEN/)
+ await rt.changeCapabilityAttachment('detach', { name: 'team' }, 'chief')
+ await rt.scheduleCapabilitiesReconcile()
+ assert.equal(first.disposed, true)
+ assert.equal(mounts.findLast(mount => mount.sessionId === 'chief' && mount.plugin.inject?.includes('skills')).disposed, true)
+ assert.equal(rt.capabilityStatusesView().chief.team, undefined)
+})
diff --git a/ds-bot/test/install.test.js b/ds-bot/test/install.test.js
index f01c8550..98c657ff 100644
--- a/ds-bot/test/install.test.js
+++ b/ds-bot/test/install.test.js
@@ -16,7 +16,7 @@ function start(state, { config = {}, services } = {}) {
route = options
return register(options)
}
- apply(ctx, { home, ...config })
+ const applyResult = apply(ctx, { home, ...config })
const call = async (endpoint, payload) => {
const response = await route.fetch(new Request('http://localhost/api/bot', { method: 'POST', body: JSON.stringify({ endpoint, payload }) }))
return response.json()
@@ -25,13 +25,14 @@ function start(state, { config = {}, services } = {}) {
ctx.dispose()
rmSync(home, { recursive: true, force: true })
}
- return { ctx, call, stop }
+ return { ctx, call, stop, applyResult }
}
// Listeners run, and tools are listed, in the order they are registered.
test('apply registers listeners, tools, and effects in a fixed order', (t) => {
- const { ctx, stop } = start()
+ const { ctx, stop, applyResult } = start()
t.after(stop)
+ assert.equal(applyResult, undefined)
assert.deepEqual(ctx.calls, [
'effect ds-bot: state lock',
'on llm/adapters-updated',
@@ -52,6 +53,11 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'tool delete_group',
'tool post_to_group',
'tool ask_user',
+ 'tool list_capabilities',
+ 'tool save_capability',
+ 'tool delete_capability',
+ 'tool attach_capability',
+ 'tool detach_capability',
'effect ds-bot: chat index',
'tool group_relay',
'tool read_own_chat',
@@ -77,6 +83,8 @@ test('apply registers listeners, tools, and effects in a fixed order', (t) => {
'on llm/stream',
'effect ds-bot: load secrets',
'effect ds-bot: connectors',
+ 'on agent/created',
+ 'effect ds-bot: capabilities',
'effect ds-bot: usage ledger',
'on llm/stream',
'effect ds-bot: update check',